From 9c3fbc67b4acf88d4e066455ca01e6cdd94ec992 Mon Sep 17 00:00:00 2001 From: DaanMeijer Date: Sun, 18 Dec 2016 20:01:44 +0100 Subject: [PATCH 01/74] Add style ID to font style, so indesign import works --- src/PhpWord/Writer/Word2007/Part/Styles.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/PhpWord/Writer/Word2007/Part/Styles.php b/src/PhpWord/Writer/Word2007/Part/Styles.php index 7bcb8d92a4..198604c7e7 100644 --- a/src/PhpWord/Writer/Word2007/Part/Styles.php +++ b/src/PhpWord/Writer/Word2007/Part/Styles.php @@ -158,6 +158,8 @@ private function writeFontStyle(XMLWriter $xmlWriter, $styleName, FontStyle $sty $xmlWriter->startElement('w:style'); $xmlWriter->writeAttribute('w:type', $type); + $xmlWriter->writeAttribute('w:customStyle', '1'); + $xmlWriter->writeAttribute('w:styleId', $styleName); // Heading style if ($styleType == 'title') { From 0ced9136f41613dde25e05a0850b180eec53dde5 Mon Sep 17 00:00:00 2001 From: FBnil Date: Mon, 25 Sep 2017 16:33:25 +0200 Subject: [PATCH 02/74] New tests for the TemplateProcessor.php functionality See TemplateProcessor.php for what has changed --- tests/PhpWord/TemplateProcessorTest.php | 122 +++++++++++++++++++++++- 1 file changed, 119 insertions(+), 3 deletions(-) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 11b43cf454..35eaa0f6cc 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -203,6 +203,7 @@ public function testMacrosCanBeReplacedInHeaderAndFooter() /** * @covers ::cloneBlock * @covers ::deleteBlock + * @covers ::getBlock * @covers ::saveAs * @test */ @@ -214,13 +215,128 @@ public function testCloneDeleteBlock() array('DELETEME', '/DELETEME', 'CLONEME', '/CLONEME'), $templateProcessor->getVariables() ); - + $clone_times = 3; $docName = 'clone-delete-block-result.docx'; - $templateProcessor->cloneBlock('CLONEME', 3); + $xmlblock = $templateProcessor->getBlock('CLONEME'); + $this->assertNotEmpty($xmlblock); + $templateProcessor->cloneBlock('CLONEME', $clone_times); $templateProcessor->deleteBlock('DELETEME'); $templateProcessor->saveAs($docName); $docFound = file_exists($docName); - unlink($docName); + if($docFound){ + # Great, so we saved the replaced document, so we open that new document + # note that we need to access private variables, so we use a sub-class + $templateProcessorNEWFILE = new OpenTemplateProcessor($docName); + # We test that all Block variables have been replaced (thus, getVariables() is empty) + $this->assertEquals( + [], + $templateProcessorNEWFILE->getVariables(), + "All block variables should have been replaced" + ); + # we cloned block CLONEME $clone_times times, so let's count to $clone_times + $this->assertEquals($clone_times, + substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $xmlblock), + "Block should be present $clone_times in the document" + ); + unlink($docName); # delete generated file + } + $this->assertTrue($docFound); } + + public function testCloneIndexedBlock() + { + $templateProcessor = new OpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + # we will fake a block with a variable inside it, as there is no template document yet. + $XMLTXT = 'This ${repeats} a few times'; + $XMLSTR = '${MYBLOCK}' . $XMLTXT . '${/MYBLOCK}'; + $templateProcessor->tempDocumentMainPart = $XMLSTR; + + $this->assertEquals( + $XMLTXT, + $templateProcessor->getBlock('MYBLOCK'), + "Block should be cut at the right place (using findBlockStart/findBlockEnd)" + ); + + # detects variables + $this->assertEquals( + array('MYBLOCK', 'repeats', '/MYBLOCK'), + $templateProcessor->getVariables(), + "Injected document should contain the right initial variables, in the right order" + ); + + $templateProcessor->cloneBlock('MYBLOCK', 4); + # detects new variables + $this->assertEquals( + array('repeats#1', 'repeats#2', 'repeats#3', 'repeats#4'), + $templateProcessor->getVariables(), + "Injected document should contain the right cloned variables, in the right order" + ); + + $ARR = [ + 'repeats#1' => 'ONE', + 'repeats#2' => 'TWO', + 'repeats#3' => 'THREE', + 'repeats#4' => 'FOUR' + ]; + $templateProcessor->setValue(array_keys($ARR), array_values($ARR)); + $this->assertEquals( + [], + $templateProcessor->getVariables(), + "Variables have been replaced and should not be present anymore" + ); + + # now we test the order of replacement: ONE,TWO,THREE then FOUR + $STR = ""; + foreach($ARR as $k => $v){ + $STR .= str_replace('${repeats}',$v, $XMLTXT); + } + $this->assertEquals(1, + substr_count($templateProcessor->tempDocumentMainPart, $STR), + "order of replacement should be: ONE,TWO,THREE then FOUR" + ); + + # Now we try again, but without variable incrementals (old behavior) + $templateProcessor->tempDocumentMainPart = $XMLSTR; + $templateProcessor->cloneBlock('MYBLOCK', 4, true, false); + + # detects new variable + $this->assertEquals( + array('repeats'), + $templateProcessor->getVariables(), + 'new variable $repeats should be present' + ); + + # we cloned block CLONEME 4 times, so let's count + $this->assertEquals(4, + substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT), + 'detects new variable $repeats to be present 4 times' + ); + + # we cloned block CLONEME 4 times, so let's see that there is no space between these blocks + $this->assertEquals(1, + substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT.$XMLTXT.$XMLTXT.$XMLTXT), + "The four times cloned block should be the same as four times the block" + ); + } + +} + +/** + * used by testCloneDeleteBlock and testCloneIndexedBlock to access private variables in a TemplateProcessor + * @test + */ +class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor +{ + public function __construct($instance) { + return parent::__construct($instance); + } + + public function __get($key) { + return $this->$key; + } + + public function __set($key, $val) { + return $this->$key = $val; + } } From d68bb3c65931b047e8ab6b86dbb55719d122087a Mon Sep 17 00:00:00 2001 From: FBnil Date: Mon, 25 Sep 2017 16:55:10 +0200 Subject: [PATCH 03/74] Fixes Block functions with documents edited by LibreOffice I removed the regexp (although I had a working regexp, it seems PHP7 does not like multiple non-greedy patterns. The need to anchor the query to is very dirty). So I implemented the findBlockStart() and findBlockEnd() that search upto a paragraph change , This has been tested with LibreOffice generated docx (that features ) and real MSOffice documents (that features extra parameters, nb: ). As well as a few new testcases to cover the new functionality. What is new? * Blocks with variables inside now expand like Rows, with #n at the end (and you can get the old behavior back with an extra parameter) * Block functions now return sensible information instead of void * you can throw exceptions if you can not find a block (enabled by an extra parameter) * getBlock() implemented See also TemplateProcessorTest.php for the additional test cases --- src/PhpWord/TemplateProcessor.php | 146 +++++++++++++++++++++++------- 1 file changed, 111 insertions(+), 35 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 2f6d6258a3..3749f96d41 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -321,60 +321,101 @@ public function cloneRow($search, $numberOfClones) * @param string $blockname * @param integer $clones * @param boolean $replace + * @param boolean $incrementVariables + * @param boolean $throwexception * * @return string|null */ - public function cloneBlock($blockname, $clones = 1, $replace = true) + public function cloneBlock($blockname, $clones = 1, $replace = true, $incrementVariables = true, $throwexception = false) { - $xmlBlock = null; - preg_match( - '/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', - $this->tempDocumentMainPart, - $matches - ); + $S_search = '${' . $blockname . '}'; + $E_search = '${/' . $blockname . '}'; + + $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); + $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); + if (!$S_tagPos || !$E_tagPos) { + if($throwexception) + throw new Exception("Can not find block '$blockname', template variable not found or variable contains markup."); + else + return null; # Block not found, return null + } + + $S_blockStart = $this->findBlockStart($S_tagPos); + $S_blockEnd = $this->findBlockEnd($S_tagPos); + #$xmlStart = $this->getSlice($S_blockStart, $S_blockEnd); - if (isset($matches[3])) { - $xmlBlock = $matches[3]; - $cloned = array(); + $E_blockStart = $this->findBlockStart($E_tagPos); + $E_blockEnd = $this->findBlockEnd($E_tagPos); + #$xmlEnd = $this->getSlice($E_blockStart, $E_blockEnd); + + $xmlBlock = $this->getSlice($S_blockEnd, $E_blockStart); + + if($replace){ + $result = $this->getSlice(0, $S_blockStart); for ($i = 1; $i <= $clones; $i++) { - $cloned[] = $xmlBlock; + if($incrementVariables) + $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlBlock); + else + $result .= $xmlBlock; } + $result .= $this->getSlice($E_blockEnd); - if ($replace) { - $this->tempDocumentMainPart = str_replace( - $matches[2] . $matches[3] . $matches[4], - implode('', $cloned), - $this->tempDocumentMainPart - ); - } + $this->tempDocumentMainPart = $result; } return $xmlBlock; } + /** + * Get a block. (first block found) + * + * @param string $blockname + * @param boolean $throwexception + * + * @return string|null + */ + public function getBlock($blockname, $throwexception = false){ + return $this->cloneBlock($blockname, 1, false, $throwexception); + } /** * Replace a block. * * @param string $blockname * @param string $replacement + * @param boolean $throwexception * - * @return void + * @return false on no replacement, true on replacement */ - public function replaceBlock($blockname, $replacement) + public function replaceBlock($blockname, $replacement, $throwexception = false) { - preg_match( - '/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', - $this->tempDocumentMainPart, - $matches - ); - - if (isset($matches[3])) { - $this->tempDocumentMainPart = str_replace( - $matches[2] . $matches[3] . $matches[4], - $replacement, - $this->tempDocumentMainPart - ); + $S_search = '${' . $blockname . '}'; + $E_search = '${/' . $blockname . '}'; + + $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); + $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); + if (!$S_tagPos || !$E_tagPos) { + if($throwexception) + throw new Exception("Can not find block '$blockname', template variable not found or variable contains markup."); + else return false; } + + $S_blockStart = $this->findBlockStart($S_tagPos); + $S_blockEnd = $this->findBlockEnd($S_tagPos); + #$xmlStart = $this->getSlice($S_blockStart, $S_blockEnd); + + $E_blockStart = $this->findBlockStart($E_tagPos); + $E_blockEnd = $this->findBlockEnd($E_tagPos); + #$xmlEnd = $this->getSlice($E_blockStart, $E_blockEnd); + + $xmlBlock = $this->getSlice($S_blockEnd, $E_blockStart); + + $result = $this->getSlice(0, $S_blockStart); + $result .= $replacement; + $result .= $this->getSlice($E_blockEnd); + + $this->tempDocumentMainPart = $result; + + return true; } /** @@ -382,11 +423,11 @@ public function replaceBlock($blockname, $replacement) * * @param string $blockname * - * @return void + * @return true on block found and deleted, false on block not found. */ public function deleteBlock($blockname) { - $this->replaceBlock($blockname, ''); + return $this->replaceBlock($blockname, '', false); } /** @@ -557,7 +598,30 @@ protected function findRowStart($offset) } /** - * Find the end position of the nearest table row after $offset. + * Find the start position of the nearest paragraph () before $offset. + * + * @param integer $offset + * + * @return integer + * + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + protected function findBlockStart($offset) + { + $blockStart = strrpos($this->tempDocumentMainPart, 'tempDocumentMainPart) - $offset) * -1)); + + if (!$blockStart) { + $blockStart = strrpos($this->tempDocumentMainPart, '', ((strlen($this->tempDocumentMainPart) - $offset) * -1)); + } + if (!$blockStart) { + throw new Exception('Can not find the start position of the row to clone.'); + } + + return $blockStart; + } + + /** + * Find the end position of the nearest paragraph () after $offset. * * @param integer $offset * @@ -568,6 +632,18 @@ protected function findRowEnd($offset) return strpos($this->tempDocumentMainPart, '', $offset) + 7; } + /** + * Find the end position of the nearest table row after $offset. + * + * @param integer $offset + * + * @return integer + */ + protected function findBlockEnd($offset) + { + return strpos($this->tempDocumentMainPart, '', $offset) + 6; + } + /** * Get a slice of a string. * From ce79bd8630b6cdc87955ea01df8881b42f37c976 Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 26 Sep 2017 09:01:57 +0200 Subject: [PATCH 04/74] passed through phpunit and corrected style --- src/PhpWord/TemplateProcessor.php | 153 ++++++++++++++++++------ tests/PhpWord/OpenTemplateProcessor.php | 40 +++++++ tests/PhpWord/TemplateProcessorTest.php | 46 +++---- 3 files changed, 173 insertions(+), 66 deletions(-) create mode 100644 tests/PhpWord/OpenTemplateProcessor.php diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 2f6d6258a3..b43161a7b9 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -235,7 +235,7 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ $this->tempDocumentMainPart = $this->setValueForPart($search, $replace, $this->tempDocumentMainPart, $limit); $this->tempDocumentFooters = $this->setValueForPart($search, $replace, $this->tempDocumentFooters, $limit); } - + /** * Returns array of all variables in template. * @@ -321,60 +321,106 @@ public function cloneRow($search, $numberOfClones) * @param string $blockname * @param integer $clones * @param boolean $replace + * @param boolean $incrementVariables + * @param boolean $throwexception * * @return string|null */ - public function cloneBlock($blockname, $clones = 1, $replace = true) + public function cloneBlock($blockname, $clones = 1, $replace = true, $incrementVariables = true, $throwexception = false) { - $xmlBlock = null; - preg_match( - '/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', - $this->tempDocumentMainPart, - $matches - ); + $S_search = '${' . $blockname . '}'; + $E_search = '${/' . $blockname . '}'; + + $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); + $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); + if (!$S_tagPos || !$E_tagPos) { + if ($throwexception) { + throw new Exception("Can not find block '$blockname', template variable not found or variable contains markup."); + } else { + return null; # Block not found, return null + } + } - if (isset($matches[3])) { - $xmlBlock = $matches[3]; - $cloned = array(); + $S_blockStart = $this->findBlockStart($S_tagPos); + $S_blockEnd = $this->findBlockEnd($S_tagPos); + #$xmlStart = $this->getSlice($S_blockStart, $S_blockEnd); + + $E_blockStart = $this->findBlockStart($E_tagPos); + $E_blockEnd = $this->findBlockEnd($E_tagPos); + #$xmlEnd = $this->getSlice($E_blockStart, $E_blockEnd); + + $xmlBlock = $this->getSlice($S_blockEnd, $E_blockStart); + + if ($replace) { + $result = $this->getSlice(0, $S_blockStart); for ($i = 1; $i <= $clones; $i++) { - $cloned[] = $xmlBlock; + if ($incrementVariables) { + $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlBlock); + } else { + $result .= $xmlBlock; + } } + $result .= $this->getSlice($E_blockEnd); - if ($replace) { - $this->tempDocumentMainPart = str_replace( - $matches[2] . $matches[3] . $matches[4], - implode('', $cloned), - $this->tempDocumentMainPart - ); - } + $this->tempDocumentMainPart = $result; } return $xmlBlock; } + /** + * Get a block. (first block found) + * + * @param string $blockname + * @param boolean $throwexception + * + * @return string|null + */ + public function getBlock($blockname, $throwexception = false) + { + return $this->cloneBlock($blockname, 1, false, $throwexception); + } /** * Replace a block. * * @param string $blockname * @param string $replacement + * @param boolean $throwexception * - * @return void + * @return false on no replacement, true on replacement */ - public function replaceBlock($blockname, $replacement) + public function replaceBlock($blockname, $replacement, $throwexception = false) { - preg_match( - '/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', - $this->tempDocumentMainPart, - $matches - ); - - if (isset($matches[3])) { - $this->tempDocumentMainPart = str_replace( - $matches[2] . $matches[3] . $matches[4], - $replacement, - $this->tempDocumentMainPart - ); + $S_search = '${' . $blockname . '}'; + $E_search = '${/' . $blockname . '}'; + + $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); + $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); + if (!$S_tagPos || !$E_tagPos) { + if ($throwexception) { + throw new Exception("Can not find block '$blockname', template variable not found or variable contains markup."); + } else { + return false; + } } + + $S_blockStart = $this->findBlockStart($S_tagPos); + $S_blockEnd = $this->findBlockEnd($S_tagPos); + #$xmlStart = $this->getSlice($S_blockStart, $S_blockEnd); + + $E_blockStart = $this->findBlockStart($E_tagPos); + $E_blockEnd = $this->findBlockEnd($E_tagPos); + #$xmlEnd = $this->getSlice($E_blockStart, $E_blockEnd); + + $xmlBlock = $this->getSlice($S_blockEnd, $E_blockStart); + + $result = $this->getSlice(0, $S_blockStart); + $result .= $replacement; + $result .= $this->getSlice($E_blockEnd); + + $this->tempDocumentMainPart = $result; + + return true; } /** @@ -382,11 +428,11 @@ public function replaceBlock($blockname, $replacement) * * @param string $blockname * - * @return void + * @return true on block found and deleted, false on block not found. */ public function deleteBlock($blockname) { - $this->replaceBlock($blockname, ''); + return $this->replaceBlock($blockname, '', false); } /** @@ -557,7 +603,30 @@ protected function findRowStart($offset) } /** - * Find the end position of the nearest table row after $offset. + * Find the start position of the nearest paragraph () before $offset. + * + * @param integer $offset + * + * @return integer + * + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + protected function findBlockStart($offset) + { + $blockStart = strrpos($this->tempDocumentMainPart, 'tempDocumentMainPart) - $offset) * -1)); + + if (!$blockStart) { + $blockStart = strrpos($this->tempDocumentMainPart, '', ((strlen($this->tempDocumentMainPart) - $offset) * -1)); + } + if (!$blockStart) { + throw new Exception('Can not find the start position of the row to clone.'); + } + + return $blockStart; + } + + /** + * Find the end position of the nearest paragraph () after $offset. * * @param integer $offset * @@ -568,6 +637,18 @@ protected function findRowEnd($offset) return strpos($this->tempDocumentMainPart, '', $offset) + 7; } + /** + * Find the end position of the nearest table row after $offset. + * + * @param integer $offset + * + * @return integer + */ + protected function findBlockEnd($offset) + { + return strpos($this->tempDocumentMainPart, '', $offset) + 6; + } + /** * Get a slice of a string. * diff --git a/tests/PhpWord/OpenTemplateProcessor.php b/tests/PhpWord/OpenTemplateProcessor.php new file mode 100644 index 0000000000..0f3e9344a9 --- /dev/null +++ b/tests/PhpWord/OpenTemplateProcessor.php @@ -0,0 +1,40 @@ +$key; + } + + public function __set($key, $val) + { + return $this->$key = $val; + } +} diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 35eaa0f6cc..db43da82cc 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -17,6 +17,8 @@ namespace PhpOffice\PhpWord; +require_once 'OpenTemplateProcessor.php'; + /** * @covers \PhpOffice\PhpWord\TemplateProcessor * @coversDefaultClass \PhpOffice\PhpWord\TemplateProcessor @@ -223,7 +225,7 @@ public function testCloneDeleteBlock() $templateProcessor->deleteBlock('DELETEME'); $templateProcessor->saveAs($docName); $docFound = file_exists($docName); - if($docFound){ + if ($docFound) { # Great, so we saved the replaced document, so we open that new document # note that we need to access private variables, so we use a sub-class $templateProcessorNEWFILE = new OpenTemplateProcessor($docName); @@ -234,7 +236,8 @@ public function testCloneDeleteBlock() "All block variables should have been replaced" ); # we cloned block CLONEME $clone_times times, so let's count to $clone_times - $this->assertEquals($clone_times, + $this->assertEquals( + $clone_times, substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $xmlblock), "Block should be present $clone_times in the document" ); @@ -274,9 +277,9 @@ public function testCloneIndexedBlock() ); $ARR = [ - 'repeats#1' => 'ONE', - 'repeats#2' => 'TWO', - 'repeats#3' => 'THREE', + 'repeats#1' => 'ONE', + 'repeats#2' => 'TWO', + 'repeats#3' => 'THREE', 'repeats#4' => 'FOUR' ]; $templateProcessor->setValue(array_keys($ARR), array_values($ARR)); @@ -288,10 +291,11 @@ public function testCloneIndexedBlock() # now we test the order of replacement: ONE,TWO,THREE then FOUR $STR = ""; - foreach($ARR as $k => $v){ - $STR .= str_replace('${repeats}',$v, $XMLTXT); + foreach ($ARR as $k => $v) { + $STR .= str_replace('${repeats}', $v, $XMLTXT); } - $this->assertEquals(1, + $this->assertEquals( + 1, substr_count($templateProcessor->tempDocumentMainPart, $STR), "order of replacement should be: ONE,TWO,THREE then FOUR" ); @@ -308,35 +312,17 @@ public function testCloneIndexedBlock() ); # we cloned block CLONEME 4 times, so let's count - $this->assertEquals(4, + $this->assertEquals( + 4, substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT), 'detects new variable $repeats to be present 4 times' ); # we cloned block CLONEME 4 times, so let's see that there is no space between these blocks - $this->assertEquals(1, + $this->assertEquals( + 1, substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT.$XMLTXT.$XMLTXT.$XMLTXT), "The four times cloned block should be the same as four times the block" ); } - -} - -/** - * used by testCloneDeleteBlock and testCloneIndexedBlock to access private variables in a TemplateProcessor - * @test - */ -class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor -{ - public function __construct($instance) { - return parent::__construct($instance); - } - - public function __get($key) { - return $this->$key; - } - - public function __set($key, $val) { - return $this->$key = $val; - } } From bf840cb3e35c4e86a4e81f9b5a851365c993993b Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 26 Sep 2017 09:23:09 +0200 Subject: [PATCH 05/74] phpcs also discovered a test function without coverage header --- tests/PhpWord/TemplateProcessorTest.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index db43da82cc..9805bdb8a8 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -247,6 +247,13 @@ public function testCloneDeleteBlock() $this->assertTrue($docFound); } + /** + * @covers ::cloneBlock + * @covers ::getVariables + * @covers ::getBlock + * @covers ::setValue + * @test + */ public function testCloneIndexedBlock() { $templateProcessor = new OpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); From ff9415cee93132c2cb1834da1592e99ccea67ed2 Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 26 Sep 2017 12:04:43 +0200 Subject: [PATCH 06/74] phpcs wants shorter lines --- src/PhpWord/TemplateProcessor.php | 41 +++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index b43161a7b9..fad6147054 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -326,8 +326,13 @@ public function cloneRow($search, $numberOfClones) * * @return string|null */ - public function cloneBlock($blockname, $clones = 1, $replace = true, $incrementVariables = true, $throwexception = false) - { + public function cloneBlock( + $blockname, + $clones = 1, + $replace = true, + $incrementVariables = true, + $throwexception = false + ) { $S_search = '${' . $blockname . '}'; $E_search = '${/' . $blockname . '}'; @@ -335,7 +340,9 @@ public function cloneBlock($blockname, $clones = 1, $replace = true, $incrementV $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); if (!$S_tagPos || !$E_tagPos) { if ($throwexception) { - throw new Exception("Can not find block '$blockname', template variable not found or variable contains markup."); + throw new Exception( + "Can not find block '$blockname', template variable not found or variable contains markup." + ); } else { return null; # Block not found, return null } @@ -398,7 +405,9 @@ public function replaceBlock($blockname, $replacement, $throwexception = false) $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); if (!$S_tagPos || !$E_tagPos) { if ($throwexception) { - throw new Exception("Can not find block '$blockname', template variable not found or variable contains markup."); + throw new Exception( + "Can not find block '$blockname', template variable not found or variable contains markup." + ); } else { return false; } @@ -590,10 +599,18 @@ protected function getFooterName($index) */ protected function findRowStart($offset) { - $rowStart = strrpos($this->tempDocumentMainPart, 'tempDocumentMainPart) - $offset) * -1)); + $rowStart = strrpos( + $this->tempDocumentMainPart, + 'tempDocumentMainPart) - $offset) * -1) + ); if (!$rowStart) { - $rowStart = strrpos($this->tempDocumentMainPart, '', ((strlen($this->tempDocumentMainPart) - $offset) * -1)); + $rowStart = strrpos( + $this->tempDocumentMainPart, + '', + ((strlen($this->tempDocumentMainPart) - $offset) * -1) + ); } if (!$rowStart) { throw new Exception('Can not find the start position of the row to clone.'); @@ -613,10 +630,18 @@ protected function findRowStart($offset) */ protected function findBlockStart($offset) { - $blockStart = strrpos($this->tempDocumentMainPart, 'tempDocumentMainPart) - $offset) * -1)); + $blockStart = strrpos( + $this->tempDocumentMainPart, + 'tempDocumentMainPart) - $offset) * -1) + ); if (!$blockStart) { - $blockStart = strrpos($this->tempDocumentMainPart, '', ((strlen($this->tempDocumentMainPart) - $offset) * -1)); + $blockStart = strrpos( + $this->tempDocumentMainPart, + '', + ((strlen($this->tempDocumentMainPart) - $offset) * -1) + ); } if (!$blockStart) { throw new Exception('Can not find the start position of the row to clone.'); From 93ab05bea8075b2c5e3145f4ccfd0ad23e3674a5 Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 26 Sep 2017 12:07:21 +0200 Subject: [PATCH 07/74] phpcs did not like the helperclass, worked around it. At least phpcs and phpunit give a green flag --- tests/PhpWord/OpenTemplateProcessor.php | 40 ------------------------- 1 file changed, 40 deletions(-) delete mode 100644 tests/PhpWord/OpenTemplateProcessor.php diff --git a/tests/PhpWord/OpenTemplateProcessor.php b/tests/PhpWord/OpenTemplateProcessor.php deleted file mode 100644 index 0f3e9344a9..0000000000 --- a/tests/PhpWord/OpenTemplateProcessor.php +++ /dev/null @@ -1,40 +0,0 @@ -$key; - } - - public function __set($key, $val) - { - return $this->$key = $val; - } -} From baf594a46f21b098205d89cc0c9569fc5ef72744 Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 26 Sep 2017 12:57:46 +0200 Subject: [PATCH 08/74] Inline helperclass (phpcs workaround) --- tests/PhpWord/TemplateProcessorTest.php | 26 +++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 9805bdb8a8..2017eebcd5 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -17,8 +17,6 @@ namespace PhpOffice\PhpWord; -require_once 'OpenTemplateProcessor.php'; - /** * @covers \PhpOffice\PhpWord\TemplateProcessor * @coversDefaultClass \PhpOffice\PhpWord\TemplateProcessor @@ -202,6 +200,26 @@ public function testMacrosCanBeReplacedInHeaderAndFooter() $this->assertTrue($docFound); } + /** + * Convoluted way to get a helper class, without using include_once (not allowed by phpcs) + * or inline (not allowed by phpcs) or touching the autoload.php (and make it accessible to users) + * this helper class returns a TemplateProcessor that allows access to private variables + * like tempDocumentMainPart, see the functions that use it for usage. + * eval is evil, but phpcs and phpunit made me do it! + */ + private function getOpenTemplateProcessor($name) + { + if (!file_exists($name) || !is_readable($name)) { + return null; + } + $ESTR = + 'class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor {' + . 'public function __construct($instance){return parent::__construct($instance);}' + . 'public function __get($key){return $this->$key;}' + . 'public function __set($key, $val){return $this->$key = $val;} };' + . 'return new OpenTemplateProcessor("'.$name.'");'; + return eval($ESTR); + } /** * @covers ::cloneBlock * @covers ::deleteBlock @@ -228,7 +246,7 @@ public function testCloneDeleteBlock() if ($docFound) { # Great, so we saved the replaced document, so we open that new document # note that we need to access private variables, so we use a sub-class - $templateProcessorNEWFILE = new OpenTemplateProcessor($docName); + $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); # We test that all Block variables have been replaced (thus, getVariables() is empty) $this->assertEquals( [], @@ -256,7 +274,7 @@ public function testCloneDeleteBlock() */ public function testCloneIndexedBlock() { - $templateProcessor = new OpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); # we will fake a block with a variable inside it, as there is no template document yet. $XMLTXT = 'This ${repeats} a few times'; $XMLSTR = '${MYBLOCK}' . $XMLTXT . '${/MYBLOCK}'; From 5e60e231ab2e4eec01441c5586bb3bbac21869d1 Mon Sep 17 00:00:00 2001 From: FBnil Date: Tue, 26 Sep 2017 13:25:05 +0200 Subject: [PATCH 09/74] Update TemplateProcessorTest.php Updating all phpcs warnings given. Basically merge develop->FBnil-patch-blocks --- tests/PhpWord/TemplateProcessorTest.php | 75 ++++++++++++++----------- 1 file changed, 43 insertions(+), 32 deletions(-) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 35eaa0f6cc..2017eebcd5 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -200,6 +200,26 @@ public function testMacrosCanBeReplacedInHeaderAndFooter() $this->assertTrue($docFound); } + /** + * Convoluted way to get a helper class, without using include_once (not allowed by phpcs) + * or inline (not allowed by phpcs) or touching the autoload.php (and make it accessible to users) + * this helper class returns a TemplateProcessor that allows access to private variables + * like tempDocumentMainPart, see the functions that use it for usage. + * eval is evil, but phpcs and phpunit made me do it! + */ + private function getOpenTemplateProcessor($name) + { + if (!file_exists($name) || !is_readable($name)) { + return null; + } + $ESTR = + 'class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor {' + . 'public function __construct($instance){return parent::__construct($instance);}' + . 'public function __get($key){return $this->$key;}' + . 'public function __set($key, $val){return $this->$key = $val;} };' + . 'return new OpenTemplateProcessor("'.$name.'");'; + return eval($ESTR); + } /** * @covers ::cloneBlock * @covers ::deleteBlock @@ -223,10 +243,10 @@ public function testCloneDeleteBlock() $templateProcessor->deleteBlock('DELETEME'); $templateProcessor->saveAs($docName); $docFound = file_exists($docName); - if($docFound){ + if ($docFound) { # Great, so we saved the replaced document, so we open that new document # note that we need to access private variables, so we use a sub-class - $templateProcessorNEWFILE = new OpenTemplateProcessor($docName); + $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); # We test that all Block variables have been replaced (thus, getVariables() is empty) $this->assertEquals( [], @@ -234,7 +254,8 @@ public function testCloneDeleteBlock() "All block variables should have been replaced" ); # we cloned block CLONEME $clone_times times, so let's count to $clone_times - $this->assertEquals($clone_times, + $this->assertEquals( + $clone_times, substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $xmlblock), "Block should be present $clone_times in the document" ); @@ -244,9 +265,16 @@ public function testCloneDeleteBlock() $this->assertTrue($docFound); } + /** + * @covers ::cloneBlock + * @covers ::getVariables + * @covers ::getBlock + * @covers ::setValue + * @test + */ public function testCloneIndexedBlock() { - $templateProcessor = new OpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); # we will fake a block with a variable inside it, as there is no template document yet. $XMLTXT = 'This ${repeats} a few times'; $XMLSTR = '${MYBLOCK}' . $XMLTXT . '${/MYBLOCK}'; @@ -274,9 +302,9 @@ public function testCloneIndexedBlock() ); $ARR = [ - 'repeats#1' => 'ONE', - 'repeats#2' => 'TWO', - 'repeats#3' => 'THREE', + 'repeats#1' => 'ONE', + 'repeats#2' => 'TWO', + 'repeats#3' => 'THREE', 'repeats#4' => 'FOUR' ]; $templateProcessor->setValue(array_keys($ARR), array_values($ARR)); @@ -288,10 +316,11 @@ public function testCloneIndexedBlock() # now we test the order of replacement: ONE,TWO,THREE then FOUR $STR = ""; - foreach($ARR as $k => $v){ - $STR .= str_replace('${repeats}',$v, $XMLTXT); + foreach ($ARR as $k => $v) { + $STR .= str_replace('${repeats}', $v, $XMLTXT); } - $this->assertEquals(1, + $this->assertEquals( + 1, substr_count($templateProcessor->tempDocumentMainPart, $STR), "order of replacement should be: ONE,TWO,THREE then FOUR" ); @@ -308,35 +337,17 @@ public function testCloneIndexedBlock() ); # we cloned block CLONEME 4 times, so let's count - $this->assertEquals(4, + $this->assertEquals( + 4, substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT), 'detects new variable $repeats to be present 4 times' ); # we cloned block CLONEME 4 times, so let's see that there is no space between these blocks - $this->assertEquals(1, + $this->assertEquals( + 1, substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT.$XMLTXT.$XMLTXT.$XMLTXT), "The four times cloned block should be the same as four times the block" ); } - -} - -/** - * used by testCloneDeleteBlock and testCloneIndexedBlock to access private variables in a TemplateProcessor - * @test - */ -class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor -{ - public function __construct($instance) { - return parent::__construct($instance); - } - - public function __get($key) { - return $this->$key; - } - - public function __set($key, $val) { - return $this->$key = $val; - } } From 003ad96c1164a66c5abb7bab4bd3cfe3a4dcd0ee Mon Sep 17 00:00:00 2001 From: FBnil Date: Tue, 26 Sep 2017 13:28:23 +0200 Subject: [PATCH 10/74] Update TemplateProcessor.php Fixed all the warnings phpcs gave --- src/PhpWord/TemplateProcessor.php | 64 +++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 17 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 3749f96d41..5b014885cf 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -326,18 +326,26 @@ public function cloneRow($search, $numberOfClones) * * @return string|null */ - public function cloneBlock($blockname, $clones = 1, $replace = true, $incrementVariables = true, $throwexception = false) - { + public function cloneBlock( + $blockname, + $clones = 1, + $replace = true, + $incrementVariables = true, + $throwexception = false + ) { $S_search = '${' . $blockname . '}'; $E_search = '${/' . $blockname . '}'; $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); if (!$S_tagPos || !$E_tagPos) { - if($throwexception) - throw new Exception("Can not find block '$blockname', template variable not found or variable contains markup."); - else + if ($throwexception) { + throw new Exception( + "Can not find block '$blockname', template variable not found or variable contains markup." + ); + } else { return null; # Block not found, return null + } } $S_blockStart = $this->findBlockStart($S_tagPos); @@ -350,13 +358,14 @@ public function cloneBlock($blockname, $clones = 1, $replace = true, $incrementV $xmlBlock = $this->getSlice($S_blockEnd, $E_blockStart); - if($replace){ + if ($replace) { $result = $this->getSlice(0, $S_blockStart); for ($i = 1; $i <= $clones; $i++) { - if($incrementVariables) + if ($incrementVariables) { $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlBlock); - else + } else { $result .= $xmlBlock; + } } $result .= $this->getSlice($E_blockEnd); @@ -374,7 +383,8 @@ public function cloneBlock($blockname, $clones = 1, $replace = true, $incrementV * * @return string|null */ - public function getBlock($blockname, $throwexception = false){ + public function getBlock($blockname, $throwexception = false) + { return $this->cloneBlock($blockname, 1, false, $throwexception); } /** @@ -394,9 +404,13 @@ public function replaceBlock($blockname, $replacement, $throwexception = false) $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); if (!$S_tagPos || !$E_tagPos) { - if($throwexception) - throw new Exception("Can not find block '$blockname', template variable not found or variable contains markup."); - else return false; + if ($throwexception) { + throw new Exception( + "Can not find block '$blockname', template variable not found or variable contains markup." + ); + } else { + return false; + } } $S_blockStart = $this->findBlockStart($S_tagPos); @@ -585,10 +599,18 @@ protected function getFooterName($index) */ protected function findRowStart($offset) { - $rowStart = strrpos($this->tempDocumentMainPart, 'tempDocumentMainPart) - $offset) * -1)); + $rowStart = strrpos( + $this->tempDocumentMainPart, + 'tempDocumentMainPart) - $offset) * -1) + ); if (!$rowStart) { - $rowStart = strrpos($this->tempDocumentMainPart, '', ((strlen($this->tempDocumentMainPart) - $offset) * -1)); + $rowStart = strrpos( + $this->tempDocumentMainPart, + '', + ((strlen($this->tempDocumentMainPart) - $offset) * -1) + ); } if (!$rowStart) { throw new Exception('Can not find the start position of the row to clone.'); @@ -605,13 +627,21 @@ protected function findRowStart($offset) * @return integer * * @throws \PhpOffice\PhpWord\Exception\Exception - */ + */ protected function findBlockStart($offset) { - $blockStart = strrpos($this->tempDocumentMainPart, 'tempDocumentMainPart) - $offset) * -1)); + $blockStart = strrpos( + $this->tempDocumentMainPart, + 'tempDocumentMainPart) - $offset) * -1) + ); if (!$blockStart) { - $blockStart = strrpos($this->tempDocumentMainPart, '', ((strlen($this->tempDocumentMainPart) - $offset) * -1)); + $blockStart = strrpos( + $this->tempDocumentMainPart, + '', + ((strlen($this->tempDocumentMainPart) - $offset) * -1) + ); } if (!$blockStart) { throw new Exception('Can not find the start position of the row to clone.'); From c39c9b40fdd0bd188be338c302f84da7cc63de95 Mon Sep 17 00:00:00 2001 From: FBnil Date: Tue, 26 Sep 2017 14:25:27 +0200 Subject: [PATCH 11/74] Update TemplateProcessor.php renamed variables to fix scrutinizer errors --- src/PhpWord/TemplateProcessor.php | 52 ++++++++++++++----------------- 1 file changed, 24 insertions(+), 28 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 5b014885cf..8f3d5a45e9 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -333,33 +333,33 @@ public function cloneBlock( $incrementVariables = true, $throwexception = false ) { - $S_search = '${' . $blockname . '}'; - $E_search = '${/' . $blockname . '}'; + $startSearch = '${' . $blockname . '}'; + $endSearch = '${/' . $blockname . '}'; - $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); - $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); - if (!$S_tagPos || !$E_tagPos) { + $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); + $EndTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); + if (!$startTagPos || !$EndTagPos) { if ($throwexception) { throw new Exception( "Can not find block '$blockname', template variable not found or variable contains markup." ); } else { - return null; # Block not found, return null + return null; // Block not found, return null } } - $S_blockStart = $this->findBlockStart($S_tagPos); - $S_blockEnd = $this->findBlockEnd($S_tagPos); - #$xmlStart = $this->getSlice($S_blockStart, $S_blockEnd); + $startBlockStart = $this->findBlockStart($startTagPos); + $startBlockEnd = $this->findBlockEnd($startTagPos); + // $xmlStart = $this->getSlice($startBlockStart, $startBlockEnd); - $E_blockStart = $this->findBlockStart($E_tagPos); - $E_blockEnd = $this->findBlockEnd($E_tagPos); - #$xmlEnd = $this->getSlice($E_blockStart, $E_blockEnd); + $endBlockStart = $this->findBlockStart($EndTagPos); + $endBlockEnd = $this->findBlockEnd($EndTagPos); + // $xmlEnd = $this->getSlice($endBlockStart, $E_blockEnd); - $xmlBlock = $this->getSlice($S_blockEnd, $E_blockStart); + $xmlBlock = $this->getSlice($startBlockEnd, $endBlockStart); if ($replace) { - $result = $this->getSlice(0, $S_blockStart); + $result = $this->getSlice(0, $startBlockStart); for ($i = 1; $i <= $clones; $i++) { if ($incrementVariables) { $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlBlock); @@ -398,12 +398,12 @@ public function getBlock($blockname, $throwexception = false) */ public function replaceBlock($blockname, $replacement, $throwexception = false) { - $S_search = '${' . $blockname . '}'; - $E_search = '${/' . $blockname . '}'; + $startSearch = '${' . $blockname . '}'; + $endSearch = '${/' . $blockname . '}'; - $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); - $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); - if (!$S_tagPos || !$E_tagPos) { + $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); + $EndTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); + if (!$startTagPos || !$EndTagPos) { if ($throwexception) { throw new Exception( "Can not find block '$blockname', template variable not found or variable contains markup." @@ -413,17 +413,13 @@ public function replaceBlock($blockname, $replacement, $throwexception = false) } } - $S_blockStart = $this->findBlockStart($S_tagPos); - $S_blockEnd = $this->findBlockEnd($S_tagPos); - #$xmlStart = $this->getSlice($S_blockStart, $S_blockEnd); + $startBlockStart = $this->findBlockStart($startTagPos); + $startBlockEnd = $this->findBlockEnd($startTagPos); - $E_blockStart = $this->findBlockStart($E_tagPos); - $E_blockEnd = $this->findBlockEnd($E_tagPos); - #$xmlEnd = $this->getSlice($E_blockStart, $E_blockEnd); + $endBlockStart = $this->findBlockStart($EndTagPos); + $E_blockEnd = $this->findBlockEnd($EndTagPos); - $xmlBlock = $this->getSlice($S_blockEnd, $E_blockStart); - - $result = $this->getSlice(0, $S_blockStart); + $result = $this->getSlice(0, $startBlockStart); $result .= $replacement; $result .= $this->getSlice($E_blockEnd); From 0df4d6df3710e6395eb0e28878a5a8e8f8476e3e Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 26 Sep 2017 17:44:56 +0200 Subject: [PATCH 12/74] refactoring --- src/PhpWord/TemplateProcessor.php | 277 ++++++++++++++++-------- tests/PhpWord/TemplateProcessorTest.php | 130 ++++++++--- 2 files changed, 285 insertions(+), 122 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 3749f96d41..be04e37611 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -262,22 +262,33 @@ public function getVariables() * @param string $search * @param integer $numberOfClones * - * @return void + * @return string|null * * @throws \PhpOffice\PhpWord\Exception\Exception */ - public function cloneRow($search, $numberOfClones) - { + public function cloneRow( + $search, + $numberOfClones = 1, + $replace = true, + $incrementVariables = true, + $throwexception = false + ) { if ('${' !== substr($search, 0, 2) && '}' !== substr($search, -1)) { $search = '${' . $search . '}'; } $tagPos = strpos($this->tempDocumentMainPart, $search); if (!$tagPos) { - throw new Exception("Can not clone row, template variable not found or variable contains markup."); + if ($throwexception) { + throw new Exception( + "Can not clone row, template variable not found or variable contains markup." + ); + } else { + return null; + } } - $rowStart = $this->findRowStart($tagPos); + $rowStart = $this->findRowStart($tagPos, $throwexception); $rowEnd = $this->findRowEnd($tagPos); $xmlRow = $this->getSlice($rowStart, $rowEnd); @@ -286,7 +297,7 @@ public function cloneRow($search, $numberOfClones) // $extraRowStart = $rowEnd; $extraRowEnd = $rowEnd; while (true) { - $extraRowStart = $this->findRowStart($extraRowEnd + 1); + $extraRowStart = $this->findRowStart($extraRowEnd + 1, $throwexception); $extraRowEnd = $this->findRowEnd($extraRowEnd + 1); // If extraRowEnd is lower then 7, there was no next row found. @@ -306,13 +317,21 @@ public function cloneRow($search, $numberOfClones) $xmlRow = $this->getSlice($rowStart, $rowEnd); } - $result = $this->getSlice(0, $rowStart); - for ($i = 1; $i <= $numberOfClones; $i++) { - $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow); + if ($replace) { + $result = $this->getSlice(0, $rowStart); + for ($i = 1; $i <= $numberOfClones; $i++) { + if ($incrementVariables) { + $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow); + } else { + $result .= $xmlRow; + } + } + $result .= $this->getSlice($rowEnd); + + $this->tempDocumentMainPart = $result; } - $result .= $this->getSlice($rowEnd); - $this->tempDocumentMainPart = $result; + return $xmlRow; } /** @@ -326,39 +345,58 @@ public function cloneRow($search, $numberOfClones) * * @return string|null */ - public function cloneBlock($blockname, $clones = 1, $replace = true, $incrementVariables = true, $throwexception = false) - { - $S_search = '${' . $blockname . '}'; - $E_search = '${/' . $blockname . '}'; - - $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); - $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); - if (!$S_tagPos || !$E_tagPos) { - if($throwexception) - throw new Exception("Can not find block '$blockname', template variable not found or variable contains markup."); - else - return null; # Block not found, return null - } - - $S_blockStart = $this->findBlockStart($S_tagPos); - $S_blockEnd = $this->findBlockEnd($S_tagPos); - #$xmlStart = $this->getSlice($S_blockStart, $S_blockEnd); - - $E_blockStart = $this->findBlockStart($E_tagPos); - $E_blockEnd = $this->findBlockEnd($E_tagPos); - #$xmlEnd = $this->getSlice($E_blockStart, $E_blockEnd); - - $xmlBlock = $this->getSlice($S_blockEnd, $E_blockStart); - - if($replace){ - $result = $this->getSlice(0, $S_blockStart); + public function cloneBlock( + $blockname, + $clones = 1, + $replace = true, + $incrementVariables = true, + $throwexception = false + ) { + $startSearch = '${' . $blockname . '}'; + $endSearch = '${/' . $blockname . '}'; + + $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); + $endTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); + if (!$startTagPos || !$endTagPos) { + if ($throwexception) { + throw new Exception( + "Can not find block '$blockname', template variable not found or variable contains markup." + ); + } else { + return null; // Block not found, return null + } + } + + $startBlockStart = $this->findBlockStart($startTagPos, $throwexception); + $startBlockEnd = $this->findBlockEnd($startTagPos); + // $xmlStart = $this->getSlice($startBlockStart, $startBlockEnd); + + $endBlockStart = $this->findBlockStart($endTagPos, $throwexception); + $endBlockEnd = $this->findBlockEnd($endTagPos); + // $xmlEnd = $this->getSlice($endBlockStart, $endBlockEnd); + + if (!$startBlockStart || !$startBlockEnd || !$endBlockStart || !$endBlockEnd) { + if ($throwexception) { + throw new Exception( + "Can not find paragraph around block '$blockname'" + ); + } else { + return false; + } + } + + $xmlBlock = $this->getSlice($startBlockEnd, $endBlockStart); + + if ($replace) { + $result = $this->getSlice(0, $startBlockStart); for ($i = 1; $i <= $clones; $i++) { - if($incrementVariables) + if ($incrementVariables) { $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlBlock); - else + } else { $result .= $xmlBlock; + } } - $result .= $this->getSlice($E_blockEnd); + $result .= $this->getSlice($endBlockEnd); $this->tempDocumentMainPart = $result; } @@ -374,9 +412,24 @@ public function cloneBlock($blockname, $clones = 1, $replace = true, $incrementV * * @return string|null */ - public function getBlock($blockname, $throwexception = false){ - return $this->cloneBlock($blockname, 1, false, $throwexception); + public function getBlock($blockname, $throwexception = false) + { + return $this->cloneBlock($blockname, 1, false, false, $throwexception); + } + + /** + * Get a row. (first block found) + * + * @param string $rowname + * @param boolean $throwexception + * + * @return string|null + */ + public function getRow($rowname, $throwexception = false) + { + return $this->cloneRow($rowname, 1, false, false, $throwexception); } + /** * Replace a block. * @@ -388,33 +441,44 @@ public function getBlock($blockname, $throwexception = false){ */ public function replaceBlock($blockname, $replacement, $throwexception = false) { - $S_search = '${' . $blockname . '}'; - $E_search = '${/' . $blockname . '}'; - - $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); - $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); - if (!$S_tagPos || !$E_tagPos) { - if($throwexception) - throw new Exception("Can not find block '$blockname', template variable not found or variable contains markup."); - else return false; - } - - $S_blockStart = $this->findBlockStart($S_tagPos); - $S_blockEnd = $this->findBlockEnd($S_tagPos); - #$xmlStart = $this->getSlice($S_blockStart, $S_blockEnd); - - $E_blockStart = $this->findBlockStart($E_tagPos); - $E_blockEnd = $this->findBlockEnd($E_tagPos); - #$xmlEnd = $this->getSlice($E_blockStart, $E_blockEnd); - - $xmlBlock = $this->getSlice($S_blockEnd, $E_blockStart); - - $result = $this->getSlice(0, $S_blockStart); + $startSearch = '${' . $blockname . '}'; + $endSearch = '${/' . $blockname . '}'; + + $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); + $endTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); + + if (!$startTagPos || !$endTagPos) { + if ($throwexception) { + throw new Exception( + "Can not find block '$blockname', template variable not found or variable contains markup." + ); + } else { + return false; + } + } + + $startBlockStart = $this->findBlockStart($startTagPos, $throwexception); + $startBlockEnd = $this->findBlockEnd($startTagPos); + + $endBlockStart = $this->findBlockStart($endTagPos, $throwexception); + $endBlockEnd = $this->findBlockEnd($endTagPos); + + if (!$startBlockStart || !$startBlockEnd || !$endBlockStart || !$endBlockEnd) { + if ($throwexception) { + throw new Exception( + "Can not find paragraph around block '$blockname'" + ); + } else { + return false; + } + } + + $result = $this->getSlice(0, $startBlockStart); $result .= $replacement; - $result .= $this->getSlice($E_blockEnd); + $result .= $this->getSlice($endBlockEnd); $this->tempDocumentMainPart = $result; - + return true; } @@ -575,53 +639,86 @@ protected function getFooterName($index) } /** - * Find the start position of the nearest table row before $offset. + * Find the start position of the nearest tag before $offset. * + * @param string $tag * @param integer $offset + * @@param boolean $throwexception * * @return integer * * @throws \PhpOffice\PhpWord\Exception\Exception */ - protected function findRowStart($offset) + protected function findTagLeft($tag, $offset = 0, $throwexception = false) { - $rowStart = strrpos($this->tempDocumentMainPart, 'tempDocumentMainPart) - $offset) * -1)); + $tagStart = strrpos( + $this->tempDocumentMainPart, + substr($tag, 0, -1) . ' ', + ((strlen($this->tempDocumentMainPart) - $offset) * -1) + ); - if (!$rowStart) { - $rowStart = strrpos($this->tempDocumentMainPart, '', ((strlen($this->tempDocumentMainPart) - $offset) * -1)); + if (!$tagStart) { + $tagStart = strrpos( + $this->tempDocumentMainPart, + $tag, + ((strlen($this->tempDocumentMainPart) - $offset) * -1) + ); } - if (!$rowStart) { - throw new Exception('Can not find the start position of the row to clone.'); + if (!$tagStart) { + if ($throwexception) { + throw new Exception('Can not find the start position of the row to clone.'); + } else { + return 0; + } } - return $rowStart; + return $tagStart; } /** - * Find the start position of the nearest paragraph () before $offset. + * Find the start position of the nearest table row before $offset. * * @param integer $offset + * @param boolean $throwexception * * @return integer * * @throws \PhpOffice\PhpWord\Exception\Exception - */ - protected function findBlockStart($offset) + */ + protected function findRowStart($offset, $throwexception) { - $blockStart = strrpos($this->tempDocumentMainPart, 'tempDocumentMainPart) - $offset) * -1)); + return $this->findTagLeft('', $offset, $throwexception); + } - if (!$blockStart) { - $blockStart = strrpos($this->tempDocumentMainPart, '', ((strlen($this->tempDocumentMainPart) - $offset) * -1)); - } - if (!$blockStart) { - throw new Exception('Can not find the start position of the row to clone.'); - } + /** + * Find the start position of the nearest paragraph before $offset. + * + * @param integer $offset + * @param boolean $throwexception + * + * @return integer + * + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + protected function findBlockStart($offset, $throwexception) + { + return $this->findTagLeft('', $offset, $throwexception); + } - return $blockStart; + /** + * Find the end position of the nearest tag after $offset. + * + * @param integer $offset + * + * @return integer + */ + protected function findTagRight($tag, $offset = 0) + { + return strpos($this->tempDocumentMainPart, $tag, $offset) + strlen($tag); } - + /** - * Find the end position of the nearest paragraph () after $offset. + * Find the end position of the nearest table row after $offset. * * @param integer $offset * @@ -629,11 +726,11 @@ protected function findBlockStart($offset) */ protected function findRowEnd($offset) { - return strpos($this->tempDocumentMainPart, '', $offset) + 7; + return $this->findTagRight('', $offset); } /** - * Find the end position of the nearest table row after $offset. + * Find the end position of the nearest paragraph after $offset. * * @param integer $offset * @@ -641,7 +738,7 @@ protected function findRowEnd($offset) */ protected function findBlockEnd($offset) { - return strpos($this->tempDocumentMainPart, '', $offset) + 6; + return $this->findTagRight('', $offset); } /** diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 35eaa0f6cc..f66e993ddd 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -157,6 +157,10 @@ final public function testXslStyleSheetCanNotBeAppliedOnFailureOfLoadingXmlFromT * @covers ::setValue * @covers ::cloneRow * @covers ::saveAs + * @covers ::findTagLeft + * @covers ::findTagRight + * @covers ::findBlockEnd + * @covers ::findBlockStart * @test */ public function testCloneRow() @@ -178,6 +182,53 @@ public function testCloneRow() $this->assertTrue($docFound); } + /** + * @covers ::getRow + * @covers ::saveAs + * @covers ::findRowStart + * @covers ::findRowEnd + * @covers ::findTagLeft + * @covers ::findTagRight + * @test + */ + public function testGetRow() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $initialArray = array('tableHeader', 'userId', 'userName', 'userLocation'); + $finalArray = array( + 'tableHeader', + 'userId#1', 'userName#1', 'userLocation#1', + 'userId#2', 'userName#2', 'userLocation#2' + ); + $row = $templateProcessor->getRow('userId'); + $this->assertNotEmpty($row); + $this->assertEquals( + $initialArray, + $templateProcessor->getVariables() + ); + $row = $templateProcessor->cloneRow('userId', 2); + $this->assertStringStartsWith('assertStringEndsWith('', $row); + $this->assertNotEmpty($row); + $this->assertEquals( + $finalArray, + $templateProcessor->getVariables() + ); + + $docName = 'test-getRow-result.docx'; + $templateProcessor->saveAs($docName); + $docFound = file_exists($docName); + $this->assertTrue($docFound); + if ($docFound) { + $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); + $this->assertEquals( + $finalArray, + $templateProcessorNEWFILE->getVariables() + ); + unlink($docName); + } + } + /** * @covers ::setValue * @covers ::saveAs @@ -200,11 +251,35 @@ public function testMacrosCanBeReplacedInHeaderAndFooter() $this->assertTrue($docFound); } + /** + * Convoluted way to get a helper class, without using include_once (not allowed by phpcs) + * or inline (not allowed by phpcs) or touching the autoload.php (and make it accessible to users) + * this helper class returns a TemplateProcessor that allows access to private variables + * like tempDocumentMainPart, see the functions that use it for usage. + * eval is evil, but phpcs and phpunit made me do it! + */ + private function getOpenTemplateProcessor($name) + { + if (!file_exists($name) || !is_readable($name)) { + return null; + } + $ESTR = + 'class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor {' + . 'public function __construct($instance){return parent::__construct($instance);}' + . 'public function __get($key){return $this->$key;}' + . 'public function __set($key, $val){return $this->$key = $val;} };' + . 'return new OpenTemplateProcessor("'.$name.'");'; + return eval($ESTR); + } /** * @covers ::cloneBlock * @covers ::deleteBlock * @covers ::getBlock * @covers ::saveAs + * @covers ::findBlockEnd + * @covers ::findBlockStart + * @covers ::findTagLeft + * @covers ::findTagRight * @test */ public function testCloneDeleteBlock() @@ -223,10 +298,10 @@ public function testCloneDeleteBlock() $templateProcessor->deleteBlock('DELETEME'); $templateProcessor->saveAs($docName); $docFound = file_exists($docName); - if($docFound){ + if ($docFound) { # Great, so we saved the replaced document, so we open that new document # note that we need to access private variables, so we use a sub-class - $templateProcessorNEWFILE = new OpenTemplateProcessor($docName); + $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); # We test that all Block variables have been replaced (thus, getVariables() is empty) $this->assertEquals( [], @@ -234,7 +309,8 @@ public function testCloneDeleteBlock() "All block variables should have been replaced" ); # we cloned block CLONEME $clone_times times, so let's count to $clone_times - $this->assertEquals($clone_times, + $this->assertEquals( + $clone_times, substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $xmlblock), "Block should be present $clone_times in the document" ); @@ -244,9 +320,16 @@ public function testCloneDeleteBlock() $this->assertTrue($docFound); } + /** + * @covers ::cloneBlock + * @covers ::getVariables + * @covers ::getBlock + * @covers ::setValue + * @test + */ public function testCloneIndexedBlock() { - $templateProcessor = new OpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); # we will fake a block with a variable inside it, as there is no template document yet. $XMLTXT = 'This ${repeats} a few times'; $XMLSTR = '${MYBLOCK}' . $XMLTXT . '${/MYBLOCK}'; @@ -274,9 +357,9 @@ public function testCloneIndexedBlock() ); $ARR = [ - 'repeats#1' => 'ONE', - 'repeats#2' => 'TWO', - 'repeats#3' => 'THREE', + 'repeats#1' => 'ONE', + 'repeats#2' => 'TWO', + 'repeats#3' => 'THREE', 'repeats#4' => 'FOUR' ]; $templateProcessor->setValue(array_keys($ARR), array_values($ARR)); @@ -288,10 +371,11 @@ public function testCloneIndexedBlock() # now we test the order of replacement: ONE,TWO,THREE then FOUR $STR = ""; - foreach($ARR as $k => $v){ - $STR .= str_replace('${repeats}',$v, $XMLTXT); + foreach ($ARR as $k => $v) { + $STR .= str_replace('${repeats}', $v, $XMLTXT); } - $this->assertEquals(1, + $this->assertEquals( + 1, substr_count($templateProcessor->tempDocumentMainPart, $STR), "order of replacement should be: ONE,TWO,THREE then FOUR" ); @@ -308,35 +392,17 @@ public function testCloneIndexedBlock() ); # we cloned block CLONEME 4 times, so let's count - $this->assertEquals(4, + $this->assertEquals( + 4, substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT), 'detects new variable $repeats to be present 4 times' ); # we cloned block CLONEME 4 times, so let's see that there is no space between these blocks - $this->assertEquals(1, + $this->assertEquals( + 1, substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT.$XMLTXT.$XMLTXT.$XMLTXT), "The four times cloned block should be the same as four times the block" ); } - -} - -/** - * used by testCloneDeleteBlock and testCloneIndexedBlock to access private variables in a TemplateProcessor - * @test - */ -class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor -{ - public function __construct($instance) { - return parent::__construct($instance); - } - - public function __get($key) { - return $this->$key; - } - - public function __set($key, $val) { - return $this->$key = $val; - } } From ba7fcb9826672475327faffd8928ca411d88627b Mon Sep 17 00:00:00 2001 From: FBnil Date: Tue, 26 Sep 2017 18:07:17 +0200 Subject: [PATCH 13/74] Update TemplateProcessor.php updating through Webbrowser as git pull and git status state that I already committed the latest... silly... --- src/PhpWord/TemplateProcessor.php | 193 ++++++++++++++++++++---------- 1 file changed, 132 insertions(+), 61 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 8f3d5a45e9..be04e37611 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -262,22 +262,33 @@ public function getVariables() * @param string $search * @param integer $numberOfClones * - * @return void + * @return string|null * * @throws \PhpOffice\PhpWord\Exception\Exception */ - public function cloneRow($search, $numberOfClones) - { + public function cloneRow( + $search, + $numberOfClones = 1, + $replace = true, + $incrementVariables = true, + $throwexception = false + ) { if ('${' !== substr($search, 0, 2) && '}' !== substr($search, -1)) { $search = '${' . $search . '}'; } $tagPos = strpos($this->tempDocumentMainPart, $search); if (!$tagPos) { - throw new Exception("Can not clone row, template variable not found or variable contains markup."); + if ($throwexception) { + throw new Exception( + "Can not clone row, template variable not found or variable contains markup." + ); + } else { + return null; + } } - $rowStart = $this->findRowStart($tagPos); + $rowStart = $this->findRowStart($tagPos, $throwexception); $rowEnd = $this->findRowEnd($tagPos); $xmlRow = $this->getSlice($rowStart, $rowEnd); @@ -286,7 +297,7 @@ public function cloneRow($search, $numberOfClones) // $extraRowStart = $rowEnd; $extraRowEnd = $rowEnd; while (true) { - $extraRowStart = $this->findRowStart($extraRowEnd + 1); + $extraRowStart = $this->findRowStart($extraRowEnd + 1, $throwexception); $extraRowEnd = $this->findRowEnd($extraRowEnd + 1); // If extraRowEnd is lower then 7, there was no next row found. @@ -306,13 +317,21 @@ public function cloneRow($search, $numberOfClones) $xmlRow = $this->getSlice($rowStart, $rowEnd); } - $result = $this->getSlice(0, $rowStart); - for ($i = 1; $i <= $numberOfClones; $i++) { - $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow); + if ($replace) { + $result = $this->getSlice(0, $rowStart); + for ($i = 1; $i <= $numberOfClones; $i++) { + if ($incrementVariables) { + $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow); + } else { + $result .= $xmlRow; + } + } + $result .= $this->getSlice($rowEnd); + + $this->tempDocumentMainPart = $result; } - $result .= $this->getSlice($rowEnd); - $this->tempDocumentMainPart = $result; + return $xmlRow; } /** @@ -337,8 +356,8 @@ public function cloneBlock( $endSearch = '${/' . $blockname . '}'; $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); - $EndTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); - if (!$startTagPos || !$EndTagPos) { + $endTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); + if (!$startTagPos || !$endTagPos) { if ($throwexception) { throw new Exception( "Can not find block '$blockname', template variable not found or variable contains markup." @@ -348,14 +367,24 @@ public function cloneBlock( } } - $startBlockStart = $this->findBlockStart($startTagPos); + $startBlockStart = $this->findBlockStart($startTagPos, $throwexception); $startBlockEnd = $this->findBlockEnd($startTagPos); // $xmlStart = $this->getSlice($startBlockStart, $startBlockEnd); - $endBlockStart = $this->findBlockStart($EndTagPos); - $endBlockEnd = $this->findBlockEnd($EndTagPos); - // $xmlEnd = $this->getSlice($endBlockStart, $E_blockEnd); - + $endBlockStart = $this->findBlockStart($endTagPos, $throwexception); + $endBlockEnd = $this->findBlockEnd($endTagPos); + // $xmlEnd = $this->getSlice($endBlockStart, $endBlockEnd); + + if (!$startBlockStart || !$startBlockEnd || !$endBlockStart || !$endBlockEnd) { + if ($throwexception) { + throw new Exception( + "Can not find paragraph around block '$blockname'" + ); + } else { + return false; + } + } + $xmlBlock = $this->getSlice($startBlockEnd, $endBlockStart); if ($replace) { @@ -367,7 +396,7 @@ public function cloneBlock( $result .= $xmlBlock; } } - $result .= $this->getSlice($E_blockEnd); + $result .= $this->getSlice($endBlockEnd); $this->tempDocumentMainPart = $result; } @@ -385,8 +414,22 @@ public function cloneBlock( */ public function getBlock($blockname, $throwexception = false) { - return $this->cloneBlock($blockname, 1, false, $throwexception); + return $this->cloneBlock($blockname, 1, false, false, $throwexception); } + + /** + * Get a row. (first block found) + * + * @param string $rowname + * @param boolean $throwexception + * + * @return string|null + */ + public function getRow($rowname, $throwexception = false) + { + return $this->cloneRow($rowname, 1, false, false, $throwexception); + } + /** * Replace a block. * @@ -402,8 +445,9 @@ public function replaceBlock($blockname, $replacement, $throwexception = false) $endSearch = '${/' . $blockname . '}'; $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); - $EndTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); - if (!$startTagPos || !$EndTagPos) { + $endTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); + + if (!$startTagPos || !$endTagPos) { if ($throwexception) { throw new Exception( "Can not find block '$blockname', template variable not found or variable contains markup." @@ -413,18 +457,28 @@ public function replaceBlock($blockname, $replacement, $throwexception = false) } } - $startBlockStart = $this->findBlockStart($startTagPos); + $startBlockStart = $this->findBlockStart($startTagPos, $throwexception); $startBlockEnd = $this->findBlockEnd($startTagPos); - $endBlockStart = $this->findBlockStart($EndTagPos); - $E_blockEnd = $this->findBlockEnd($EndTagPos); - + $endBlockStart = $this->findBlockStart($endTagPos, $throwexception); + $endBlockEnd = $this->findBlockEnd($endTagPos); + + if (!$startBlockStart || !$startBlockEnd || !$endBlockStart || !$endBlockEnd) { + if ($throwexception) { + throw new Exception( + "Can not find paragraph around block '$blockname'" + ); + } else { + return false; + } + } + $result = $this->getSlice(0, $startBlockStart); $result .= $replacement; - $result .= $this->getSlice($E_blockEnd); + $result .= $this->getSlice($endBlockEnd); $this->tempDocumentMainPart = $result; - + return true; } @@ -585,69 +639,86 @@ protected function getFooterName($index) } /** - * Find the start position of the nearest table row before $offset. + * Find the start position of the nearest tag before $offset. * + * @param string $tag * @param integer $offset + * @@param boolean $throwexception * * @return integer * * @throws \PhpOffice\PhpWord\Exception\Exception */ - protected function findRowStart($offset) + protected function findTagLeft($tag, $offset = 0, $throwexception = false) { - $rowStart = strrpos( + $tagStart = strrpos( $this->tempDocumentMainPart, - 'tempDocumentMainPart) - $offset) * -1) ); - if (!$rowStart) { - $rowStart = strrpos( + if (!$tagStart) { + $tagStart = strrpos( $this->tempDocumentMainPart, - '', + $tag, ((strlen($this->tempDocumentMainPart) - $offset) * -1) ); } - if (!$rowStart) { - throw new Exception('Can not find the start position of the row to clone.'); + if (!$tagStart) { + if ($throwexception) { + throw new Exception('Can not find the start position of the row to clone.'); + } else { + return 0; + } } - return $rowStart; + return $tagStart; } /** - * Find the start position of the nearest paragraph () before $offset. + * Find the start position of the nearest table row before $offset. * * @param integer $offset + * @param boolean $throwexception * * @return integer * * @throws \PhpOffice\PhpWord\Exception\Exception */ - protected function findBlockStart($offset) + protected function findRowStart($offset, $throwexception) { - $blockStart = strrpos( - $this->tempDocumentMainPart, - 'tempDocumentMainPart) - $offset) * -1) - ); + return $this->findTagLeft('', $offset, $throwexception); + } - if (!$blockStart) { - $blockStart = strrpos( - $this->tempDocumentMainPart, - '', - ((strlen($this->tempDocumentMainPart) - $offset) * -1) - ); - } - if (!$blockStart) { - throw new Exception('Can not find the start position of the row to clone.'); - } + /** + * Find the start position of the nearest paragraph before $offset. + * + * @param integer $offset + * @param boolean $throwexception + * + * @return integer + * + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + protected function findBlockStart($offset, $throwexception) + { + return $this->findTagLeft('', $offset, $throwexception); + } - return $blockStart; + /** + * Find the end position of the nearest tag after $offset. + * + * @param integer $offset + * + * @return integer + */ + protected function findTagRight($tag, $offset = 0) + { + return strpos($this->tempDocumentMainPart, $tag, $offset) + strlen($tag); } - + /** - * Find the end position of the nearest paragraph () after $offset. + * Find the end position of the nearest table row after $offset. * * @param integer $offset * @@ -655,11 +726,11 @@ protected function findBlockStart($offset) */ protected function findRowEnd($offset) { - return strpos($this->tempDocumentMainPart, '', $offset) + 7; + return $this->findTagRight('', $offset); } /** - * Find the end position of the nearest table row after $offset. + * Find the end position of the nearest paragraph after $offset. * * @param integer $offset * @@ -667,7 +738,7 @@ protected function findRowEnd($offset) */ protected function findBlockEnd($offset) { - return strpos($this->tempDocumentMainPart, '', $offset) + 6; + return $this->findTagRight('', $offset); } /** From 3d50682eef922bc08ccaa785b560b7107b821b32 Mon Sep 17 00:00:00 2001 From: FBnil Date: Tue, 26 Sep 2017 18:09:23 +0200 Subject: [PATCH 14/74] new test case for getRow() --- tests/PhpWord/TemplateProcessorTest.php | 55 +++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 2017eebcd5..f66e993ddd 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -157,6 +157,10 @@ final public function testXslStyleSheetCanNotBeAppliedOnFailureOfLoadingXmlFromT * @covers ::setValue * @covers ::cloneRow * @covers ::saveAs + * @covers ::findTagLeft + * @covers ::findTagRight + * @covers ::findBlockEnd + * @covers ::findBlockStart * @test */ public function testCloneRow() @@ -178,6 +182,53 @@ public function testCloneRow() $this->assertTrue($docFound); } + /** + * @covers ::getRow + * @covers ::saveAs + * @covers ::findRowStart + * @covers ::findRowEnd + * @covers ::findTagLeft + * @covers ::findTagRight + * @test + */ + public function testGetRow() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $initialArray = array('tableHeader', 'userId', 'userName', 'userLocation'); + $finalArray = array( + 'tableHeader', + 'userId#1', 'userName#1', 'userLocation#1', + 'userId#2', 'userName#2', 'userLocation#2' + ); + $row = $templateProcessor->getRow('userId'); + $this->assertNotEmpty($row); + $this->assertEquals( + $initialArray, + $templateProcessor->getVariables() + ); + $row = $templateProcessor->cloneRow('userId', 2); + $this->assertStringStartsWith('assertStringEndsWith('', $row); + $this->assertNotEmpty($row); + $this->assertEquals( + $finalArray, + $templateProcessor->getVariables() + ); + + $docName = 'test-getRow-result.docx'; + $templateProcessor->saveAs($docName); + $docFound = file_exists($docName); + $this->assertTrue($docFound); + if ($docFound) { + $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); + $this->assertEquals( + $finalArray, + $templateProcessorNEWFILE->getVariables() + ); + unlink($docName); + } + } + /** * @covers ::setValue * @covers ::saveAs @@ -225,6 +276,10 @@ private function getOpenTemplateProcessor($name) * @covers ::deleteBlock * @covers ::getBlock * @covers ::saveAs + * @covers ::findBlockEnd + * @covers ::findBlockStart + * @covers ::findTagLeft + * @covers ::findTagRight * @test */ public function testCloneDeleteBlock() From f32d00d390cf9e542f29dfa9c2186e7caf4502b3 Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 26 Sep 2017 18:28:41 +0200 Subject: [PATCH 15/74] Should be <=7 if not found. By ensuring 0 when not found, we have clearer code --- src/PhpWord/TemplateProcessor.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index be04e37611..2c571fb301 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -300,8 +300,7 @@ public function cloneRow( $extraRowStart = $this->findRowStart($extraRowEnd + 1, $throwexception); $extraRowEnd = $this->findRowEnd($extraRowEnd + 1); - // If extraRowEnd is lower then 7, there was no next row found. - if ($extraRowEnd < 7) { + if (!$extraRowEnd) { break; } @@ -714,7 +713,12 @@ protected function findBlockStart($offset, $throwexception) */ protected function findTagRight($tag, $offset = 0) { - return strpos($this->tempDocumentMainPart, $tag, $offset) + strlen($tag); + $pos = strpos($this->tempDocumentMainPart, $tag, $offset); + if ($pos) { + return $pos + strlen($tag); + } else { + return 0; + } } /** From 5675bcdc6dd0b2aba8bb86203ef47966aabdee07 Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 26 Sep 2017 18:34:00 +0200 Subject: [PATCH 16/74] More generic error message --- src/PhpWord/TemplateProcessor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 2c571fb301..ac1e21a123 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -665,7 +665,7 @@ protected function findTagLeft($tag, $offset = 0, $throwexception = false) } if (!$tagStart) { if ($throwexception) { - throw new Exception('Can not find the start position of the row to clone.'); + throw new Exception('Can not find the start position of the item to clone.'); } else { return 0; } From 07e21d4919b97af615ba536515016b135b9e6a9f Mon Sep 17 00:00:00 2001 From: Nilton Date: Fri, 29 Sep 2017 19:57:01 +0200 Subject: [PATCH 17/74] Adding multiline string support in setValue() (contributed by various people) --- src/PhpWord/TemplateProcessor.php | 9 +++++ tests/PhpWord/TemplateProcessorTest.php | 47 +++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index ac1e21a123..297f1f5baa 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -582,6 +582,15 @@ function ($match) { */ protected function setValueForPart($search, $replace, $documentPartXML, $limit) { + // Shift-Enter + if (is_array($replace)) { + foreach ($replace as &$item) { + $item = preg_replace('~\R~u', '', $item); + } + } else { + $replace = preg_replace('~\R~u', '', $replace); + } + // Note: we can't use the same function for both cases here, because of performance considerations. if (self::MAXIMUM_REPLACEMENTS_DEFAULT === $limit) { return str_replace($search, $replace, $documentPartXML); diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index f66e993ddd..70786a58e5 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -405,4 +405,51 @@ public function testCloneIndexedBlock() "The four times cloned block should be the same as four times the block" ); } + + /** + * @covers ::setValue + * @covers ::cloneRow + * @covers ::saveAs + * @covers ::findTagLeft + * @covers ::findTagRight + * @covers ::findBlockEnd + * @covers ::findBlockStart + * @test + */ + public function testSetValueMultiline() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + + $this->assertEquals( + array('tableHeader', 'userId', 'userName', 'userLocation'), + $templateProcessor->getVariables() + ); + + $docName = 'multiline-test-result.docx'; + $helloworld = "hello\nworld"; + $templateProcessor->setValue('userName', $helloworld); + $templateProcessor->saveAs($docName); + $docFound = file_exists($docName); + $this->assertTrue($docFound); + if ($docFound) { + # Great, so we saved the replaced document, so we open that new document + # note that we need to access private variables, so we use a sub-class + $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); + echo $templateProcessorNEWFILE->tempDocumentMainPart; + # We test that all Block variables have been replaced (thus, getVariables() is empty) + $this->assertEquals( + 0, + substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $helloworld), + "there should be a multiline" + ); + # we cloned block CLONEME $clone_times times, so let's count to $clone_times + $xmlblock = 'helloworld'; + $this->assertEquals( + 1, + substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $xmlblock), + "multiline should be present 1 in the document" + ); + unlink($docName); # delete generated file + } + } } From 5bd9bfac503705200ed84789afe4a1e0f02fe7f7 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 30 Sep 2017 03:49:10 +0200 Subject: [PATCH 18/74] Allow Shift-Enter/newlines in setValue --- src/PhpWord/TemplateProcessor.php | 269 +++++++++++++++++------- tests/PhpWord/TemplateProcessorTest.php | 158 +++++++++++++- 2 files changed, 345 insertions(+), 82 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index fad6147054..f736729d17 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -261,23 +261,37 @@ public function getVariables() * * @param string $search * @param integer $numberOfClones + * @param bool $replace + * @param bool $incrementVariables + * @param bool $throwexception * - * @return void + * @return string|null * * @throws \PhpOffice\PhpWord\Exception\Exception */ - public function cloneRow($search, $numberOfClones) - { + public function cloneRow( + $search, + $numberOfClones = 1, + $replace = true, + $incrementVariables = true, + $throwexception = false + ) { if ('${' !== substr($search, 0, 2) && '}' !== substr($search, -1)) { $search = '${' . $search . '}'; } $tagPos = strpos($this->tempDocumentMainPart, $search); if (!$tagPos) { - throw new Exception("Can not clone row, template variable not found or variable contains markup."); + if ($throwexception) { + throw new Exception( + "Can not clone row, template variable not found or variable contains markup." + ); + } else { + return null; + } } - $rowStart = $this->findRowStart($tagPos); + $rowStart = $this->findRowStart($tagPos, $throwexception); $rowEnd = $this->findRowEnd($tagPos); $xmlRow = $this->getSlice($rowStart, $rowEnd); @@ -286,11 +300,10 @@ public function cloneRow($search, $numberOfClones) // $extraRowStart = $rowEnd; $extraRowEnd = $rowEnd; while (true) { - $extraRowStart = $this->findRowStart($extraRowEnd + 1); + $extraRowStart = $this->findRowStart($extraRowEnd + 1, $throwexception); $extraRowEnd = $this->findRowEnd($extraRowEnd + 1); - // If extraRowEnd is lower then 7, there was no next row found. - if ($extraRowEnd < 7) { + if (!$extraRowEnd) { break; } @@ -306,13 +319,21 @@ public function cloneRow($search, $numberOfClones) $xmlRow = $this->getSlice($rowStart, $rowEnd); } - $result = $this->getSlice(0, $rowStart); - for ($i = 1; $i <= $numberOfClones; $i++) { - $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow); + if ($replace) { + $result = $this->getSlice(0, $rowStart); + for ($i = 1; $i <= $numberOfClones; $i++) { + if ($incrementVariables) { + $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow); + } else { + $result .= $xmlRow; + } + } + $result .= $this->getSlice($rowEnd); + + $this->tempDocumentMainPart = $result; } - $result .= $this->getSlice($rowEnd); - $this->tempDocumentMainPart = $result; + return $xmlRow; } /** @@ -333,33 +354,64 @@ public function cloneBlock( $incrementVariables = true, $throwexception = false ) { - $S_search = '${' . $blockname . '}'; - $E_search = '${/' . $blockname . '}'; + $singleton = substr($blockname, -1) == '/'; + $startSearch = '${' . $blockname . '}'; + $endSearch = '${/' . $blockname . '}'; + + $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); + $endTagPos = $singleton? $startTagPos : strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); - $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); - $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); - if (!$S_tagPos || !$E_tagPos) { + if (!$startTagPos || !$endTagPos) { if ($throwexception) { throw new Exception( "Can not find block '$blockname', template variable not found or variable contains markup." ); } else { - return null; # Block not found, return null + return null; // Block not found, return null + } + } + + $startBlockStart = $this->findBlockStart($startTagPos, $throwexception); + $startBlockEnd = $this->findBlockEnd($startTagPos); + // $xmlStart = $this->getSlice($startBlockStart, $startBlockEnd); + + if (!$startBlockStart || !$startBlockEnd) { + if ($throwexception) { + throw new Exception( + "Can not find start paragraph around block '$blockname'" + ); + } else { + return false; } } - $S_blockStart = $this->findBlockStart($S_tagPos); - $S_blockEnd = $this->findBlockEnd($S_tagPos); - #$xmlStart = $this->getSlice($S_blockStart, $S_blockEnd); + $endBlockStart = 0; + $endBlockEnd = 0; + $xmlBlock = null; + if (substr($blockname, -1) == '/') { + $endBlockStart = $startBlockStart; + $endBlockEnd = $startBlockEnd; + $xmlBlock = $this->getSlice($startBlockStart, $endBlockEnd); + } else { + $endBlockStart = $this->findBlockStart($endTagPos, $throwexception); + $endBlockEnd = $this->findBlockEnd($endTagPos); + // $xmlEnd = $this->getSlice($endBlockStart, $endBlockEnd); + + if (!$endBlockStart || !$endBlockEnd) { + if ($throwexception) { + throw new Exception( + "Can not find end paragraph around block '$blockname'" + ); + } else { + return false; + } + } - $E_blockStart = $this->findBlockStart($E_tagPos); - $E_blockEnd = $this->findBlockEnd($E_tagPos); - #$xmlEnd = $this->getSlice($E_blockStart, $E_blockEnd); - - $xmlBlock = $this->getSlice($S_blockEnd, $E_blockStart); + $xmlBlock = $this->getSlice($startBlockEnd, $endBlockStart); + } if ($replace) { - $result = $this->getSlice(0, $S_blockStart); + $result = $this->getSlice(0, $startBlockStart); for ($i = 1; $i <= $clones; $i++) { if ($incrementVariables) { $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlBlock); @@ -367,7 +419,7 @@ public function cloneBlock( $result .= $xmlBlock; } } - $result .= $this->getSlice($E_blockEnd); + $result .= $this->getSlice($endBlockEnd); $this->tempDocumentMainPart = $result; } @@ -385,8 +437,22 @@ public function cloneBlock( */ public function getBlock($blockname, $throwexception = false) { - return $this->cloneBlock($blockname, 1, false, $throwexception); + return $this->cloneBlock($blockname, 1, false, false, $throwexception); } + + /** + * Get a row. (first block found) + * + * @param string $rowname + * @param boolean $throwexception + * + * @return string|null + */ + public function getRow($rowname, $throwexception = false) + { + return $this->cloneRow($rowname, 1, false, false, $throwexception); + } + /** * Replace a block. * @@ -398,12 +464,14 @@ public function getBlock($blockname, $throwexception = false) */ public function replaceBlock($blockname, $replacement, $throwexception = false) { - $S_search = '${' . $blockname . '}'; - $E_search = '${/' . $blockname . '}'; + $singleton = substr($blockname, -1) == '/'; + $startSearch = '${' . $blockname . '}'; + $endSearch = '${/' . $blockname . '}'; + + $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); + $endTagPos = $singleton? $startTagPos : strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); - $S_tagPos = strpos($this->tempDocumentMainPart, $S_search); - $E_tagPos = strpos($this->tempDocumentMainPart, $E_search, $S_tagPos); - if (!$S_tagPos || !$E_tagPos) { + if (!$startTagPos || !$endTagPos) { if ($throwexception) { throw new Exception( "Can not find block '$blockname', template variable not found or variable contains markup." @@ -413,22 +481,32 @@ public function replaceBlock($blockname, $replacement, $throwexception = false) } } - $S_blockStart = $this->findBlockStart($S_tagPos); - $S_blockEnd = $this->findBlockEnd($S_tagPos); - #$xmlStart = $this->getSlice($S_blockStart, $S_blockEnd); + $startBlockStart = $this->findBlockStart($startTagPos, $throwexception); + $startBlockEnd = $this->findBlockEnd($startTagPos); + + $endBlockEnd = 0; + if (substr($blockname, -1) == '/') { + $endBlockEnd = $startBlockEnd; + } else { + $endBlockEnd = $this->findBlockEnd($endTagPos); + + if (!$endBlockEnd) { + if ($throwexception) { + throw new Exception( + "Can not find end paragraph around block '$blockname'" + ); + } else { + return false; + } + } + } - $E_blockStart = $this->findBlockStart($E_tagPos); - $E_blockEnd = $this->findBlockEnd($E_tagPos); - #$xmlEnd = $this->getSlice($E_blockStart, $E_blockEnd); - - $xmlBlock = $this->getSlice($S_blockEnd, $E_blockStart); - - $result = $this->getSlice(0, $S_blockStart); + $result = $this->getSlice(0, $startBlockStart); $result .= $replacement; - $result .= $this->getSlice($E_blockEnd); + $result .= $this->getSlice($endBlockEnd); $this->tempDocumentMainPart = $result; - + return true; } @@ -533,6 +611,15 @@ function ($match) { */ protected function setValueForPart($search, $replace, $documentPartXML, $limit) { + // Shift-Enter + if (is_array($replace)) { + foreach ($replace as &$item) { + $item = preg_replace('~\R~u', '', $item); + } + } else { + $replace = preg_replace('~\R~u', '', $replace); + } + // Note: we can't use the same function for both cases here, because of performance considerations. if (self::MAXIMUM_REPLACEMENTS_DEFAULT === $limit) { return str_replace($search, $replace, $documentPartXML); @@ -589,69 +676,91 @@ protected function getFooterName($index) } /** - * Find the start position of the nearest table row before $offset. + * Find the start position of the nearest tag before $offset. * + * @param string $tag * @param integer $offset + * @param boolean $throwexception * * @return integer * * @throws \PhpOffice\PhpWord\Exception\Exception */ - protected function findRowStart($offset) + protected function findTagLeft($tag, $offset = 0, $throwexception = false) { - $rowStart = strrpos( + $tagStart = strrpos( $this->tempDocumentMainPart, - 'tempDocumentMainPart) - $offset) * -1) ); - if (!$rowStart) { - $rowStart = strrpos( + if (!$tagStart) { + $tagStart = strrpos( $this->tempDocumentMainPart, - '', + $tag, ((strlen($this->tempDocumentMainPart) - $offset) * -1) ); } - if (!$rowStart) { - throw new Exception('Can not find the start position of the row to clone.'); + if (!$tagStart) { + if ($throwexception) { + throw new Exception('Can not find the start position of the item to clone.'); + } else { + return 0; + } } - return $rowStart; + return $tagStart; } /** - * Find the start position of the nearest paragraph () before $offset. + * Find the start position of the nearest table row before $offset. * * @param integer $offset + * @param boolean $throwexception * * @return integer * * @throws \PhpOffice\PhpWord\Exception\Exception */ - protected function findBlockStart($offset) + protected function findRowStart($offset, $throwexception) { - $blockStart = strrpos( - $this->tempDocumentMainPart, - 'tempDocumentMainPart) - $offset) * -1) - ); + return $this->findTagLeft('', $offset, $throwexception); + } - if (!$blockStart) { - $blockStart = strrpos( - $this->tempDocumentMainPart, - '', - ((strlen($this->tempDocumentMainPart) - $offset) * -1) - ); - } - if (!$blockStart) { - throw new Exception('Can not find the start position of the row to clone.'); - } + /** + * Find the start position of the nearest paragraph before $offset. + * + * @param integer $offset + * @param boolean $throwexception + * + * @return integer + * + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + protected function findBlockStart($offset, $throwexception) + { + return $this->findTagLeft('', $offset, $throwexception); + } - return $blockStart; + /** + * Find the end position of the nearest tag after $offset. + * + * @param integer $offset + * + * @return integer + */ + protected function findTagRight($tag, $offset = 0) + { + $pos = strpos($this->tempDocumentMainPart, $tag, $offset); + if ($pos) { + return $pos + strlen($tag); + } else { + return 0; + } } - + /** - * Find the end position of the nearest paragraph () after $offset. + * Find the end position of the nearest table row after $offset. * * @param integer $offset * @@ -659,11 +768,11 @@ protected function findBlockStart($offset) */ protected function findRowEnd($offset) { - return strpos($this->tempDocumentMainPart, '', $offset) + 7; + return $this->findTagRight('', $offset); } /** - * Find the end position of the nearest table row after $offset. + * Find the end position of the nearest paragraph after $offset. * * @param integer $offset * @@ -671,7 +780,7 @@ protected function findRowEnd($offset) */ protected function findBlockEnd($offset) { - return strpos($this->tempDocumentMainPart, '', $offset) + 6; + return $this->findTagRight('', $offset); } /** diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 2017eebcd5..d34d21fc2c 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -157,6 +157,10 @@ final public function testXslStyleSheetCanNotBeAppliedOnFailureOfLoadingXmlFromT * @covers ::setValue * @covers ::cloneRow * @covers ::saveAs + * @covers ::findTagLeft + * @covers ::findTagRight + * @covers ::findBlockEnd + * @covers ::findBlockStart * @test */ public function testCloneRow() @@ -178,6 +182,53 @@ public function testCloneRow() $this->assertTrue($docFound); } + /** + * @covers ::getRow + * @covers ::saveAs + * @covers ::findRowStart + * @covers ::findRowEnd + * @covers ::findTagLeft + * @covers ::findTagRight + * @test + */ + public function testGetRow() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $initialArray = array('tableHeader', 'userId', 'userName', 'userLocation'); + $finalArray = array( + 'tableHeader', + 'userId#1', 'userName#1', 'userLocation#1', + 'userId#2', 'userName#2', 'userLocation#2' + ); + $row = $templateProcessor->getRow('userId'); + $this->assertNotEmpty($row); + $this->assertEquals( + $initialArray, + $templateProcessor->getVariables() + ); + $row = $templateProcessor->cloneRow('userId', 2); + $this->assertStringStartsWith('assertStringEndsWith('', $row); + $this->assertNotEmpty($row); + $this->assertEquals( + $finalArray, + $templateProcessor->getVariables() + ); + + $docName = 'test-getRow-result.docx'; + $templateProcessor->saveAs($docName); + $docFound = file_exists($docName); + $this->assertTrue($docFound); + if ($docFound) { + $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); + $this->assertEquals( + $finalArray, + $templateProcessorNEWFILE->getVariables() + ); + unlink($docName); + } + } + /** * @covers ::setValue * @covers ::saveAs @@ -225,6 +276,10 @@ private function getOpenTemplateProcessor($name) * @covers ::deleteBlock * @covers ::getBlock * @covers ::saveAs + * @covers ::findBlockEnd + * @covers ::findBlockStart + * @covers ::findTagLeft + * @covers ::findTagRight * @test */ public function testCloneDeleteBlock() @@ -292,7 +347,7 @@ public function testCloneIndexedBlock() $templateProcessor->getVariables(), "Injected document should contain the right initial variables, in the right order" ); - + $templateProcessor->cloneBlock('MYBLOCK', 4); # detects new variables $this->assertEquals( @@ -324,7 +379,7 @@ public function testCloneIndexedBlock() substr_count($templateProcessor->tempDocumentMainPart, $STR), "order of replacement should be: ONE,TWO,THREE then FOUR" ); - + # Now we try again, but without variable incrementals (old behavior) $templateProcessor->tempDocumentMainPart = $XMLSTR; $templateProcessor->cloneBlock('MYBLOCK', 4, true, false); @@ -350,4 +405,103 @@ public function testCloneIndexedBlock() "The four times cloned block should be the same as four times the block" ); } + + /** + * @covers ::cloneBlock + * @covers ::getVariables + * @covers ::getBlock + * @covers ::setValue + * @test + */ + public function testClosedBlock() + { + $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $XMLTXT = 'This ${BLOCKCLOSE/} is here.'; + $XMLSTR = '${BEFORE}' . $XMLTXT . '${AFTER}'; + $templateProcessor->tempDocumentMainPart = $XMLSTR; + + $this->assertEquals( + $XMLTXT, + $templateProcessor->getBlock('BLOCKCLOSE/'), + "Block should be cut at the right place (using findBlockStart/findBlockEnd)" + ); + + # detects variables + $this->assertEquals( + array('BEFORE', 'BLOCKCLOSE/', 'AFTER'), + $templateProcessor->getVariables(), + "Injected document should contain the right initial variables, in the right order" + ); + + # inserting itself should result in no change + $oldvalue = $templateProcessor->tempDocumentMainPart; + $block = $templateProcessor->getBlock('BLOCKCLOSE/'); + $templateProcessor->replaceBlock('BLOCKCLOSE/', $block); + $this->assertEquals( + $oldvalue, + $templateProcessor->tempDocumentMainPart, + "ReplaceBlock should replace at the right position" + ); + + $templateProcessor->cloneBlock('BLOCKCLOSE/', 4); + # detects new variables + $this->assertEquals( + array('BEFORE', 'BLOCKCLOSE/#1', 'BLOCKCLOSE/#2', 'BLOCKCLOSE/#3', 'BLOCKCLOSE/#4', 'AFTER'), + $templateProcessor->getVariables(), + "Injected document should contain the right cloned variables, in the right order" + ); + + $templateProcessor->tempDocumentMainPart = $XMLSTR; + $templateProcessor->deleteBlock('BLOCKCLOSE/'); + $this->assertEquals( + '${BEFORE}${AFTER}', + $templateProcessor->tempDocumentMainPart, + 'closedblock should delete properly' + ); + } + + /** + * @covers ::setValue + * @covers ::cloneRow + * @covers ::saveAs + * @covers ::findTagLeft + * @covers ::findTagRight + * @covers ::findBlockEnd + * @covers ::findBlockStart + * @test + */ + public function testSetValueMultiline() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + + $this->assertEquals( + array('tableHeader', 'userId', 'userName', 'userLocation'), + $templateProcessor->getVariables() + ); + + $docName = 'multiline-test-result.docx'; + $helloworld = "hello\nworld"; + $templateProcessor->setValue('userName', $helloworld); + $templateProcessor->saveAs($docName); + $docFound = file_exists($docName); + $this->assertTrue($docFound); + if ($docFound) { + # We open that new document (and use the OpenTemplateProcessor to access private variables) + $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); + # We test that all Block variables have been replaced (thus, getVariables() is empty) + $this->assertEquals( + 0, + substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $helloworld), + "there should be a multiline" + ); + # The block it should be turned into: + $xmlblock = 'helloworld'; + $this->assertEquals( + 1, + substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $xmlblock), + "multiline should be present 1 in the document" + ); + unlink($docName); # delete generated file + } + } } From 5bb24f040fa5fc7309d393fa10d852b8e6f30245 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 30 Sep 2017 04:39:21 +0200 Subject: [PATCH 19/74] expose $templateProcessor->zipClass->AddFromString() to replace images in the document --- src/PhpWord/TemplateProcessor.php | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index f736729d17..077979f956 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -235,7 +235,20 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ $this->tempDocumentMainPart = $this->setValueForPart($search, $replace, $this->tempDocumentMainPart, $limit); $this->tempDocumentFooters = $this->setValueForPart($search, $replace, $this->tempDocumentFooters, $limit); } - + + /** + * Updates a file inside the document, from a string (with binary data) + * + * @param string $localname + * @param string $contents + * + * @return bool + */ + public function zipAddFromString($localname, $contents) + { + return $this->zipClass->AddFromString($localname, $contents); + } + /** * Returns array of all variables in template. * From 52d4173136175cde1ef8c7a0e1b0c2090ec142b9 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 30 Sep 2017 06:01:48 +0200 Subject: [PATCH 20/74] Make scrutinizer happier. --- src/PhpWord/TemplateProcessor.php | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 077979f956..cd172fd445 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -398,11 +398,8 @@ public function cloneBlock( } } - $endBlockStart = 0; - $endBlockEnd = 0; - $xmlBlock = null; - if (substr($blockname, -1) == '/') { - $endBlockStart = $startBlockStart; + if ($singleton) { + // $endBlockStart = $startBlockStart; $endBlockEnd = $startBlockEnd; $xmlBlock = $this->getSlice($startBlockStart, $endBlockEnd); } else { @@ -497,8 +494,7 @@ public function replaceBlock($blockname, $replacement, $throwexception = false) $startBlockStart = $this->findBlockStart($startTagPos, $throwexception); $startBlockEnd = $this->findBlockEnd($startTagPos); - $endBlockEnd = 0; - if (substr($blockname, -1) == '/') { + if ($singleton) { $endBlockEnd = $startBlockEnd; } else { $endBlockEnd = $this->findBlockEnd($endTagPos); From d6a3b803056e0ab0aba879a0c743135dcc6a89d1 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 30 Sep 2017 08:02:44 +0200 Subject: [PATCH 21/74] camelCased a few variables to keep phpunit happy. --- tests/PhpWord/TemplateProcessorTest.php | 51 +++++++++++++------------ 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index d34d21fc2c..457af1af1e 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -263,13 +263,13 @@ private function getOpenTemplateProcessor($name) if (!file_exists($name) || !is_readable($name)) { return null; } - $ESTR = + $evaluatedString = 'class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor {' . 'public function __construct($instance){return parent::__construct($instance);}' . 'public function __get($key){return $this->$key;}' . 'public function __set($key, $val){return $this->$key = $val;} };' . 'return new OpenTemplateProcessor("'.$name.'");'; - return eval($ESTR); + return eval($evaluatedString); } /** * @covers ::cloneBlock @@ -290,11 +290,11 @@ public function testCloneDeleteBlock() array('DELETEME', '/DELETEME', 'CLONEME', '/CLONEME'), $templateProcessor->getVariables() ); - $clone_times = 3; + $cloneTimes = 3; $docName = 'clone-delete-block-result.docx'; $xmlblock = $templateProcessor->getBlock('CLONEME'); $this->assertNotEmpty($xmlblock); - $templateProcessor->cloneBlock('CLONEME', $clone_times); + $templateProcessor->cloneBlock('CLONEME', $cloneTimes); $templateProcessor->deleteBlock('DELETEME'); $templateProcessor->saveAs($docName); $docFound = file_exists($docName); @@ -308,11 +308,11 @@ public function testCloneDeleteBlock() $templateProcessorNEWFILE->getVariables(), "All block variables should have been replaced" ); - # we cloned block CLONEME $clone_times times, so let's count to $clone_times + # we cloned block CLONEME $cloneTimes times, so let's count to $cloneTimes $this->assertEquals( - $clone_times, + $cloneTimes, substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $xmlblock), - "Block should be present $clone_times in the document" + "Block should be present $cloneTimes in the document" ); unlink($docName); # delete generated file } @@ -331,12 +331,12 @@ public function testCloneIndexedBlock() { $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); # we will fake a block with a variable inside it, as there is no template document yet. - $XMLTXT = 'This ${repeats} a few times'; - $XMLSTR = '${MYBLOCK}' . $XMLTXT . '${/MYBLOCK}'; - $templateProcessor->tempDocumentMainPart = $XMLSTR; + $xmlTxt = 'This ${repeats} a few times'; + $xmlStr = '${MYBLOCK}' . $xmlTxt . '${/MYBLOCK}'; + $templateProcessor->tempDocumentMainPart = $xmlStr; $this->assertEquals( - $XMLTXT, + $xmlTxt, $templateProcessor->getBlock('MYBLOCK'), "Block should be cut at the right place (using findBlockStart/findBlockEnd)" ); @@ -356,13 +356,13 @@ public function testCloneIndexedBlock() "Injected document should contain the right cloned variables, in the right order" ); - $ARR = [ + $replaceArray = [ 'repeats#1' => 'ONE', 'repeats#2' => 'TWO', 'repeats#3' => 'THREE', 'repeats#4' => 'FOUR' ]; - $templateProcessor->setValue(array_keys($ARR), array_values($ARR)); + $templateProcessor->setValue(array_keys($replaceArray), array_values($replaceArray)); $this->assertEquals( [], $templateProcessor->getVariables(), @@ -370,18 +370,19 @@ public function testCloneIndexedBlock() ); # now we test the order of replacement: ONE,TWO,THREE then FOUR - $STR = ""; - foreach ($ARR as $k => $v) { - $STR .= str_replace('${repeats}', $v, $XMLTXT); + $replaceString = ""; + foreach ($replaceArray as $replaceKey) { + $replaceValue = $replaceArray[$replaceKey]; + $replaceString .= str_replace('${repeats}', $replaceValue, $xmlTxt); } $this->assertEquals( 1, - substr_count($templateProcessor->tempDocumentMainPart, $STR), + substr_count($templateProcessor->tempDocumentMainPart, $replaceString), "order of replacement should be: ONE,TWO,THREE then FOUR" ); # Now we try again, but without variable incrementals (old behavior) - $templateProcessor->tempDocumentMainPart = $XMLSTR; + $templateProcessor->tempDocumentMainPart = $xmlStr; $templateProcessor->cloneBlock('MYBLOCK', 4, true, false); # detects new variable @@ -394,14 +395,14 @@ public function testCloneIndexedBlock() # we cloned block CLONEME 4 times, so let's count $this->assertEquals( 4, - substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT), + substr_count($templateProcessor->tempDocumentMainPart, $xmlTxt), 'detects new variable $repeats to be present 4 times' ); # we cloned block CLONEME 4 times, so let's see that there is no space between these blocks $this->assertEquals( 1, - substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT.$XMLTXT.$XMLTXT.$XMLTXT), + substr_count($templateProcessor->tempDocumentMainPart, $xmlTxt.$xmlTxt.$xmlTxt.$xmlTxt), "The four times cloned block should be the same as four times the block" ); } @@ -416,12 +417,12 @@ public function testCloneIndexedBlock() public function testClosedBlock() { $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); - $XMLTXT = 'This ${BLOCKCLOSE/} is here.'; - $XMLSTR = '${BEFORE}' . $XMLTXT . '${AFTER}'; - $templateProcessor->tempDocumentMainPart = $XMLSTR; + $xmlTxt = 'This ${BLOCKCLOSE/} is here.'; + $xmlStr = '${BEFORE}' . $xmlTxt . '${AFTER}'; + $templateProcessor->tempDocumentMainPart = $xmlStr; $this->assertEquals( - $XMLTXT, + $xmlTxt, $templateProcessor->getBlock('BLOCKCLOSE/'), "Block should be cut at the right place (using findBlockStart/findBlockEnd)" ); @@ -451,7 +452,7 @@ public function testClosedBlock() "Injected document should contain the right cloned variables, in the right order" ); - $templateProcessor->tempDocumentMainPart = $XMLSTR; + $templateProcessor->tempDocumentMainPart = $xmlStr; $templateProcessor->deleteBlock('BLOCKCLOSE/'); $this->assertEquals( '${BEFORE}${AFTER}', From a1c16141a329e822a9177e908a3bef3161496b85 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 30 Sep 2017 08:21:12 +0200 Subject: [PATCH 22/74] oops, foreach loops through values, not keys --- tests/PhpWord/TemplateProcessorTest.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 457af1af1e..66dcaa5c13 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -304,7 +304,7 @@ public function testCloneDeleteBlock() $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); # We test that all Block variables have been replaced (thus, getVariables() is empty) $this->assertEquals( - [], + array(), $templateProcessorNEWFILE->getVariables(), "All block variables should have been replaced" ); @@ -371,8 +371,7 @@ public function testCloneIndexedBlock() # now we test the order of replacement: ONE,TWO,THREE then FOUR $replaceString = ""; - foreach ($replaceArray as $replaceKey) { - $replaceValue = $replaceArray[$replaceKey]; + foreach ($replaceArray as $replaceValue) { $replaceString .= str_replace('${repeats}', $replaceValue, $xmlTxt); } $this->assertEquals( From 496ea7034057c3519d6da290501d7f2299349b25 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 7 Oct 2017 13:32:41 +0200 Subject: [PATCH 23/74] Introducing *Segment functions; Inline-Blocks and cleanup/indenting. --- src/PhpWord/TemplateProcessor.php | 342 ++++++++++++++++-------- tests/PhpWord/TemplateProcessorTest.php | 52 ++-- 2 files changed, 250 insertions(+), 144 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index cd172fd445..5dae4d26a0 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -11,7 +11,7 @@ * contributors, visit https://github.com/PHPOffice/PHPWord/contributors. * * @link https://github.com/PHPOffice/PHPWord - * @copyright 2010-2016 PHPWord contributors + * @copyright 2010-2017 PHPWord contributors * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3 */ @@ -272,11 +272,11 @@ public function getVariables() /** * Clone a table row in a template document. * - * @param string $search + * @param string $search * @param integer $numberOfClones - * @param bool $replace - * @param bool $incrementVariables - * @param bool $throwexception + * @param bool $replace + * @param bool $incrementVariables + * @param bool $throwexception * * @return string|null * @@ -304,8 +304,8 @@ public function cloneRow( } } - $rowStart = $this->findRowStart($tagPos, $throwexception); - $rowEnd = $this->findRowEnd($tagPos); + $rowStart = $this->findTagLeft('', $tagPos, $throwexception); // findRowStart + $rowEnd = $this->findTagRight('', $tagPos); // findRowEnd $xmlRow = $this->getSlice($rowStart, $rowEnd); // Check if there's a cell spanning multiple rows. @@ -313,8 +313,8 @@ public function cloneRow( // $extraRowStart = $rowEnd; $extraRowEnd = $rowEnd; while (true) { - $extraRowStart = $this->findRowStart($extraRowEnd + 1, $throwexception); - $extraRowEnd = $this->findRowEnd($extraRowEnd + 1); + $extraRowStart = $this->findTagLeft('', $extraRowEnd + 1, $throwexception); // findRowStart + $extraRowEnd = $this->findTagRight('', $extraRowEnd + 1); // findRowEnd if (!$extraRowEnd) { break; @@ -322,8 +322,9 @@ public function cloneRow( // If tmpXmlRow doesn't contain continue, this row is no longer part of the spanned row. $tmpXmlRow = $this->getSlice($extraRowStart, $extraRowEnd); - if (!preg_match('##', $tmpXmlRow) && - !preg_match('##', $tmpXmlRow)) { + if (!preg_match('##', $tmpXmlRow) + && !preg_match('##', $tmpXmlRow) + ) { break; } // This row was a spanned row, update $rowEnd and search for the next row. @@ -349,10 +350,22 @@ public function cloneRow( return $xmlRow; } + /** + * Delete a row containing the given variable + * + * @param string $search + * + * @return \PhpOffice\PhpWord\Template + */ + public function deleteRow($search) + { + return $this->deleteSegment($this->ensureMacroCompleted($search), 'w:tr'); + } + /** * Clone a block. * - * @param string $blockname + * @param string $blockname * @param integer $clones * @param boolean $replace * @param boolean $incrementVariables @@ -367,12 +380,23 @@ public function cloneBlock( $incrementVariables = true, $throwexception = false ) { - $singleton = substr($blockname, -1) == '/'; $startSearch = '${' . $blockname . '}'; $endSearch = '${/' . $blockname . '}'; + if (substr($blockname, -1) == '/') { // singleton/closed block + return $this->cloneSegment( + $startSearch, + 'w:p', + 'MainPart', + $clones, + $replace, + $incrementVariables, + $throwexception + ); + } + $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); - $endTagPos = $singleton? $startTagPos : strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); + $endTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); if (!$startTagPos || !$endTagPos) { if ($throwexception) { @@ -384,8 +408,8 @@ public function cloneBlock( } } - $startBlockStart = $this->findBlockStart($startTagPos, $throwexception); - $startBlockEnd = $this->findBlockEnd($startTagPos); + $startBlockStart = $this->findTagLeft('', $startTagPos, $throwexception); // findBlockStart() + $startBlockEnd = $this->findTagRight('', $startTagPos); // findBlockEnd() // $xmlStart = $this->getSlice($startBlockStart, $startBlockEnd); if (!$startBlockStart || !$startBlockEnd) { @@ -398,28 +422,29 @@ public function cloneBlock( } } - if ($singleton) { - // $endBlockStart = $startBlockStart; - $endBlockEnd = $startBlockEnd; - $xmlBlock = $this->getSlice($startBlockStart, $endBlockEnd); - } else { - $endBlockStart = $this->findBlockStart($endTagPos, $throwexception); - $endBlockEnd = $this->findBlockEnd($endTagPos); - // $xmlEnd = $this->getSlice($endBlockStart, $endBlockEnd); - - if (!$endBlockStart || !$endBlockEnd) { - if ($throwexception) { - throw new Exception( - "Can not find end paragraph around block '$blockname'" - ); - } else { - return false; - } + $endBlockStart = $this->findTagLeft('', $endTagPos, $throwexception); // findBlockStart() + $endBlockEnd = $this->findTagRight('', $endTagPos); // findBlockEnd() + // $xmlEnd = $this->getSlice($endBlockStart, $endBlockEnd); + + if (!$endBlockStart || !$endBlockEnd) { + if ($throwexception) { + throw new Exception( + "Can not find end paragraph around block '$blockname'" + ); + } else { + return false; } + } - $xmlBlock = $this->getSlice($startBlockEnd, $endBlockStart); + if ($startBlockEnd == $endBlockEnd) { // inline block + $startBlockStart = $startTagPos; + $startBlockEnd = $startTagPos + strlen($startSearch); + $endBlockStart = $endTagPos; + $endBlockEnd = $endTagPos + strlen($endSearch); } + $xmlBlock = $this->getSlice($startBlockEnd, $endBlockStart); + if ($replace) { $result = $this->getSlice(0, $startBlockStart); for ($i = 1; $i <= $clones; $i++) { @@ -437,10 +462,76 @@ public function cloneBlock( return $xmlBlock; } + /** + * Clone a segment. + * + * @param string $needle + * @param string $xmltag + * @param string $docpart + * @param integer $clones + * @param boolean $replace + * @param boolean $incrementVariables + * @param boolean $throwexception + * + * @return string|null + */ + public function cloneSegment( + $needle, + $xmltag, + $docpart = 'MainPart', + $clones = 1, + $replace = true, + $incrementVariables = true, + $throwexception = false + ) { + $needlePos = strpos($this->{"tempDocument$docpart"}, $needle); + + if (!$needlePos) { + if ($throwexception) { + throw new Exception( + "Can not find segment '$needle', text not found or text contains markup." + ); + } else { + return null; // Segment not found, return null + } + } + + $startSegmentStart = $this->findTagLeft("<$xmltag>", $needlePos, $throwexception); + $endSegmentEnd = $this->findTagRight("", $needlePos); + + if (!$startSegmentStart || !$endSegmentEnd) { + if ($throwexception) { + throw new Exception( + "Can not find <$xmltag> around segment '$needle'" + ); + } else { + return false; + } + } + + $xmlSegment = $this->getSlice($startSegmentStart, $endSegmentEnd); + + if ($replace) { + $result = $this->getSlice(0, $startSegmentStart); + for ($i = 1; $i <= $clones; $i++) { + if ($incrementVariables) { + $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlSegment); + } else { + $result .= $xmlSegment; + } + } + $result .= $this->getSlice($endSegmentEnd); + + $this->{"tempDocument$docpart"} = $result; + } + + return $xmlSegment; + } + /** * Get a block. (first block found) * - * @param string $blockname + * @param string $blockname * @param boolean $throwexception * * @return string|null @@ -450,10 +541,25 @@ public function getBlock($blockname, $throwexception = false) return $this->cloneBlock($blockname, 1, false, false, $throwexception); } + /** + * Get a segment. (first segment found) + * + * @param string $needle + * @param string $xmltag + * @param string $docpart + * @param boolean $throwexception + * + * @return string|null + */ + public function getSegment($needle, $xmltag, $docpart = 'MainPart', $throwexception = false) + { + return $this->cloneSegment($needle, $xmltag, $docpart, 1, false, false, $throwexception); + } + /** * Get a row. (first block found) * - * @param string $rowname + * @param string $rowname * @param boolean $throwexception * * @return string|null @@ -466,20 +572,23 @@ public function getRow($rowname, $throwexception = false) /** * Replace a block. * - * @param string $blockname - * @param string $replacement + * @param string $blockname + * @param string $replacement * @param boolean $throwexception * * @return false on no replacement, true on replacement */ - public function replaceBlock($blockname, $replacement, $throwexception = false) + public function replaceBlock($blockname, $replacement = '', $throwexception = false) { - $singleton = substr($blockname, -1) == '/'; $startSearch = '${' . $blockname . '}'; $endSearch = '${/' . $blockname . '}'; + if (substr($blockname, -1) == '/') { // singleton/closed block + return $this->replaceSegment($startSearch, 'w:p', $replacement, 'MainPart', $throwexception); + } + $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); - $endTagPos = $singleton? $startTagPos : strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); + $endTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); if (!$startTagPos || !$endTagPos) { if ($throwexception) { @@ -491,30 +600,66 @@ public function replaceBlock($blockname, $replacement, $throwexception = false) } } - $startBlockStart = $this->findBlockStart($startTagPos, $throwexception); - $startBlockEnd = $this->findBlockEnd($startTagPos); + $startBlockStart = $this->findTagLeft('', $startTagPos, $throwexception); // findBlockStart() + $endBlockEnd = $this->findTagRight('', $endTagPos); // findBlockEnd() - if ($singleton) { - $endBlockEnd = $startBlockEnd; - } else { - $endBlockEnd = $this->findBlockEnd($endTagPos); + if (!$startBlockStart || !$endBlockEnd) { + if ($throwexception) { + throw new Exception( + "Can not find end paragraph around block '$blockname'" + ); + } else { + return false; + } + } - if (!$endBlockEnd) { - if ($throwexception) { - throw new Exception( - "Can not find end paragraph around block '$blockname'" - ); - } else { - return false; - } + $startBlockEnd = $this->findTagRight('', $startTagPos); // findBlockEnd() + if ($startBlockEnd == $endBlockEnd) { // inline block + $startBlockStart = $startTagPos; + $endBlockEnd = $endTagPos + strlen($endSearch); + } + + $this->tempDocumentMainPart = + $this->getSlice(0, $startBlockStart) + . $replacement + . $this->getSlice($endBlockEnd); + + return true; + } + + + /** + * Replace a segment. + * + * @param string $needle + * @param string $xmltag + * @param string $replacement + * @param string $docpart + * @param boolean $throwexception + * + * @return false on no replacement, true on replacement + */ + public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = 'MainPart', $throwexception = false) + { + $TagPos = strpos($this->{"tempDocument$docpart"}, $needle); + + if ($TagPos === false) { + if ($throwexception) { + throw new Exception( + "Can not find segment '$needle', text not found or text contains markup." + ); + } else { + return false; } } - $result = $this->getSlice(0, $startBlockStart); - $result .= $replacement; - $result .= $this->getSlice($endBlockEnd); + $SegmentStart = $this->findTagLeft("<$xmltag>", $TagPos, $throwexception); + $SegmentEnd = $this->findTagRight("", $TagPos); - $this->tempDocumentMainPart = $result; + $this->{"tempDocument$docpart"} = + $this->getSlice(0, $SegmentStart) + . $replacement + . $this->getSlice($SegmentEnd); return true; } @@ -531,6 +676,20 @@ public function deleteBlock($blockname) return $this->replaceBlock($blockname, '', false); } + /** + * Delete a segment of text. + * + * @param string $needle + * @param string $xmltag + * @param string $docpart + * + * @return true on segment found and deleted, false on segment not found. + */ + public function deleteSegment($needle, $xmltag, $docpart = 'MainPart') + { + return $this->replaceSegment($needle, $xmltag, '', $docpart, false); + } + /** * Saves the result document. * @@ -611,9 +770,9 @@ function ($match) { /** * Find and replace macros in the given XML section. * - * @param mixed $search - * @param mixed $replace - * @param string $documentPartXML + * @param mixed $search + * @param mixed $replace + * @param string $documentPartXML * @param integer $limit * * @return string @@ -722,38 +881,9 @@ protected function findTagLeft($tag, $offset = 0, $throwexception = false) } /** - * Find the start position of the nearest table row before $offset. - * - * @param integer $offset - * @param boolean $throwexception - * - * @return integer - * - * @throws \PhpOffice\PhpWord\Exception\Exception - */ - protected function findRowStart($offset, $throwexception) - { - return $this->findTagLeft('', $offset, $throwexception); - } - - /** - * Find the start position of the nearest paragraph before $offset. - * - * @param integer $offset - * @param boolean $throwexception - * - * @return integer - * - * @throws \PhpOffice\PhpWord\Exception\Exception - */ - protected function findBlockStart($offset, $throwexception) - { - return $this->findTagLeft('', $offset, $throwexception); - } - - /** - * Find the end position of the nearest tag after $offset. + * Find the end position of the nearest $tag after $offset. * + * @param string $tag * @param integer $offset * * @return integer @@ -761,37 +891,13 @@ protected function findBlockStart($offset, $throwexception) protected function findTagRight($tag, $offset = 0) { $pos = strpos($this->tempDocumentMainPart, $tag, $offset); - if ($pos) { + if ($pos !== false) { return $pos + strlen($tag); } else { return 0; } } - /** - * Find the end position of the nearest table row after $offset. - * - * @param integer $offset - * - * @return integer - */ - protected function findRowEnd($offset) - { - return $this->findTagRight('', $offset); - } - - /** - * Find the end position of the nearest paragraph after $offset. - * - * @param integer $offset - * - * @return integer - */ - protected function findBlockEnd($offset) - { - return $this->findTagRight('', $offset); - } - /** * Get a slice of a string. * diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 66dcaa5c13..d34d21fc2c 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -263,13 +263,13 @@ private function getOpenTemplateProcessor($name) if (!file_exists($name) || !is_readable($name)) { return null; } - $evaluatedString = + $ESTR = 'class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor {' . 'public function __construct($instance){return parent::__construct($instance);}' . 'public function __get($key){return $this->$key;}' . 'public function __set($key, $val){return $this->$key = $val;} };' . 'return new OpenTemplateProcessor("'.$name.'");'; - return eval($evaluatedString); + return eval($ESTR); } /** * @covers ::cloneBlock @@ -290,11 +290,11 @@ public function testCloneDeleteBlock() array('DELETEME', '/DELETEME', 'CLONEME', '/CLONEME'), $templateProcessor->getVariables() ); - $cloneTimes = 3; + $clone_times = 3; $docName = 'clone-delete-block-result.docx'; $xmlblock = $templateProcessor->getBlock('CLONEME'); $this->assertNotEmpty($xmlblock); - $templateProcessor->cloneBlock('CLONEME', $cloneTimes); + $templateProcessor->cloneBlock('CLONEME', $clone_times); $templateProcessor->deleteBlock('DELETEME'); $templateProcessor->saveAs($docName); $docFound = file_exists($docName); @@ -304,15 +304,15 @@ public function testCloneDeleteBlock() $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); # We test that all Block variables have been replaced (thus, getVariables() is empty) $this->assertEquals( - array(), + [], $templateProcessorNEWFILE->getVariables(), "All block variables should have been replaced" ); - # we cloned block CLONEME $cloneTimes times, so let's count to $cloneTimes + # we cloned block CLONEME $clone_times times, so let's count to $clone_times $this->assertEquals( - $cloneTimes, + $clone_times, substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $xmlblock), - "Block should be present $cloneTimes in the document" + "Block should be present $clone_times in the document" ); unlink($docName); # delete generated file } @@ -331,12 +331,12 @@ public function testCloneIndexedBlock() { $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); # we will fake a block with a variable inside it, as there is no template document yet. - $xmlTxt = 'This ${repeats} a few times'; - $xmlStr = '${MYBLOCK}' . $xmlTxt . '${/MYBLOCK}'; - $templateProcessor->tempDocumentMainPart = $xmlStr; + $XMLTXT = 'This ${repeats} a few times'; + $XMLSTR = '${MYBLOCK}' . $XMLTXT . '${/MYBLOCK}'; + $templateProcessor->tempDocumentMainPart = $XMLSTR; $this->assertEquals( - $xmlTxt, + $XMLTXT, $templateProcessor->getBlock('MYBLOCK'), "Block should be cut at the right place (using findBlockStart/findBlockEnd)" ); @@ -356,13 +356,13 @@ public function testCloneIndexedBlock() "Injected document should contain the right cloned variables, in the right order" ); - $replaceArray = [ + $ARR = [ 'repeats#1' => 'ONE', 'repeats#2' => 'TWO', 'repeats#3' => 'THREE', 'repeats#4' => 'FOUR' ]; - $templateProcessor->setValue(array_keys($replaceArray), array_values($replaceArray)); + $templateProcessor->setValue(array_keys($ARR), array_values($ARR)); $this->assertEquals( [], $templateProcessor->getVariables(), @@ -370,18 +370,18 @@ public function testCloneIndexedBlock() ); # now we test the order of replacement: ONE,TWO,THREE then FOUR - $replaceString = ""; - foreach ($replaceArray as $replaceValue) { - $replaceString .= str_replace('${repeats}', $replaceValue, $xmlTxt); + $STR = ""; + foreach ($ARR as $k => $v) { + $STR .= str_replace('${repeats}', $v, $XMLTXT); } $this->assertEquals( 1, - substr_count($templateProcessor->tempDocumentMainPart, $replaceString), + substr_count($templateProcessor->tempDocumentMainPart, $STR), "order of replacement should be: ONE,TWO,THREE then FOUR" ); # Now we try again, but without variable incrementals (old behavior) - $templateProcessor->tempDocumentMainPart = $xmlStr; + $templateProcessor->tempDocumentMainPart = $XMLSTR; $templateProcessor->cloneBlock('MYBLOCK', 4, true, false); # detects new variable @@ -394,14 +394,14 @@ public function testCloneIndexedBlock() # we cloned block CLONEME 4 times, so let's count $this->assertEquals( 4, - substr_count($templateProcessor->tempDocumentMainPart, $xmlTxt), + substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT), 'detects new variable $repeats to be present 4 times' ); # we cloned block CLONEME 4 times, so let's see that there is no space between these blocks $this->assertEquals( 1, - substr_count($templateProcessor->tempDocumentMainPart, $xmlTxt.$xmlTxt.$xmlTxt.$xmlTxt), + substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT.$XMLTXT.$XMLTXT.$XMLTXT), "The four times cloned block should be the same as four times the block" ); } @@ -416,12 +416,12 @@ public function testCloneIndexedBlock() public function testClosedBlock() { $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); - $xmlTxt = 'This ${BLOCKCLOSE/} is here.'; - $xmlStr = '${BEFORE}' . $xmlTxt . '${AFTER}'; - $templateProcessor->tempDocumentMainPart = $xmlStr; + $XMLTXT = 'This ${BLOCKCLOSE/} is here.'; + $XMLSTR = '${BEFORE}' . $XMLTXT . '${AFTER}'; + $templateProcessor->tempDocumentMainPart = $XMLSTR; $this->assertEquals( - $xmlTxt, + $XMLTXT, $templateProcessor->getBlock('BLOCKCLOSE/'), "Block should be cut at the right place (using findBlockStart/findBlockEnd)" ); @@ -451,7 +451,7 @@ public function testClosedBlock() "Injected document should contain the right cloned variables, in the right order" ); - $templateProcessor->tempDocumentMainPart = $xmlStr; + $templateProcessor->tempDocumentMainPart = $XMLSTR; $templateProcessor->deleteBlock('BLOCKCLOSE/'); $this->assertEquals( '${BEFORE}${AFTER}', From 6137d9af9cd5c861abfcd2314a1da62946498694 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 7 Oct 2017 13:39:24 +0200 Subject: [PATCH 24/74] Make it harder for fixBrokenMacros() to magically break a document --- src/PhpWord/TemplateProcessor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 5dae4d26a0..aea947fcd8 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -757,7 +757,7 @@ protected function fixBrokenMacros($documentPart) $fixedDocumentPart = $documentPart; $fixedDocumentPart = preg_replace_callback( - '|\$[^{]*\{[^}]*\}|U', + '|\$(?:<[^{]*)?\{[^}]*\}|U', function ($match) { return strip_tags($match[0]); }, From e3c23ac5323b2e81ce4d996648815cf95fede0b6 Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 10 Oct 2017 00:35:58 +0200 Subject: [PATCH 25/74] camelCase for Scrutinizer --- src/PhpWord/TemplateProcessor.php | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index aea947fcd8..04db1a8581 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -641,9 +641,9 @@ public function replaceBlock($blockname, $replacement = '', $throwexception = fa */ public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = 'MainPart', $throwexception = false) { - $TagPos = strpos($this->{"tempDocument$docpart"}, $needle); + $tagPos = strpos($this->{"tempDocument$docpart"}, $needle); - if ($TagPos === false) { + if ($tagPos === false) { if ($throwexception) { throw new Exception( "Can not find segment '$needle', text not found or text contains markup." @@ -653,13 +653,23 @@ public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = ' } } - $SegmentStart = $this->findTagLeft("<$xmltag>", $TagPos, $throwexception); - $SegmentEnd = $this->findTagRight("", $TagPos); + $segmentStart = $this->findTagLeft("<$xmltag>", $tagPos, $throwexception); + $segmentEnd = $this->findTagRight("", $tagPos); + + if (!$segmentStart || !$segmentEnd) { + if ($throwexception) { + throw new Exception( + "Can not find tag $xmltag around segment '$needle'." + ); + } else { + return false; + } + } $this->{"tempDocument$docpart"} = - $this->getSlice(0, $SegmentStart) + $this->getSlice(0, $segmentStart) . $replacement - . $this->getSlice($SegmentEnd); + . $this->getSlice($segmentEnd); return true; } From d5c888c04c055ad8814deec53e24b15573dc977a Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 10 Oct 2017 01:29:04 +0200 Subject: [PATCH 26/74] Add a test for inline blocks --- tests/PhpWord/TemplateProcessorTest.php | 56 ++++++++++++++++++++----- 1 file changed, 45 insertions(+), 11 deletions(-) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index d34d21fc2c..669670d854 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -159,8 +159,6 @@ final public function testXslStyleSheetCanNotBeAppliedOnFailureOfLoadingXmlFromT * @covers ::saveAs * @covers ::findTagLeft * @covers ::findTagRight - * @covers ::findBlockEnd - * @covers ::findBlockStart * @test */ public function testCloneRow() @@ -185,8 +183,6 @@ public function testCloneRow() /** * @covers ::getRow * @covers ::saveAs - * @covers ::findRowStart - * @covers ::findRowEnd * @covers ::findTagLeft * @covers ::findTagRight * @test @@ -276,8 +272,6 @@ private function getOpenTemplateProcessor($name) * @covers ::deleteBlock * @covers ::getBlock * @covers ::saveAs - * @covers ::findBlockEnd - * @covers ::findBlockStart * @covers ::findTagLeft * @covers ::findTagRight * @test @@ -324,6 +318,8 @@ public function testCloneDeleteBlock() * @covers ::cloneBlock * @covers ::getVariables * @covers ::getBlock + * @covers ::findTagLeft + * @covers ::findTagRight * @covers ::setValue * @test */ @@ -338,7 +334,7 @@ public function testCloneIndexedBlock() $this->assertEquals( $XMLTXT, $templateProcessor->getBlock('MYBLOCK'), - "Block should be cut at the right place (using findBlockStart/findBlockEnd)" + "Block should be cut at the right place (using findTagLeft/findTagRight)" ); # detects variables @@ -411,6 +407,8 @@ public function testCloneIndexedBlock() * @covers ::getVariables * @covers ::getBlock * @covers ::setValue + * @covers ::findTagLeft + * @covers ::findTagRight * @test */ public function testClosedBlock() @@ -423,7 +421,7 @@ public function testClosedBlock() $this->assertEquals( $XMLTXT, $templateProcessor->getBlock('BLOCKCLOSE/'), - "Block should be cut at the right place (using findBlockStart/findBlockEnd)" + "Block should be cut at the right place (using findTagLeft/findTagRight)" ); # detects variables @@ -462,12 +460,9 @@ public function testClosedBlock() /** * @covers ::setValue - * @covers ::cloneRow * @covers ::saveAs * @covers ::findTagLeft * @covers ::findTagRight - * @covers ::findBlockEnd - * @covers ::findBlockStart * @test */ public function testSetValueMultiline() @@ -504,4 +499,43 @@ public function testSetValueMultiline() unlink($docName); # delete generated file } } + + /** + * @covers ::replaceBlock + * @covers ::getBlock + * @covers ::findTagLeft + * @covers ::findTagRight + * @test + */ + public function testInlineBlock() + { + $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $XMLSTR = ''. + 'This'. + '${inline}'. + ' has been'. + '${/inline}'. + ' block'; + + $templateProcessor->tempDocumentMainPart = $XMLSTR; + + $this->assertEquals( + $templateProcessor->getBlock('inline'), + ''. + ' has been', + "When inside the same , cut inside the paragraph" + ); + + $templateProcessor->replaceBlock('inline', 'shows'); + + $this->assertEquals( + $templateProcessor->tempDocumentMainPart, + ''. + ''. + 'This'. + 'shows'. + ' block', + "InlineBlock replace is malformed" + ); + } } From d4588ca4008a6b20465aa7613bfec86afb7573fa Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 10 Oct 2017 02:08:54 +0200 Subject: [PATCH 27/74] More camelCase variables! --- tests/PhpWord/TemplateProcessorTest.php | 46 ++++++++++++------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 669670d854..a7cbb770ee 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -104,9 +104,9 @@ final public function testXslStyleSheetCanBeApplied($actualDocumentFqfn) throw new \Exception("Could not close zip file \"{$expectedDocumentFqfn}\"."); } - $this->assertXmlStringEqualsXmlString($expectedHeaderXml, $actualHeaderXml); - $this->assertXmlStringEqualsXmlString($expectedMainPartXml, $actualMainPartXml); - $this->assertXmlStringEqualsXmlString($expectedFooterXml, $actualFooterXml); + $this->assertxmlStringEqualsxmlString($expectedHeaderXml, $actualHeaderXml); + $this->assertxmlStringEqualsxmlString($expectedMainPartXml, $actualMainPartXml); + $this->assertxmlStringEqualsxmlString($expectedFooterXml, $actualFooterXml); } /** @@ -327,12 +327,12 @@ public function testCloneIndexedBlock() { $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); # we will fake a block with a variable inside it, as there is no template document yet. - $XMLTXT = 'This ${repeats} a few times'; - $XMLSTR = '${MYBLOCK}' . $XMLTXT . '${/MYBLOCK}'; - $templateProcessor->tempDocumentMainPart = $XMLSTR; + $xmlTxt = 'This ${repeats} a few times'; + $xmlStr = '${MYBLOCK}' . $xmlTxt . '${/MYBLOCK}'; + $templateProcessor->tempDocumentMainPart = $xmlStr; $this->assertEquals( - $XMLTXT, + $xmlTxt, $templateProcessor->getBlock('MYBLOCK'), "Block should be cut at the right place (using findTagLeft/findTagRight)" ); @@ -352,13 +352,13 @@ public function testCloneIndexedBlock() "Injected document should contain the right cloned variables, in the right order" ); - $ARR = [ + $variablesArray = [ 'repeats#1' => 'ONE', 'repeats#2' => 'TWO', 'repeats#3' => 'THREE', 'repeats#4' => 'FOUR' ]; - $templateProcessor->setValue(array_keys($ARR), array_values($ARR)); + $templateProcessor->setValue(array_keys($variablesArray), array_values($variablesArray)); $this->assertEquals( [], $templateProcessor->getVariables(), @@ -366,18 +366,18 @@ public function testCloneIndexedBlock() ); # now we test the order of replacement: ONE,TWO,THREE then FOUR - $STR = ""; - foreach ($ARR as $k => $v) { - $STR .= str_replace('${repeats}', $v, $XMLTXT); + $tmpStr = ""; + foreach ($variablesArray as $variable) { + $tmpStr .= str_replace('${repeats}', $variable, $xmlTxt); } $this->assertEquals( 1, - substr_count($templateProcessor->tempDocumentMainPart, $STR), + substr_count($templateProcessor->tempDocumentMainPart, $tmpStr), "order of replacement should be: ONE,TWO,THREE then FOUR" ); # Now we try again, but without variable incrementals (old behavior) - $templateProcessor->tempDocumentMainPart = $XMLSTR; + $templateProcessor->tempDocumentMainPart = $xmlStr; $templateProcessor->cloneBlock('MYBLOCK', 4, true, false); # detects new variable @@ -390,14 +390,14 @@ public function testCloneIndexedBlock() # we cloned block CLONEME 4 times, so let's count $this->assertEquals( 4, - substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT), + substr_count($templateProcessor->tempDocumentMainPart, $xmlTxt), 'detects new variable $repeats to be present 4 times' ); # we cloned block CLONEME 4 times, so let's see that there is no space between these blocks $this->assertEquals( 1, - substr_count($templateProcessor->tempDocumentMainPart, $XMLTXT.$XMLTXT.$XMLTXT.$XMLTXT), + substr_count($templateProcessor->tempDocumentMainPart, $xmlTxt.$xmlTxt.$xmlTxt.$xmlTxt), "The four times cloned block should be the same as four times the block" ); } @@ -414,12 +414,12 @@ public function testCloneIndexedBlock() public function testClosedBlock() { $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); - $XMLTXT = 'This ${BLOCKCLOSE/} is here.'; - $XMLSTR = '${BEFORE}' . $XMLTXT . '${AFTER}'; - $templateProcessor->tempDocumentMainPart = $XMLSTR; + $xmlTxt = 'This ${BLOCKCLOSE/} is here.'; + $xmlStr = '${BEFORE}' . $xmlTxt . '${AFTER}'; + $templateProcessor->tempDocumentMainPart = $xmlStr; $this->assertEquals( - $XMLTXT, + $xmlTxt, $templateProcessor->getBlock('BLOCKCLOSE/'), "Block should be cut at the right place (using findTagLeft/findTagRight)" ); @@ -449,7 +449,7 @@ public function testClosedBlock() "Injected document should contain the right cloned variables, in the right order" ); - $templateProcessor->tempDocumentMainPart = $XMLSTR; + $templateProcessor->tempDocumentMainPart = $xmlStr; $templateProcessor->deleteBlock('BLOCKCLOSE/'); $this->assertEquals( '${BEFORE}${AFTER}', @@ -510,14 +510,14 @@ public function testSetValueMultiline() public function testInlineBlock() { $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); - $XMLSTR = ''. + $xmlStr = ''. 'This'. '${inline}'. ' has been'. '${/inline}'. ' block'; - $templateProcessor->tempDocumentMainPart = $XMLSTR; + $templateProcessor->tempDocumentMainPart = $xmlStr; $this->assertEquals( $templateProcessor->getBlock('inline'), From 9dbd834446d4dba4b40069ea3fc15e24ac189ee1 Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 10 Oct 2017 22:50:08 +0200 Subject: [PATCH 28/74] Adding setBlock() for closed block only --- src/PhpWord/TemplateProcessor.php | 82 +++++++++++++++++++++++++ tests/PhpWord/TemplateProcessorTest.php | 55 +++++++++++++++++ 2 files changed, 137 insertions(+) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 04db1a8581..b86e615a91 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -236,6 +236,43 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ $this->tempDocumentFooters = $this->setValueForPart($search, $replace, $this->tempDocumentFooters, $limit); } + /** + * Replaces a closed block with text. The text can be multiline. + * + * @param mixed $blockname + * @param mixed $replace + * @param integer $limit + * + * @return void + */ + public function setBlock($blockname, $replace, $limit = self::MAXIMUM_REPLACEMENTS_DEFAULT) + { + if (is_array($blockname)) { + $hash = array_combine($blockname, $replace); + foreach ($hash as $block => $value) { + if (preg_match('~\R~u', $value)) { + $values = preg_split('~\R~u', $value); + $this->cloneBlock($block, count($values), true, false); + foreach ($values as $oneVal) { + $this->setValue($block, $oneVal, 1); + } + } else { + $this->setValue($block, $value, $limit); + } + } + } else { + if (preg_match('~\R~u', $replace)) { + $replaces = preg_split('~\R~u', $replace); + $this->cloneBlock($blockname, count($replaces), true, false); + foreach ($replaces as $oneVal) { + $this->setValue($blockname, $oneVal, 1); + } + } else { + $this->setValue($blockname, $replace, $limit); + } + } + } + /** * Updates a file inside the document, from a string (with binary data) * @@ -924,4 +961,49 @@ protected function getSlice($startPosition, $endPosition = 0) return substr($this->tempDocumentMainPart, $startPosition, ($endPosition - $startPosition)); } + + /** + * Return a table. + * + * @param obj an object + * @param string tag + * @param bool withTags + * + * @return string|false + */ + public function makeTable() + { + return (new \PhpOffice\PhpWord\PhpWord())->addSection()->addTable(); + } + + /** + * Convert a Word2007 object to xml. + * + * @param obj an object + * @param string tag + * @param bool withTags + * + * @return string|false + */ + public function toXML($obj, $tag = '', $withTags = true) + { + if (!is_Object($obj)) { + throw new Exception("toXML(): First parameter is not an object"); + } + if (!$tag) { + $tagList = array('Table' => 'w:tbl', 'Cell' => 'w:p'); // needs more entries + $class = preg_replace('/^(?:.*\/)?/', '', get_class($obj)); + if (!in_array($class, $tagList)) { + throw new Exception("toXML: tag parameter required"); + } + $tag = $tagList[$class]; + } + $phpWord = $obj->getPhpWord(); + $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); + $fullXml = $objWriter->getWriterPart('Document')->write(); + $regExp = $withTags ? + "/^[\s\S]*(<$tag\b.*<\/$tag>).*/" : + "/^[\s\S]*<$tag\b[^>]*>(.*)<\/$tag>.*/" ; + return preg_replace($regExp, '$1', $fullXml); + } } diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index a7cbb770ee..0ee9760ef2 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -538,4 +538,59 @@ public function testInlineBlock() "InlineBlock replace is malformed" ); } + + /** + * @covers ::replaceBlock + * @covers ::cloneBlock + * @covers ::setValue + * @test + */ + public function testSetBlock() + { + $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $xmlStr = ''. + ''. + ''. + 'BEFORE'. + '${inline/}'. + 'AFTER'. + ''. + ''; + + $templateProcessor->tempDocumentMainPart = $xmlStr; + $templateProcessor->setBlock('inline/', "one\ntwo"); + + // XMLReader::xml($templateProcessor->tempDocumentMainPart)->isValid() + + $this->assertEquals( + ''. + ''. + ''. + 'BEFORE'. + 'one'. + 'AFTER'. + ''. + ''. + 'BEFORE'. + 'two'. + 'AFTER'. + ''. + '', + $templateProcessor->tempDocumentMainPart + ); + + $templateProcessor->tempDocumentMainPart = $xmlStr; + $templateProcessor->setBlock('inline/', "simplé`"); + $this->assertEquals( + ''. + ''. + ''. + 'BEFORE'. + 'simplé`'. + 'AFTER'. + ''. + '', + $templateProcessor->tempDocumentMainPart + ); + } } From 937041143311103a7887f84ff4c09f1b35435db3 Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 10 Oct 2017 23:35:12 +0200 Subject: [PATCH 29/74] backslash, not forwardslash in classes. --- src/PhpWord/TemplateProcessor.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index b86e615a91..c40d687eec 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -991,10 +991,10 @@ public function toXML($obj, $tag = '', $withTags = true) throw new Exception("toXML(): First parameter is not an object"); } if (!$tag) { - $tagList = array('Table' => 'w:tbl', 'Cell' => 'w:p'); // needs more entries - $class = preg_replace('/^(?:.*\/)?/', '', get_class($obj)); - if (!in_array($class, $tagList)) { - throw new Exception("toXML: tag parameter required"); + $tagList = array('Table' => 'w:tbl', 'Cell' => 'w:tc'); // needs more entries + $class = preg_replace('/^(.*\\\)/', '', get_class($obj)); + if (!array_key_exists($class, $tagList)) { + throw new Exception("toXML(): tag parameter required for " . get_class($obj)); } $tag = $tagList[$class]; } From 392635b821baa85eacb2103f853bbb7c31e185c0 Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 10 Oct 2017 23:35:23 +0200 Subject: [PATCH 30/74] Added testcase testMakeTable --- tests/PhpWord/TemplateProcessorTest.php | 34 +++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 0ee9760ef2..20e88c8d9f 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -593,4 +593,38 @@ public function testSetBlock() $templateProcessor->tempDocumentMainPart ); } + + /** + * @covers ::makeTable + * @covers ::toXML + * @test + */ + public function testMakeTable() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + + $table = $templateProcessor->makeTable(); + $cell = $table->addRow()->addCell(); + $cell->addText("CELL-A1"); + + $this->assertEquals( + ''. + ''. + 'CELL-A1'. + '', + $templateProcessor->toXML($table) + ); + + $this->assertEquals( + ''. + 'CELL-A1'. + '', + $templateProcessor->toXML($cell) + ); + + $this->assertEquals( + 'CELL-A1', + $templateProcessor->toXML($cell, 'w:p') + ); + } } From 15b07b618810ab2993d8bc6935d0d7bb0f64bf81 Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 00:01:55 +0200 Subject: [PATCH 31/74] Make a part that Scrutinizer found too complex, recursive --- src/PhpWord/TemplateProcessor.php | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index c40d687eec..156954185e 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -250,15 +250,7 @@ public function setBlock($blockname, $replace, $limit = self::MAXIMUM_REPLACEMEN if (is_array($blockname)) { $hash = array_combine($blockname, $replace); foreach ($hash as $block => $value) { - if (preg_match('~\R~u', $value)) { - $values = preg_split('~\R~u', $value); - $this->cloneBlock($block, count($values), true, false); - foreach ($values as $oneVal) { - $this->setValue($block, $oneVal, 1); - } - } else { - $this->setValue($block, $value, $limit); - } + $this->setBlock($block, $value, $limit); } } else { if (preg_match('~\R~u', $replace)) { From ba947398596bb8cf7a87b9ff2d8763ba714fddba Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 00:03:24 +0200 Subject: [PATCH 32/74] add an assertion test for zipAddFromString() to get a better CRAP score --- tests/PhpWord/TemplateProcessorTest.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 20e88c8d9f..0f978712ae 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -28,6 +28,7 @@ final class TemplateProcessorTest extends \PHPUnit_Framework_TestCase * Template can be saved in temporary location. * * @covers ::save + * @covers ::zipAddFromString * @test */ final public function testTemplateCanBeSavedInTemporaryLocation() @@ -41,6 +42,8 @@ final public function testTemplateCanBeSavedInTemporaryLocation() $templateProcessor->applyXslStyleSheet($xslDomDocument, array('needle' => $needle)); } + $embeddingText = "The quick Brown Fox jumped over the lazy unitTester"; + $templateProcessor->zipAddFromString('word/embeddings/fox.bin', $embeddingText); $documentFqfn = $templateProcessor->save(); $this->assertNotEmpty($documentFqfn, 'FQFN of the saved document is empty.'); @@ -51,6 +54,7 @@ final public function testTemplateCanBeSavedInTemporaryLocation() $templateHeaderXml = $templateZip->getFromName('word/header1.xml'); $templateMainPartXml = $templateZip->getFromName('word/document.xml'); $templateFooterXml = $templateZip->getFromName('word/footer1.xml'); + $templateFooterXml = $templateZip->getFromName('word/footer1.xml'); if (false === $templateZip->close()) { throw new \Exception("Could not close zip file \"{$templateZip}\"."); } @@ -60,6 +64,7 @@ final public function testTemplateCanBeSavedInTemporaryLocation() $documentHeaderXml = $documentZip->getFromName('word/header1.xml'); $documentMainPartXml = $documentZip->getFromName('word/document.xml'); $documentFooterXml = $documentZip->getFromName('word/footer1.xml'); + $documentEmbedding = $documentZip->getFromName('word/embeddings/fox.bin'); if (false === $documentZip->close()) { throw new \Exception("Could not close zip file \"{$documentZip}\"."); } @@ -68,6 +73,8 @@ final public function testTemplateCanBeSavedInTemporaryLocation() $this->assertNotEquals($templateMainPartXml, $documentMainPartXml); $this->assertNotEquals($templateFooterXml, $documentFooterXml); + $this->assertEquals($embeddingText, $documentEmbedding); + return $documentFqfn; } From 880443c701e29961a418d797a147bbe2d876ffb3 Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 02:50:25 +0200 Subject: [PATCH 33/74] failGraciously() for all new functions that have mixed failure results. --- src/PhpWord/TemplateProcessor.php | 208 +++++++++++++++--------------- 1 file changed, 103 insertions(+), 105 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 156954185e..68873437c5 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -278,6 +278,24 @@ public function zipAddFromString($localname, $contents) return $this->zipClass->AddFromString($localname, $contents); } + /** + * If $throwException is true, it throws an exception, else it returns $elseReturn + * + * @param string $exceptionText + * @param bool $throwException + * @param mixed $elseReturn + * + * @return mixed + */ + private function failGraciously($exceptionText, $throwException, $elseReturn) + { + if ($throwException) { + throw new Exception($exceptionText); + } else { + return $elseReturn; + } + } + /** * Returns array of all variables in template. * @@ -305,7 +323,7 @@ public function getVariables() * @param integer $numberOfClones * @param bool $replace * @param bool $incrementVariables - * @param bool $throwexception + * @param bool $throwException * * @return string|null * @@ -316,7 +334,7 @@ public function cloneRow( $numberOfClones = 1, $replace = true, $incrementVariables = true, - $throwexception = false + $throwException = false ) { if ('${' !== substr($search, 0, 2) && '}' !== substr($search, -1)) { $search = '${' . $search . '}'; @@ -324,16 +342,14 @@ public function cloneRow( $tagPos = strpos($this->tempDocumentMainPart, $search); if (!$tagPos) { - if ($throwexception) { - throw new Exception( - "Can not clone row, template variable not found or variable contains markup." - ); - } else { - return null; - } + failGraciously( + "Can not clone row, template variable not found or variable contains markup.", + $throwException, + null + ); } - $rowStart = $this->findTagLeft('', $tagPos, $throwexception); // findRowStart + $rowStart = $this->findTagLeft('', $tagPos, $throwException); // findRowStart $rowEnd = $this->findTagRight('', $tagPos); // findRowEnd $xmlRow = $this->getSlice($rowStart, $rowEnd); @@ -342,7 +358,7 @@ public function cloneRow( // $extraRowStart = $rowEnd; $extraRowEnd = $rowEnd; while (true) { - $extraRowStart = $this->findTagLeft('', $extraRowEnd + 1, $throwexception); // findRowStart + $extraRowStart = $this->findTagLeft('', $extraRowEnd + 1, $throwException); // findRowStart $extraRowEnd = $this->findTagRight('', $extraRowEnd + 1); // findRowEnd if (!$extraRowEnd) { @@ -398,7 +414,7 @@ public function deleteRow($search) * @param integer $clones * @param boolean $replace * @param boolean $incrementVariables - * @param boolean $throwexception + * @param boolean $throwException * * @return string|null */ @@ -407,7 +423,7 @@ public function cloneBlock( $clones = 1, $replace = true, $incrementVariables = true, - $throwexception = false + $throwException = false ) { $startSearch = '${' . $blockname . '}'; $endSearch = '${/' . $blockname . '}'; @@ -420,7 +436,7 @@ public function cloneBlock( $clones, $replace, $incrementVariables, - $throwexception + $throwException ); } @@ -428,41 +444,35 @@ public function cloneBlock( $endTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); if (!$startTagPos || !$endTagPos) { - if ($throwexception) { - throw new Exception( - "Can not find block '$blockname', template variable not found or variable contains markup." - ); - } else { - return null; // Block not found, return null - } + failGraciously( + "Can not find block '$blockname', template variable not found or variable contains markup.", + $throwException, + null + ); } - $startBlockStart = $this->findTagLeft('', $startTagPos, $throwexception); // findBlockStart() + $startBlockStart = $this->findTagLeft('', $startTagPos, $throwException); // findBlockStart() $startBlockEnd = $this->findTagRight('', $startTagPos); // findBlockEnd() // $xmlStart = $this->getSlice($startBlockStart, $startBlockEnd); if (!$startBlockStart || !$startBlockEnd) { - if ($throwexception) { - throw new Exception( - "Can not find start paragraph around block '$blockname'" - ); - } else { - return false; - } + failGraciously( + "Can not find start paragraph around block '$blockname'", + $throwException, + false + ); } - $endBlockStart = $this->findTagLeft('', $endTagPos, $throwexception); // findBlockStart() + $endBlockStart = $this->findTagLeft('', $endTagPos, $throwException); // findBlockStart() $endBlockEnd = $this->findTagRight('', $endTagPos); // findBlockEnd() // $xmlEnd = $this->getSlice($endBlockStart, $endBlockEnd); if (!$endBlockStart || !$endBlockEnd) { - if ($throwexception) { - throw new Exception( - "Can not find end paragraph around block '$blockname'" - ); - } else { - return false; - } + failGraciously( + "Can not find end paragraph around block '$blockname'", + $throwException, + false + ); } if ($startBlockEnd == $endBlockEnd) { // inline block @@ -500,7 +510,7 @@ public function cloneBlock( * @param integer $clones * @param boolean $replace * @param boolean $incrementVariables - * @param boolean $throwexception + * @param boolean $throwException * * @return string|null */ @@ -511,31 +521,27 @@ public function cloneSegment( $clones = 1, $replace = true, $incrementVariables = true, - $throwexception = false + $throwException = false ) { $needlePos = strpos($this->{"tempDocument$docpart"}, $needle); if (!$needlePos) { - if ($throwexception) { - throw new Exception( - "Can not find segment '$needle', text not found or text contains markup." - ); - } else { - return null; // Segment not found, return null - } + failGraciously( + "Can not find segment '$needle', text not found or text contains markup.", + $throwException, + null + ); } - $startSegmentStart = $this->findTagLeft("<$xmltag>", $needlePos, $throwexception); + $startSegmentStart = $this->findTagLeft("<$xmltag>", $needlePos, $throwException); $endSegmentEnd = $this->findTagRight("", $needlePos); if (!$startSegmentStart || !$endSegmentEnd) { - if ($throwexception) { - throw new Exception( - "Can not find <$xmltag> around segment '$needle'" - ); - } else { - return false; - } + failGraciously( + "Can not find <$xmltag> around segment '$needle'", + $throwException, + false + ); } $xmlSegment = $this->getSlice($startSegmentStart, $endSegmentEnd); @@ -561,13 +567,13 @@ public function cloneSegment( * Get a block. (first block found) * * @param string $blockname - * @param boolean $throwexception + * @param boolean $throwException * * @return string|null */ - public function getBlock($blockname, $throwexception = false) + public function getBlock($blockname, $throwException = false) { - return $this->cloneBlock($blockname, 1, false, false, $throwexception); + return $this->cloneBlock($blockname, 1, false, false, $throwException); } /** @@ -576,26 +582,26 @@ public function getBlock($blockname, $throwexception = false) * @param string $needle * @param string $xmltag * @param string $docpart - * @param boolean $throwexception + * @param boolean $throwException * * @return string|null */ - public function getSegment($needle, $xmltag, $docpart = 'MainPart', $throwexception = false) + public function getSegment($needle, $xmltag, $docpart = 'MainPart', $throwException = false) { - return $this->cloneSegment($needle, $xmltag, $docpart, 1, false, false, $throwexception); + return $this->cloneSegment($needle, $xmltag, $docpart, 1, false, false, $throwException); } /** * Get a row. (first block found) * * @param string $rowname - * @param boolean $throwexception + * @param boolean $throwException * * @return string|null */ - public function getRow($rowname, $throwexception = false) + public function getRow($rowname, $throwException = false) { - return $this->cloneRow($rowname, 1, false, false, $throwexception); + return $this->cloneRow($rowname, 1, false, false, $throwException); } /** @@ -603,43 +609,39 @@ public function getRow($rowname, $throwexception = false) * * @param string $blockname * @param string $replacement - * @param boolean $throwexception + * @param boolean $throwException * * @return false on no replacement, true on replacement */ - public function replaceBlock($blockname, $replacement = '', $throwexception = false) + public function replaceBlock($blockname, $replacement = '', $throwException = false) { $startSearch = '${' . $blockname . '}'; $endSearch = '${/' . $blockname . '}'; if (substr($blockname, -1) == '/') { // singleton/closed block - return $this->replaceSegment($startSearch, 'w:p', $replacement, 'MainPart', $throwexception); + return $this->replaceSegment($startSearch, 'w:p', $replacement, 'MainPart', $throwException); } $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); $endTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); if (!$startTagPos || !$endTagPos) { - if ($throwexception) { - throw new Exception( - "Can not find block '$blockname', template variable not found or variable contains markup." - ); - } else { - return false; - } + failGraciously( + "Can not find block '$blockname', template variable not found or variable contains markup.", + $throwException, + false + ); } - $startBlockStart = $this->findTagLeft('', $startTagPos, $throwexception); // findBlockStart() + $startBlockStart = $this->findTagLeft('', $startTagPos, $throwException); // findBlockStart() $endBlockEnd = $this->findTagRight('', $endTagPos); // findBlockEnd() if (!$startBlockStart || !$endBlockEnd) { - if ($throwexception) { - throw new Exception( - "Can not find end paragraph around block '$blockname'" - ); - } else { - return false; - } + failGraciously( + "Can not find end paragraph around block '$blockname'", + $throwException, + false + ); } $startBlockEnd = $this->findTagRight('', $startTagPos); // findBlockEnd() @@ -664,35 +666,31 @@ public function replaceBlock($blockname, $replacement = '', $throwexception = fa * @param string $xmltag * @param string $replacement * @param string $docpart - * @param boolean $throwexception + * @param boolean $throwException * * @return false on no replacement, true on replacement */ - public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = 'MainPart', $throwexception = false) + public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = 'MainPart', $throwException = false) { $tagPos = strpos($this->{"tempDocument$docpart"}, $needle); if ($tagPos === false) { - if ($throwexception) { - throw new Exception( - "Can not find segment '$needle', text not found or text contains markup." - ); - } else { - return false; - } + failGraciously( + "Can not find segment '$needle', text not found or text contains markup.", + $throwException, + false + ); } - $segmentStart = $this->findTagLeft("<$xmltag>", $tagPos, $throwexception); + $segmentStart = $this->findTagLeft("<$xmltag>", $tagPos, $throwException); $segmentEnd = $this->findTagRight("", $tagPos); if (!$segmentStart || !$segmentEnd) { - if ($throwexception) { - throw new Exception( - "Can not find tag $xmltag around segment '$needle'." - ); - } else { - return false; - } + failGraciously( + "Can not find tag $xmltag around segment '$needle'.", + $throwException, + false + ); } $this->{"tempDocument$docpart"} = @@ -887,13 +885,13 @@ protected function getFooterName($index) * * @param string $tag * @param integer $offset - * @param boolean $throwexception + * @param boolean $throwException * * @return integer * * @throws \PhpOffice\PhpWord\Exception\Exception */ - protected function findTagLeft($tag, $offset = 0, $throwexception = false) + protected function findTagLeft($tag, $offset = 0, $throwException = false) { $tagStart = strrpos( $this->tempDocumentMainPart, @@ -909,11 +907,11 @@ protected function findTagLeft($tag, $offset = 0, $throwexception = false) ); } if (!$tagStart) { - if ($throwexception) { - throw new Exception('Can not find the start position of the item to clone.'); - } else { - return 0; - } + failGraciously( + "Can not find the start position of the item to clone.", + $throwException, + 0 + ); } return $tagStart; From 947ea09e925bfff5aeb9e11a96eed7af82038214 Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 05:25:28 +0200 Subject: [PATCH 34/74] forgot to return from this in failGraciously() --- src/PhpWord/TemplateProcessor.php | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 68873437c5..3b25ff24e0 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -342,7 +342,7 @@ public function cloneRow( $tagPos = strpos($this->tempDocumentMainPart, $search); if (!$tagPos) { - failGraciously( + return $this->failGraciously( "Can not clone row, template variable not found or variable contains markup.", $throwException, null @@ -444,7 +444,7 @@ public function cloneBlock( $endTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); if (!$startTagPos || !$endTagPos) { - failGraciously( + return $this->failGraciously( "Can not find block '$blockname', template variable not found or variable contains markup.", $throwException, null @@ -456,7 +456,7 @@ public function cloneBlock( // $xmlStart = $this->getSlice($startBlockStart, $startBlockEnd); if (!$startBlockStart || !$startBlockEnd) { - failGraciously( + return $this->failGraciously( "Can not find start paragraph around block '$blockname'", $throwException, false @@ -468,7 +468,7 @@ public function cloneBlock( // $xmlEnd = $this->getSlice($endBlockStart, $endBlockEnd); if (!$endBlockStart || !$endBlockEnd) { - failGraciously( + return $this->failGraciously( "Can not find end paragraph around block '$blockname'", $throwException, false @@ -526,7 +526,7 @@ public function cloneSegment( $needlePos = strpos($this->{"tempDocument$docpart"}, $needle); if (!$needlePos) { - failGraciously( + return $this->failGraciously( "Can not find segment '$needle', text not found or text contains markup.", $throwException, null @@ -537,7 +537,7 @@ public function cloneSegment( $endSegmentEnd = $this->findTagRight("", $needlePos); if (!$startSegmentStart || !$endSegmentEnd) { - failGraciously( + return $this->failGraciously( "Can not find <$xmltag> around segment '$needle'", $throwException, false @@ -626,7 +626,7 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa $endTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); if (!$startTagPos || !$endTagPos) { - failGraciously( + return $this->failGraciously( "Can not find block '$blockname', template variable not found or variable contains markup.", $throwException, false @@ -637,7 +637,7 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa $endBlockEnd = $this->findTagRight('', $endTagPos); // findBlockEnd() if (!$startBlockStart || !$endBlockEnd) { - failGraciously( + return $this->failGraciously( "Can not find end paragraph around block '$blockname'", $throwException, false @@ -675,7 +675,7 @@ public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = ' $tagPos = strpos($this->{"tempDocument$docpart"}, $needle); if ($tagPos === false) { - failGraciously( + return $this->failGraciously( "Can not find segment '$needle', text not found or text contains markup.", $throwException, false @@ -686,7 +686,7 @@ public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = ' $segmentEnd = $this->findTagRight("", $tagPos); if (!$segmentStart || !$segmentEnd) { - failGraciously( + return $this->failGraciously( "Can not find tag $xmltag around segment '$needle'.", $throwException, false @@ -907,7 +907,7 @@ protected function findTagLeft($tag, $offset = 0, $throwException = false) ); } if (!$tagStart) { - failGraciously( + return $this->failGraciously( "Can not find the start position of the item to clone.", $throwException, 0 From 4d0ec75fc6ef381e327158399612cd9f8c869cd1 Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 10:07:22 +0200 Subject: [PATCH 35/74] new bool variable TemplateProcessor::$ensureMacroCompletion --- src/PhpWord/TemplateProcessor.php | 9 ++-- tests/PhpWord/TemplateProcessorTest.php | 70 +++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 3b25ff24e0..dd47d644c8 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -29,6 +29,7 @@ class TemplateProcessor { const MAXIMUM_REPLACEMENTS_DEFAULT = -1; + public static $ensureMacroCompletion = true; /** * ZipArchive object. * @@ -180,7 +181,7 @@ public function applyXslStyleSheet($xslDomDocument, $xslOptions = array(), $xslO */ protected static function ensureMacroCompleted($macro) { - if (substr($macro, 0, 2) !== '${' && substr($macro, -1) !== '}') { + if (TemplateProcessor::$ensureMacroCompletion && substr($macro, 0, 2) !== '${' && substr($macro, -1) !== '}') { $macro = '${' . $macro . '}'; } @@ -336,11 +337,7 @@ public function cloneRow( $incrementVariables = true, $throwException = false ) { - if ('${' !== substr($search, 0, 2) && '}' !== substr($search, -1)) { - $search = '${' . $search . '}'; - } - - $tagPos = strpos($this->tempDocumentMainPart, $search); + $tagPos = strpos($this->tempDocumentMainPart, $this->ensureMacroCompleted($search)); if (!$tagPos) { return $this->failGraciously( "Can not clone row, template variable not found or variable contains markup.", diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 0f978712ae..ab85811600 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -269,6 +269,7 @@ private function getOpenTemplateProcessor($name) $ESTR = 'class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor {' . 'public function __construct($instance){return parent::__construct($instance);}' + . 'public function __call($method, $args) {return call_user_func_array(array($this, $method), $args);}' . 'public function __get($key){return $this->$key;}' . 'public function __set($key, $val){return $this->$key = $val;} };' . 'return new OpenTemplateProcessor("'.$name.'");'; @@ -634,4 +635,73 @@ public function testMakeTable() $templateProcessor->toXML($cell, 'w:p') ); } + + /** + * @covers ::fixBrokenMacros + * @covers ::ensureMacroCompleted + * @test + */ + public function testFixBrokenMacros() + { + $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $xmlStr = '${aaaaa'. + '}'; + $macro = $templateProcessor->ensureMacroCompleted('aaaaa'); + $this->assertEquals( + $macro, + '${aaaaa}' + ); + + TemplateProcessor::$ensureMacroCompletion = false; + $this->assertEquals( + $templateProcessor->ensureMacroCompleted('aaaaa'), + 'aaaaa' + ); + TemplateProcessor::$ensureMacroCompletion = true; + + $xmlFixed = $templateProcessor->fixBrokenMacros($xmlStr); + $this->assertEquals( + 1, + substr_count($xmlFixed, $macro), + "could not find '$macro' in: $xmlFixed" + ); + } + + /** + * @covers ::failGraciously + * @covers ::cloneSegment + * @test + */ + public function testFailGraciously() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + + $this->assertEquals( + null, + $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 'MainPart', 1, true, true, false) + ); + + $this->assertEquals( + false, + $templateProcessor->cloneSegment('tableHeader', 'DESPACITO', 'MainPart', 1, true, true, false) + ); + } + + /** + * XSL stylesheet can be applied on failure of loading XML from template. + * + * @covers ::failGraciously + * @covers ::cloneSegment + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage Can not find segment 'I-DO-NOT-EXIST', text not found or text contains markup + * @test + */ + final public function testThrowFailGraciously() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $this->assertEquals( + null, + $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 'MainPart', 1, true, true, true) + ); + } } From 66fbbe747a2f50f8c8cc91f298b8c16ebcc8d7e2 Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 11:16:22 +0200 Subject: [PATCH 36/74] setValueForPart needs strings, not arrays. Thanks to Scrutinizer for catching this one --- src/PhpWord/TemplateProcessor.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index dd47d644c8..110fff5acc 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -232,9 +232,14 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ $replace = $xmlEscaper->escape($replace); } - $this->tempDocumentHeaders = $this->setValueForPart($search, $replace, $this->tempDocumentHeaders, $limit); $this->tempDocumentMainPart = $this->setValueForPart($search, $replace, $this->tempDocumentMainPart, $limit); - $this->tempDocumentFooters = $this->setValueForPart($search, $replace, $this->tempDocumentFooters, $limit); + + $documentParts = ['tempDocumentHeaders', 'tempDocumentFooters']; + foreach ($documentParts as $tempDocumentParts) { + foreach ($this->{$tempDocumentParts} as &$tempDocumentPart) { + $tempDocumentPart = $this->setValueForPart($search, $replace, $tempDocumentPart, $limit); + } + } } /** From 9f63a84bfa202eb699210821415f9cd37570a8bf Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 11:18:03 +0200 Subject: [PATCH 37/74] setValueForPart needs strings, not arrays. Thanks to Scrutinizer for catching this one --- src/PhpWord/TemplateProcessor.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 110fff5acc..83f135648c 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -169,9 +169,9 @@ public function applyXslStyleSheet($xslDomDocument, $xslOptions = array(), $xslO throw new Exception('Could not set values for the given XSL style sheet parameters.'); } - $this->tempDocumentHeaders = $this->transformXml($this->tempDocumentHeaders, $xsltProcessor); - $this->tempDocumentMainPart = $this->transformXml($this->tempDocumentMainPart, $xsltProcessor); - $this->tempDocumentFooters = $this->transformXml($this->tempDocumentFooters, $xsltProcessor); + $this->tempDocumentHeaders = $this->transformXml((array)$this->tempDocumentHeaders, $xsltProcessor); + $this->tempDocumentMainPart = $this->transformXml((string)$this->tempDocumentMainPart, $xsltProcessor); + $this->tempDocumentFooters = $this->transformXml((array)$this->tempDocumentFooters, $xsltProcessor); } /** From ddfa934ae1d4eb34af49de86c71430d0d4a45020 Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 12:06:50 +0200 Subject: [PATCH 38/74] fixes *Segment() functions when trying to replace Footers and Headers --- src/PhpWord/TemplateProcessor.php | 57 ++++++++++++++++--------------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 83f135648c..afcff179f8 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -243,31 +243,26 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ } /** - * Replaces a closed block with text. The text can be multiline. + * Replaces a closed block with text * - * @param mixed $blockname - * @param mixed $replace + * @param string $blockname Your macro must end with slash, i.e.: ${value/} + * @param mixed $replace Array or the text can be multiline (contain \n). It will cloneBlock(). * @param integer $limit * * @return void */ public function setBlock($blockname, $replace, $limit = self::MAXIMUM_REPLACEMENTS_DEFAULT) { - if (is_array($blockname)) { - $hash = array_combine($blockname, $replace); - foreach ($hash as $block => $value) { - $this->setBlock($block, $value, $limit); + if (preg_match('~\R~u', $replace)) { + $replace = preg_split('~\R~u', $replace); + } + if (is_array($replace)) { + $this->cloneBlock($blockname, count($replace), true, false); + foreach ($replace as $oneVal) { + $this->setValue($blockname, $oneVal, 1); } } else { - if (preg_match('~\R~u', $replace)) { - $replaces = preg_split('~\R~u', $replace); - $this->cloneBlock($blockname, count($replaces), true, false); - foreach ($replaces as $oneVal) { - $this->setValue($blockname, $oneVal, 1); - } - } else { - $this->setValue($blockname, $replace, $limit); - } + $this->setValue($blockname, $replace, $limit); } } @@ -581,9 +576,9 @@ public function getBlock($blockname, $throwException = false) /** * Get a segment. (first segment found) * - * @param string $needle - * @param string $xmltag - * @param string $docpart + * @param string $needle If this is a macro, you need to add the ${} yourself. + * @param string $xmltag an xml tag without brackets, for example: w:p + * @param string $docpart 'MainPart' (default) 'Footers:0' (first footer) or 'Headers:1' (second header) * @param boolean $throwException * * @return string|null @@ -664,17 +659,23 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa /** * Replace a segment. * - * @param string $needle - * @param string $xmltag + * @param string $needle If this is a macro, you need to add the ${} yourself. + * @param string $xmltag an xml tag without brackets, for example: w:p * @param string $replacement - * @param string $docpart + * @param string $docpart 'MainPart' (default) 'Footers:0' (first footer) or 'Headers:1' (second header) * @param boolean $throwException * * @return false on no replacement, true on replacement */ public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = 'MainPart', $throwException = false) { - $tagPos = strpos($this->{"tempDocument$docpart"}, $needle); + $docpart = preg_split('/:/', $docpart); + if (count($docpart)>1) { + $part = &$this->{"tempDocument$docpart[0]"}[$docpart[1]]; + } else { + $part = &$this->{"tempDocument$docpart[0]"}; + } + $tagPos = strpos($part, $needle); if ($tagPos === false) { return $this->failGraciously( @@ -695,7 +696,7 @@ public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = ' ); } - $this->{"tempDocument$docpart"} = + $part = $this->getSlice(0, $segmentStart) . $replacement . $this->getSlice($segmentEnd); @@ -718,9 +719,9 @@ public function deleteBlock($blockname) /** * Delete a segment of text. * - * @param string $needle - * @param string $xmltag - * @param string $docpart + * @param string $needle If this is a macro, you need to add the ${} yourself. + * @param string $xmltag an xml tag without brackets, for example: w:p + * @param string $docpart 'MainPart' (default) 'Footers:0' (first footer) or 'Headers:1' (second header) * * @return true on segment found and deleted, false on segment not found. */ @@ -732,7 +733,7 @@ public function deleteSegment($needle, $xmltag, $docpart = 'MainPart') /** * Saves the result document. * - * @return string + * @return string The filename of the document * * @throws \PhpOffice\PhpWord\Exception\Exception */ From 56f35886ea1c092718ff70811f7a031769f0acf5 Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 14:09:37 +0200 Subject: [PATCH 39/74] modified findTagRight, findTagLeft and getSlice to be aware of Headers and Footers. Segments now allow acations on Headers and Footers. --- src/PhpWord/TemplateProcessor.php | 142 +++++++++++++----------- tests/PhpWord/TemplateProcessorTest.php | 59 +++++++++- 2 files changed, 135 insertions(+), 66 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index afcff179f8..695e1ccdca 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -61,7 +61,7 @@ class TemplateProcessor * * @var string[] */ - protected $tempDocumentFooters = array(); + public $tempDocumentFooters = array(); /** * @since 0.12.0 Throws CreateTemporaryFileException and CopyFileException instead of Exception. @@ -346,24 +346,29 @@ public function cloneRow( ); } - $rowStart = $this->findTagLeft('', $tagPos, $throwException); // findRowStart - $rowEnd = $this->findTagRight('', $tagPos); // findRowEnd - $xmlRow = $this->getSlice($rowStart, $rowEnd); + $rowStart = $this->findTagLeft($this->tempDocumentMainPart, '', $tagPos, $throwException); + $rowEnd = $this->findTagRight($this->tempDocumentMainPart, '', $tagPos); + $xmlRow = $this->getSlice($this->tempDocumentMainPart, $rowStart, $rowEnd); // Check if there's a cell spanning multiple rows. if (preg_match('##', $xmlRow)) { // $extraRowStart = $rowEnd; $extraRowEnd = $rowEnd; while (true) { - $extraRowStart = $this->findTagLeft('', $extraRowEnd + 1, $throwException); // findRowStart - $extraRowEnd = $this->findTagRight('', $extraRowEnd + 1); // findRowEnd + $extraRowStart = $this->findTagLeft( + $this->tempDocumentMainPart, + '', + $extraRowEnd + 1, + $throwException + ); + $extraRowEnd = $this->findTagRight($this->tempDocumentMainPart, '', $extraRowEnd + 1); if (!$extraRowEnd) { break; } // If tmpXmlRow doesn't contain continue, this row is no longer part of the spanned row. - $tmpXmlRow = $this->getSlice($extraRowStart, $extraRowEnd); + $tmpXmlRow = $this->getSlice($this->tempDocumentMainPart, $extraRowStart, $extraRowEnd); if (!preg_match('##', $tmpXmlRow) && !preg_match('##', $tmpXmlRow) ) { @@ -372,11 +377,11 @@ public function cloneRow( // This row was a spanned row, update $rowEnd and search for the next row. $rowEnd = $extraRowEnd; } - $xmlRow = $this->getSlice($rowStart, $rowEnd); + $xmlRow = $this->getSlice($this->tempDocumentMainPart, $rowStart, $rowEnd); } if ($replace) { - $result = $this->getSlice(0, $rowStart); + $result = $this->getSlice($this->tempDocumentMainPart, 0, $rowStart); for ($i = 1; $i <= $numberOfClones; $i++) { if ($incrementVariables) { $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow); @@ -384,7 +389,7 @@ public function cloneRow( $result .= $xmlRow; } } - $result .= $this->getSlice($rowEnd); + $result .= $this->getSlice($this->tempDocumentMainPart, $rowEnd); $this->tempDocumentMainPart = $result; } @@ -448,9 +453,8 @@ public function cloneBlock( ); } - $startBlockStart = $this->findTagLeft('', $startTagPos, $throwException); // findBlockStart() - $startBlockEnd = $this->findTagRight('', $startTagPos); // findBlockEnd() - // $xmlStart = $this->getSlice($startBlockStart, $startBlockEnd); + $startBlockStart = $this->findTagLeft($this->tempDocumentMainPart, '', $startTagPos, $throwException); + $startBlockEnd = $this->findTagRight($this->tempDocumentMainPart, '', $startTagPos); if (!$startBlockStart || !$startBlockEnd) { return $this->failGraciously( @@ -460,9 +464,8 @@ public function cloneBlock( ); } - $endBlockStart = $this->findTagLeft('', $endTagPos, $throwException); // findBlockStart() - $endBlockEnd = $this->findTagRight('', $endTagPos); // findBlockEnd() - // $xmlEnd = $this->getSlice($endBlockStart, $endBlockEnd); + $endBlockStart = $this->findTagLeft($this->tempDocumentMainPart, '', $endTagPos, $throwException); + $endBlockEnd = $this->findTagRight($this->tempDocumentMainPart, '', $endTagPos); if (!$endBlockStart || !$endBlockEnd) { return $this->failGraciously( @@ -479,10 +482,10 @@ public function cloneBlock( $endBlockEnd = $endTagPos + strlen($endSearch); } - $xmlBlock = $this->getSlice($startBlockEnd, $endBlockStart); + $xmlBlock = $this->getSlice($this->tempDocumentMainPart, $startBlockEnd, $endBlockStart); if ($replace) { - $result = $this->getSlice(0, $startBlockStart); + $result = $this->getSlice($this->tempDocumentMainPart, 0, $startBlockStart); for ($i = 1; $i <= $clones; $i++) { if ($incrementVariables) { $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlBlock); @@ -490,7 +493,7 @@ public function cloneBlock( $result .= $xmlBlock; } } - $result .= $this->getSlice($endBlockEnd); + $result .= $this->getSlice($this->tempDocumentMainPart, $endBlockEnd); $this->tempDocumentMainPart = $result; } @@ -503,7 +506,7 @@ public function cloneBlock( * * @param string $needle * @param string $xmltag - * @param string $docpart + * @param string $docPart * @param integer $clones * @param boolean $replace * @param boolean $incrementVariables @@ -514,13 +517,19 @@ public function cloneBlock( public function cloneSegment( $needle, $xmltag, - $docpart = 'MainPart', + $docPart = 'MainPart', $clones = 1, $replace = true, $incrementVariables = true, $throwException = false ) { - $needlePos = strpos($this->{"tempDocument$docpart"}, $needle); + $docPart = preg_split('/:/', $docPart); + if (count($docPart)>1) { + $part = &$this->{"tempDocument".$docPart[0]}[$docPart[1]]; + } else { + $part = &$this->{"tempDocument".$docPart[0]}; + } + $needlePos = strpos($part, $needle); if (!$needlePos) { return $this->failGraciously( @@ -530,8 +539,8 @@ public function cloneSegment( ); } - $startSegmentStart = $this->findTagLeft("<$xmltag>", $needlePos, $throwException); - $endSegmentEnd = $this->findTagRight("", $needlePos); + $startSegmentStart = $this->findTagLeft($part, "<$xmltag>", $needlePos, $throwException); + $endSegmentEnd = $this->findTagRight($part, "", $needlePos); if (!$startSegmentStart || !$endSegmentEnd) { return $this->failGraciously( @@ -541,10 +550,10 @@ public function cloneSegment( ); } - $xmlSegment = $this->getSlice($startSegmentStart, $endSegmentEnd); + $xmlSegment = $this->getSlice($part, $startSegmentStart, $endSegmentEnd); if ($replace) { - $result = $this->getSlice(0, $startSegmentStart); + $result = $this->getSlice($part, 0, $startSegmentStart); for ($i = 1; $i <= $clones; $i++) { if ($incrementVariables) { $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlSegment); @@ -552,9 +561,9 @@ public function cloneSegment( $result .= $xmlSegment; } } - $result .= $this->getSlice($endSegmentEnd); + $result .= $this->getSlice($part, $endSegmentEnd); - $this->{"tempDocument$docpart"} = $result; + $part = $result; } return $xmlSegment; @@ -578,14 +587,14 @@ public function getBlock($blockname, $throwException = false) * * @param string $needle If this is a macro, you need to add the ${} yourself. * @param string $xmltag an xml tag without brackets, for example: w:p - * @param string $docpart 'MainPart' (default) 'Footers:0' (first footer) or 'Headers:1' (second header) + * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) * @param boolean $throwException * * @return string|null */ - public function getSegment($needle, $xmltag, $docpart = 'MainPart', $throwException = false) + public function getSegment($needle, $xmltag, $docPart = 'MainPart', $throwException = false) { - return $this->cloneSegment($needle, $xmltag, $docpart, 1, false, false, $throwException); + return $this->cloneSegment($needle, $xmltag, $docPart, 1, false, false, $throwException); } /** @@ -630,8 +639,8 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa ); } - $startBlockStart = $this->findTagLeft('', $startTagPos, $throwException); // findBlockStart() - $endBlockEnd = $this->findTagRight('', $endTagPos); // findBlockEnd() + $startBlockStart = $this->findTagLeft($this->tempDocumentMainPart, '', $startTagPos, $throwException); + $endBlockEnd = $this->findTagRight($this->tempDocumentMainPart, '', $endTagPos); if (!$startBlockStart || !$endBlockEnd) { return $this->failGraciously( @@ -641,16 +650,16 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa ); } - $startBlockEnd = $this->findTagRight('', $startTagPos); // findBlockEnd() + $startBlockEnd = $this->findTagRight($this->tempDocumentMainPart, '', $startTagPos); if ($startBlockEnd == $endBlockEnd) { // inline block $startBlockStart = $startTagPos; $endBlockEnd = $endTagPos + strlen($endSearch); } $this->tempDocumentMainPart = - $this->getSlice(0, $startBlockStart) + $this->getSlice($this->tempDocumentMainPart, 0, $startBlockStart) . $replacement - . $this->getSlice($endBlockEnd); + . $this->getSlice($this->tempDocumentMainPart, $endBlockEnd); return true; } @@ -662,22 +671,22 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa * @param string $needle If this is a macro, you need to add the ${} yourself. * @param string $xmltag an xml tag without brackets, for example: w:p * @param string $replacement - * @param string $docpart 'MainPart' (default) 'Footers:0' (first footer) or 'Headers:1' (second header) + * @param string $docPart 'MainPart' (default) 'Footers:0' (first footer) or 'Headers:1' (second header) * @param boolean $throwException * * @return false on no replacement, true on replacement */ - public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = 'MainPart', $throwException = false) + public function replaceSegment($needle, $xmltag, $replacement = '', $docPart = 'MainPart', $throwException = false) { - $docpart = preg_split('/:/', $docpart); - if (count($docpart)>1) { - $part = &$this->{"tempDocument$docpart[0]"}[$docpart[1]]; + $docPart = preg_split('/:/', $docPart); + if (count($docPart)>1) { + $part = &$this->{"tempDocument$docPart[0]"}[$docPart[1]]; } else { - $part = &$this->{"tempDocument$docpart[0]"}; + $part = &$this->{"tempDocument$docPart[0]"}; } - $tagPos = strpos($part, $needle); + $needlePos = strpos($part, $needle); - if ($tagPos === false) { + if ($needlePos === false) { return $this->failGraciously( "Can not find segment '$needle', text not found or text contains markup.", $throwException, @@ -685,8 +694,8 @@ public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = ' ); } - $segmentStart = $this->findTagLeft("<$xmltag>", $tagPos, $throwException); - $segmentEnd = $this->findTagRight("", $tagPos); + $segmentStart = $this->findTagLeft($part, "<$xmltag>", $needlePos, $throwException); + $segmentEnd = $this->findTagRight($part, "", $needlePos); if (!$segmentStart || !$segmentEnd) { return $this->failGraciously( @@ -697,9 +706,9 @@ public function replaceSegment($needle, $xmltag, $replacement = '', $docpart = ' } $part = - $this->getSlice(0, $segmentStart) + $this->getSlice($part, 0, $segmentStart) . $replacement - . $this->getSlice($segmentEnd); + . $this->getSlice($part, $segmentEnd); return true; } @@ -721,13 +730,13 @@ public function deleteBlock($blockname) * * @param string $needle If this is a macro, you need to add the ${} yourself. * @param string $xmltag an xml tag without brackets, for example: w:p - * @param string $docpart 'MainPart' (default) 'Footers:0' (first footer) or 'Headers:1' (second header) + * @param string $docPart 'MainPart' (default) 'Footers:0' (first footer) or 'Headers:1' (second header) * * @return true on segment found and deleted, false on segment not found. */ - public function deleteSegment($needle, $xmltag, $docpart = 'MainPart') + public function deleteSegment($needle, $xmltag, $docPart = 'MainPart') { - return $this->replaceSegment($needle, $xmltag, '', $docpart, false); + return $this->replaceSegment($needle, $xmltag, '', $docPart, false); } /** @@ -886,27 +895,28 @@ protected function getFooterName($index) /** * Find the start position of the nearest tag before $offset. * - * @param string $tag - * @param integer $offset + * @param string $searchString The string we are searching in (the mainbody or an array element of Footers/Headers) + * @param string $tag Fully qualified tag, for example: '' + * @param integer $offset Do not look from the beginning, but starting at $offset * @param boolean $throwException * * @return integer * * @throws \PhpOffice\PhpWord\Exception\Exception */ - protected function findTagLeft($tag, $offset = 0, $throwException = false) + protected function findTagLeft(&$searchString, $tag, $offset = 0, $throwException = false) { $tagStart = strrpos( - $this->tempDocumentMainPart, + $searchString, substr($tag, 0, -1) . ' ', - ((strlen($this->tempDocumentMainPart) - $offset) * -1) + ((strlen($searchString) - $offset) * -1) ); if (!$tagStart) { $tagStart = strrpos( - $this->tempDocumentMainPart, + $searchString, $tag, - ((strlen($this->tempDocumentMainPart) - $offset) * -1) + ((strlen($searchString) - $offset) * -1) ); } if (!$tagStart) { @@ -923,14 +933,15 @@ protected function findTagLeft($tag, $offset = 0, $throwException = false) /** * Find the end position of the nearest $tag after $offset. * - * @param string $tag - * @param integer $offset + * @param string $searchString The string we are searching in (the MainPart or an array element of Footers/Headers) + * @param string $tag Fully qualified tag, for example: '' + * @param integer $offset Do not look from the beginning, but starting at $offset * * @return integer */ - protected function findTagRight($tag, $offset = 0) + protected function findTagRight(&$searchString, $tag, $offset = 0, $docPart = 'MainPart') { - $pos = strpos($this->tempDocumentMainPart, $tag, $offset); + $pos = strpos($searchString, $tag, $offset); if ($pos !== false) { return $pos + strlen($tag); } else { @@ -941,18 +952,19 @@ protected function findTagRight($tag, $offset = 0) /** * Get a slice of a string. * + * @param string $searchString The string we are searching in (the MainPart or an array element of Footers/Headers) * @param integer $startPosition * @param integer $endPosition * * @return string */ - protected function getSlice($startPosition, $endPosition = 0) + protected function getSlice(&$searchString, $startPosition, $endPosition = 0) { if (!$endPosition) { - $endPosition = strlen($this->tempDocumentMainPart); + $endPosition = strlen($searchString); } - return substr($this->tempDocumentMainPart, $startPosition, ($endPosition - $startPosition)); + return substr($searchString, $startPosition, ($endPosition - $startPosition)); } /** diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index ab85811600..950813ca88 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -42,7 +42,7 @@ final public function testTemplateCanBeSavedInTemporaryLocation() $templateProcessor->applyXslStyleSheet($xslDomDocument, array('needle' => $needle)); } - $embeddingText = "The quick Brown Fox jumped over the lazy unitTester"; + $embeddingText = "The quick Brown Fox jumped over the lazy^H^H^H^Htired unitTester"; $templateProcessor->zipAddFromString('word/embeddings/fox.bin', $embeddingText); $documentFqfn = $templateProcessor->save(); @@ -687,6 +687,63 @@ public function testFailGraciously() ); } + /** + * @covers ::cloneSegment + * @covers ::getVariables + * @covers ::setBlock + * @covers ::saveAs + * @test + */ + public function testCloneSegment() + { + $testDocument = __DIR__ . '/_files/templates/header-footer.docx'; + $templateProcessor = new TemplateProcessor($testDocument); + + $this->assertEquals( + ['documentContent', 'headerValue', 'footerValue'], + $templateProcessor->getVariables() + ); + + $zipFile = new \ZipArchive(); + $zipFile->open($testDocument); + $originalFooterXml = $zipFile->getFromName('word/footer1.xml'); + if (false === $zipFile->close()) { + throw new \Exception("Could not close zip file"); + } + + $segment = $templateProcessor->cloneSegment('${footerValue}', 'w:p', 'Footers:1', 2); + $this->assertNotNull($segment); + $segment = $templateProcessor->cloneSegment('${headerValue}', 'w:p', 'Headers:1', 2); + $this->assertNotNull($segment); + $segment = $templateProcessor->cloneSegment('${documentContent}', 'w:p', 'MainPart', 1); + $this->assertNotNull($segment); + $templateProcessor->setBlock('headerValue#1', "In the end, it doesn't even matter."); + + $docName = 'header-footer-test-result.docx'; + $templateProcessor->saveAs($docName); + $docFound = file_exists($docName); + if ($docFound) { + $zipFile->open($docName); + $updatedFooterXml = $zipFile->getFromName('word/footer1.xml'); + if (false === $zipFile->close()) { + throw new \Exception("Could not close zip file"); + } + + $this->assertNotEquals( + $originalFooterXml, + $updatedFooterXml + ); + + $templateProcessor2 = new TemplateProcessor($docName); + $this->assertEquals( + ['documentContent#1', 'headerValue#2', 'footerValue#1', 'footerValue#2'], + $templateProcessor2->getVariables() + ); + unlink($docName); + } + $this->assertTrue($docFound); + } + /** * XSL stylesheet can be applied on failure of loading XML from template. * From aafb1acaa7c23245d67479491b5b11f3737f106f Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 14:11:42 +0200 Subject: [PATCH 40/74] make $tempDocumentFooters protected again (was debugging) --- src/PhpWord/TemplateProcessor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 695e1ccdca..6713060068 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -61,7 +61,7 @@ class TemplateProcessor * * @var string[] */ - public $tempDocumentFooters = array(); + protected $tempDocumentFooters = array(); /** * @since 0.12.0 Throws CreateTemporaryFileException and CopyFileException instead of Exception. From af358ad93c297c5ac3c99cb3e83bb7349e48744e Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 14:37:02 +0200 Subject: [PATCH 41/74] Stronger typecasting to quench Scrutinizer.... --- src/PhpWord/TemplateProcessor.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 6713060068..e5274907a2 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -139,11 +139,11 @@ protected function transformXml($xml, $xsltProcessor) foreach ($xml as &$item) { $item = $this->transformSingleXml($item, $xsltProcessor); } + return (array)$xml; } else { $xml = $this->transformSingleXml($xml, $xsltProcessor); + return (string)$xml; } - - return $xml; } /** @@ -169,9 +169,9 @@ public function applyXslStyleSheet($xslDomDocument, $xslOptions = array(), $xslO throw new Exception('Could not set values for the given XSL style sheet parameters.'); } - $this->tempDocumentHeaders = $this->transformXml((array)$this->tempDocumentHeaders, $xsltProcessor); - $this->tempDocumentMainPart = $this->transformXml((string)$this->tempDocumentMainPart, $xsltProcessor); - $this->tempDocumentFooters = $this->transformXml((array)$this->tempDocumentFooters, $xsltProcessor); + $this->tempDocumentHeaders = (array)$this->transformXml($this->tempDocumentHeaders, $xsltProcessor); + $this->tempDocumentMainPart = (string)$this->transformXml($this->tempDocumentMainPart, $xsltProcessor); + $this->tempDocumentFooters = (array)$this->transformXml($this->tempDocumentFooters, $xsltProcessor); } /** @@ -939,7 +939,7 @@ protected function findTagLeft(&$searchString, $tag, $offset = 0, $throwExceptio * * @return integer */ - protected function findTagRight(&$searchString, $tag, $offset = 0, $docPart = 'MainPart') + protected function findTagRight(&$searchString, $tag, $offset = 0) { $pos = strpos($searchString, $tag, $offset); if ($pos !== false) { From d7ede2e9ecfc5a1f3792af366df223a28e2c73e7 Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 11 Oct 2017 15:48:27 +0200 Subject: [PATCH 42/74] More testcases, better documentation --- src/PhpWord/TemplateProcessor.php | 17 ++--- tests/PhpWord/TemplateProcessorTest.php | 88 ++++++++++++++++++++++++- 2 files changed, 92 insertions(+), 13 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index e5274907a2..33135439ce 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -664,7 +664,6 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa return true; } - /** * Replace a segment. * @@ -968,13 +967,9 @@ protected function getSlice(&$searchString, $startPosition, $endPosition = 0) } /** - * Return a table. - * - * @param obj an object - * @param string tag - * @param bool withTags + * Returns a table object from the Word2007 / PhpWord(). * - * @return string|false + * @return object of type PhpOffice\PhpWord\Element\Table */ public function makeTable() { @@ -984,11 +979,11 @@ public function makeTable() /** * Convert a Word2007 object to xml. * - * @param obj an object - * @param string tag - * @param bool withTags + * @param object $obj an object + * @param string $tag a tag like 'w:p' or 'w:tbl' if the tag is not found, return the whole xml as string. + * @param bool $withTags include ... xml tags in the result * - * @return string|false + * @return string|Exception */ public function toXML($obj, $tag = '', $withTags = true) { diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 950813ca88..1002d69201 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -670,6 +670,8 @@ public function testFixBrokenMacros() /** * @covers ::failGraciously * @covers ::cloneSegment + * @covers ::replaceSegment + * @covers ::deleteSegment * @test */ public function testFailGraciously() @@ -685,6 +687,21 @@ public function testFailGraciously() false, $templateProcessor->cloneSegment('tableHeader', 'DESPACITO', 'MainPart', 1, true, true, false) ); + + $this->assertEquals( + null, + $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 'IOU', 'MainPart', false) + ); + + $this->assertEquals( + false, + $templateProcessor->replaceSegment('tableHeader', 'we:be', 'BodyMoving', 'MainPart', false) + ); + + $this->assertEquals( + false, + $templateProcessor->deleteSegment('tableHeader', '>sabotage<', 'MainPart', 1, true, true, false) + ); } /** @@ -745,8 +762,6 @@ public function testCloneSegment() } /** - * XSL stylesheet can be applied on failure of loading XML from template. - * * @covers ::failGraciously * @covers ::cloneSegment * @expectedException \PhpOffice\PhpWord\Exception\Exception @@ -761,4 +776,73 @@ final public function testThrowFailGraciously() $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 'MainPart', 1, true, true, true) ); } + + /** + * @covers ::failGraciously + * @covers ::replaceSegment + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage Can not find segment 'I-DO-NOT-EXIST', text not found or text contains markup + * @test + */ + final public function testAnotherThrowFailGraciously() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $this->assertEquals( + null, + $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 'IOU', 'MainPart', true) + ); + } + + /** + * @covers ::cloneSegment + * @covers ::getVariables + * @covers ::setBlock + * @covers ::saveAs + * @test + */ + public function testToXML() + { + $testDocument = __DIR__ . '/_files/templates/header-footer.docx'; + $templateProcessor = new TemplateProcessor($testDocument); + $myTable = $templateProcessor->makeTable(); + $randomText = "I was going to go to school, but then I got testcased."; + $resultXml = '' . $randomText . ''; + $myTable->addRow()->addCell()->addText($randomText); + $this->assertEquals( + $resultXml, + $templateProcessor->toXML($myTable, 'w:t') + ); + } + + /** + * @covers ::toXML + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage toXML(): First parameter is not an object + * @test + */ + final public function testToXMLException() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $this->assertEquals( + null, + $templateProcessor->toXML(null, 'w:t') + ); + } + + /** + * @covers ::toXML + * @covers ::makeTable + * @expectedException Error + * @expectedExceptionMessage Call to undefined method PhpOffice\PhpWord\Element\Table::createRow() + * @test + */ + final public function testToXMLException2() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $myRow = $templateProcessor->makeTable()->createRow(); + $this->assertEquals( + null, + $templateProcessor->toXML($myRow) + ); + } } From 84173c8546d27b176f17b9fde7804654ff4c548c Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 14 Oct 2017 00:46:09 +0200 Subject: [PATCH 43/74] Fix fixBrokenMacros() but it is slower. Remove makeTable() and toXML(), they will go to separate class. --- src/PhpWord/TemplateProcessor.php | 67 +++----------- tests/PhpWord/TemplateProcessorTest.php | 113 ++++-------------------- 2 files changed, 31 insertions(+), 149 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 33135439ce..7e54fc1866 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -30,6 +30,7 @@ class TemplateProcessor const MAXIMUM_REPLACEMENTS_DEFAULT = -1; public static $ensureMacroCompletion = true; + /** * ZipArchive object. * @@ -795,6 +796,7 @@ public function saveAs($fileName) /** * Finds parts of broken macros and sticks them together. * Macros, while being edited, could be implicitly broken by some of the word processors. + * In order to limit side-effects, we limit matches to only inside (inner) paragraphs * * @param string $documentPart The document part in XML representation. * @@ -802,17 +804,17 @@ public function saveAs($fileName) */ protected function fixBrokenMacros($documentPart) { - $fixedDocumentPart = $documentPart; - - $fixedDocumentPart = preg_replace_callback( - '|\$(?:<[^{]*)?\{[^}]*\}|U', - function ($match) { - return strip_tags($match[0]); - }, - $fixedDocumentPart - ); - - return $fixedDocumentPart; + $paragraphs = preg_split('@(]*>)@', $documentPart, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); + foreach($paragraphs as &$paragraph){ + $paragraph = preg_replace_callback( + '|\$(?:<[^{}]*)?\{[^{}]*\}|U', + function ($match) { + return strip_tags($match[0]); + }, + $paragraph + ); + } + return implode('', $paragraphs); } /** @@ -854,7 +856,7 @@ protected function setValueForPart($search, $replace, $documentPartXML, $limit) */ protected function getVariablesForPart($documentPartXML) { - preg_match_all('/\$\{(.*?)}/i', $documentPartXML, $matches); + preg_match_all('/\$\{([^<>{}]*?)}/i', $documentPartXML, $matches); return $matches[1]; } @@ -965,45 +967,4 @@ protected function getSlice(&$searchString, $startPosition, $endPosition = 0) return substr($searchString, $startPosition, ($endPosition - $startPosition)); } - - /** - * Returns a table object from the Word2007 / PhpWord(). - * - * @return object of type PhpOffice\PhpWord\Element\Table - */ - public function makeTable() - { - return (new \PhpOffice\PhpWord\PhpWord())->addSection()->addTable(); - } - - /** - * Convert a Word2007 object to xml. - * - * @param object $obj an object - * @param string $tag a tag like 'w:p' or 'w:tbl' if the tag is not found, return the whole xml as string. - * @param bool $withTags include ... xml tags in the result - * - * @return string|Exception - */ - public function toXML($obj, $tag = '', $withTags = true) - { - if (!is_Object($obj)) { - throw new Exception("toXML(): First parameter is not an object"); - } - if (!$tag) { - $tagList = array('Table' => 'w:tbl', 'Cell' => 'w:tc'); // needs more entries - $class = preg_replace('/^(.*\\\)/', '', get_class($obj)); - if (!array_key_exists($class, $tagList)) { - throw new Exception("toXML(): tag parameter required for " . get_class($obj)); - } - $tag = $tagList[$class]; - } - $phpWord = $obj->getPhpWord(); - $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); - $fullXml = $objWriter->getWriterPart('Document')->write(); - $regExp = $withTags ? - "/^[\s\S]*(<$tag\b.*<\/$tag>).*/" : - "/^[\s\S]*<$tag\b[^>]*>(.*)<\/$tag>.*/" ; - return preg_replace($regExp, '$1', $fullXml); - } } diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 1002d69201..db391dc0ab 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -266,14 +266,14 @@ private function getOpenTemplateProcessor($name) if (!file_exists($name) || !is_readable($name)) { return null; } - $ESTR = + $evalString = 'class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor {' . 'public function __construct($instance){return parent::__construct($instance);}' . 'public function __call($method, $args) {return call_user_func_array(array($this, $method), $args);}' . 'public function __get($key){return $this->$key;}' . 'public function __set($key, $val){return $this->$key = $val;} };' . 'return new OpenTemplateProcessor("'.$name.'");'; - return eval($ESTR); + return eval($evalString); } /** * @covers ::cloneBlock @@ -292,11 +292,11 @@ public function testCloneDeleteBlock() array('DELETEME', '/DELETEME', 'CLONEME', '/CLONEME'), $templateProcessor->getVariables() ); - $clone_times = 3; + $cloneTimes = 3; $docName = 'clone-delete-block-result.docx'; $xmlblock = $templateProcessor->getBlock('CLONEME'); $this->assertNotEmpty($xmlblock); - $templateProcessor->cloneBlock('CLONEME', $clone_times); + $templateProcessor->cloneBlock('CLONEME', $cloneTimes); $templateProcessor->deleteBlock('DELETEME'); $templateProcessor->saveAs($docName); $docFound = file_exists($docName); @@ -306,15 +306,15 @@ public function testCloneDeleteBlock() $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); # We test that all Block variables have been replaced (thus, getVariables() is empty) $this->assertEquals( - [], + array(), $templateProcessorNEWFILE->getVariables(), "All block variables should have been replaced" ); - # we cloned block CLONEME $clone_times times, so let's count to $clone_times + # we cloned block CLONEME $cloneTimes times, so let's count to $cloneTimes $this->assertEquals( - $clone_times, + $cloneTimes, substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $xmlblock), - "Block should be present $clone_times in the document" + "Block should be present $cloneTimes in the document" ); unlink($docName); # delete generated file } @@ -368,7 +368,7 @@ public function testCloneIndexedBlock() ]; $templateProcessor->setValue(array_keys($variablesArray), array_values($variablesArray)); $this->assertEquals( - [], + array(), $templateProcessor->getVariables(), "Variables have been replaced and should not be present anymore" ); @@ -603,47 +603,21 @@ public function testSetBlock() } /** - * @covers ::makeTable - * @covers ::toXML + * @covers ::fixBrokenMacros + * @covers ::ensureMacroCompleted + * @covers ::getVariables * @test */ - public function testMakeTable() + public function testFixBrokenMacros() { - $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); - - $table = $templateProcessor->makeTable(); - $cell = $table->addRow()->addCell(); - $cell->addText("CELL-A1"); + $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/bad-tags.docx'); + // the only tag that is a real tag $this->assertEquals( - ''. - ''. - 'CELL-A1'. - '', - $templateProcessor->toXML($table) - ); - - $this->assertEquals( - ''. - 'CELL-A1'. - '', - $templateProcessor->toXML($cell) - ); - - $this->assertEquals( - 'CELL-A1', - $templateProcessor->toXML($cell, 'w:p') + ['tag'], + $templateProcessor->getVariables() ); - } - /** - * @covers ::fixBrokenMacros - * @covers ::ensureMacroCompleted - * @test - */ - public function testFixBrokenMacros() - { - $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); $xmlStr = '${aaaaa'. '}'; $macro = $templateProcessor->ensureMacroCompleted('aaaaa'); @@ -792,57 +766,4 @@ final public function testAnotherThrowFailGraciously() $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 'IOU', 'MainPart', true) ); } - - /** - * @covers ::cloneSegment - * @covers ::getVariables - * @covers ::setBlock - * @covers ::saveAs - * @test - */ - public function testToXML() - { - $testDocument = __DIR__ . '/_files/templates/header-footer.docx'; - $templateProcessor = new TemplateProcessor($testDocument); - $myTable = $templateProcessor->makeTable(); - $randomText = "I was going to go to school, but then I got testcased."; - $resultXml = '' . $randomText . ''; - $myTable->addRow()->addCell()->addText($randomText); - $this->assertEquals( - $resultXml, - $templateProcessor->toXML($myTable, 'w:t') - ); - } - - /** - * @covers ::toXML - * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage toXML(): First parameter is not an object - * @test - */ - final public function testToXMLException() - { - $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); - $this->assertEquals( - null, - $templateProcessor->toXML(null, 'w:t') - ); - } - - /** - * @covers ::toXML - * @covers ::makeTable - * @expectedException Error - * @expectedExceptionMessage Call to undefined method PhpOffice\PhpWord\Element\Table::createRow() - * @test - */ - final public function testToXMLException2() - { - $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); - $myRow = $templateProcessor->makeTable()->createRow(); - $this->assertEquals( - null, - $templateProcessor->toXML($myRow) - ); - } } From 0c935c566389c7fe16d01ab9b4a4a32903ec8e36 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 14 Oct 2017 00:47:07 +0200 Subject: [PATCH 44/74] New test document with broken macros to test new fixBrokenMacros() function --- tests/PhpWord/_files/templates/bad-tags.docx | Bin 0 -> 4418 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 tests/PhpWord/_files/templates/bad-tags.docx diff --git a/tests/PhpWord/_files/templates/bad-tags.docx b/tests/PhpWord/_files/templates/bad-tags.docx new file mode 100644 index 0000000000000000000000000000000000000000..e2ca8e37c2abc30b02fb52644aafa90be67b3ec4 GIT binary patch literal 4418 zcmaJ^2{@E(7q%Nk#8CD%*_W|oE5<&CA!~LT+sGJOb|119vMb5HGmPvMku1@OEQJPB zmdKZ-ko_ON|NHax|9|JbuJ?N1>w3=nyw82kxzBwJprm9#A^-qD#A6DB5}mTMglAhX zM>lVAvEzGHiXM~{OdY*?z^L{W=O!H6H@L;4isIR%jLcm5Iy6Wrg{V532A^p)xR=-a zEa2N3+gs$|VIJ&pTpYNo0s;1v7;cqt^`E*b&S^Iy-fDI&X;dfEN~mHwvcR4mk{H{q zyHYMK=~g zrcO?b5f4L#set!}^ng2kwIGICDN859liqDM zA+6Y|)aBFTl8ct@;VBd0W&--v!bYIQ{8vw$_T%QmVy;VfUXtT~2yd39zP%a?%eb?h z5qRrfkBSF1d0O7%ZU>b$^DiA~TgwsAEe08H*=4NKeH}2@ZcLor-aD}4yka<`+=+@S zb(C@yFliGyCjf;d7`TVY(}iEjL$=%xNZ{l!^G>7T1<^o&DgH9?2&H`ZM$WA5>a8x> zYF*Ph=UF&$25Witb9?Baw!f7`I_ltslmULAHu-z`ZW?)=J3g^JgX?SJ^e3I_FJ(&e zhf;4{G@^Zcv&}hcA~Pq7#VY35<)F@W$U26(m>0oz zflU9LV+>AbCJdk6EZ=&hs@N^QUB`(v58^1K84M(eiBD0U5TG>Tb#jQBX=mQe+vJmz zJK|l@sHdTxVFur8FyYobZTwMsb=IV+dO(k>4MtBIX!D^B)?G7ugZ+ zn;Z+i_SYSDDv25C4|=k`Eyx14PEc3A*G?%%K%L{asIw7J_d|I(i2p?ygfh8}baeMQ z2LCVmNY*>^LV_-8JBR1>bcqRFa*4aThwvtmWOiexEY&N4z#!6l76Kn%%V_?npVUTH9rCVk^QeyX!_6Z>)>qpVW!aDMSZPIhS&WRMciC4xb+@pkFe0u(AE>C3w<~ z!=7I*Q-QT0``biQ9Z#(KL+40VGJqB3&E>g!lnT0#=uL>G+NJtfEJUDI<)tJIL`p6p z=8;0VB*+8TgAm}u+r>ro*Myhre3+cCy*qzjX|=Qx&_(fMIZX#wP(|Bq>x{NG`+nB~ zzzDgdS|G#61Hb)&+Gx7-hYf8fQ|Y&)5FV{F7lOER>08hVis}a>wS|&oEP7i)z>aTi z&i-*gXssIbTC{JKx|n6X$V#DX*E075SvdXSFr(wBn-E^n@bCv5owK+S;@|j3twb}V z*}%Wsj+cn8cI7eiN>qBRtZ&*Fyt=~PUN%0D=LTH%_E)s)Li2dRGP$tdYCwLaBv7|( zyf=4WVG~xBI3?G@-Wo_XN?QP^U}tr?tCqygIILcESIV-43_||){8*pZm4=Zx7g68% zOnw;aUOMK;8N|wV=DT3+P@mcqlJ8py@;EvA9C26oD0i3 zVCSscP-Nk>cge?)z_sV+a-dX=ffKtHm<0C6?sBeQiqO|x+hU)5z%G#W5LMn~^k3^@9QSekp(K(eGln>|Z&uSV^s5Y=YKS&4ymdX zuS8JN=d#+)cn@N+^JA&NSG+goEF9Z*C+R;Pc%1TbE!ec$u0mK z>>_XI&qW5r0pziL@dM`NBs~(myaVN22su14dgC)MBXdg`SMW3uj)M6U#TS!@d9K5D zc?#Qgf0E`t$X=IL@y^*>&Uhx38J&Q@isBsIe9hJ~&EDxrBM}#-dUEH-d(OI*6`zG- zL2R6AsY<*fv+1$@!b16iZPC2Nw(o}D_!xD#)_iQSNob=ojf9Xhh*w@2)qgG<9qSn8v1D|NI8VH8@sLc^uzL`)?g&h)l(m7)otgi(}#BXwTT4KJ}r?tK()FlAnQ)kFYfBd%b)3M7mYdK>LISS>ewV=XeQ^l}o&Hd$KmX+YR zjKXX>Dv927XO^o3C098ZW5n=GbD`)f+QNCF%F9k02Er?X+AHFFC^5F|hHM%n7O_ht z)p}iCip31puvx>;g`Ryk6SMud&be@XW+C|$HF8JPAp;__5-!!4TWX(2s{${mUJN+f zse)K1DIZ>mTgvw!)2fGoexdB z4_+wqlYT6=gX@O^odegl*iX7=V_Dfnf|xKN{T;6V>7L$>K0XL{=M!qs&?msELVY5% zeMk-S)hCRt0zYc*5MA*cN%#G8Y!VrUan7%3#`<%xY)`!bW}RiEdBMS9Dk}Z5P&eF} zmU9nxK*1t2M^z{h@PjAnPmg!v*(v6?5k{;xo_2S=67d^c@-K*NP0_V#C`^kqMP%Z5 z9Q!pi4XcKMIQZ1HmdJ4Xvh*3Aa`RSQM?P8FESct+J#{T5t*K9V9G_V)d11`r*1S++ z3TSfZX=t;Lsn!te{dCfzC7BSHanM+pnJ>VotnZ*0B~GJ!jKmNtJ7|EAKNkpS{Qr@I zfw00-jgVagEoEyQ;Nj?PeL|CIVCYMNnp)ix)~SA55=fWa7(}PE%&}~K6NHRF(t|v4 z2ivgL;#h#S**hrrT-$aVvufO?`{z_q|IzWZ70`e=iKa!do@H(6?zJ}iFRmt|L6i@Z z#_e9U(tQwJ6i~cK<}@CjpVhMqCR5nWP~^7NIJ+n3zhNH zElj?|^>(C)Y9R~kQum&;tDSOxk16JZMzC6+#k231m70qwyuWXp<09L53_okMVQg=* zwjO#th;*Y4n7x{%cJ9 z)%~=pKAu>9S~G!m{^S1d`Q=yd(<1a(dH*yq!Wn<3!+-tK=}!I6V_YTw9}@Og_tQLi z+|Ga6O#*YC{K(Jd{;TuODKa>w(x1jl2*ru>KZx~L|I;P(&wmdh=#IZOKSdzFx}Q#q e<2w6kQ8fRv>I|Ud6vvCG2$vEeN^9qi-~I&+SS}L) literal 0 HcmV?d00001 From 82475a910e3d669de60750d3a470f62268d29ca9 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 14 Oct 2017 02:51:02 +0200 Subject: [PATCH 45/74] coding style changes [] to array() --- tests/PhpWord/TemplateProcessorTest.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index db391dc0ab..0f335f0833 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -360,12 +360,12 @@ public function testCloneIndexedBlock() "Injected document should contain the right cloned variables, in the right order" ); - $variablesArray = [ + $variablesArray = array( 'repeats#1' => 'ONE', 'repeats#2' => 'TWO', 'repeats#3' => 'THREE', 'repeats#4' => 'FOUR' - ]; + ); $templateProcessor->setValue(array_keys($variablesArray), array_values($variablesArray)); $this->assertEquals( array(), @@ -614,7 +614,7 @@ public function testFixBrokenMacros() // the only tag that is a real tag $this->assertEquals( - ['tag'], + array('tag'), $templateProcessor->getVariables() ); @@ -691,7 +691,7 @@ public function testCloneSegment() $templateProcessor = new TemplateProcessor($testDocument); $this->assertEquals( - ['documentContent', 'headerValue', 'footerValue'], + array('documentContent', 'headerValue', 'footerValue'), $templateProcessor->getVariables() ); @@ -727,7 +727,7 @@ public function testCloneSegment() $templateProcessor2 = new TemplateProcessor($docName); $this->assertEquals( - ['documentContent#1', 'headerValue#2', 'footerValue#1', 'footerValue#2'], + array('documentContent#1', 'headerValue#2', 'footerValue#1', 'footerValue#2'), $templateProcessor2->getVariables() ); unlink($docName); From 760d3cb7ba1bb42061919b6096b7d3b57062ad18 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 14 Oct 2017 02:52:37 +0200 Subject: [PATCH 46/74] documentation and splitting too long line --- src/PhpWord/TemplateProcessor.php | 67 +++++++++++++++++-------------- 1 file changed, 36 insertions(+), 31 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 7e54fc1866..8969463437 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -235,7 +235,7 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ $this->tempDocumentMainPart = $this->setValueForPart($search, $replace, $this->tempDocumentMainPart, $limit); - $documentParts = ['tempDocumentHeaders', 'tempDocumentFooters']; + $documentParts = array('tempDocumentHeaders', 'tempDocumentFooters'); foreach ($documentParts as $tempDocumentParts) { foreach ($this->{$tempDocumentParts} as &$tempDocumentPart) { $tempDocumentPart = $this->setValueForPart($search, $replace, $tempDocumentPart, $limit); @@ -505,15 +505,15 @@ public function cloneBlock( /** * Clone a segment. * - * @param string $needle - * @param string $xmltag - * @param string $docPart - * @param integer $clones - * @param boolean $replace - * @param boolean $incrementVariables - * @param boolean $throwException + * @param string $needle If this is a macro, you need to add the ${} around it yourself. + * @param string $xmltag an xml tag without brackets, for example: w:p + * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) + * @param integer $clones How many times the segment needs to be cloned + * @param boolean $replace true by default (if you use false, cloneSegment behaves like getSegment()) + * @param boolean $incrementVariables true by default (variables get appended #1, #2 inside the cloned blocks) + * @param boolean $throwException false by default (it then returns false or null on errors). * - * @return string|null + * @return string|false|null Returns the cloned segment, or false if $needle can not be found or null for no tags */ public function cloneSegment( $needle, @@ -532,29 +532,29 @@ public function cloneSegment( } $needlePos = strpos($part, $needle); - if (!$needlePos) { + if ($needlePos === false) { return $this->failGraciously( "Can not find segment '$needle', text not found or text contains markup.", $throwException, - null + false ); } - $startSegmentStart = $this->findTagLeft($part, "<$xmltag>", $needlePos, $throwException); - $endSegmentEnd = $this->findTagRight($part, "", $needlePos); + $segmentStart = $this->findTagLeft($part, "<$xmltag>", $needlePos, $throwException); + $segmentEnd = $this->findTagRight($part, "", $needlePos); - if (!$startSegmentStart || !$endSegmentEnd) { + if (!$segmentStart || !$segmentEnd) { return $this->failGraciously( "Can not find <$xmltag> around segment '$needle'", $throwException, - false + null ); } - $xmlSegment = $this->getSlice($part, $startSegmentStart, $endSegmentEnd); + $xmlSegment = $this->getSlice($part, $segmentStart, $segmentEnd); if ($replace) { - $result = $this->getSlice($part, 0, $startSegmentStart); + $result = $this->getSlice($part, 0, $segmentStart); for ($i = 1; $i <= $clones; $i++) { if ($incrementVariables) { $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlSegment); @@ -562,7 +562,7 @@ public function cloneSegment( $result .= $xmlSegment; } } - $result .= $this->getSlice($part, $endSegmentEnd); + $result .= $this->getSlice($part, $segmentEnd); $part = $result; } @@ -586,10 +586,10 @@ public function getBlock($blockname, $throwException = false) /** * Get a segment. (first segment found) * - * @param string $needle If this is a macro, you need to add the ${} yourself. + * @param string $needle If this is a macro, you need to add the ${} around it yourself. * @param string $xmltag an xml tag without brackets, for example: w:p * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) - * @param boolean $throwException + * @param boolean $throwException false by default (it then returns false or null on errors). * * @return string|null */ @@ -668,21 +668,21 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa /** * Replace a segment. * - * @param string $needle If this is a macro, you need to add the ${} yourself. + * @param string $needle If this is a macro, you need to add the ${} around it yourself. * @param string $xmltag an xml tag without brackets, for example: w:p - * @param string $replacement - * @param string $docPart 'MainPart' (default) 'Footers:0' (first footer) or 'Headers:1' (second header) - * @param boolean $throwException + * @param string $replacement The replacement xml string. Be careful and keep the xml uncorrupted. + * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:2' (second header) + * @param boolean $throwException false by default (it then returns false or null on errors). * - * @return false on no replacement, true on replacement + * @return true on replacement, false if $needle can not be found or null if no tags can be found around $needle */ public function replaceSegment($needle, $xmltag, $replacement = '', $docPart = 'MainPart', $throwException = false) { $docPart = preg_split('/:/', $docPart); if (count($docPart)>1) { - $part = &$this->{"tempDocument$docPart[0]"}[$docPart[1]]; + $part = &$this->{"tempDocument".$docPart[0]}[$docPart[1]]; } else { - $part = &$this->{"tempDocument$docPart[0]"}; + $part = &$this->{"tempDocument".$docPart[0]}; } $needlePos = strpos($part, $needle); @@ -701,7 +701,7 @@ public function replaceSegment($needle, $xmltag, $replacement = '', $docPart = ' return $this->failGraciously( "Can not find tag $xmltag around segment '$needle'.", $throwException, - false + null ); } @@ -730,7 +730,7 @@ public function deleteBlock($blockname) * * @param string $needle If this is a macro, you need to add the ${} yourself. * @param string $xmltag an xml tag without brackets, for example: w:p - * @param string $docPart 'MainPart' (default) 'Footers:0' (first footer) or 'Headers:1' (second header) + * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (second header) * * @return true on segment found and deleted, false on segment not found. */ @@ -804,8 +804,13 @@ public function saveAs($fileName) */ protected function fixBrokenMacros($documentPart) { - $paragraphs = preg_split('@(]*>)@', $documentPart, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); - foreach($paragraphs as &$paragraph){ + $paragraphs = preg_split( + '@(]*>)@', + $documentPart, + -1, + PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE + ); + foreach ($paragraphs as &$paragraph) { $paragraph = preg_replace_callback( '|\$(?:<[^{}]*)?\{[^{}]*\}|U', function ($match) { From 9f716a52949bf66c3e7f25dd031c43f1db60ef39 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 14 Oct 2017 03:48:14 +0200 Subject: [PATCH 47/74] small update to the function Documentation --- src/PhpWord/TemplateProcessor.php | 41 ++++++++++++++++++------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 8969463437..498b919d32 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -29,6 +29,12 @@ class TemplateProcessor { const MAXIMUM_REPLACEMENTS_DEFAULT = -1; + /** + * Enable/disable setValue('key') becoming setValue('${key}') automatically. + * Call it like: TemplateProcessor::$ensureMacroCompletion = false; + * + * @var boolean + */ public static $ensureMacroCompletion = true; /** @@ -204,9 +210,9 @@ protected static function ensureUtf8Encoded($subject) } /** - * @param mixed $search - * @param mixed $replace - * @param integer $limit + * @param mixed $search macro name you want to replace (or an array of these) + * @param mixed $replace replace string (or an array of these) + * @param integer $limit How many times it will have to replace the same variable all over the document. * * @return void */ @@ -269,9 +275,10 @@ public function setBlock($blockname, $replace, $limit = self::MAXIMUM_REPLACEMEN /** * Updates a file inside the document, from a string (with binary data) + * To replace an image: $templateProcessor->zipAddFromString("word/media/image1.jpg", file_get_contents($file)); * - * @param string $localname - * @param string $contents + * @param string $localname The path and name inside the docx/zip file + * @param mixed $contents Text or Binary data * * @return bool */ @@ -419,7 +426,7 @@ public function deleteRow($search) * @param boolean $incrementVariables * @param boolean $throwException * - * @return string|null + * @return string|false|null */ public function cloneBlock( $blockname, @@ -450,7 +457,7 @@ public function cloneBlock( return $this->failGraciously( "Can not find block '$blockname', template variable not found or variable contains markup.", $throwException, - null + false ); } @@ -461,7 +468,7 @@ public function cloneBlock( return $this->failGraciously( "Can not find start paragraph around block '$blockname'", $throwException, - false + null ); } @@ -472,7 +479,7 @@ public function cloneBlock( return $this->failGraciously( "Can not find end paragraph around block '$blockname'", $throwException, - false + null ); } @@ -591,7 +598,7 @@ public function getBlock($blockname, $throwException = false) * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) * @param boolean $throwException false by default (it then returns false or null on errors). * - * @return string|null + * @return string|false|null true (replaced), false ($needle not found) or null (no tags found around $needle) */ public function getSegment($needle, $xmltag, $docPart = 'MainPart', $throwException = false) { @@ -614,11 +621,11 @@ public function getRow($rowname, $throwException = false) /** * Replace a block. * - * @param string $blockname - * @param string $replacement - * @param boolean $throwException + * @param string $blockname The name of the macro start and end (without the macro marker ${}) + * @param string $replacement The replacement xml + * @param boolean $throwException false by default. * - * @return false on no replacement, true on replacement + * @return string|true|false|null false-ish on no replacement, true-ish on replacement */ public function replaceBlock($blockname, $replacement = '', $throwException = false) { @@ -645,9 +652,9 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa if (!$startBlockStart || !$endBlockEnd) { return $this->failGraciously( - "Can not find end paragraph around block '$blockname'", + "Can not find paragraph around block '$blockname'", $throwException, - false + null ); } @@ -674,7 +681,7 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:2' (second header) * @param boolean $throwException false by default (it then returns false or null on errors). * - * @return true on replacement, false if $needle can not be found or null if no tags can be found around $needle + * @return true|false|null true (replaced), false ($needle not found) or null (no tags found around $needle) */ public function replaceSegment($needle, $xmltag, $replacement = '', $docPart = 'MainPart', $throwException = false) { From 0b8a89e4a71de32fc378d12df950f36d5af4c038 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 14 Oct 2017 05:11:46 +0200 Subject: [PATCH 48/74] small cleanups --- src/PhpWord/TemplateProcessor.php | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 498b919d32..3827a33d9e 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -334,7 +334,7 @@ public function getVariables() * @param bool $incrementVariables * @param bool $throwException * - * @return string|null + * @return string|false Returns the row cloned or false if the $search macro is not found * * @throws \PhpOffice\PhpWord\Exception\Exception */ @@ -346,11 +346,11 @@ public function cloneRow( $throwException = false ) { $tagPos = strpos($this->tempDocumentMainPart, $this->ensureMacroCompleted($search)); - if (!$tagPos) { + if ($tagPos === false) { return $this->failGraciously( "Can not clone row, template variable not found or variable contains markup.", $throwException, - null + false ); } @@ -909,14 +909,15 @@ protected function getFooterName($index) * Find the start position of the nearest tag before $offset. * * @param string $searchString The string we are searching in (the mainbody or an array element of Footers/Headers) - * @param string $tag Fully qualified tag, for example: '' + * @param string $tag Fully qualified tag, for example: '' (with brackets!) * @param integer $offset Do not look from the beginning, but starting at $offset * @param boolean $throwException * - * @return integer + * @return integer Zero if not found (due to the nature of xml, your document never starts at 0) * * @throws \PhpOffice\PhpWord\Exception\Exception */ + protected function findTagLeft(&$searchString, $tag, $offset = 0, $throwException = false) { $tagStart = strrpos( @@ -932,6 +933,7 @@ protected function findTagLeft(&$searchString, $tag, $offset = 0, $throwExceptio ((strlen($searchString) - $offset) * -1) ); } + if (!$tagStart) { return $this->failGraciously( "Can not find the start position of the item to clone.", @@ -950,7 +952,7 @@ protected function findTagLeft(&$searchString, $tag, $offset = 0, $throwExceptio * @param string $tag Fully qualified tag, for example: '' * @param integer $offset Do not look from the beginning, but starting at $offset * - * @return integer + * @return integer Zero if not found */ protected function findTagRight(&$searchString, $tag, $offset = 0) { From 6ceee2fa4c0803223f4dc0c100a3075ea736bc2d Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 14 Oct 2017 05:56:23 +0200 Subject: [PATCH 49/74] Revert back something I should not have touched --- src/PhpWord/Writer/Word2007/Part/Styles.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/PhpWord/Writer/Word2007/Part/Styles.php b/src/PhpWord/Writer/Word2007/Part/Styles.php index 4ad35d1c8f..01b84c0815 100644 --- a/src/PhpWord/Writer/Word2007/Part/Styles.php +++ b/src/PhpWord/Writer/Word2007/Part/Styles.php @@ -158,8 +158,6 @@ private function writeFontStyle(XMLWriter $xmlWriter, $styleName, FontStyle $sty $xmlWriter->startElement('w:style'); $xmlWriter->writeAttribute('w:type', $type); - $xmlWriter->writeAttribute('w:customStyle', '1'); - $xmlWriter->writeAttribute('w:styleId', $styleName); // Heading style if ($styleType == 'title') { From e90362c8965ad5eaf61b288a7b4eaf0a8de71178 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 14 Oct 2017 06:12:45 +0200 Subject: [PATCH 50/74] More return types... (documentation) --- src/PhpWord/TemplateProcessor.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 3827a33d9e..2d30d20f1b 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -725,7 +725,7 @@ public function replaceSegment($needle, $xmltag, $replacement = '', $docPart = ' * * @param string $blockname * - * @return true on block found and deleted, false on block not found. + * @return string|true|false|null true-ish on block found and deleted, falseish on block not found. */ public function deleteBlock($blockname) { @@ -739,7 +739,7 @@ public function deleteBlock($blockname) * @param string $xmltag an xml tag without brackets, for example: w:p * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (second header) * - * @return true on segment found and deleted, false on segment not found. + * @return true|false|null true (segment deleted), false ($needle not found) or null (no tags found around $needle) */ public function deleteSegment($needle, $xmltag, $docPart = 'MainPart') { From 330a7cf4532942212097320e64081a33e6095bd7 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 14 Oct 2017 08:41:35 +0200 Subject: [PATCH 51/74] Trying to get Scrutinizer to not complain about the @return values --- src/PhpWord/TemplateProcessor.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 2d30d20f1b..6b25563b0a 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -295,6 +295,8 @@ public function zipAddFromString($localname, $contents) * @param mixed $elseReturn * * @return mixed + * + * @throws \PhpOffice\PhpWord\Exception\Exception */ private function failGraciously($exceptionText, $throwException, $elseReturn) { @@ -426,7 +428,9 @@ public function deleteRow($search) * @param boolean $incrementVariables * @param boolean $throwException * - * @return string|false|null + * @return mixed The cloned string if successful, false ($blockname not found) or Null (no paragraph found) + * + * @throws \PhpOffice\PhpWord\Exception\Exception */ public function cloneBlock( $blockname, @@ -625,7 +629,7 @@ public function getRow($rowname, $throwException = false) * @param string $replacement The replacement xml * @param boolean $throwException false by default. * - * @return string|true|false|null false-ish on no replacement, true-ish on replacement + * @return string|boolean|null false-ish on no replacement, true-ish on replacement */ public function replaceBlock($blockname, $replacement = '', $throwException = false) { @@ -681,7 +685,7 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:2' (second header) * @param boolean $throwException false by default (it then returns false or null on errors). * - * @return true|false|null true (replaced), false ($needle not found) or null (no tags found around $needle) + * @return boolean|null true (replaced), false ($needle not found) or null (no tags found around $needle) */ public function replaceSegment($needle, $xmltag, $replacement = '', $docPart = 'MainPart', $throwException = false) { From 2700fde2ec2e90d39085ff0d5dfdc57b201c8b73 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 14 Oct 2017 15:16:22 +0200 Subject: [PATCH 52/74] removed eval in favour of Reflections. Added more test for coverage --- tests/PhpWord/TemplateProcessorTest.php | 306 +++++++++++++++++------- 1 file changed, 224 insertions(+), 82 deletions(-) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 0f335f0833..04c0f17e61 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -24,6 +24,26 @@ */ final class TemplateProcessorTest extends \PHPUnit_Framework_TestCase { + // http://php.net/manual/en/class.reflectionobject.php + public function poke(&$object, $property, $newValue = null) + { + $refObject = new \ReflectionObject($object); + $refProperty = $refObject->getProperty($property); + $refProperty->setAccessible(true); + if ($newValue !== null) { + $refProperty->setValue($object, $newValue); + } + return $refProperty; + } + + public function peek(&$object, $property) + { + $refObject = new \ReflectionObject($object); + $refProperty = $refObject->getProperty($property); + $refProperty->setAccessible(true); + return $refProperty->getValue($object); + } + /** * Template can be saved in temporary location. * @@ -163,9 +183,12 @@ final public function testXslStyleSheetCanNotBeAppliedOnFailureOfLoadingXmlFromT /** * @covers ::setValue * @covers ::cloneRow + * @covers ::deleteRow * @covers ::saveAs * @covers ::findTagLeft * @covers ::findTagRight + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage Can not clone row, template variable not found or variable contains markup. * @test */ public function testCloneRow() @@ -179,12 +202,22 @@ public function testCloneRow() $docName = 'clone-test-result.docx'; $templateProcessor->setValue('tableHeader', utf8_decode('ééé')); - $templateProcessor->cloneRow('userId', 1); + $templateProcessor->cloneRow('userId', 2, true, true); $templateProcessor->setValue('userId#1', 'Test'); + $this->assertTrue( + $templateProcessor->deleteRow('userId#2') + ); + $this->assertFalse( + $templateProcessor->deleteRow('userId#3') + ); $templateProcessor->saveAs($docName); $docFound = file_exists($docName); unlink($docName); $this->assertTrue($docFound); + $this->assertEquals( + null, + $templateProcessor->cloneRow('userId', 2, false, false, true) + ); } /** @@ -198,10 +231,15 @@ public function testGetRow() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); $initialArray = array('tableHeader', 'userId', 'userName', 'userLocation'); + $midArray = array( + 'tableHeader', + 'userId', 'userName', 'foo', 'userLocation' + ); $finalArray = array( 'tableHeader', - 'userId#1', 'userName#1', 'userLocation#1', - 'userId#2', 'userName#2', 'userLocation#2' + 'userId#1', 'userName#1', 'foo#1', + 'userId#2', 'userName#2', 'foo#2', + 'userId', 'userName', 'userLocation' ); $row = $templateProcessor->getRow('userId'); $this->assertNotEmpty($row); @@ -209,10 +247,17 @@ public function testGetRow() $initialArray, $templateProcessor->getVariables() ); - $row = $templateProcessor->cloneRow('userId', 2); + $row = $templateProcessor->cloneRow('userId', 2, true, false, false); $this->assertStringStartsWith('assertStringEndsWith('', $row); $this->assertNotEmpty($row); + $templateProcessor->setValue('userLocation', '${foo}', 1); + $this->assertEquals( + $midArray, + array_values($templateProcessor->getVariables()), + implode("|", $templateProcessor->getVariables()) + ); + $row = $templateProcessor->cloneRow('userId', 2, true, true, false); $this->assertEquals( $finalArray, $templateProcessor->getVariables() @@ -223,10 +268,10 @@ public function testGetRow() $docFound = file_exists($docName); $this->assertTrue($docFound); if ($docFound) { - $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); + $templateProcessorNewFile = new TemplateProcessor($docName); $this->assertEquals( $finalArray, - $templateProcessorNEWFILE->getVariables() + $templateProcessorNewFile->getVariables() ); unlink($docName); } @@ -254,27 +299,6 @@ public function testMacrosCanBeReplacedInHeaderAndFooter() $this->assertTrue($docFound); } - /** - * Convoluted way to get a helper class, without using include_once (not allowed by phpcs) - * or inline (not allowed by phpcs) or touching the autoload.php (and make it accessible to users) - * this helper class returns a TemplateProcessor that allows access to private variables - * like tempDocumentMainPart, see the functions that use it for usage. - * eval is evil, but phpcs and phpunit made me do it! - */ - private function getOpenTemplateProcessor($name) - { - if (!file_exists($name) || !is_readable($name)) { - return null; - } - $evalString = - 'class OpenTemplateProcessor extends \PhpOffice\PhpWord\TemplateProcessor {' - . 'public function __construct($instance){return parent::__construct($instance);}' - . 'public function __call($method, $args) {return call_user_func_array(array($this, $method), $args);}' - . 'public function __get($key){return $this->$key;}' - . 'public function __set($key, $val){return $this->$key = $val;} };' - . 'return new OpenTemplateProcessor("'.$name.'");'; - return eval($evalString); - } /** * @covers ::cloneBlock * @covers ::deleteBlock @@ -303,17 +327,17 @@ public function testCloneDeleteBlock() if ($docFound) { # Great, so we saved the replaced document, so we open that new document # note that we need to access private variables, so we use a sub-class - $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); + $templateProcessorNewFile = new TemplateProcessor($docName); # We test that all Block variables have been replaced (thus, getVariables() is empty) $this->assertEquals( array(), - $templateProcessorNEWFILE->getVariables(), + $templateProcessorNewFile->getVariables(), "All block variables should have been replaced" ); # we cloned block CLONEME $cloneTimes times, so let's count to $cloneTimes $this->assertEquals( $cloneTimes, - substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $xmlblock), + substr_count($this->peek($templateProcessorNewFile, 'tempDocumentMainPart'), $xmlblock), "Block should be present $cloneTimes in the document" ); unlink($docName); # delete generated file @@ -333,11 +357,11 @@ public function testCloneDeleteBlock() */ public function testCloneIndexedBlock() { - $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); # we will fake a block with a variable inside it, as there is no template document yet. $xmlTxt = 'This ${repeats} a few times'; $xmlStr = '${MYBLOCK}' . $xmlTxt . '${/MYBLOCK}'; - $templateProcessor->tempDocumentMainPart = $xmlStr; + $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); $this->assertEquals( $xmlTxt, @@ -380,12 +404,12 @@ public function testCloneIndexedBlock() } $this->assertEquals( 1, - substr_count($templateProcessor->tempDocumentMainPart, $tmpStr), + substr_count($this->peek($templateProcessor, 'tempDocumentMainPart'), $tmpStr), "order of replacement should be: ONE,TWO,THREE then FOUR" ); # Now we try again, but without variable incrementals (old behavior) - $templateProcessor->tempDocumentMainPart = $xmlStr; + $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); $templateProcessor->cloneBlock('MYBLOCK', 4, true, false); # detects new variable @@ -398,14 +422,14 @@ public function testCloneIndexedBlock() # we cloned block CLONEME 4 times, so let's count $this->assertEquals( 4, - substr_count($templateProcessor->tempDocumentMainPart, $xmlTxt), + substr_count($this->peek($templateProcessor, 'tempDocumentMainPart'), $xmlTxt), 'detects new variable $repeats to be present 4 times' ); # we cloned block CLONEME 4 times, so let's see that there is no space between these blocks $this->assertEquals( 1, - substr_count($templateProcessor->tempDocumentMainPart, $xmlTxt.$xmlTxt.$xmlTxt.$xmlTxt), + substr_count($this->peek($templateProcessor, 'tempDocumentMainPart'), $xmlTxt.$xmlTxt.$xmlTxt.$xmlTxt), "The four times cloned block should be the same as four times the block" ); } @@ -421,10 +445,10 @@ public function testCloneIndexedBlock() */ public function testClosedBlock() { - $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); $xmlTxt = 'This ${BLOCKCLOSE/} is here.'; $xmlStr = '${BEFORE}' . $xmlTxt . '${AFTER}'; - $templateProcessor->tempDocumentMainPart = $xmlStr; + $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); $this->assertEquals( $xmlTxt, @@ -440,12 +464,12 @@ public function testClosedBlock() ); # inserting itself should result in no change - $oldvalue = $templateProcessor->tempDocumentMainPart; + $oldvalue = $this->peek($templateProcessor, 'tempDocumentMainPart'); $block = $templateProcessor->getBlock('BLOCKCLOSE/'); $templateProcessor->replaceBlock('BLOCKCLOSE/', $block); $this->assertEquals( $oldvalue, - $templateProcessor->tempDocumentMainPart, + $this->peek($templateProcessor, 'tempDocumentMainPart'), "ReplaceBlock should replace at the right position" ); @@ -457,15 +481,32 @@ public function testClosedBlock() "Injected document should contain the right cloned variables, in the right order" ); - $templateProcessor->tempDocumentMainPart = $xmlStr; + $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); $templateProcessor->deleteBlock('BLOCKCLOSE/'); $this->assertEquals( '${BEFORE}${AFTER}', - $templateProcessor->tempDocumentMainPart, + $this->peek($templateProcessor, 'tempDocumentMainPart'), 'closedblock should delete properly' ); } + + /** + * @covers ::setValue + * @test + */ + public function testSetValue() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + Settings::setOutputEscapingEnabled(true); + $helloworld = "hello\nworld"; + $templateProcessor->setValue('userName', $helloworld); + $this->assertEquals( + array('tableHeader', 'userId', 'userLocation'), + $templateProcessor->getVariables() + ); + } + /** * @covers ::setValue * @covers ::saveAs @@ -490,18 +531,18 @@ public function testSetValueMultiline() $this->assertTrue($docFound); if ($docFound) { # We open that new document (and use the OpenTemplateProcessor to access private variables) - $templateProcessorNEWFILE = $this->getOpenTemplateProcessor($docName); + $templateProcessorNewFile = new TemplateProcessor($docName); # We test that all Block variables have been replaced (thus, getVariables() is empty) $this->assertEquals( 0, - substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $helloworld), + substr_count($this->peek($templateProcessorNewFile, 'tempDocumentMainPart'), $helloworld), "there should be a multiline" ); # The block it should be turned into: $xmlblock = 'helloworld'; $this->assertEquals( 1, - substr_count($templateProcessorNEWFILE->tempDocumentMainPart, $xmlblock), + substr_count($this->peek($templateProcessorNewFile, 'tempDocumentMainPart'), $xmlblock), "multiline should be present 1 in the document" ); unlink($docName); # delete generated file @@ -517,7 +558,7 @@ public function testSetValueMultiline() */ public function testInlineBlock() { - $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); $xmlStr = ''. 'This'. '${inline}'. @@ -525,19 +566,19 @@ public function testInlineBlock() '${/inline}'. ' block'; - $templateProcessor->tempDocumentMainPart = $xmlStr; + $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); $this->assertEquals( $templateProcessor->getBlock('inline'), ''. - ' has been', + ' has been', "When inside the same , cut inside the paragraph" ); $templateProcessor->replaceBlock('inline', 'shows'); $this->assertEquals( - $templateProcessor->tempDocumentMainPart, + $this->peek($templateProcessor, 'tempDocumentMainPart'), ''. ''. 'This'. @@ -555,7 +596,7 @@ public function testInlineBlock() */ public function testSetBlock() { - $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); $xmlStr = ''. ''. ''. @@ -565,7 +606,7 @@ public function testSetBlock() ''. ''; - $templateProcessor->tempDocumentMainPart = $xmlStr; + $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); $templateProcessor->setBlock('inline/', "one\ntwo"); // XMLReader::xml($templateProcessor->tempDocumentMainPart)->isValid() @@ -584,10 +625,10 @@ public function testSetBlock() 'AFTER'. ''. '', - $templateProcessor->tempDocumentMainPart + $this->peek($templateProcessor, 'tempDocumentMainPart') ); - $templateProcessor->tempDocumentMainPart = $xmlStr; + $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); $templateProcessor->setBlock('inline/', "simplé`"); $this->assertEquals( ''. @@ -598,46 +639,47 @@ public function testSetBlock() 'AFTER'. ''. '', - $templateProcessor->tempDocumentMainPart + $this->peek($templateProcessor, 'tempDocumentMainPart') ); } + /** - * @covers ::fixBrokenMacros - * @covers ::ensureMacroCompleted - * @covers ::getVariables + * @covers ::replaceBlock + * @covers ::cloneBlock + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage Can not find paragraph around block * @test */ - public function testFixBrokenMacros() + public function testReplaceBlock() { - $templateProcessor = $this->getOpenTemplateProcessor(__DIR__ . '/_files/templates/bad-tags.docx'); + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $xmlStr = ''. + '${/nostart}'. + ''. + '${malformedblock}'. + '${notABlock}'. + ''. + '${/malformedblock}'; - // the only tag that is a real tag - $this->assertEquals( - array('tag'), - $templateProcessor->getVariables() - ); + $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); - $xmlStr = '${aaaaa'. - '}'; - $macro = $templateProcessor->ensureMacroCompleted('aaaaa'); - $this->assertEquals( - $macro, - '${aaaaa}' + $this->assertFalse( + $templateProcessor->replaceBlock('notABlock', "") ); - - TemplateProcessor::$ensureMacroCompletion = false; - $this->assertEquals( - $templateProcessor->ensureMacroCompleted('aaaaa'), - 'aaaaa' + $this->assertFalse( + $templateProcessor->cloneBlock('notABlock', "", 10) + ); + $this->assertNull( + $templateProcessor->cloneBlock('malformedblock', 11) + ); + $this->assertNull( + $templateProcessor->cloneBlock('nostart', 11) ); - TemplateProcessor::$ensureMacroCompletion = true; - - $xmlFixed = $templateProcessor->fixBrokenMacros($xmlStr); $this->assertEquals( - 1, - substr_count($xmlFixed, $macro), - "could not find '$macro' in: $xmlFixed" + null, + $got = $templateProcessor->replaceBlock('malformedblock', "", true), + $got ); } @@ -652,6 +694,11 @@ public function testFailGraciously() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $this->assertEquals( + null, + $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', 'MainPart', false) + ); + $this->assertEquals( null, $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 'MainPart', 1, true, true, false) @@ -664,7 +711,7 @@ public function testFailGraciously() $this->assertEquals( null, - $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 'IOU', 'MainPart', false) + $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 'IOU', 'Footer:1', false) ); $this->assertEquals( @@ -766,4 +813,99 @@ final public function testAnotherThrowFailGraciously() $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 'IOU', 'MainPart', true) ); } + + /** + * @covers ::save + * @covers ::saveas + * @test1 + */ + public function testSaveAs() + { + $testDocument = __DIR__ . '/_files/templates/header-footer.docx'; + $templateProcessor = new TemplateProcessor($testDocument); + $tempFileName = "tempfilename.docx"; + $this->assertEquals( + null, + $templateProcessor->saveAs($tempFileName) + ); + $this->assertTrue( + file_exists($tempFileName) + ); + $templateProcessor = new TemplateProcessor($tempFileName); + $this->assertEquals( + null, + $templateProcessor->saveAs($tempFileName), + 'Second save should succeed, but does not' + ); + $this->assertTrue( + file_exists($tempFileName) + ); + unlink($tempFileName); + } + + /** + * @covers ::save + * @test + */ + public function testSave() + { + $testDocument = __DIR__ . '/_files/templates/header-footer.docx'; + $templateProcessor = new TemplateProcessor($testDocument); + + $this->assertNotEquals( + $testDocument, + $tempFileName = $templateProcessor->save(), + 'Do not clobber the original file' + ); + + $this->assertTrue( + file_exists($tempFileName) + ); + unlink($tempFileName); + } + + /** + * @covers ::replaceBlock + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage Can not find block 'I-DO-NOT-EXIST', template variable not found or variable contains + * @test + */ + final public function testReplaceBlockThrow() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $this->assertEquals( + null, + $templateProcessor->replaceBlock('I-DO-NOT-EXIST', 'IOU', true) + ); + } + + /** + * @covers ::getSegment + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage Can not find segment 'I-DO-NOT-EXIST', text not found or text contains markup. + * @test + */ + final public function testgetSegmentThrow() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $this->assertEquals( + null, + $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', 'MainPart', true) + ); + } + + /** + * @covers ::cloneBlock + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage Can not find block + * @test + */ + final public function testCloneBlockThrow() + { + $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $this->assertEquals( + null, + $templateProcessor->cloneBlock('I-DO-NOT-EXIST', 'replace', 1, true, true) + ); + } } From 1e78c85c273722b72515a129e36dd0b4be14012c Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 14 Oct 2017 15:42:37 +0200 Subject: [PATCH 53/74] Multi-line function call not indented correctly; expected 12 spaces but found 16 --- tests/PhpWord/TemplateProcessorTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 04c0f17e61..24a6523950 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -571,7 +571,7 @@ public function testInlineBlock() $this->assertEquals( $templateProcessor->getBlock('inline'), ''. - ' has been', + ' has been', "When inside the same , cut inside the paragraph" ); From 85394d1f1baa56a2a1b383b80a9ab294189897f4 Mon Sep 17 00:00:00 2001 From: Nilton Date: Thu, 19 Oct 2017 08:37:17 +0200 Subject: [PATCH 54/74] Make everything depend on Segments --- src/PhpWord/TemplateProcessor.php | 448 ++++++++++++------------ tests/PhpWord/TemplateProcessorTest.php | 62 +++- 2 files changed, 271 insertions(+), 239 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 6b25563b0a..6a5596fc3d 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -186,7 +186,7 @@ public function applyXslStyleSheet($xslDomDocument, $xslOptions = array(), $xslO * * @return string */ - protected static function ensureMacroCompleted($macro) + protected static function ensureMacroCompleted(&$macro) { if (TemplateProcessor::$ensureMacroCompletion && substr($macro, 0, 2) !== '${' && substr($macro, -1) !== '}') { $macro = '${' . $macro . '}'; @@ -220,10 +220,10 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ { if (is_array($search)) { foreach ($search as &$item) { - $item = self::ensureMacroCompleted($item); + self::ensureMacroCompleted($item); } } else { - $search = self::ensureMacroCompleted($search); + self::ensureMacroCompleted($search); } if (is_array($replace)) { @@ -264,7 +264,7 @@ public function setBlock($blockname, $replace, $limit = self::MAXIMUM_REPLACEMEN $replace = preg_split('~\R~u', $replace); } if (is_array($replace)) { - $this->cloneBlock($blockname, count($replace), true, false); + $this->processBlock($blockname, count($replace), true, false); foreach ($replace as $oneVal) { $this->setValue($blockname, $oneVal, 1); } @@ -328,11 +328,33 @@ public function getVariables() } /** - * Clone a table row in a template document. + * Clone a string and enumerate ( i.e. ${macro#1} ) + * + * @param string $text Must be a variable as we use references for speed + * @param integer $numberOfClones How many times $text needs to be duplicated + * @param bool $incrementVariables If true, the macro's inside the string get numerated + * + * @return string + */ + private function cloneString(&$text, $numberOfClones = 1, $incrementVariables = true) + { + $result = ''; + for ($i = 1; $i <= $numberOfClones; $i++) { + if ($incrementVariables) { + $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $text); + } else { + $result .= $text; + } + } + return $result; + } + + /** + * Process a table row in a template document. * * @param string $search * @param integer $numberOfClones - * @param bool $replace + * @param mixed $replace (true to clone, or a string to replace) * @param bool $incrementVariables * @param bool $throwException * @@ -340,71 +362,94 @@ public function getVariables() * * @throws \PhpOffice\PhpWord\Exception\Exception */ - public function cloneRow( + private function processRow( $search, $numberOfClones = 1, $replace = true, $incrementVariables = true, $throwException = false ) { - $tagPos = strpos($this->tempDocumentMainPart, $this->ensureMacroCompleted($search)); - if ($tagPos === false) { - return $this->failGraciously( - "Can not clone row, template variable not found or variable contains markup.", - $throwException, - false - ); - } - - $rowStart = $this->findTagLeft($this->tempDocumentMainPart, '', $tagPos, $throwException); - $rowEnd = $this->findTagRight($this->tempDocumentMainPart, '', $tagPos); - $xmlRow = $this->getSlice($this->tempDocumentMainPart, $rowStart, $rowEnd); - - // Check if there's a cell spanning multiple rows. - if (preg_match('##', $xmlRow)) { - // $extraRowStart = $rowEnd; - $extraRowEnd = $rowEnd; - while (true) { - $extraRowStart = $this->findTagLeft( - $this->tempDocumentMainPart, - '', - $extraRowEnd + 1, - $throwException - ); - $extraRowEnd = $this->findTagRight($this->tempDocumentMainPart, '', $extraRowEnd + 1); - - if (!$extraRowEnd) { - break; - } - - // If tmpXmlRow doesn't contain continue, this row is no longer part of the spanned row. - $tmpXmlRow = $this->getSlice($this->tempDocumentMainPart, $extraRowStart, $extraRowEnd); - if (!preg_match('##', $tmpXmlRow) - && !preg_match('##', $tmpXmlRow) - ) { - break; + return $this->processSegment( + $this->ensureMacroCompleted($search), + 'w:tr', + $numberOfClones, + 'MainPart', + function (&$xmlSegment, &$segmentStart, &$segmentEnd, &$part) use (&$replace) { + if (strpos($xmlSegment, 'findTagRight($part, '', $extraRowStart); + + if (!$extraRowEnd) { + break; + } + + // If tmpXmlRow doesn't contain continue, this row is no longer part of the spanned row. + $tmpXmlRow = $this->getSlice($part, $extraRowStart, $extraRowEnd); + if (!preg_match('##', $tmpXmlRow) + && !preg_match('##', $tmpXmlRow) + ) { + break; + } + // This row was a spanned row, update $segmentEnd and search for the next row. + $segmentEnd = $extraRowEnd; + } + $xmlSegment = $this->getSlice($part, $segmentStart, $segmentEnd); } - // This row was a spanned row, update $rowEnd and search for the next row. - $rowEnd = $extraRowEnd; - } - $xmlRow = $this->getSlice($this->tempDocumentMainPart, $rowStart, $rowEnd); - } + return $replace; + }, + $incrementVariables, + $throwException + ); + } - if ($replace) { - $result = $this->getSlice($this->tempDocumentMainPart, 0, $rowStart); - for ($i = 1; $i <= $numberOfClones; $i++) { - if ($incrementVariables) { - $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlRow); - } else { - $result .= $xmlRow; - } - } - $result .= $this->getSlice($this->tempDocumentMainPart, $rowEnd); + /** + * Clone a table row in a template document. + * + * @param string $search + * @param integer $numberOfClones + * @param bool $incrementVariables + * @param bool $throwException + * + * @return mixed Returns true if row cloned succesfully or or false if the $search macro is not found + * + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + public function cloneRow( + $search, + $numberOfClones = 1, + $incrementVariables = true, + $throwException = false + ) { + return $this->processRow($search, $numberOfClones, true, $incrementVariables, $throwException); + } - $this->tempDocumentMainPart = $result; - } + /** + * Get a row. (first block found) + * + * @param string $search + * @param boolean $throwException + * + * @return string|null + */ + public function getRow($search, $throwException = false) + { + return $this->processRow($search, 0, false, false, $throwException); + } - return $xmlRow; + /** + * Replace a row. + * + * @param string $search a macro name in a table row + * @param string $replacement The replacement xml string. Be careful and keep the xml uncorrupted. + * @param boolean $throwException false by default (it then returns false or null on errors). + * + * @return mixed true (replaced), false ($search not found) or null (no tags found around $search) + */ + public function replaceRow($search, $replacement = '', $throwException = false) + { + return $this->processRow($search, 1, (string)$replacement, false, $throwException); } /** @@ -412,19 +457,19 @@ public function cloneRow( * * @param string $search * - * @return \PhpOffice\PhpWord\Template + * @return boolean */ public function deleteRow($search) { - return $this->deleteSegment($this->ensureMacroCompleted($search), 'w:tr'); + return $this->processRow($search, 0, '', false, false); } /** - * Clone a block. + * process a block. * * @param string $blockname * @param integer $clones - * @param boolean $replace + * @param mixed $replace * @param boolean $incrementVariables * @param boolean $throwException * @@ -432,7 +477,7 @@ public function deleteRow($search) * * @throws \PhpOffice\PhpWord\Exception\Exception */ - public function cloneBlock( + private function processBlock( $blockname, $clones = 1, $replace = true, @@ -443,11 +488,11 @@ public function cloneBlock( $endSearch = '${/' . $blockname . '}'; if (substr($blockname, -1) == '/') { // singleton/closed block - return $this->cloneSegment( + return $this->processSegment( $startSearch, 'w:p', - 'MainPart', $clones, + 'MainPart', $replace, $incrementVariables, $throwException @@ -496,41 +541,98 @@ public function cloneBlock( $xmlBlock = $this->getSlice($this->tempDocumentMainPart, $startBlockEnd, $endBlockStart); - if ($replace) { - $result = $this->getSlice($this->tempDocumentMainPart, 0, $startBlockStart); - for ($i = 1; $i <= $clones; $i++) { - if ($incrementVariables) { - $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlBlock); - } else { - $result .= $xmlBlock; - } + if ($replace !== false) { + if ($replace === true) { + $replace = $this->cloneString($xmlBlock, $clones, $incrementVariables); } - $result .= $this->getSlice($this->tempDocumentMainPart, $endBlockEnd); - - $this->tempDocumentMainPart = $result; + $this->tempDocumentMainPart = + $this->getSlice($this->tempDocumentMainPart, 0, $startBlockStart) + . $replace + . $this->getSlice($this->tempDocumentMainPart, $endBlockEnd); + return true; } return $xmlBlock; } /** - * Clone a segment. + * Clone a block. + * + * @param string $blockname The blockname without '${}', it will search for '${BLOCKNAME}' and '${/BLOCKNAME} + * @param integer $clones How many times the block needs to be cloned + * @param boolean $incrementVariables true by default (variables get appended #1, #2 inside the cloned blocks) + * @param boolean $throwException false by default (it then returns false or null on errors). + * + * @return mixed True if successful, false ($blockname not found) or null (no paragraph found) + * + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + public function cloneBlock( + $blockname, + $clones = 1, + $incrementVariables = true, + $throwException = false + ) { + return $this->processBlock($blockname, $clones, true, $incrementVariables, $throwException); + } + + /** + * Get a block. (first block found) + * + * @param string $blockname + * @param boolean $throwException false by default + * + * @return mixed a string when $blockname is found, false ($blockname not found) or null (no paragraph found) + */ + public function getBlock($blockname, $throwException = false) + { + return $this->processBlock($blockname, 0, false, false, $throwException); + } + + /** + * Replace a block. + * + * @param string $blockname The name of the macro start and end (without the macro marker ${}) + * @param string $replacement The replacement xml + * @param boolean $throwException false by default. + * + * @return mixed false-ish on no replacement, true-ish on replacement + */ + public function replaceBlock($blockname, $replacement = '', $throwException = false) + { + return $this->processBlock($blockname, 0, (string)$replacement, false, $throwException); + } + + /** + * Delete a block of text. + * + * @param string $blockname + * + * @return mixed true-ish on block found and deleted, falseish on block not found. + */ + public function deleteBlock($blockname) + { + return $this->replaceBlock($blockname, '', false); + } + + /** + * process a segment. * * @param string $needle If this is a macro, you need to add the ${} around it yourself. * @param string $xmltag an xml tag without brackets, for example: w:p - * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) * @param integer $clones How many times the segment needs to be cloned - * @param boolean $replace true by default (if you use false, cloneSegment behaves like getSegment()) + * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) + * @param mixed $replace true (default/cloneSegment) false(getSegment) string(replaceSegment) function(callback) * @param boolean $incrementVariables true by default (variables get appended #1, #2 inside the cloned blocks) * @param boolean $throwException false by default (it then returns false or null on errors). * - * @return string|false|null Returns the cloned segment, or false if $needle can not be found or null for no tags + * @return mixed The segment(getSegment), false (no $needle), null (no tags), true (clone/replace) */ - public function cloneSegment( + public function processSegment( $needle, $xmltag, - $docPart = 'MainPart', $clones = 1, + $docPart = 'MainPart', $replace = true, $incrementVariables = true, $throwException = false @@ -545,7 +647,7 @@ public function cloneSegment( if ($needlePos === false) { return $this->failGraciously( - "Can not find segment '$needle', text not found or text contains markup.", + "Can not find macro '$needle', text not found or text contains markup.", $throwException, false ); @@ -556,7 +658,7 @@ public function cloneSegment( if (!$segmentStart || !$segmentEnd) { return $this->failGraciously( - "Can not find <$xmltag> around segment '$needle'", + "Can not find <$xmltag> ($segmentStart,$segmentEnd) around segment '$needle'", $throwException, null ); @@ -564,34 +666,44 @@ public function cloneSegment( $xmlSegment = $this->getSlice($part, $segmentStart, $segmentEnd); - if ($replace) { - $result = $this->getSlice($part, 0, $segmentStart); - for ($i = 1; $i <= $clones; $i++) { - if ($incrementVariables) { - $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $xmlSegment); - } else { - $result .= $xmlSegment; - } + if (is_callable($replace)) { + $replace = $replace($xmlSegment, $segmentStart, $segmentEnd, $part); + } + if ($replace !== false) { + if ($replace === true) { + $replace = $this->cloneString($xmlSegment, $clones, $incrementVariables); } - $result .= $this->getSlice($part, $segmentEnd); - - $part = $result; + $part = + $this->getSlice($part, 0, $segmentStart) + . $replace + . $this->getSlice($part, $segmentEnd); + return true; } return $xmlSegment; } /** - * Get a block. (first block found) + * Clone a segment. * - * @param string $blockname - * @param boolean $throwException + * @param string $needle If this is a macro, you need to add the ${} around it yourself. + * @param string $xmltag an xml tag without brackets, for example: w:p + * @param integer $clones How many times the segment needs to be cloned + * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) + * @param boolean $incrementVariables true by default (variables get appended #1, #2 inside the cloned blocks) + * @param boolean $throwException false by default (it then returns false or null on errors). * - * @return string|null + * @return mixed Returns true when succesfully cloned, false (no $needle found), null (no tags found) */ - public function getBlock($blockname, $throwException = false) - { - return $this->cloneBlock($blockname, 1, false, false, $throwException); + public function cloneSegment( + $needle, + $xmltag, + $clones = 1, + $docPart = 'MainPart', + $incrementVariables = true, + $throwException = false + ) { + return $this->processSegment($needle, $xmltag, $clones, $docPart, true, $incrementVariables, $throwException); } /** @@ -602,78 +714,11 @@ public function getBlock($blockname, $throwException = false) * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) * @param boolean $throwException false by default (it then returns false or null on errors). * - * @return string|false|null true (replaced), false ($needle not found) or null (no tags found around $needle) + * @return mixed Segment String, false ($needle not found) or null (no tags found around $needle) */ public function getSegment($needle, $xmltag, $docPart = 'MainPart', $throwException = false) { - return $this->cloneSegment($needle, $xmltag, $docPart, 1, false, false, $throwException); - } - - /** - * Get a row. (first block found) - * - * @param string $rowname - * @param boolean $throwException - * - * @return string|null - */ - public function getRow($rowname, $throwException = false) - { - return $this->cloneRow($rowname, 1, false, false, $throwException); - } - - /** - * Replace a block. - * - * @param string $blockname The name of the macro start and end (without the macro marker ${}) - * @param string $replacement The replacement xml - * @param boolean $throwException false by default. - * - * @return string|boolean|null false-ish on no replacement, true-ish on replacement - */ - public function replaceBlock($blockname, $replacement = '', $throwException = false) - { - $startSearch = '${' . $blockname . '}'; - $endSearch = '${/' . $blockname . '}'; - - if (substr($blockname, -1) == '/') { // singleton/closed block - return $this->replaceSegment($startSearch, 'w:p', $replacement, 'MainPart', $throwException); - } - - $startTagPos = strpos($this->tempDocumentMainPart, $startSearch); - $endTagPos = strpos($this->tempDocumentMainPart, $endSearch, $startTagPos); - - if (!$startTagPos || !$endTagPos) { - return $this->failGraciously( - "Can not find block '$blockname', template variable not found or variable contains markup.", - $throwException, - false - ); - } - - $startBlockStart = $this->findTagLeft($this->tempDocumentMainPart, '', $startTagPos, $throwException); - $endBlockEnd = $this->findTagRight($this->tempDocumentMainPart, '', $endTagPos); - - if (!$startBlockStart || !$endBlockEnd) { - return $this->failGraciously( - "Can not find paragraph around block '$blockname'", - $throwException, - null - ); - } - - $startBlockEnd = $this->findTagRight($this->tempDocumentMainPart, '', $startTagPos); - if ($startBlockEnd == $endBlockEnd) { // inline block - $startBlockStart = $startTagPos; - $endBlockEnd = $endTagPos + strlen($endSearch); - } - - $this->tempDocumentMainPart = - $this->getSlice($this->tempDocumentMainPart, 0, $startBlockStart) - . $replacement - . $this->getSlice($this->tempDocumentMainPart, $endBlockEnd); - - return true; + return $this->processSegment($needle, $xmltag, 0, $docPart, false, false, $throwException); } /** @@ -685,72 +730,28 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:2' (second header) * @param boolean $throwException false by default (it then returns false or null on errors). * - * @return boolean|null true (replaced), false ($needle not found) or null (no tags found around $needle) + * @return mixed true (replaced), false ($needle not found) or null (no tags found around $needle) */ public function replaceSegment($needle, $xmltag, $replacement = '', $docPart = 'MainPart', $throwException = false) { - $docPart = preg_split('/:/', $docPart); - if (count($docPart)>1) { - $part = &$this->{"tempDocument".$docPart[0]}[$docPart[1]]; - } else { - $part = &$this->{"tempDocument".$docPart[0]}; - } - $needlePos = strpos($part, $needle); - - if ($needlePos === false) { - return $this->failGraciously( - "Can not find segment '$needle', text not found or text contains markup.", - $throwException, - false - ); - } - - $segmentStart = $this->findTagLeft($part, "<$xmltag>", $needlePos, $throwException); - $segmentEnd = $this->findTagRight($part, "", $needlePos); - - if (!$segmentStart || !$segmentEnd) { - return $this->failGraciously( - "Can not find tag $xmltag around segment '$needle'.", - $throwException, - null - ); - } - - $part = - $this->getSlice($part, 0, $segmentStart) - . $replacement - . $this->getSlice($part, $segmentEnd); - - return true; - } - - /** - * Delete a block of text. - * - * @param string $blockname - * - * @return string|true|false|null true-ish on block found and deleted, falseish on block not found. - */ - public function deleteBlock($blockname) - { - return $this->replaceBlock($blockname, '', false); + return $this->processSegment($needle, $xmltag, 0, $docPart, (string)$replacement, false, $throwException); } /** - * Delete a segment of text. + * Delete a segment. * * @param string $needle If this is a macro, you need to add the ${} yourself. * @param string $xmltag an xml tag without brackets, for example: w:p * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (second header) * - * @return true|false|null true (segment deleted), false ($needle not found) or null (no tags found around $needle) + * @return mixed true (segment deleted), false ($needle not found) or null (no tags found around $needle) */ public function deleteSegment($needle, $xmltag, $docPart = 'MainPart') { return $this->replaceSegment($needle, $xmltag, '', $docPart, false); } - /** + /** * Saves the result document. * * @return string The filename of the document @@ -777,6 +778,7 @@ public function save() return $this->tempDocumentFilename; } + /** * Saves the result document to the user defined file. * diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 24a6523950..dd25d3b08c 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -44,6 +44,21 @@ public function peek(&$object, $property) return $refProperty->getValue($object); } + /** + * Construct test + * + * @covers ::__construct + + * @test + */ + public function testConstruct() + { + $object = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\TemplateProcessor', $object); + $this->assertEquals(array(), $object->getVariables()); + } + /** * Template can be saved in temporary location. * @@ -188,7 +203,7 @@ final public function testXslStyleSheetCanNotBeAppliedOnFailureOfLoadingXmlFromT * @covers ::findTagLeft * @covers ::findTagRight * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage Can not clone row, template variable not found or variable contains markup. + * @expectedExceptionMessage Can not find macro * @test */ public function testCloneRow() @@ -216,12 +231,13 @@ public function testCloneRow() $this->assertTrue($docFound); $this->assertEquals( null, - $templateProcessor->cloneRow('userId', 2, false, false, true) + $templateProcessor->cloneRow('userId', 2, false, true) ); } /** * @covers ::getRow + * @covers ::replaceRow * @covers ::saveAs * @covers ::findTagLeft * @covers ::findTagRight @@ -247,17 +263,18 @@ public function testGetRow() $initialArray, $templateProcessor->getVariables() ); - $row = $templateProcessor->cloneRow('userId', 2, true, false, false); $this->assertStringStartsWith('assertStringEndsWith('', $row); - $this->assertNotEmpty($row); + + $result = $templateProcessor->cloneRow('userId', 2, false, false); + $this->assertTrue($result); $templateProcessor->setValue('userLocation', '${foo}', 1); $this->assertEquals( $midArray, array_values($templateProcessor->getVariables()), implode("|", $templateProcessor->getVariables()) ); - $row = $templateProcessor->cloneRow('userId', 2, true, true, false); + $row = $templateProcessor->cloneRow('userId', 2, true, false); $this->assertEquals( $finalArray, $templateProcessor->getVariables() @@ -273,6 +290,19 @@ public function testGetRow() $finalArray, $templateProcessorNewFile->getVariables() ); + $row = $templateProcessorNewFile->getRow('userId'); + $this->assertTrue(strlen($row)>10); + $this->assertTrue( + $templateProcessorNewFile->replaceRow('userId#1', $row) + ); + $this->assertTrue( + $templateProcessorNewFile->replaceRow('userId#2', $row) + ); + // now we have less macro variables (although multiple of them) + $this->assertEquals( + $initialArray, + $templateProcessorNewFile->getVariables() + ); unlink($docName); } } @@ -410,7 +440,7 @@ public function testCloneIndexedBlock() # Now we try again, but without variable incrementals (old behavior) $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); - $templateProcessor->cloneBlock('MYBLOCK', 4, true, false); + $templateProcessor->cloneBlock('MYBLOCK', 4, false); # detects new variable $this->assertEquals( @@ -648,7 +678,7 @@ public function testSetBlock() * @covers ::replaceBlock * @covers ::cloneBlock * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage Can not find paragraph around block + * @expectedExceptionMessage Can not find end paragraph around block * @test */ public function testReplaceBlock() @@ -701,12 +731,12 @@ public function testFailGraciously() $this->assertEquals( null, - $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 'MainPart', 1, true, true, false) + $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 1, 'MainPart', true, false) ); $this->assertEquals( false, - $templateProcessor->cloneSegment('tableHeader', 'DESPACITO', 'MainPart', 1, true, true, false) + $templateProcessor->cloneSegment('tableHeader', 'DESPACITO', 1, 'MainPart', true, false) ); $this->assertEquals( @@ -749,11 +779,11 @@ public function testCloneSegment() throw new \Exception("Could not close zip file"); } - $segment = $templateProcessor->cloneSegment('${footerValue}', 'w:p', 'Footers:1', 2); + $segment = $templateProcessor->cloneSegment('${footerValue}', 'w:p', 2, 'Footers:1'); $this->assertNotNull($segment); - $segment = $templateProcessor->cloneSegment('${headerValue}', 'w:p', 'Headers:1', 2); + $segment = $templateProcessor->cloneSegment('${headerValue}', 'w:p', 2, 'Headers:1'); $this->assertNotNull($segment); - $segment = $templateProcessor->cloneSegment('${documentContent}', 'w:p', 'MainPart', 1); + $segment = $templateProcessor->cloneSegment('${documentContent}', 'w:p', 1, 'MainPart'); $this->assertNotNull($segment); $templateProcessor->setBlock('headerValue#1', "In the end, it doesn't even matter."); @@ -786,7 +816,7 @@ public function testCloneSegment() * @covers ::failGraciously * @covers ::cloneSegment * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage Can not find segment 'I-DO-NOT-EXIST', text not found or text contains markup + * @expectedExceptionMessage Can not find macro 'I-DO-NOT-EXIST', text not found or text contains markup * @test */ final public function testThrowFailGraciously() @@ -794,7 +824,7 @@ final public function testThrowFailGraciously() $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); $this->assertEquals( null, - $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 'MainPart', 1, true, true, true) + $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 1, 'MainPart', true, true) ); } @@ -802,7 +832,7 @@ final public function testThrowFailGraciously() * @covers ::failGraciously * @covers ::replaceSegment * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage Can not find segment 'I-DO-NOT-EXIST', text not found or text contains markup + * @expectedExceptionMessage Can not find macro 'I-DO-NOT-EXIST', text not found or text contains markup * @test */ final public function testAnotherThrowFailGraciously() @@ -882,7 +912,7 @@ final public function testReplaceBlockThrow() /** * @covers ::getSegment * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage Can not find segment 'I-DO-NOT-EXIST', text not found or text contains markup. + * @expectedExceptionMessage Can not find macro 'I-DO-NOT-EXIST', text not found or text contains markup. * @test */ final public function testgetSegmentThrow() From 4f653336bdd93544422807a2d1f2a089cdd7d1a7 Mon Sep 17 00:00:00 2001 From: Nilton Date: Thu, 19 Oct 2017 09:14:57 +0200 Subject: [PATCH 55/74] Stop using this in callback function --- src/PhpWord/TemplateProcessor.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 6a5596fc3d..02f50f9f84 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -379,14 +379,14 @@ function (&$xmlSegment, &$segmentStart, &$segmentEnd, &$part) use (&$replace) { $extraRowEnd = $segmentEnd; while (true) { $extraRowStart = $extraRowEnd + 1; - $extraRowEnd = $this->findTagRight($part, '', $extraRowStart); + $extraRowEnd = strpos($part, '', $extraRowStart); if (!$extraRowEnd) { break; } - + $extraRowEnd += strlen(''); // If tmpXmlRow doesn't contain continue, this row is no longer part of the spanned row. - $tmpXmlRow = $this->getSlice($part, $extraRowStart, $extraRowEnd); + $tmpXmlRow = substr($part, $extraRowStart, ($extraRowEnd - $extraRowStart)); if (!preg_match('##', $tmpXmlRow) && !preg_match('##', $tmpXmlRow) ) { @@ -395,7 +395,7 @@ function (&$xmlSegment, &$segmentStart, &$segmentEnd, &$part) use (&$replace) { // This row was a spanned row, update $segmentEnd and search for the next row. $segmentEnd = $extraRowEnd; } - $xmlSegment = $this->getSlice($part, $segmentStart, $segmentEnd); + $xmlSegment = substr($part, $segmentStart, ($segmentEnd - $segmentStart)); } return $replace; }, From 27dce1e44c5181ac83d9c50afce88913efb8de3d Mon Sep 17 00:00:00 2001 From: Nilton Date: Thu, 19 Oct 2017 17:44:36 +0200 Subject: [PATCH 56/74] Testing protected functions (first steps into 100% test coverage) --- tests/PhpWord/TemplateProcessorTest.php | 33 +++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index dd25d3b08c..20491265ab 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -44,6 +44,21 @@ public function peek(&$object, $property) return $refProperty->getValue($object); } + /** + * Helper function to call protected method + * + * @param mixed $object + * @param string $method + * @param array $args + */ + public static function callProtectedMethod($object, $method, array $args = array()) + { + $class = new \ReflectionClass(get_class($object)); + $method = $class->getMethod($method); + $method->setAccessible(true); + return $method->invokeArgs($object, $args); + } + /** * Construct test * @@ -938,4 +953,22 @@ final public function testCloneBlockThrow() $templateProcessor->cloneBlock('I-DO-NOT-EXIST', 'replace', 1, true, true) ); } + + /** + * Example of testing protected functions + * + * @covers ::findTagRight + * @covers ::findTagLeft + * @test + */ + public function testFindTagRightAndLeft() + { + $testDocument = __DIR__ . '/_files/templates/header-footer.docx'; + $stub = $this->getMockForAbstractClass('\PhpOffice\PhpWord\TemplateProcessor', array($testDocument)); + + $str = '...abcd${dream}efg...'; + $this->assertEquals(true, self::callProtectedMethod($stub, 'findTagRight', array(&$str, '', 0))); + $this->assertEquals(26, self::callProtectedMethod($stub, 'findTagRight', array(&$str, '', 0))); + $this->assertEquals(07, self::callProtectedMethod($stub, 'findTagLeft', array(&$str, '', 20))); + } } From 9fd0fd0704342d3b833e4baa4e0595e9d4058040 Mon Sep 17 00:00:00 2001 From: Nilton Date: Thu, 19 Oct 2017 17:45:56 +0200 Subject: [PATCH 57/74] Incorporating changes from @abcdmitry (unset of references) --- src/PhpWord/TemplateProcessor.php | 62 +++++++++++++++++++------------ 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 02f50f9f84..cd5f24107e 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -182,14 +182,15 @@ public function applyXslStyleSheet($xslDomDocument, $xslOptions = array(), $xslO } /** - * @param string $macro + * @param string $macro If written as VALUE it will return ${VALUE} if TemplateProcessor::$ensureMacroCompletion + * @param boolean $closing False by default, if set to true, will add ${/ } around the macro * * @return string */ - protected static function ensureMacroCompleted(&$macro) + protected static function ensureMacroCompleted($macro, $closing = false) { if (TemplateProcessor::$ensureMacroCompletion && substr($macro, 0, 2) !== '${' && substr($macro, -1) !== '}') { - $macro = '${' . $macro . '}'; + $macro = '${' . ($closing ? '/' : '') . $macro . '}'; } return $macro; @@ -220,18 +221,20 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ { if (is_array($search)) { foreach ($search as &$item) { - self::ensureMacroCompleted($item); + $item = static::ensureMacroCompleted($item); } + unset($item); } else { - self::ensureMacroCompleted($search); + $search = static::ensureMacroCompleted($search); } if (is_array($replace)) { - foreach ($replace as &$item) { - $item = self::ensureUtf8Encoded($item); + foreach ((array)$replace as &$item) { + $item = static::ensureUtf8Encoded($item); } + unset($item); } else { - $replace = self::ensureUtf8Encoded($replace); + $replace = static::ensureUtf8Encoded($replace); } if (Settings::isOutputEscapingEnabled()) { @@ -239,20 +242,30 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ $replace = $xmlEscaper->escape($replace); } - $this->tempDocumentMainPart = $this->setValueForPart($search, $replace, $this->tempDocumentMainPart, $limit); - - $documentParts = array('tempDocumentHeaders', 'tempDocumentFooters'); - foreach ($documentParts as $tempDocumentParts) { - foreach ($this->{$tempDocumentParts} as &$tempDocumentPart) { - $tempDocumentPart = $this->setValueForPart($search, $replace, $tempDocumentPart, $limit); - } - } + $this->tempDocumentHeaders = (array)$this->setValueForPart( + $search, + $replace, + (array)$this->tempDocumentHeaders, + $limit + ); + $this->tempDocumentMainPart = (string)$this->setValueForPart( + $search, + $replace, + (string)$this->tempDocumentMainPart, + $limit + ); + $this->tempDocumentFooters = (array)$this->setValueForPart( + $search, + $replace, + (array)$this->tempDocumentFooters, + $limit + ); } /** * Replaces a closed block with text * - * @param string $blockname Your macro must end with slash, i.e.: ${value/} + * @param string $blockname The blockname without '${}'. Your macro must end with slash, i.e.: ${value/} * @param mixed $replace Array or the text can be multiline (contain \n). It will cloneBlock(). * @param integer $limit * @@ -370,7 +383,7 @@ private function processRow( $throwException = false ) { return $this->processSegment( - $this->ensureMacroCompleted($search), + static::ensureMacroCompleted($search), 'w:tr', $numberOfClones, 'MainPart', @@ -467,7 +480,7 @@ public function deleteRow($search) /** * process a block. * - * @param string $blockname + * @param string $blockname The blockname without '${}' * @param integer $clones * @param mixed $replace * @param boolean $incrementVariables @@ -484,8 +497,8 @@ private function processBlock( $incrementVariables = true, $throwException = false ) { - $startSearch = '${' . $blockname . '}'; - $endSearch = '${/' . $blockname . '}'; + $startSearch = static::ensureMacroCompleted($blockname); + $endSearch = static::ensureMacroCompleted($blockname, true); if (substr($blockname, -1) == '/') { // singleton/closed block return $this->processSegment( @@ -579,7 +592,7 @@ public function cloneBlock( /** * Get a block. (first block found) * - * @param string $blockname + * @param string $blockname The blockname without '${}' * @param boolean $throwException false by default * * @return mixed a string when $blockname is found, false ($blockname not found) or null (no paragraph found) @@ -840,10 +853,10 @@ function ($match) { * * @param mixed $search * @param mixed $replace - * @param string $documentPartXML + * @param mixed $documentPartXML Array or string (Header/Footer) * @param integer $limit * - * @return string + * @return mixed */ protected function setValueForPart($search, $replace, $documentPartXML, $limit) { @@ -852,6 +865,7 @@ protected function setValueForPart($search, $replace, $documentPartXML, $limit) foreach ($replace as &$item) { $item = preg_replace('~\R~u', '', $item); } + unset($item); } else { $replace = preg_replace('~\R~u', '', $replace); } From 883d072d5c5cc156f5d21a74785d341225796fc4 Mon Sep 17 00:00:00 2001 From: Nilton Date: Fri, 20 Oct 2017 04:24:37 +0200 Subject: [PATCH 58/74] More static, better inheritance! --- src/PhpWord/TemplateProcessor.php | 18 +++++++++--------- tests/PhpWord/TemplateProcessorTest.php | 4 ++-- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index cd5f24107e..50241dce81 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -182,14 +182,14 @@ public function applyXslStyleSheet($xslDomDocument, $xslOptions = array(), $xslO } /** - * @param string $macro If written as VALUE it will return ${VALUE} if TemplateProcessor::$ensureMacroCompletion + * @param string $macro If written as VALUE it will return ${VALUE} if static::$ensureMacroCompletion * @param boolean $closing False by default, if set to true, will add ${/ } around the macro * * @return string */ protected static function ensureMacroCompleted($macro, $closing = false) { - if (TemplateProcessor::$ensureMacroCompletion && substr($macro, 0, 2) !== '${' && substr($macro, -1) !== '}') { + if (static::$ensureMacroCompletion && substr($macro, 0, 2) !== '${' && substr($macro, -1) !== '}') { $macro = '${' . ($closing ? '/' : '') . $macro . '}'; } @@ -229,7 +229,7 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ } if (is_array($replace)) { - foreach ((array)$replace as &$item) { + foreach ($replace as &$item) { $item = static::ensureUtf8Encoded($item); } unset($item); @@ -349,12 +349,12 @@ public function getVariables() * * @return string */ - private function cloneString(&$text, $numberOfClones = 1, $incrementVariables = true) + private static function cloneSlice(&$text, $numberOfClones = 1, $incrementVariables = true) { $result = ''; for ($i = 1; $i <= $numberOfClones; $i++) { if ($incrementVariables) { - $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#' . $i . '}', $text); + $result .= preg_replace('/\$\{(.*?)(\/?)\}/', '\${\\1#' . $i . '\\2}', $text); } else { $result .= $text; } @@ -367,7 +367,7 @@ private function cloneString(&$text, $numberOfClones = 1, $incrementVariables = * * @param string $search * @param integer $numberOfClones - * @param mixed $replace (true to clone, or a string to replace) + * @param mixed $replace (true to clone, or a string to replace) * @param bool $incrementVariables * @param bool $throwException * @@ -556,7 +556,7 @@ private function processBlock( if ($replace !== false) { if ($replace === true) { - $replace = $this->cloneString($xmlBlock, $clones, $incrementVariables); + $replace = static::cloneSlice($xmlBlock, $clones, $incrementVariables); } $this->tempDocumentMainPart = $this->getSlice($this->tempDocumentMainPart, 0, $startBlockStart) @@ -684,7 +684,7 @@ public function processSegment( } if ($replace !== false) { if ($replace === true) { - $replace = $this->cloneString($xmlSegment, $clones, $incrementVariables); + $replace = static::cloneSlice($xmlSegment, $clones, $incrementVariables); } $part = $this->getSlice($part, 0, $segmentStart) @@ -886,7 +886,7 @@ protected function setValueForPart($search, $replace, $documentPartXML, $limit) * * @return string[] */ - protected function getVariablesForPart($documentPartXML) + protected static function getVariablesForPart($documentPartXML) { preg_match_all('/\$\{([^<>{}]*?)}/i', $documentPartXML, $matches); diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 20491265ab..c39a68c38b 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -66,7 +66,7 @@ public static function callProtectedMethod($object, $method, array $args = array * @test */ - public function testConstruct() + public function testTheConstruct() { $object = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); @@ -521,7 +521,7 @@ public function testClosedBlock() $templateProcessor->cloneBlock('BLOCKCLOSE/', 4); # detects new variables $this->assertEquals( - array('BEFORE', 'BLOCKCLOSE/#1', 'BLOCKCLOSE/#2', 'BLOCKCLOSE/#3', 'BLOCKCLOSE/#4', 'AFTER'), + array('BEFORE', 'BLOCKCLOSE#1/', 'BLOCKCLOSE#2/', 'BLOCKCLOSE#3/', 'BLOCKCLOSE#4/', 'AFTER'), $templateProcessor->getVariables(), "Injected document should contain the right cloned variables, in the right order" ); From dfa1d692eccd031e6a569397f3a59db1a5e672ba Mon Sep 17 00:00:00 2001 From: Nilton Date: Fri, 20 Oct 2017 04:36:28 +0200 Subject: [PATCH 59/74] Private -> Protected due to static --- src/PhpWord/TemplateProcessor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 50241dce81..53ce5905ae 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -349,7 +349,7 @@ public function getVariables() * * @return string */ - private static function cloneSlice(&$text, $numberOfClones = 1, $incrementVariables = true) + protected static function cloneSlice(&$text, $numberOfClones = 1, $incrementVariables = true) { $result = ''; for ($i = 1; $i <= $numberOfClones; $i++) { From e7faad15b7bc9c4ce809b7690c6383e23076e725 Mon Sep 17 00:00:00 2001 From: Nilton Date: Fri, 20 Oct 2017 04:55:38 +0200 Subject: [PATCH 60/74] Methods with the same name as their class will not be constructors in a future version of PHP --- tests/PhpWord/Shared/ZipArchiveTest.php | 2 +- tests/PhpWord/Writer/PDF/MPDFTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/PhpWord/Shared/ZipArchiveTest.php b/tests/PhpWord/Shared/ZipArchiveTest.php index 1adcfbfc5d..fc5be7523d 100644 --- a/tests/PhpWord/Shared/ZipArchiveTest.php +++ b/tests/PhpWord/Shared/ZipArchiveTest.php @@ -108,7 +108,7 @@ public function testZipArchive($zipClass = 'ZipArchive') * * @covers :: */ - public function testPCLZip() + public function testPCLZipArchiveInstance() { $this->testZipArchive('PhpOffice\PhpWord\Shared\ZipArchive'); } diff --git a/tests/PhpWord/Writer/PDF/MPDFTest.php b/tests/PhpWord/Writer/PDF/MPDFTest.php index b6c85a408e..e0f10fdc7b 100644 --- a/tests/PhpWord/Writer/PDF/MPDFTest.php +++ b/tests/PhpWord/Writer/PDF/MPDFTest.php @@ -30,7 +30,7 @@ class MPDFTest extends \PHPUnit_Framework_TestCase /** * Test construct */ - public function testConstruct() + public function testConstructMPDF() { $file = __DIR__ . '/../../_files/mpdf.pdf'; From 641c2d5014d8b219f2611b7ed2e26cd531c4dcbc Mon Sep 17 00:00:00 2001 From: Nilton Date: Fri, 20 Oct 2017 05:24:48 +0200 Subject: [PATCH 61/74] PHP4 style contructor name = class name to __construct --- src/PhpWord/Shared/PCLZip/pclzip.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PhpWord/Shared/PCLZip/pclzip.lib.php b/src/PhpWord/Shared/PCLZip/pclzip.lib.php index 4e2a496f20..149bf587ad 100644 --- a/src/PhpWord/Shared/PCLZip/pclzip.lib.php +++ b/src/PhpWord/Shared/PCLZip/pclzip.lib.php @@ -212,7 +212,7 @@ class PclZip // Note that no real action is taken, if the archive does not exist it is not // created. Use create() for that. // -------------------------------------------------------------------------------- - function PclZip($p_zipname) + function __construct($p_zipname) { // ----- Tests the zlib From 44b173dd534706a92d734f3959b886bf56664af0 Mon Sep 17 00:00:00 2001 From: Nilton Date: Fri, 20 Oct 2017 05:49:16 +0200 Subject: [PATCH 62/74] revert! --- tests/PhpWord/Shared/ZipArchiveTest.php | 2 +- tests/PhpWord/Writer/PDF/MPDFTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/PhpWord/Shared/ZipArchiveTest.php b/tests/PhpWord/Shared/ZipArchiveTest.php index fc5be7523d..5faed3a23c 100644 --- a/tests/PhpWord/Shared/ZipArchiveTest.php +++ b/tests/PhpWord/Shared/ZipArchiveTest.php @@ -108,7 +108,7 @@ public function testZipArchive($zipClass = 'ZipArchive') * * @covers :: */ - public function testPCLZipArchiveInstance() + public function testPCLZipArchive() { $this->testZipArchive('PhpOffice\PhpWord\Shared\ZipArchive'); } diff --git a/tests/PhpWord/Writer/PDF/MPDFTest.php b/tests/PhpWord/Writer/PDF/MPDFTest.php index e0f10fdc7b..b6c85a408e 100644 --- a/tests/PhpWord/Writer/PDF/MPDFTest.php +++ b/tests/PhpWord/Writer/PDF/MPDFTest.php @@ -30,7 +30,7 @@ class MPDFTest extends \PHPUnit_Framework_TestCase /** * Test construct */ - public function testConstructMPDF() + public function testConstruct() { $file = __DIR__ . '/../../_files/mpdf.pdf'; From f3f8f41a2b30ff3d0c2ddcf317872dce7ac33c86 Mon Sep 17 00:00:00 2001 From: Nilton Date: Fri, 20 Oct 2017 06:05:58 +0200 Subject: [PATCH 63/74] undo unintended --- tests/PhpWord/Shared/ZipArchiveTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/PhpWord/Shared/ZipArchiveTest.php b/tests/PhpWord/Shared/ZipArchiveTest.php index 5faed3a23c..1adcfbfc5d 100644 --- a/tests/PhpWord/Shared/ZipArchiveTest.php +++ b/tests/PhpWord/Shared/ZipArchiveTest.php @@ -108,7 +108,7 @@ public function testZipArchive($zipClass = 'ZipArchive') * * @covers :: */ - public function testPCLZipArchive() + public function testPCLZip() { $this->testZipArchive('PhpOffice\PhpWord\Shared\ZipArchive'); } From 37a11d4dfba26ef8b3f4ffca10d127e50e5ddce2 Mon Sep 17 00:00:00 2001 From: Nilton Date: Fri, 20 Oct 2017 18:39:46 +0200 Subject: [PATCH 64/74] Eat your own dogfood. setBlock: preg_match is only for strings --- src/PhpWord/TemplateProcessor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 53ce5905ae..250d0adda4 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -273,7 +273,7 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ */ public function setBlock($blockname, $replace, $limit = self::MAXIMUM_REPLACEMENTS_DEFAULT) { - if (preg_match('~\R~u', $replace)) { + if (is_string($replace) && preg_match('~\R~u', $replace)) { $replace = preg_split('~\R~u', $replace); } if (is_array($replace)) { From e7ab8b5336f4155eefbf643d1c5f6381ae736e4f Mon Sep 17 00:00:00 2001 From: Nilton Date: Fri, 27 Oct 2017 03:46:59 +0200 Subject: [PATCH 65/74] Bold decision to allow recursive callbacks, this will allow to nest function blocks while still allowing users to use a callback function --- src/PhpWord/TemplateProcessor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 250d0adda4..877de130fc 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -679,7 +679,7 @@ public function processSegment( $xmlSegment = $this->getSlice($part, $segmentStart, $segmentEnd); - if (is_callable($replace)) { + while (is_callable($replace)) { $replace = $replace($xmlSegment, $segmentStart, $segmentEnd, $part); } if ($replace !== false) { From 89d60bb082897a38c10dbbe84279ee9e6b69149b Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 1 Nov 2017 10:19:23 +0100 Subject: [PATCH 66/74] Make the ${ detection harder to grab too much --- src/PhpWord/TemplateProcessor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index 877de130fc..d0dab35132 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -838,7 +838,7 @@ protected function fixBrokenMacros($documentPart) ); foreach ($paragraphs as &$paragraph) { $paragraph = preg_replace_callback( - '|\$(?:<[^{}]*)?\{[^{}]*\}|U', + '|\$(?:<[^\${}]+>)?\{[^{}]*\}|U', function ($match) { return strip_tags($match[0]); }, From 95da7b990d8f974c2b61ff468458b24a68eaf906 Mon Sep 17 00:00:00 2001 From: Nilton Date: Sat, 11 Nov 2017 08:08:06 +0100 Subject: [PATCH 67/74] added param integer $direction in which direction should be searched. -1 left, 1 right. Default 0: around --- src/PhpWord/TemplateProcessor.php | 50 +++++++++++++++++++++---- tests/PhpWord/TemplateProcessorTest.php | 24 ++++++------ 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index d0dab35132..b233a3f8f2 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -385,6 +385,7 @@ private function processRow( return $this->processSegment( static::ensureMacroCompleted($search), 'w:tr', + 0, $numberOfClones, 'MainPart', function (&$xmlSegment, &$segmentStart, &$segmentEnd, &$part) use (&$replace) { @@ -504,6 +505,7 @@ private function processBlock( return $this->processSegment( $startSearch, 'w:p', + 0, $clones, 'MainPart', $replace, @@ -633,6 +635,7 @@ public function deleteBlock($blockname) * * @param string $needle If this is a macro, you need to add the ${} around it yourself. * @param string $xmltag an xml tag without brackets, for example: w:p + * @param integer $direction in which direction should be searched. -1 left, 1 right. Default 0: around * @param integer $clones How many times the segment needs to be cloned * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) * @param mixed $replace true (default/cloneSegment) false(getSegment) string(replaceSegment) function(callback) @@ -644,6 +647,7 @@ public function deleteBlock($blockname) public function processSegment( $needle, $xmltag, + $direction = 0, $clones = 1, $docPart = 'MainPart', $replace = true, @@ -666,8 +670,10 @@ public function processSegment( ); } - $segmentStart = $this->findTagLeft($part, "<$xmltag>", $needlePos, $throwException); - $segmentEnd = $this->findTagRight($part, "", $needlePos); + $directionStart = $direction == 1 ? 'findTagRight' : 'findTagLeft'; + $directionEnd = $direction == -1 ? 'findTagLeft' : 'findTagRight'; + $segmentStart = $this->{$directionStart}($part, "<$xmltag>", $needlePos, $throwException); + $segmentEnd = $this->{$directionEnd}($part, "", $needlePos); if (!$segmentStart || !$segmentEnd) { return $this->failGraciously( @@ -701,6 +707,7 @@ public function processSegment( * * @param string $needle If this is a macro, you need to add the ${} around it yourself. * @param string $xmltag an xml tag without brackets, for example: w:p + * @param integer $direction in which direction should be searched. -1 left, 1 right. Default 0: around * @param integer $clones How many times the segment needs to be cloned * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) * @param boolean $incrementVariables true by default (variables get appended #1, #2 inside the cloned blocks) @@ -711,12 +718,22 @@ public function processSegment( public function cloneSegment( $needle, $xmltag, + $direction = 0, $clones = 1, $docPart = 'MainPart', $incrementVariables = true, $throwException = false ) { - return $this->processSegment($needle, $xmltag, $clones, $docPart, true, $incrementVariables, $throwException); + return $this->processSegment( + $needle, + $xmltag, + $direction, + $clones, + $docPart, + true, + $incrementVariables, + $throwException + ); } /** @@ -724,14 +741,15 @@ public function cloneSegment( * * @param string $needle If this is a macro, you need to add the ${} around it yourself. * @param string $xmltag an xml tag without brackets, for example: w:p + * @param integer $direction in which direction should be searched. -1 left, 1 right. Default 0: around * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) * @param boolean $throwException false by default (it then returns false or null on errors). * * @return mixed Segment String, false ($needle not found) or null (no tags found around $needle) */ - public function getSegment($needle, $xmltag, $docPart = 'MainPart', $throwException = false) + public function getSegment($needle, $xmltag, $direction = 0, $docPart = 'MainPart', $throwException = false) { - return $this->processSegment($needle, $xmltag, 0, $docPart, false, false, $throwException); + return $this->processSegment($needle, $xmltag, $direction, 0, $docPart, false, false, $throwException); } /** @@ -739,15 +757,31 @@ public function getSegment($needle, $xmltag, $docPart = 'MainPart', $throwExcept * * @param string $needle If this is a macro, you need to add the ${} around it yourself. * @param string $xmltag an xml tag without brackets, for example: w:p + * @param integer $direction in which direction should be searched. -1 left, 1 right. Default 0: around * @param string $replacement The replacement xml string. Be careful and keep the xml uncorrupted. * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:2' (second header) * @param boolean $throwException false by default (it then returns false or null on errors). * * @return mixed true (replaced), false ($needle not found) or null (no tags found around $needle) */ - public function replaceSegment($needle, $xmltag, $replacement = '', $docPart = 'MainPart', $throwException = false) - { - return $this->processSegment($needle, $xmltag, 0, $docPart, (string)$replacement, false, $throwException); + public function replaceSegment( + $needle, + $xmltag, + $direction = 0, + $replacement = '', + $docPart = 'MainPart', + $throwException = false + ) { + return $this->processSegment( + $needle, + $xmltag, + $direction, + 0, + $docPart, + (string)$replacement, + false, + $throwException + ); } /** diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index c39a68c38b..358fd59d1b 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -741,32 +741,32 @@ public function testFailGraciously() $this->assertEquals( null, - $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', 'MainPart', false) + $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', 0, 'MainPart', false) ); $this->assertEquals( null, - $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 1, 'MainPart', true, false) + $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 0, 1, 'MainPart', true, false) ); $this->assertEquals( false, - $templateProcessor->cloneSegment('tableHeader', 'DESPACITO', 1, 'MainPart', true, false) + $templateProcessor->cloneSegment('tableHeader', 'DESPACITO', 0, 1, 'MainPart', true, false) ); $this->assertEquals( null, - $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 'IOU', 'Footer:1', false) + $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 0, 'IOU', 'Footer:1', false) ); $this->assertEquals( false, - $templateProcessor->replaceSegment('tableHeader', 'we:be', 'BodyMoving', 'MainPart', false) + $templateProcessor->replaceSegment('tableHeader', 'we:be', 0, 'BodyMoving', 'MainPart', false) ); $this->assertEquals( false, - $templateProcessor->deleteSegment('tableHeader', '>sabotage<', 'MainPart', 1, true, true, false) + $templateProcessor->deleteSegment('tableHeader', '>sabotage<', 'MainPart', 0, 1, true, true, false) ); } @@ -794,11 +794,11 @@ public function testCloneSegment() throw new \Exception("Could not close zip file"); } - $segment = $templateProcessor->cloneSegment('${footerValue}', 'w:p', 2, 'Footers:1'); + $segment = $templateProcessor->cloneSegment('${footerValue}', 'w:p', 0, 2, 'Footers:1'); $this->assertNotNull($segment); - $segment = $templateProcessor->cloneSegment('${headerValue}', 'w:p', 2, 'Headers:1'); + $segment = $templateProcessor->cloneSegment('${headerValue}', 'w:p', 0, 2, 'Headers:1'); $this->assertNotNull($segment); - $segment = $templateProcessor->cloneSegment('${documentContent}', 'w:p', 1, 'MainPart'); + $segment = $templateProcessor->cloneSegment('${documentContent}', 'w:p', 0, 1, 'MainPart'); $this->assertNotNull($segment); $templateProcessor->setBlock('headerValue#1', "In the end, it doesn't even matter."); @@ -839,7 +839,7 @@ final public function testThrowFailGraciously() $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); $this->assertEquals( null, - $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 1, 'MainPart', true, true) + $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 0, 1, 'MainPart', true, true) ); } @@ -855,7 +855,7 @@ final public function testAnotherThrowFailGraciously() $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); $this->assertEquals( null, - $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 'IOU', 'MainPart', true) + $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 0, 'IOU', 'MainPart', true) ); } @@ -935,7 +935,7 @@ final public function testgetSegmentThrow() $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); $this->assertEquals( null, - $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', 'MainPart', true) + $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', 0, 'MainPart', true) ); } From eeb540245bbbdc1bfcb5cfd1e5c68ba803a9af3d Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 15 Nov 2017 17:02:49 +0100 Subject: [PATCH 68/74] add same changes as in original tree --- src/PhpWord/Shared/PCLZip/pclzip.lib.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PhpWord/Shared/PCLZip/pclzip.lib.php b/src/PhpWord/Shared/PCLZip/pclzip.lib.php index 149bf587ad..38b83d110a 100644 --- a/src/PhpWord/Shared/PCLZip/pclzip.lib.php +++ b/src/PhpWord/Shared/PCLZip/pclzip.lib.php @@ -202,7 +202,7 @@ class PclZip // ----- Current status of the magic_quotes_runtime // This value store the php configuration for magic_quotes // The class can then disable the magic_quotes and reset it after - var $magic_quotes_status; + public $magic_quotes_status; // -------------------------------------------------------------------------------- // Function : PclZip() @@ -212,7 +212,7 @@ class PclZip // Note that no real action is taken, if the archive does not exist it is not // created. Use create() for that. // -------------------------------------------------------------------------------- - function __construct($p_zipname) + public function __construct($p_zipname) { // ----- Tests the zlib From 4cc08b4283c6061e9e476c8839f675afb0d2cd43 Mon Sep 17 00:00:00 2001 From: Nilton Date: Wed, 15 Nov 2017 17:05:34 +0100 Subject: [PATCH 69/74] Make Segments also look left/right of the needle to find a block --- src/PhpWord/TemplateProcessor.php | 20 ++++++++------ tests/PhpWord/TemplateProcessorTest.php | 35 ++++++++++++++++--------- 2 files changed, 35 insertions(+), 20 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index b233a3f8f2..fc207ecef9 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -10,7 +10,7 @@ * file that was distributed with this source code. For the full list of * contributors, visit https://github.com/PHPOffice/PHPWord/contributors. * - * @link https://github.com/PHPOffice/PHPWord + * @see https://github.com/PHPOffice/PHPWord * @copyright 2010-2017 PHPWord contributors * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3 */ @@ -29,6 +29,10 @@ class TemplateProcessor { const MAXIMUM_REPLACEMENTS_DEFAULT = -1; + const SEARCH_LEFT = -1; + const SEARCH_RIGHT = 1; + const SEARCH_AROUND = 0; + /** * Enable/disable setValue('key') becoming setValue('${key}') automatically. * Call it like: TemplateProcessor::$ensureMacroCompletion = false; @@ -647,7 +651,7 @@ public function deleteBlock($blockname) public function processSegment( $needle, $xmltag, - $direction = 0, + $direction = self::SEARCH_AROUND, $clones = 1, $docPart = 'MainPart', $replace = true, @@ -670,8 +674,8 @@ public function processSegment( ); } - $directionStart = $direction == 1 ? 'findTagRight' : 'findTagLeft'; - $directionEnd = $direction == -1 ? 'findTagLeft' : 'findTagRight'; + $directionStart = $direction == self::SEARCH_RIGHT ? 'findTagRight' : 'findTagLeft'; + $directionEnd = $direction == self::SEARCH_LEFT ? 'findTagLeft' : 'findTagRight'; $segmentStart = $this->{$directionStart}($part, "<$xmltag>", $needlePos, $throwException); $segmentEnd = $this->{$directionEnd}($part, "", $needlePos); @@ -718,7 +722,7 @@ public function processSegment( public function cloneSegment( $needle, $xmltag, - $direction = 0, + $direction = self::SEARCH_AROUND, $clones = 1, $docPart = 'MainPart', $incrementVariables = true, @@ -767,7 +771,7 @@ public function getSegment($needle, $xmltag, $direction = 0, $docPart = 'MainPar public function replaceSegment( $needle, $xmltag, - $direction = 0, + $direction = self::SEARCH_AROUND, $replacement = '', $docPart = 'MainPart', $throwException = false @@ -801,9 +805,9 @@ public function deleteSegment($needle, $xmltag, $docPart = 'MainPart') /** * Saves the result document. * - * @return string The filename of the document - * * @throws \PhpOffice\PhpWord\Exception\Exception + * + * @return string The filename of the document */ public function save() { diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 358fd59d1b..301aa68ea1 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -738,35 +738,36 @@ public function testReplaceBlock() public function testFailGraciously() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $around = TemplateProcessor::SEARCH_AROUND; $this->assertEquals( null, - $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', 0, 'MainPart', false) + $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', $around, 'MainPart', false) ); $this->assertEquals( null, - $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 0, 1, 'MainPart', true, false) + $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', $around, 1, 'MainPart', true, false) ); $this->assertEquals( false, - $templateProcessor->cloneSegment('tableHeader', 'DESPACITO', 0, 1, 'MainPart', true, false) + $templateProcessor->cloneSegment('tableHeader', 'DESPACITO', $around, 1, 'MainPart', true, false) ); $this->assertEquals( null, - $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 0, 'IOU', 'Footer:1', false) + $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', $around, 'IOU', 'Footer:1', false) ); $this->assertEquals( false, - $templateProcessor->replaceSegment('tableHeader', 'we:be', 0, 'BodyMoving', 'MainPart', false) + $templateProcessor->replaceSegment('tableHeader', 'we:be', $around, 'BodyMoving', 'MainPart', false) ); $this->assertEquals( false, - $templateProcessor->deleteSegment('tableHeader', '>sabotage<', 'MainPart', 0, 1, true, true, false) + $templateProcessor->deleteSegment('tableHeader', '>sabotage<', 'MainPart', $around, 1, true, true, false) ); } @@ -794,11 +795,12 @@ public function testCloneSegment() throw new \Exception("Could not close zip file"); } - $segment = $templateProcessor->cloneSegment('${footerValue}', 'w:p', 0, 2, 'Footers:1'); + $around = TemplateProcessor::SEARCH_AROUND; + $segment = $templateProcessor->cloneSegment('${footerValue}', 'w:p', $around, 2, 'Footers:1'); $this->assertNotNull($segment); - $segment = $templateProcessor->cloneSegment('${headerValue}', 'w:p', 0, 2, 'Headers:1'); + $segment = $templateProcessor->cloneSegment('${headerValue}', 'w:p', $around, 2, 'Headers:1'); $this->assertNotNull($segment); - $segment = $templateProcessor->cloneSegment('${documentContent}', 'w:p', 0, 1, 'MainPart'); + $segment = $templateProcessor->cloneSegment('${documentContent}', 'w:p', $around, 1, 'MainPart'); $this->assertNotNull($segment); $templateProcessor->setBlock('headerValue#1', "In the end, it doesn't even matter."); @@ -839,7 +841,15 @@ final public function testThrowFailGraciously() $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); $this->assertEquals( null, - $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', 0, 1, 'MainPart', true, true) + $templateProcessor->cloneSegment( + 'I-DO-NOT-EXIST', + 'w:p', + TemplateProcessor::SEARCH_AROUND, + 1, + 'MainPart', + true, + true + ) ); } @@ -853,9 +863,10 @@ final public function testThrowFailGraciously() final public function testAnotherThrowFailGraciously() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); + $around = TemplateProcessor::SEARCH_AROUND; $this->assertEquals( null, - $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', 0, 'IOU', 'MainPart', true) + $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', $around, 'IOU', 'MainPart', true) ); } @@ -935,7 +946,7 @@ final public function testgetSegmentThrow() $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); $this->assertEquals( null, - $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', 0, 'MainPart', true) + $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', TemplateProcessor::SEARCH_AROUND, 'MainPart', true) ); } From 1137923703070255f0c159e9d5569e10978b3b66 Mon Sep 17 00:00:00 2001 From: Nilton Date: Thu, 16 Nov 2017 22:32:19 +0100 Subject: [PATCH 70/74] A bug was introduced when search direction was introduced in Segments --- src/PhpWord/TemplateProcessor.php | 109 ++++++++++++++++---- tests/PhpWord/TemplateProcessorTest.php | 127 +++++++++++++++++++----- 2 files changed, 193 insertions(+), 43 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index fc207ecef9..cdcbdb777e 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -529,8 +529,8 @@ private function processBlock( ); } - $startBlockStart = $this->findTagLeft($this->tempDocumentMainPart, '', $startTagPos, $throwException); - $startBlockEnd = $this->findTagRight($this->tempDocumentMainPart, '', $startTagPos); + $startBlockStart = $this->findOpenTagLeft($this->tempDocumentMainPart, '', $startTagPos, $throwException); + $startBlockEnd = $this->findCloseTagRight($this->tempDocumentMainPart, '', $startTagPos); if (!$startBlockStart || !$startBlockEnd) { return $this->failGraciously( @@ -540,8 +540,8 @@ private function processBlock( ); } - $endBlockStart = $this->findTagLeft($this->tempDocumentMainPart, '', $endTagPos, $throwException); - $endBlockEnd = $this->findTagRight($this->tempDocumentMainPart, '', $endTagPos); + $endBlockStart = $this->findOpenTagLeft($this->tempDocumentMainPart, '', $endTagPos, $throwException); + $endBlockEnd = $this->findCloseTagRight($this->tempDocumentMainPart, '', $endTagPos); if (!$endBlockStart || !$endBlockEnd) { return $this->failGraciously( @@ -642,7 +642,7 @@ public function deleteBlock($blockname) * @param integer $direction in which direction should be searched. -1 left, 1 right. Default 0: around * @param integer $clones How many times the segment needs to be cloned * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) - * @param mixed $replace true (default/cloneSegment) false(getSegment) string(replaceSegment) function(callback) + * @param mixed $replace true (default/cloneSegment) false(getSegment) string(replaceSegment) function(callback) * @param boolean $incrementVariables true by default (variables get appended #1, #2 inside the cloned blocks) * @param boolean $throwException false by default (it then returns false or null on errors). * @@ -674,10 +674,18 @@ public function processSegment( ); } - $directionStart = $direction == self::SEARCH_RIGHT ? 'findTagRight' : 'findTagLeft'; - $directionEnd = $direction == self::SEARCH_LEFT ? 'findTagLeft' : 'findTagRight'; + $directionStart = $direction == self::SEARCH_RIGHT ? 'findOpenTagRight' : 'findOpenTagLeft'; + $directionEnd = $direction == self::SEARCH_LEFT ? 'findCloseTagLeft' : 'findCloseTagRight'; $segmentStart = $this->{$directionStart}($part, "<$xmltag>", $needlePos, $throwException); - $segmentEnd = $this->{$directionEnd}($part, "", $needlePos); + $segmentEnd = $this->{$directionEnd}($part, "", $needlePos, $throwException); + + if ($segmentStart >= $segmentEnd && $segmentEnd) { + if ($direction == self::SEARCH_RIGHT) { + $segmentEnd = $this->findCloseTagRight($part, "", $segmentStart); + } else { + $segmentStart = $this->findOpenTagLeft($part, "<$xmltag>", $segmentEnd - 1, $throwException); + } + } if (!$segmentStart || !$segmentEnd) { return $this->failGraciously( @@ -793,13 +801,14 @@ public function replaceSegment( * * @param string $needle If this is a macro, you need to add the ${} yourself. * @param string $xmltag an xml tag without brackets, for example: w:p + * @param integer $direction in which direction should be searched. -1 left, 1 right. Default 0: around * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (second header) * * @return mixed true (segment deleted), false ($needle not found) or null (no tags found around $needle) */ - public function deleteSegment($needle, $xmltag, $docPart = 'MainPart') + public function deleteSegment($needle, $xmltag, $direction = self::SEARCH_AROUND, $docPart = 'MainPart') { - return $this->replaceSegment($needle, $xmltag, '', $docPart, false); + return $this->replaceSegment($needle, $xmltag, $direction, '', $docPart, false); } /** @@ -976,7 +985,7 @@ protected function getFooterName($index) * @throws \PhpOffice\PhpWord\Exception\Exception */ - protected function findTagLeft(&$searchString, $tag, $offset = 0, $throwException = false) + protected function findOpenTagLeft(&$searchString, $tag, $offset = 0, $throwException = false) { $tagStart = strrpos( $searchString, @@ -984,20 +993,60 @@ protected function findTagLeft(&$searchString, $tag, $offset = 0, $throwExceptio ((strlen($searchString) - $offset) * -1) ); - if (!$tagStart) { + if ($tagStart === false) { $tagStart = strrpos( $searchString, $tag, ((strlen($searchString) - $offset) * -1) ); + + if ($tagStart === false) { + return $this->failGraciously( + "Can not find the start position of the item to clone.", + $throwException, + 0 + ); + } } - if (!$tagStart) { - return $this->failGraciously( - "Can not find the start position of the item to clone.", - $throwException, - 0 + return $tagStart; + } + + /** + * Find the start position of the nearest tag before $offset. + * + * @param string $searchString The string we are searching in (the mainbody or an array element of Footers/Headers) + * @param string $tag Fully qualified tag, for example: '' (with brackets!) + * @param integer $offset Do not look from the beginning, but starting at $offset + * @param boolean $throwException + * + * @return integer Zero if not found (due to the nature of xml, your document never starts at 0) + * + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + + protected function findOpenTagRight(&$searchString, $tag, $offset = 0, $throwException = false) + { + $tagStart = strpos( + $searchString, + substr($tag, 0, -1) . ' ', + $offset + ); + + if ($tagStart === false) { + $tagStart = strrpos( + $searchString, + $tag, + $offset ); + + if ($tagStart === false) { + return $this->failGraciously( + "Can not find the start position of the item to clone.", + $throwException, + 0 + ); + } } return $tagStart; @@ -1007,14 +1056,36 @@ protected function findTagLeft(&$searchString, $tag, $offset = 0, $throwExceptio * Find the end position of the nearest $tag after $offset. * * @param string $searchString The string we are searching in (the MainPart or an array element of Footers/Headers) - * @param string $tag Fully qualified tag, for example: '' + * @param string $tag Fully qualified tag, for example: '' * @param integer $offset Do not look from the beginning, but starting at $offset * * @return integer Zero if not found */ - protected function findTagRight(&$searchString, $tag, $offset = 0) + protected function findCloseTagLeft(&$searchString, $tag, $offset = 0) + { + $pos = strrpos($searchString, $tag, ((strlen($searchString) - $offset) * -1)); + + if ($pos !== false) { + return $pos + strlen($tag); + } else { + return 0; + } + } + + + /** + * Find the end position of the nearest $tag after $offset. + * + * @param string $searchString The string we are searching in (the MainPart or an array element of Footers/Headers) + * @param string $tag Fully qualified tag, for example: '' + * @param integer $offset Do not look from the beginning, but starting at $offset + * + * @return integer Zero if not found + */ + protected function findCloseTagRight(&$searchString, $tag, $offset = 0) { $pos = strpos($searchString, $tag, $offset); + if ($pos !== false) { return $pos + strlen($tag); } else { diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 301aa68ea1..c93eb08b5d 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -10,8 +10,8 @@ * file that was distributed with this source code. For the full list of * contributors, visit https://github.com/PHPOffice/PHPWord/contributors. * - * @link https://github.com/PHPOffice/PHPWord - * @copyright 2010-2016 PHPWord contributors + * @see https://github.com/PHPOffice/PHPWord + * @copyright 2010-2017 PHPWord contributors * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3 */ @@ -215,8 +215,8 @@ final public function testXslStyleSheetCanNotBeAppliedOnFailureOfLoadingXmlFromT * @covers ::cloneRow * @covers ::deleteRow * @covers ::saveAs - * @covers ::findTagLeft - * @covers ::findTagRight + * @covers ::findOpenTagLeft + * @covers ::findCloseTagRight * @expectedException \PhpOffice\PhpWord\Exception\Exception * @expectedExceptionMessage Can not find macro * @test @@ -254,8 +254,8 @@ public function testCloneRow() * @covers ::getRow * @covers ::replaceRow * @covers ::saveAs - * @covers ::findTagLeft - * @covers ::findTagRight + * @covers ::findOpenTagLeft + * @covers ::findCloseTagRight * @test */ public function testGetRow() @@ -349,8 +349,8 @@ public function testMacrosCanBeReplacedInHeaderAndFooter() * @covers ::deleteBlock * @covers ::getBlock * @covers ::saveAs - * @covers ::findTagLeft - * @covers ::findTagRight + * @covers ::findOpenTagLeft + * @covers ::findCloseTagRight * @test */ public function testCloneDeleteBlock() @@ -395,8 +395,8 @@ public function testCloneDeleteBlock() * @covers ::cloneBlock * @covers ::getVariables * @covers ::getBlock - * @covers ::findTagLeft - * @covers ::findTagRight + * @covers ::findOpenTagLeft + * @covers ::findCloseTagRight * @covers ::setValue * @test */ @@ -411,7 +411,7 @@ public function testCloneIndexedBlock() $this->assertEquals( $xmlTxt, $templateProcessor->getBlock('MYBLOCK'), - "Block should be cut at the right place (using findTagLeft/findTagRight)" + "Block should be cut at the right place (using findOpenTagLeft/findCloseTagRight)" ); # detects variables @@ -484,8 +484,8 @@ public function testCloneIndexedBlock() * @covers ::getVariables * @covers ::getBlock * @covers ::setValue - * @covers ::findTagLeft - * @covers ::findTagRight + * @covers ::findOpenTagLeft + * @covers ::findCloseTagRight * @test */ public function testClosedBlock() @@ -498,7 +498,7 @@ public function testClosedBlock() $this->assertEquals( $xmlTxt, $templateProcessor->getBlock('BLOCKCLOSE/'), - "Block should be cut at the right place (using findTagLeft/findTagRight)" + "Block should be cut at the right place (using findOpenTagLeft/findCloseTagRight)" ); # detects variables @@ -555,8 +555,8 @@ public function testSetValue() /** * @covers ::setValue * @covers ::saveAs - * @covers ::findTagLeft - * @covers ::findTagRight + * @covers ::findOpenTagLeft + * @covers ::findCloseTagRight * @test */ public function testSetValueMultiline() @@ -597,8 +597,8 @@ public function testSetValueMultiline() /** * @covers ::replaceBlock * @covers ::getBlock - * @covers ::findTagLeft - * @covers ::findTagRight + * @covers ::findOpenTagLeft + * @covers ::findCloseTagRight * @test */ public function testInlineBlock() @@ -769,6 +769,18 @@ public function testFailGraciously() false, $templateProcessor->deleteSegment('tableHeader', '>sabotage<', 'MainPart', $around, 1, true, true, false) ); + $left = TemplateProcessor::SEARCH_LEFT; + $right = TemplateProcessor::SEARCH_RIGHT; + + $this->assertEquals( + false, + $templateProcessor->deleteSegment('tableHeader', '>sabotage<', 'MainPart', $right, 1, true, true, false) + ); + + $this->assertEquals( + false, + $templateProcessor->deleteSegment('tableHeader', '>sabotage<', 'MainPart', $left, 1, true, true, false) + ); } /** @@ -968,18 +980,85 @@ final public function testCloneBlockThrow() /** * Example of testing protected functions * - * @covers ::findTagRight - * @covers ::findTagLeft + * @covers ::findCloseTagRight + * @covers ::findOpenTagLeft + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage Can not find the start position * @test */ - public function testFindTagRightAndLeft() + public function testfindTagRightAndLeft() { $testDocument = __DIR__ . '/_files/templates/header-footer.docx'; $stub = $this->getMockForAbstractClass('\PhpOffice\PhpWord\TemplateProcessor', array($testDocument)); $str = '...abcd${dream}efg...'; - $this->assertEquals(true, self::callProtectedMethod($stub, 'findTagRight', array(&$str, '', 0))); - $this->assertEquals(26, self::callProtectedMethod($stub, 'findTagRight', array(&$str, '', 0))); - $this->assertEquals(07, self::callProtectedMethod($stub, 'findTagLeft', array(&$str, '', 20))); + $this->assertEquals(true, self::callProtectedMethod($stub, 'findCloseTagRight', array(&$str, '', 0))); + $this->assertEquals(26, self::callProtectedMethod($stub, 'findCloseTagRight', array(&$str, '', 0))); + $this->assertEquals(7, self::callProtectedMethod($stub, 'findOpenTagRight', array(&$str, '', 0))); + $this->assertEquals(07, self::callProtectedMethod($stub, 'findOpenTagLeft', array(&$str, '', 20))); + + $str = '...before...abcd${dream}efg...after...'; + $this->assertEquals(0, self::callProtectedMethod($stub, 'findCloseTagRight', array(&$str, '', 44))); + $this->assertEquals(56, self::callProtectedMethod($stub, 'findCloseTagRight', array(&$str, '', 44))); + $this->assertEquals(88, self::callProtectedMethod($stub, 'findCloseTagRight', array(&$str, '', 56))); + $this->assertEquals(3, self::callProtectedMethod($stub, 'findOpenTagLeft', array(&$str, '', 44))); + $this->assertEquals(30, self::callProtectedMethod($stub, 'findCloseTagLeft', array(&$str, '', 44))); + $this->assertEquals(0, self::callProtectedMethod($stub, 'findCloseTagLeft', array(&$str, '', 20))); + + $snipEnd = self::callProtectedMethod($stub, 'findCloseTagLeft', array(&$str, '', 44)); + $snipStart = self::callProtectedMethod($stub, 'findOpenTagLeft', array(&$str, '', $snipEnd)); + $this->assertEquals( + 'before', + self::callProtectedMethod($stub, 'getSlice', array(&$str, $snipStart, $snipEnd)) + ); + + $want = 'after'; + $snipStart = self::callProtectedMethod($stub, 'findOpenTagRight', array(&$str, '', 44)); + $snipEnd = self::callProtectedMethod($stub, 'findCloseTagRight', array(&$str, '', $snipStart)); + $this->assertEquals( + $want, + self::callProtectedMethod($stub, 'getSlice', array(&$str, $snipStart, $snipEnd)) + ); + + + // now throw an exception + $snipStart = self::callProtectedMethod($stub, 'findOpenTagRight', array(&$str, '', $snipStart+1, true)); + } + /** + * testing grabbing segments left and right + * + * @covers ::getSegment + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage Can not find the start position + * @test + */ + public function testGetSegment() + { + $template = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); + $xmlStr = ''. + 'before'. + ''. + '${middle}'. + ''. + 'after'; + + $this->poke($template, 'tempDocumentMainPart', $xmlStr); + + $this->assertEquals( + 'after', + $template->getSegment('${middle}', 'w:p', 1) + ); + + $this->assertEquals( + '${middle}', + $template->getSegment('${middle}', 'w:p', 0) + ); + + $this->assertEquals( + 'before', + $template->getSegment('${middle}', 'w:p', -1) + ); + + $template->getSegment('after', 'w:p', 1, 'MainPart', true); } } From 58eb17336c0a0c41751ebc74bfd75cf0b7b3e2cd Mon Sep 17 00:00:00 2001 From: Nilton Date: Thu, 16 Nov 2017 23:06:44 +0100 Subject: [PATCH 71/74] Replace file to latest develop version, where indentation is different --- src/PhpWord/Shared/PCLZip/pclzip.lib.php | 9506 +++++++++++----------- 1 file changed, 4615 insertions(+), 4891 deletions(-) diff --git a/src/PhpWord/Shared/PCLZip/pclzip.lib.php b/src/PhpWord/Shared/PCLZip/pclzip.lib.php index 38b83d110a..0a69f687a8 100644 --- a/src/PhpWord/Shared/PCLZip/pclzip.lib.php +++ b/src/PhpWord/Shared/PCLZip/pclzip.lib.php @@ -25,5473 +25,5208 @@ // $Id: pclzip.lib.php,v 1.60 2009/09/30 21:01:04 vblavet Exp $ // -------------------------------------------------------------------------------- - // ----- Constants - if (!defined('PCLZIP_READ_BLOCK_SIZE')) { - define( 'PCLZIP_READ_BLOCK_SIZE', 2048 ); - } - - // ----- File list separator - // In version 1.x of PclZip, the separator for file list is a space - // (which is not a very smart choice, specifically for windows paths !). - // A better separator should be a comma (,). This constant gives you the - // abilty to change that. - // However notice that changing this value, may have impact on existing - // scripts, using space separated filenames. - // Recommanded values for compatibility with older versions : - //define( 'PCLZIP_SEPARATOR', ' ' ); - // Recommanded values for smart separation of filenames. - if (!defined('PCLZIP_SEPARATOR')) { - define( 'PCLZIP_SEPARATOR', ',' ); - } - - // ----- Error configuration - // 0 : PclZip Class integrated error handling - // 1 : PclError external library error handling. By enabling this - // you must ensure that you have included PclError library. - // [2,...] : reserved for futur use - if (!defined('PCLZIP_ERROR_EXTERNAL')) { - define( 'PCLZIP_ERROR_EXTERNAL', 0 ); - } - - // ----- Optional static temporary directory - // By default temporary files are generated in the script current - // path. - // If defined : - // - MUST BE terminated by a '/'. - // - MUST be a valid, already created directory - // Samples : - // define( 'PCLZIP_TEMPORARY_DIR', '/temp/' ); - // define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' ); - if (!defined('PCLZIP_TEMPORARY_DIR')) { - define( 'PCLZIP_TEMPORARY_DIR', '' ); - } - - // ----- Optional threshold ratio for use of temporary files - // Pclzip sense the size of the file to add/extract and decide to - // use or not temporary file. The algorythm is looking for - // memory_limit of PHP and apply a ratio. - // threshold = memory_limit * ratio. - // Recommended values are under 0.5. Default 0.47. - // Samples : - // define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.5 ); - if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { - define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.47 ); - } +// ----- Constants +if (!defined('PCLZIP_READ_BLOCK_SIZE')) { + define('PCLZIP_READ_BLOCK_SIZE', 2048); +} + +// ----- File list separator +// In version 1.x of PclZip, the separator for file list is a space +// (which is not a very smart choice, specifically for windows paths !). +// A better separator should be a comma (,). This constant gives you the +// abilty to change that. +// However notice that changing this value, may have impact on existing +// scripts, using space separated filenames. +// Recommanded values for compatibility with older versions : +//define( 'PCLZIP_SEPARATOR', ' ' ); +// Recommanded values for smart separation of filenames. +if (!defined('PCLZIP_SEPARATOR')) { + define('PCLZIP_SEPARATOR', ','); +} + +// ----- Error configuration +// 0 : PclZip Class integrated error handling +// 1 : PclError external library error handling. By enabling this +// you must ensure that you have included PclError library. +// [2,...] : reserved for futur use +if (!defined('PCLZIP_ERROR_EXTERNAL')) { + define('PCLZIP_ERROR_EXTERNAL', 0); +} + +// ----- Optional static temporary directory +// By default temporary files are generated in the script current +// path. +// If defined : +// - MUST BE terminated by a '/'. +// - MUST be a valid, already created directory +// Samples : +// define( 'PCLZIP_TEMPORARY_DIR', '/temp/' ); +// define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' ); +if (!defined('PCLZIP_TEMPORARY_DIR')) { + define('PCLZIP_TEMPORARY_DIR', ''); +} + +// ----- Optional threshold ratio for use of temporary files +// Pclzip sense the size of the file to add/extract and decide to +// use or not temporary file. The algorythm is looking for +// memory_limit of PHP and apply a ratio. +// threshold = memory_limit * ratio. +// Recommended values are under 0.5. Default 0.47. +// Samples : +// define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.5 ); +if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { + define('PCLZIP_TEMPORARY_FILE_RATIO', 0.47); +} // -------------------------------------------------------------------------------- // ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED ***** // -------------------------------------------------------------------------------- - // ----- Global variables - $g_pclzip_version = "2.8.2"; - - // ----- Error codes - // -1 : Unable to open file in binary write mode - // -2 : Unable to open file in binary read mode - // -3 : Invalid parameters - // -4 : File does not exist - // -5 : Filename is too long (max. 255) - // -6 : Not a valid zip file - // -7 : Invalid extracted file size - // -8 : Unable to create directory - // -9 : Invalid archive extension - // -10 : Invalid archive format - // -11 : Unable to delete file (unlink) - // -12 : Unable to rename file (rename) - // -13 : Invalid header checksum - // -14 : Invalid archive size - define( 'PCLZIP_ERR_USER_ABORTED', 2 ); - define( 'PCLZIP_ERR_NO_ERROR', 0 ); - define( 'PCLZIP_ERR_WRITE_OPEN_FAIL', -1 ); - define( 'PCLZIP_ERR_READ_OPEN_FAIL', -2 ); - define( 'PCLZIP_ERR_INVALID_PARAMETER', -3 ); - define( 'PCLZIP_ERR_MISSING_FILE', -4 ); - define( 'PCLZIP_ERR_FILENAME_TOO_LONG', -5 ); - define( 'PCLZIP_ERR_INVALID_ZIP', -6 ); - define( 'PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 ); - define( 'PCLZIP_ERR_DIR_CREATE_FAIL', -8 ); - define( 'PCLZIP_ERR_BAD_EXTENSION', -9 ); - define( 'PCLZIP_ERR_BAD_FORMAT', -10 ); - define( 'PCLZIP_ERR_DELETE_FILE_FAIL', -11 ); - define( 'PCLZIP_ERR_RENAME_FILE_FAIL', -12 ); - define( 'PCLZIP_ERR_BAD_CHECKSUM', -13 ); - define( 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 ); - define( 'PCLZIP_ERR_MISSING_OPTION_VALUE', -15 ); - define( 'PCLZIP_ERR_INVALID_OPTION_VALUE', -16 ); - define( 'PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 ); - define( 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 ); - define( 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 ); - define( 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20 ); - define( 'PCLZIP_ERR_DIRECTORY_RESTRICTION', -21 ); - - // ----- Options values - define( 'PCLZIP_OPT_PATH', 77001 ); - define( 'PCLZIP_OPT_ADD_PATH', 77002 ); - define( 'PCLZIP_OPT_REMOVE_PATH', 77003 ); - define( 'PCLZIP_OPT_REMOVE_ALL_PATH', 77004 ); - define( 'PCLZIP_OPT_SET_CHMOD', 77005 ); - define( 'PCLZIP_OPT_EXTRACT_AS_STRING', 77006 ); - define( 'PCLZIP_OPT_NO_COMPRESSION', 77007 ); - define( 'PCLZIP_OPT_BY_NAME', 77008 ); - define( 'PCLZIP_OPT_BY_INDEX', 77009 ); - define( 'PCLZIP_OPT_BY_EREG', 77010 ); - define( 'PCLZIP_OPT_BY_PREG', 77011 ); - define( 'PCLZIP_OPT_COMMENT', 77012 ); - define( 'PCLZIP_OPT_ADD_COMMENT', 77013 ); - define( 'PCLZIP_OPT_PREPEND_COMMENT', 77014 ); - define( 'PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 ); - define( 'PCLZIP_OPT_REPLACE_NEWER', 77016 ); - define( 'PCLZIP_OPT_STOP_ON_ERROR', 77017 ); - // Having big trouble with crypt. Need to multiply 2 long int - // which is not correctly supported by PHP ... - //define( 'PCLZIP_OPT_CRYPT', 77018 ); - define( 'PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019 ); - define( 'PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020 ); - define( 'PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020 ); // alias - define( 'PCLZIP_OPT_TEMP_FILE_ON', 77021 ); - define( 'PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021 ); // alias - define( 'PCLZIP_OPT_TEMP_FILE_OFF', 77022 ); - define( 'PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022 ); // alias - - // ----- File description attributes - define( 'PCLZIP_ATT_FILE_NAME', 79001 ); - define( 'PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002 ); - define( 'PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003 ); - define( 'PCLZIP_ATT_FILE_MTIME', 79004 ); - define( 'PCLZIP_ATT_FILE_CONTENT', 79005 ); - define( 'PCLZIP_ATT_FILE_COMMENT', 79006 ); - - // ----- Call backs values - define( 'PCLZIP_CB_PRE_EXTRACT', 78001 ); - define( 'PCLZIP_CB_POST_EXTRACT', 78002 ); - define( 'PCLZIP_CB_PRE_ADD', 78003 ); - define( 'PCLZIP_CB_POST_ADD', 78004 ); - /* For futur use - define( 'PCLZIP_CB_PRE_LIST', 78005 ); - define( 'PCLZIP_CB_POST_LIST', 78006 ); - define( 'PCLZIP_CB_PRE_DELETE', 78007 ); - define( 'PCLZIP_CB_POST_DELETE', 78008 ); - */ - - // -------------------------------------------------------------------------------- - // Class : PclZip - // Description : - // PclZip is the class that represent a Zip archive. - // The public methods allow the manipulation of the archive. - // Attributes : - // Attributes must not be accessed directly. - // Methods : - // PclZip() : Object creator - // create() : Creates the Zip archive - // listContent() : List the content of the Zip archive - // extract() : Extract the content of the archive - // properties() : List the properties of the archive - // -------------------------------------------------------------------------------- - class PclZip - { +// ----- Global variables +$g_pclzip_version = "2.8.2"; + +// ----- Error codes +// -1 : Unable to open file in binary write mode +// -2 : Unable to open file in binary read mode +// -3 : Invalid parameters +// -4 : File does not exist +// -5 : Filename is too long (max. 255) +// -6 : Not a valid zip file +// -7 : Invalid extracted file size +// -8 : Unable to create directory +// -9 : Invalid archive extension +// -10 : Invalid archive format +// -11 : Unable to delete file (unlink) +// -12 : Unable to rename file (rename) +// -13 : Invalid header checksum +// -14 : Invalid archive size +define('PCLZIP_ERR_USER_ABORTED', 2); +define('PCLZIP_ERR_NO_ERROR', 0); +define('PCLZIP_ERR_WRITE_OPEN_FAIL', -1); +define('PCLZIP_ERR_READ_OPEN_FAIL', -2); +define('PCLZIP_ERR_INVALID_PARAMETER', -3); +define('PCLZIP_ERR_MISSING_FILE', -4); +define('PCLZIP_ERR_FILENAME_TOO_LONG', -5); +define('PCLZIP_ERR_INVALID_ZIP', -6); +define('PCLZIP_ERR_BAD_EXTRACTED_FILE', -7); +define('PCLZIP_ERR_DIR_CREATE_FAIL', -8); +define('PCLZIP_ERR_BAD_EXTENSION', -9); +define('PCLZIP_ERR_BAD_FORMAT', -10); +define('PCLZIP_ERR_DELETE_FILE_FAIL', -11); +define('PCLZIP_ERR_RENAME_FILE_FAIL', -12); +define('PCLZIP_ERR_BAD_CHECKSUM', -13); +define('PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14); +define('PCLZIP_ERR_MISSING_OPTION_VALUE', -15); +define('PCLZIP_ERR_INVALID_OPTION_VALUE', -16); +define('PCLZIP_ERR_ALREADY_A_DIRECTORY', -17); +define('PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18); +define('PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19); +define('PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20); +define('PCLZIP_ERR_DIRECTORY_RESTRICTION', -21); + +// ----- Options values +define('PCLZIP_OPT_PATH', 77001); +define('PCLZIP_OPT_ADD_PATH', 77002); +define('PCLZIP_OPT_REMOVE_PATH', 77003); +define('PCLZIP_OPT_REMOVE_ALL_PATH', 77004); +define('PCLZIP_OPT_SET_CHMOD', 77005); +define('PCLZIP_OPT_EXTRACT_AS_STRING', 77006); +define('PCLZIP_OPT_NO_COMPRESSION', 77007); +define('PCLZIP_OPT_BY_NAME', 77008); +define('PCLZIP_OPT_BY_INDEX', 77009); +define('PCLZIP_OPT_BY_EREG', 77010); +define('PCLZIP_OPT_BY_PREG', 77011); +define('PCLZIP_OPT_COMMENT', 77012); +define('PCLZIP_OPT_ADD_COMMENT', 77013); +define('PCLZIP_OPT_PREPEND_COMMENT', 77014); +define('PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015); +define('PCLZIP_OPT_REPLACE_NEWER', 77016); +define('PCLZIP_OPT_STOP_ON_ERROR', 77017); +// Having big trouble with crypt. Need to multiply 2 long int +// which is not correctly supported by PHP ... +//define( 'PCLZIP_OPT_CRYPT', 77018 ); +define('PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019); +define('PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020); +define('PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020); // alias +define('PCLZIP_OPT_TEMP_FILE_ON', 77021); +define('PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021); // alias +define('PCLZIP_OPT_TEMP_FILE_OFF', 77022); +define('PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022); // alias + +// ----- File description attributes +define('PCLZIP_ATT_FILE_NAME', 79001); +define('PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002); +define('PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003); +define('PCLZIP_ATT_FILE_MTIME', 79004); +define('PCLZIP_ATT_FILE_CONTENT', 79005); +define('PCLZIP_ATT_FILE_COMMENT', 79006); + +// ----- Call backs values +define('PCLZIP_CB_PRE_EXTRACT', 78001); +define('PCLZIP_CB_POST_EXTRACT', 78002); +define('PCLZIP_CB_PRE_ADD', 78003); +define('PCLZIP_CB_POST_ADD', 78004); +/* For futur use +define( 'PCLZIP_CB_PRE_LIST', 78005 ); +define( 'PCLZIP_CB_POST_LIST', 78006 ); +define( 'PCLZIP_CB_PRE_DELETE', 78007 ); +define( 'PCLZIP_CB_POST_DELETE', 78008 ); +*/ + +// -------------------------------------------------------------------------------- +// Class : PclZip +// Description : +// PclZip is the class that represent a Zip archive. +// The public methods allow the manipulation of the archive. +// Attributes : +// Attributes must not be accessed directly. +// Methods : +// PclZip() : Object creator +// create() : Creates the Zip archive +// listContent() : List the content of the Zip archive +// extract() : Extract the content of the archive +// properties() : List the properties of the archive +// -------------------------------------------------------------------------------- +class PclZip +{ // ----- Filename of the zip file - var $zipname = ''; + public $zipname = ''; // ----- File descriptor of the zip file - var $zip_fd = 0; + public $zip_fd = 0; // ----- Internal error handling - var $error_code = 1; - var $error_string = ''; + public $error_code = 1; + public $error_string = ''; // ----- Current status of the magic_quotes_runtime // This value store the php configuration for magic_quotes // The class can then disable the magic_quotes and reset it after public $magic_quotes_status; - // -------------------------------------------------------------------------------- - // Function : PclZip() - // Description : - // Creates a PclZip object and set the name of the associated Zip archive - // filename. - // Note that no real action is taken, if the archive does not exist it is not - // created. Use create() for that. - // -------------------------------------------------------------------------------- - public function __construct($p_zipname) - { - - // ----- Tests the zlib - if (!function_exists('gzopen')) + // -------------------------------------------------------------------------------- + // Function : PclZip() + // Description : + // Creates a PclZip object and set the name of the associated Zip archive + // filename. + // Note that no real action is taken, if the archive does not exist it is not + // created. Use create() for that. + // -------------------------------------------------------------------------------- + public function __construct($p_zipname) { - die('Abort '.basename(__FILE__).' : Missing zlib extensions'); - } - - // ----- Set the attributes - $this->zipname = $p_zipname; - $this->zip_fd = 0; - $this->magic_quotes_status = -1; - // ----- Return - return; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // create($p_filelist, $p_add_dir="", $p_remove_dir="") - // create($p_filelist, $p_option, $p_option_value, ...) - // Description : - // This method supports two different synopsis. The first one is historical. - // This method creates a Zip Archive. The Zip file is created in the - // filesystem. The files and directories indicated in $p_filelist - // are added in the archive. See the parameters description for the - // supported format of $p_filelist. - // When a directory is in the list, the directory and its content is added - // in the archive. - // In this synopsis, the function takes an optional variable list of - // options. See bellow the supported options. - // Parameters : - // $p_filelist : An array containing file or directory names, or - // a string containing one filename or one directory name, or - // a string containing a list of filenames and/or directory - // names separated by spaces. - // $p_add_dir : A path to add before the real path of the archived file, - // in order to have it memorized in the archive. - // $p_remove_dir : A path to remove from the real path of the file to archive, - // in order to have a shorter path memorized in the archive. - // When $p_add_dir and $p_remove_dir are set, $p_remove_dir - // is removed first, before $p_add_dir is added. - // Options : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_OPT_COMMENT : - // PCLZIP_CB_PRE_ADD : - // PCLZIP_CB_POST_ADD : - // Return Values : - // 0 on failure, - // The list of the added files, with a status of the add action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function create($p_filelist) - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Set default values - $v_options = array(); - $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Look for arguments - if ($v_size > 1) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Remove from the options list the first argument - array_shift($v_arg_list); - $v_size--; - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_ADD => 'optional', - PCLZIP_CB_POST_ADD => 'optional', - PCLZIP_OPT_NO_COMPRESSION => 'optional', - PCLZIP_OPT_COMMENT => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - //, PCLZIP_OPT_CRYPT => 'optional' - )); - if ($v_result != 1) { - return 0; + // ----- Tests the zlib + if (!function_exists('gzopen')) { + die('Abort ' . basename(__FILE__) . ' : Missing zlib extensions'); } - } - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else { + // ----- Set the attributes + $this->zipname = $p_zipname; + $this->zip_fd = 0; + $this->magic_quotes_status = -1; - // ----- Get the first argument - $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; + // ----- Return + return; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // create($p_filelist, $p_add_dir="", $p_remove_dir="") + // create($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two different synopsis. The first one is historical. + // This method creates a Zip Archive. The Zip file is created in the + // filesystem. The files and directories indicated in $p_filelist + // are added in the archive. See the parameters description for the + // supported format of $p_filelist. + // When a directory is in the list, the directory and its content is added + // in the archive. + // In this synopsis, the function takes an optional variable list of + // options. See bellow the supported options. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + public function create($p_filelist) + { + $v_result = 1; - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; - } - else if ($v_size > 2) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, - "Invalid number / type of arguments"); - return 0; + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove from the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + } else { + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } elseif ($v_size > 2) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + return 0; + } + } } - } - } - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); - // ----- Init - $v_string_list = array(); - $v_att_list = array(); - $v_filedescr_list = array(); - $p_result_list = array(); + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); - // ----- Look if the $p_filelist is really an array - if (is_array($p_filelist)) { + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { - // ----- Look if the first element is also an array - // This will mean that this is a file description entry - if (isset($p_filelist[0]) && is_array($p_filelist[0])) { - $v_att_list = $p_filelist; - } + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; - // ----- The list is a list of string names - else { - $v_string_list = $p_filelist; - } - } + // ----- The list is a list of string names + } else { + $v_string_list = $p_filelist; + } - // ----- Look if the $p_filelist is a string - else if (is_string($p_filelist)) { - // ----- Create a list from the string - $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); - } + // ----- Look if the $p_filelist is a string + } elseif (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); - // ----- Invalid variable type for $p_filelist - else { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); - return 0; - } + // ----- Invalid variable type for $p_filelist + } else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); - // ----- Reformat the string list - if (sizeof($v_string_list) != 0) { - foreach ($v_string_list as $v_string) { - if ($v_string != '') { - $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + return 0; } - else { - } - } - } - // ----- For each file in the list check the attributes - $v_supported_attributes - = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' - ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' - ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' - ,PCLZIP_ATT_FILE_MTIME => 'optional' - ,PCLZIP_ATT_FILE_CONTENT => 'optional' - ,PCLZIP_ATT_FILE_COMMENT => 'optional' - ); - foreach ($v_att_list as $v_entry) { - $v_result = $this->privFileDescrParseAtt($v_entry, - $v_filedescr_list[], - $v_options, - $v_supported_attributes); - if ($v_result != 1) { - return 0; - } - } - - // ----- Expand the filelist (expand directories) - $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); - if ($v_result != 1) { - return 0; - } + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + if ($v_string != '') { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } else { + } + } + } - // ----- Call the create fct - $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); - if ($v_result != 1) { - return 0; - } + // ----- For each file in the list check the attributes + $v_supported_attributes = array( + PCLZIP_ATT_FILE_NAME => 'mandatory', + PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional', + PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional', + PCLZIP_ATT_FILE_MTIME => 'optional', + PCLZIP_ATT_FILE_CONTENT => 'optional', + PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } - // ----- Return - return $p_result_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // add($p_filelist, $p_add_dir="", $p_remove_dir="") - // add($p_filelist, $p_option, $p_option_value, ...) - // Description : - // This method supports two synopsis. The first one is historical. - // This methods add the list of files in an existing archive. - // If a file with the same name already exists, it is added at the end of the - // archive, the first one is still present. - // If the archive does not exist, it is created. - // Parameters : - // $p_filelist : An array containing file or directory names, or - // a string containing one filename or one directory name, or - // a string containing a list of filenames and/or directory - // names separated by spaces. - // $p_add_dir : A path to add before the real path of the archived file, - // in order to have it memorized in the archive. - // $p_remove_dir : A path to remove from the real path of the file to archive, - // in order to have a shorter path memorized in the archive. - // When $p_add_dir and $p_remove_dir are set, $p_remove_dir - // is removed first, before $p_add_dir is added. - // Options : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_OPT_COMMENT : - // PCLZIP_OPT_ADD_COMMENT : - // PCLZIP_OPT_PREPEND_COMMENT : - // PCLZIP_CB_PRE_ADD : - // PCLZIP_CB_POST_ADD : - // Return Values : - // 0 on failure, - // The list of the added files, with a status of the add action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function add($p_filelist) - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Set default values - $v_options = array(); - $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Look for arguments - if ($v_size > 1) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Remove form the options list the first argument - array_shift($v_arg_list); - $v_size--; - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_ADD => 'optional', - PCLZIP_CB_POST_ADD => 'optional', - PCLZIP_OPT_NO_COMPRESSION => 'optional', - PCLZIP_OPT_COMMENT => 'optional', - PCLZIP_OPT_ADD_COMMENT => 'optional', - PCLZIP_OPT_PREPEND_COMMENT => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - //, PCLZIP_OPT_CRYPT => 'optional' - )); + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); if ($v_result != 1) { - return 0; + return 0; } - } - - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else { - // ----- Get the first argument - $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; - - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + // ----- Call the create fct + $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; } - else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - // ----- Return - return 0; + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // add($p_filelist, $p_add_dir="", $p_remove_dir="") + // add($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two synopsis. The first one is historical. + // This methods add the list of files in an existing archive. + // If a file with the same name already exists, it is added at the end of the + // archive, the first one is still present. + // If the archive does not exist, it is created. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_OPT_ADD_COMMENT : + // PCLZIP_OPT_PREPEND_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + public function add($p_filelist) + { + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_ADD_COMMENT => 'optional', + PCLZIP_OPT_PREPEND_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + } else { + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } elseif ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } } - } - } - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); - // ----- Init - $v_string_list = array(); - $v_att_list = array(); - $v_filedescr_list = array(); - $p_result_list = array(); + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); - // ----- Look if the $p_filelist is really an array - if (is_array($p_filelist)) { + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { - // ----- Look if the first element is also an array - // This will mean that this is a file description entry - if (isset($p_filelist[0]) && is_array($p_filelist[0])) { - $v_att_list = $p_filelist; - } + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; - // ----- The list is a list of string names - else { - $v_string_list = $p_filelist; - } - } + // ----- The list is a list of string names + } else { + $v_string_list = $p_filelist; + } - // ----- Look if the $p_filelist is a string - else if (is_string($p_filelist)) { - // ----- Create a list from the string - $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); - } + // ----- Look if the $p_filelist is a string + } elseif (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); - // ----- Invalid variable type for $p_filelist - else { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); - return 0; - } + // ----- Invalid variable type for $p_filelist + } else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '" . gettype($p_filelist) . "' for p_filelist"); - // ----- Reformat the string list - if (sizeof($v_string_list) != 0) { - foreach ($v_string_list as $v_string) { - $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; - } - } + return 0; + } - // ----- For each file in the list check the attributes - $v_supported_attributes - = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' - ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' - ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' - ,PCLZIP_ATT_FILE_MTIME => 'optional' - ,PCLZIP_ATT_FILE_CONTENT => 'optional' - ,PCLZIP_ATT_FILE_COMMENT => 'optional' - ); - foreach ($v_att_list as $v_entry) { - $v_result = $this->privFileDescrParseAtt($v_entry, - $v_filedescr_list[], - $v_options, - $v_supported_attributes); - if ($v_result != 1) { - return 0; - } - } + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + } - // ----- Expand the filelist (expand directories) - $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); - if ($v_result != 1) { - return 0; - } + // ----- For each file in the list check the attributes + $v_supported_attributes = array( + PCLZIP_ATT_FILE_NAME => 'mandatory', + PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional', + PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional', + PCLZIP_ATT_FILE_MTIME => 'optional', + PCLZIP_ATT_FILE_CONTENT => 'optional', + PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } - // ----- Call the create fct - $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); - if ($v_result != 1) { - return 0; - } + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + return 0; + } - // ----- Return - return $p_result_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : listContent() - // Description : - // This public method, gives the list of the files and directories, with their - // properties. - // The properties of each entries in the list are (used also in other functions) : - // filename : Name of the file. For a create or add action it is the filename - // given by the user. For an extract function it is the filename - // of the extracted file. - // stored_filename : Name of the file / directory stored in the archive. - // size : Size of the stored file. - // compressed_size : Size of the file's data compressed in the archive - // (without the headers overhead) - // mtime : Last known modification date of the file (UNIX timestamp) - // comment : Comment associated with the file - // folder : true | false - // index : index of the file in the archive - // status : status of the action (depending of the action) : - // Values are : - // ok : OK ! - // filtered : the file / dir is not extracted (filtered by user) - // already_a_directory : the file can not be extracted because a - // directory with the same name already exists - // write_protected : the file can not be extracted because a file - // with the same name already exists and is - // write protected - // newer_exist : the file was not extracted because a newer file exists - // path_creation_fail : the file is not extracted because the folder - // does not exist and can not be created - // write_error : the file was not extracted because there was a - // error while writing the file - // read_error : the file was not extracted because there was a error - // while reading the file - // invalid_header : the file was not extracted because of an archive - // format error (bad file header) - // Note that each time a method can continue operating when there - // is an action error on a file, the error is only logged in the file status. - // Return Values : - // 0 on an unrecoverable failure, - // The list of the files in the archive. - // -------------------------------------------------------------------------------- - function listContent() - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } + // ----- Call the create fct + $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; + } - // ----- Call the extracting fct - $p_list = array(); - if (($v_result = $this->privList($p_list)) != 1) + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : listContent() + // Description : + // This public method, gives the list of the files and directories, with their + // properties. + // The properties of each entries in the list are (used also in other functions) : + // filename : Name of the file. For a create or add action it is the filename + // given by the user. For an extract function it is the filename + // of the extracted file. + // stored_filename : Name of the file / directory stored in the archive. + // size : Size of the stored file. + // compressed_size : Size of the file's data compressed in the archive + // (without the headers overhead) + // mtime : Last known modification date of the file (UNIX timestamp) + // comment : Comment associated with the file + // folder : true | false + // index : index of the file in the archive + // status : status of the action (depending of the action) : + // Values are : + // ok : OK ! + // filtered : the file / dir is not extracted (filtered by user) + // already_a_directory : the file can not be extracted because a + // directory with the same name already exists + // write_protected : the file can not be extracted because a file + // with the same name already exists and is + // write protected + // newer_exist : the file was not extracted because a newer file exists + // path_creation_fail : the file is not extracted because the folder + // does not exist and can not be created + // write_error : the file was not extracted because there was a + // error while writing the file + // read_error : the file was not extracted because there was a error + // while reading the file + // invalid_header : the file was not extracted because of an archive + // format error (bad file header) + // Note that each time a method can continue operating when there + // is an action error on a file, the error is only logged in the file status. + // Return Values : + // 0 on an unrecoverable failure, + // The list of the files in the archive. + // -------------------------------------------------------------------------------- + public function listContent() { - unset($p_list); - return(0); - } + $v_result = 1; - // ----- Return - return $p_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // extract($p_path="./", $p_remove_path="") - // extract([$p_option, $p_option_value, ...]) - // Description : - // This method supports two synopsis. The first one is historical. - // This method extract all the files / directories from the archive to the - // folder indicated in $p_path. - // If you want to ignore the 'root' part of path of the memorized files - // you can indicate this in the optional $p_remove_path parameter. - // By default, if a newer file with the same name already exists, the - // file is not extracted. - // - // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions - // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append - // at the end of the path value of PCLZIP_OPT_PATH. - // Parameters : - // $p_path : Path where the files and directories are to be extracted - // $p_remove_path : First part ('root' part) of the memorized path - // (if any similar) to remove while extracting. - // Options : - // PCLZIP_OPT_PATH : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_CB_PRE_EXTRACT : - // PCLZIP_CB_POST_EXTRACT : - // Return Values : - // 0 or a negative value on failure, - // The list of the extracted files, with a status of the action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function extract() - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } + // ----- Reset the error handler + $this->privErrorReset(); - // ----- Set default values - $v_options = array(); -// $v_path = "./"; - $v_path = ''; - $v_remove_path = ""; - $v_remove_all_path = false; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Default values for option - $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; - - // ----- Look for arguments - if ($v_size > 0) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_PATH => 'optional', - PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_EXTRACT => 'optional', - PCLZIP_CB_POST_EXTRACT => 'optional', - PCLZIP_OPT_SET_CHMOD => 'optional', - PCLZIP_OPT_BY_NAME => 'optional', - PCLZIP_OPT_BY_EREG => 'optional', - PCLZIP_OPT_BY_PREG => 'optional', - PCLZIP_OPT_BY_INDEX => 'optional', - PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', - PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', - PCLZIP_OPT_REPLACE_NEWER => 'optional' - ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' - ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - )); - if ($v_result != 1) { - return 0; + // ----- Check archive + if (!$this->privCheckFormat()) { + return (0); } - // ----- Set the arguments - if (isset($v_options[PCLZIP_OPT_PATH])) { - $v_path = $v_options[PCLZIP_OPT_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { - $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; - } - if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { - $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; - } - if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { - // ----- Check for '/' in last path char - if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { - $v_path .= '/'; - } - $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + // ----- Call the extracting fct + $p_list = array(); + if (($v_result = $this->privList($p_list)) != 1) { + unset($p_list); + + return (0); } - } - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else { + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // extract($p_path="./", $p_remove_path="") + // extract([$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method extract all the files / directories from the archive to the + // folder indicated in $p_path. + // If you want to ignore the 'root' part of path of the memorized files + // you can indicate this in the optional $p_remove_path parameter. + // By default, if a newer file with the same name already exists, the + // file is not extracted. + // + // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions + // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append + // at the end of the path value of PCLZIP_OPT_PATH. + // Parameters : + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 or a negative value on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + public function extract() + { + $v_result = 1; - // ----- Get the first argument - $v_path = $v_arg_list[0]; + // ----- Reset the error handler + $this->privErrorReset(); - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_remove_path = $v_arg_list[1]; + // ----- Check archive + if (!$this->privCheckFormat()) { + return (0); } - else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - // ----- Return - return 0; + // ----- Set default values + $v_options = array(); + // $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( + PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional', + PCLZIP_OPT_STOP_ON_ERROR => 'optional', + PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + } else { + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } elseif ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } } - } - } - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); - // ----- Trace - - // ----- Call the extracting fct - $p_list = array(); - $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, - $v_remove_all_path, $v_options); - if ($v_result < 1) { - unset($p_list); - return(0); - } + // ----- Trace - // ----- Return - return $p_list; - } - // -------------------------------------------------------------------------------- - - - // -------------------------------------------------------------------------------- - // Function : - // extractByIndex($p_index, $p_path="./", $p_remove_path="") - // extractByIndex($p_index, [$p_option, $p_option_value, ...]) - // Description : - // This method supports two synopsis. The first one is historical. - // This method is doing a partial extract of the archive. - // The extracted files or folders are identified by their index in the - // archive (from 0 to n). - // Note that if the index identify a folder, only the folder entry is - // extracted, not all the files included in the archive. - // Parameters : - // $p_index : A single index (integer) or a string of indexes of files to - // extract. The form of the string is "0,4-6,8-12" with only numbers - // and '-' for range or ',' to separate ranges. No spaces or ';' - // are allowed. - // $p_path : Path where the files and directories are to be extracted - // $p_remove_path : First part ('root' part) of the memorized path - // (if any similar) to remove while extracting. - // Options : - // PCLZIP_OPT_PATH : - // PCLZIP_OPT_ADD_PATH : - // PCLZIP_OPT_REMOVE_PATH : - // PCLZIP_OPT_REMOVE_ALL_PATH : - // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and - // not as files. - // The resulting content is in a new field 'content' in the file - // structure. - // This option must be used alone (any other options are ignored). - // PCLZIP_CB_PRE_EXTRACT : - // PCLZIP_CB_POST_EXTRACT : - // Return Values : - // 0 on failure, - // The list of the extracted files, with a status of the action. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - //function extractByIndex($p_index, options...) - function extractByIndex($p_index) - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } + // ----- Call the extracting fct + $p_list = array(); + $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options); + if ($v_result < 1) { + unset($p_list); - // ----- Set default values - $v_options = array(); -// $v_path = "./"; - $v_path = ''; - $v_remove_path = ""; - $v_remove_all_path = false; - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Default values for option - $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; - - // ----- Look for arguments - if ($v_size > 1) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Remove form the options list the first argument - array_shift($v_arg_list); - $v_size--; - - // ----- Look for first arg - if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_PATH => 'optional', - PCLZIP_OPT_REMOVE_PATH => 'optional', - PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', - PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', - PCLZIP_OPT_ADD_PATH => 'optional', - PCLZIP_CB_PRE_EXTRACT => 'optional', - PCLZIP_CB_POST_EXTRACT => 'optional', - PCLZIP_OPT_SET_CHMOD => 'optional', - PCLZIP_OPT_REPLACE_NEWER => 'optional' - ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' - ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', - PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', - PCLZIP_OPT_TEMP_FILE_ON => 'optional', - PCLZIP_OPT_TEMP_FILE_OFF => 'optional' - )); - if ($v_result != 1) { - return 0; + return (0); } - // ----- Set the arguments - if (isset($v_options[PCLZIP_OPT_PATH])) { - $v_path = $v_options[PCLZIP_OPT_PATH]; + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + + // -------------------------------------------------------------------------------- + // Function : + // extractByIndex($p_index, $p_path="./", $p_remove_path="") + // extractByIndex($p_index, [$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method is doing a partial extract of the archive. + // The extracted files or folders are identified by their index in the + // archive (from 0 to n). + // Note that if the index identify a folder, only the folder entry is + // extracted, not all the files included in the archive. + // Parameters : + // $p_index : A single index (integer) or a string of indexes of files to + // extract. The form of the string is "0,4-6,8-12" with only numbers + // and '-' for range or ',' to separate ranges. No spaces or ';' + // are allowed. + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and + // not as files. + // The resulting content is in a new field 'content' in the file + // structure. + // This option must be used alone (any other options are ignored). + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + //function extractByIndex($p_index, options...) + public function extractByIndex($p_index) + { + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return (0); } - if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { - $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + + // ----- Set default values + $v_options = array(); + // $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( + PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional', + PCLZIP_OPT_STOP_ON_ERROR => 'optional', + PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + } else { + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + } else { + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } elseif ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } } - if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { - $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + + // ----- Trace + + // ----- Trick + // Here I want to reuse extractByRule(), so I need to parse the $p_index + // with privParseOptions() + $v_arg_trick = array( + PCLZIP_OPT_BY_INDEX, + $p_index + ); + $v_options_trick = array(); + $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, array( + PCLZIP_OPT_BY_INDEX => 'optional' + )); + if ($v_result != 1) { + return 0; } - if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { - // ----- Check for '/' in last path char - if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { - $v_path .= '/'; - } - $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Call the extracting fct + if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { + return (0); } - if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { - $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // delete([$p_option, $p_option_value, ...]) + // Description : + // This method removes files from the archive. + // If no parameters are given, then all the archive is emptied. + // Parameters : + // None or optional arguments. + // Options : + // PCLZIP_OPT_BY_INDEX : + // PCLZIP_OPT_BY_NAME : + // PCLZIP_OPT_BY_EREG : + // PCLZIP_OPT_BY_PREG : + // Return Values : + // 0 on failure, + // The list of the files which are still present in the archive. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + public function delete() + { + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return (0); } - else { + + // ----- Set default values + $v_options = array(); + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( + PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional' + )); + if ($v_result != 1) { + return 0; + } } - } - // ----- Look for 2 args - // Here we need to support the first historic synopsis of the - // method. - else { + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); - // ----- Get the first argument - $v_path = $v_arg_list[0]; + // ----- Call the delete fct + $v_list = array(); + if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { + $this->privSwapBackMagicQuotes(); + unset($v_list); - // ----- Look for the optional second argument - if ($v_size == 2) { - $v_remove_path = $v_arg_list[1]; + return (0); } - else if ($v_size > 2) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); - // ----- Return - return 0; - } - } - } + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); - // ----- Trace - - // ----- Trick - // Here I want to reuse extractByRule(), so I need to parse the $p_index - // with privParseOptions() - $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); - $v_options_trick = array(); - $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, - array (PCLZIP_OPT_BY_INDEX => 'optional' )); - if ($v_result != 1) { - return 0; + // ----- Return + return $v_list; } - $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; + // -------------------------------------------------------------------------------- - // ----- Look for default option values - $this->privOptionDefaultThreshold($v_options); + // -------------------------------------------------------------------------------- + // Function : deleteByIndex() + // Description : + // ***** Deprecated ***** + // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. + // -------------------------------------------------------------------------------- + public function deleteByIndex($p_index) + { - // ----- Call the extracting fct - if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { - return(0); - } + $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); - // ----- Return - return $p_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : - // delete([$p_option, $p_option_value, ...]) - // Description : - // This method removes files from the archive. - // If no parameters are given, then all the archive is emptied. - // Parameters : - // None or optional arguments. - // Options : - // PCLZIP_OPT_BY_INDEX : - // PCLZIP_OPT_BY_NAME : - // PCLZIP_OPT_BY_EREG : - // PCLZIP_OPT_BY_PREG : - // Return Values : - // 0 on failure, - // The list of the files which are still present in the archive. - // (see PclZip::listContent() for list entry format) - // -------------------------------------------------------------------------------- - function delete() - { - $v_result=1; - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : properties() + // Description : + // This method gives the properties of the archive. + // The properties are : + // nb : Number of files in the archive + // comment : Comment associated with the archive file + // status : not_exist, ok + // Parameters : + // None + // Return Values : + // 0 on failure, + // An array with the archive properties. + // -------------------------------------------------------------------------------- + public function properties() + { - // ----- Set default values - $v_options = array(); - - // ----- Look for variable options arguments - $v_size = func_num_args(); - - // ----- Look for arguments - if ($v_size > 0) { - // ----- Get the arguments - $v_arg_list = func_get_args(); - - // ----- Parse the options - $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, - array (PCLZIP_OPT_BY_NAME => 'optional', - PCLZIP_OPT_BY_EREG => 'optional', - PCLZIP_OPT_BY_PREG => 'optional', - PCLZIP_OPT_BY_INDEX => 'optional' )); - if ($v_result != 1) { - return 0; - } - } + // ----- Reset the error handler + $this->privErrorReset(); - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); - // ----- Call the delete fct - $v_list = array(); - if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { - $this->privSwapBackMagicQuotes(); - unset($v_list); - return(0); - } + // ----- Check archive + if (!$this->privCheckFormat()) { + $this->privSwapBackMagicQuotes(); - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); + return (0); + } - // ----- Return - return $v_list; - } - // -------------------------------------------------------------------------------- + // ----- Default properties + $v_prop = array(); + $v_prop['comment'] = ''; + $v_prop['nb'] = 0; + $v_prop['status'] = 'not_exist'; - // -------------------------------------------------------------------------------- - // Function : deleteByIndex() - // Description : - // ***** Deprecated ***** - // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. - // -------------------------------------------------------------------------------- - function deleteByIndex($p_index) - { + // ----- Look if file exists + if (@is_file($this->zipname)) { + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) { + $this->privSwapBackMagicQuotes(); - $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \'' . $this->zipname . '\' in binary read mode'); - // ----- Return - return $p_list; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : properties() - // Description : - // This method gives the properties of the archive. - // The properties are : - // nb : Number of files in the archive - // comment : Comment associated with the archive file - // status : not_exist, ok - // Parameters : - // None - // Return Values : - // 0 on failure, - // An array with the archive properties. - // -------------------------------------------------------------------------------- - function properties() - { - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); - - // ----- Check archive - if (!$this->privCheckFormat()) { - $this->privSwapBackMagicQuotes(); - return(0); - } + // ----- Return + return 0; + } - // ----- Default properties - $v_prop = array(); - $v_prop['comment'] = ''; - $v_prop['nb'] = 0; - $v_prop['status'] = 'not_exist'; + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + $this->privSwapBackMagicQuotes(); - // ----- Look if file exists - if (@is_file($this->zipname)) - { - // ----- Open the zip file - if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) - { - $this->privSwapBackMagicQuotes(); + return 0; + } - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + // ----- Close the zip file + $this->privCloseFd(); - // ----- Return - return 0; - } + // ----- Set the user attributes + $v_prop['comment'] = $v_central_dir['comment']; + $v_prop['nb'] = $v_central_dir['entries']; + $v_prop['status'] = 'ok'; + } - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { + // ----- Magic quotes trick $this->privSwapBackMagicQuotes(); - return 0; - } - // ----- Close the zip file - $this->privCloseFd(); + // ----- Return + return $v_prop; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : duplicate() + // Description : + // This method creates an archive by copying the content of an other one. If + // the archive already exist, it is replaced by the new one without any warning. + // Parameters : + // $p_archive : The filename of a valid archive, or + // a valid PclZip object. + // Return Values : + // 1 on success. + // 0 or a negative value on error (error code). + // -------------------------------------------------------------------------------- + public function duplicate($p_archive) + { + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); - // ----- Set the user attributes - $v_prop['comment'] = $v_central_dir['comment']; - $v_prop['nb'] = $v_central_dir['entries']; - $v_prop['status'] = 'ok'; - } + // ----- Look if the $p_archive is a PclZip object + if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) { - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive->zipname); - // ----- Return - return $v_prop; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : duplicate() - // Description : - // This method creates an archive by copying the content of an other one. If - // the archive already exist, it is replaced by the new one without any warning. - // Parameters : - // $p_archive : The filename of a valid archive, or - // a valid PclZip object. - // Return Values : - // 1 on success. - // 0 or a negative value on error (error code). - // -------------------------------------------------------------------------------- - function duplicate($p_archive) - { - $v_result = 1; + // ----- Look if the $p_archive is a string (so a filename) + } elseif (is_string($p_archive)) { - // ----- Reset the error handler - $this->privErrorReset(); + // ----- Check that $p_archive is a valid zip file + // TBC : Should also check the archive format + if (!is_file($p_archive)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '" . $p_archive . "'"); + $v_result = PCLZIP_ERR_MISSING_FILE; + } else { + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive); + } - // ----- Look if the $p_archive is a PclZip object - if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) - { + // ----- Invalid variable + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } - // ----- Duplicate the archive - $v_result = $this->privDuplicate($p_archive->zipname); + // ----- Return + return $v_result; } - - // ----- Look if the $p_archive is a string (so a filename) - else if (is_string($p_archive)) + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : merge() + // Description : + // This method merge the $p_archive_to_add archive at the end of the current + // one ($this). + // If the archive ($this) does not exist, the merge becomes a duplicate. + // If the $p_archive_to_add archive does not exist, the merge is a success. + // Parameters : + // $p_archive_to_add : It can be directly the filename of a valid zip archive, + // or a PclZip object archive. + // Return Values : + // 1 on success, + // 0 or negative values on error (see below). + // -------------------------------------------------------------------------------- + public function merge($p_archive_to_add) { + $v_result = 1; - // ----- Check that $p_archive is a valid zip file - // TBC : Should also check the archive format - if (!is_file($p_archive)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); - $v_result = PCLZIP_ERR_MISSING_FILE; - } - else { - // ----- Duplicate the archive - $v_result = $this->privDuplicate($p_archive); - } - } + // ----- Reset the error handler + $this->privErrorReset(); - // ----- Invalid variable - else - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); - $v_result = PCLZIP_ERR_INVALID_PARAMETER; - } + // ----- Check archive + if (!$this->privCheckFormat()) { + return (0); + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : merge() - // Description : - // This method merge the $p_archive_to_add archive at the end of the current - // one ($this). - // If the archive ($this) does not exist, the merge becomes a duplicate. - // If the $p_archive_to_add archive does not exist, the merge is a success. - // Parameters : - // $p_archive_to_add : It can be directly the filename of a valid zip archive, - // or a PclZip object archive. - // Return Values : - // 1 on success, - // 0 or negative values on error (see below). - // -------------------------------------------------------------------------------- - function merge($p_archive_to_add) - { - $v_result = 1; + // ----- Look if the $p_archive_to_add is a PclZip object + if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) { - // ----- Reset the error handler - $this->privErrorReset(); + // ----- Merge the archive + $v_result = $this->privMerge($p_archive_to_add); - // ----- Check archive - if (!$this->privCheckFormat()) { - return(0); - } + // ----- Look if the $p_archive_to_add is a string (so a filename) + } elseif (is_string($p_archive_to_add)) { - // ----- Look if the $p_archive_to_add is a PclZip object - if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) - { + // ----- Create a temporary archive + $v_object_archive = new PclZip($p_archive_to_add); - // ----- Merge the archive - $v_result = $this->privMerge($p_archive_to_add); + // ----- Merge the archive + $v_result = $this->privMerge($v_object_archive); + + // ----- Invalid variable + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- - // ----- Look if the $p_archive_to_add is a string (so a filename) - else if (is_string($p_archive_to_add)) + // -------------------------------------------------------------------------------- + // Function : errorCode() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function errorCode() { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return (PclErrorCode()); + } else { + return ($this->error_code); + } + } + // -------------------------------------------------------------------------------- - // ----- Create a temporary archive - $v_object_archive = new PclZip($p_archive_to_add); + // -------------------------------------------------------------------------------- + // Function : errorName() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function errorName($p_with_code = false) + { + $v_name = array( + PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', + PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', + PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', + PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', + PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', + PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', + PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', + PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', + PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', + PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', + PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', + PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', + PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', + PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', + PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', + PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', + PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', + PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', + PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', + PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', + PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' + ); + + if (isset($v_name[$this->error_code])) { + $v_value = $v_name[$this->error_code]; + } else { + $v_value = 'NoName'; + } - // ----- Merge the archive - $v_result = $this->privMerge($v_object_archive); + if ($p_with_code) { + return ($v_value . ' (' . $this->error_code . ')'); + } else { + return ($v_value); + } } + // -------------------------------------------------------------------------------- - // ----- Invalid variable - else + // -------------------------------------------------------------------------------- + // Function : errorInfo() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function errorInfo($p_full = false) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); - $v_result = PCLZIP_ERR_INVALID_PARAMETER; + if (PCLZIP_ERROR_EXTERNAL == 1) { + return (PclErrorString()); + } else { + if ($p_full) { + return ($this->errorName(true) . " : " . $this->error_string); + } else { + return ($this->error_string . " [code " . $this->error_code . "]"); + } + } } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** + // ***** ***** + // ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCheckFormat() + // Description : + // This method check that the archive exists and is a valid zip archive. + // Several level of check exists. (futur) + // Parameters : + // $p_level : Level of check. Default 0. + // 0 : Check the first bytes (magic codes) (default value)) + // 1 : 0 + Check the central directory (futur) + // 2 : 1 + Check each file header (futur) + // Return Values : + // true on success, + // false on error, the error code is set. + // -------------------------------------------------------------------------------- + public function privCheckFormat($p_level = 0) + { + $v_result = true; - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- + // ----- Reset the file system cache + clearstatcache(); + // ----- Reset the error handler + $this->privErrorReset(); + // ----- Look if the file exits + if (!is_file($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '" . $this->zipname . "'"); - // -------------------------------------------------------------------------------- - // Function : errorCode() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function errorCode() - { - if (PCLZIP_ERROR_EXTERNAL == 1) { - return(PclErrorCode()); - } - else { - return($this->error_code); - } - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : errorName() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function errorName($p_with_code=false) - { - $v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', - PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', - PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', - PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', - PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', - PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', - PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', - PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', - PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', - PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', - PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', - PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', - PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', - PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', - PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', - PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', - PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', - PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', - PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' - ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' - ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' - ); - - if (isset($v_name[$this->error_code])) { - $v_value = $v_name[$this->error_code]; - } - else { - $v_value = 'NoName'; - } + return (false); + } - if ($p_with_code) { - return($v_value.' ('.$this->error_code.')'); - } - else { - return($v_value); - } - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : errorInfo() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function errorInfo($p_full=false) - { - if (PCLZIP_ERROR_EXTERNAL == 1) { - return(PclErrorString()); - } - else { - if ($p_full) { - return($this->errorName(true)." : ".$this->error_string); - } - else { - return($this->error_string." [code ".$this->error_code."]"); - } - } - } - // -------------------------------------------------------------------------------- + // ----- Check that the file is readeable + if (!is_readable($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '" . $this->zipname . "'"); + return (false); + } -// -------------------------------------------------------------------------------- -// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** -// ***** ***** -// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** -// -------------------------------------------------------------------------------- + // ----- Check the magic code + // TBC + // ----- Check the central header + // TBC + // ----- Check each file header + // TBC - // -------------------------------------------------------------------------------- - // Function : privCheckFormat() - // Description : - // This method check that the archive exists and is a valid zip archive. - // Several level of check exists. (futur) - // Parameters : - // $p_level : Level of check. Default 0. - // 0 : Check the first bytes (magic codes) (default value)) - // 1 : 0 + Check the central directory (futur) - // 2 : 1 + Check each file header (futur) - // Return Values : - // true on success, - // false on error, the error code is set. - // -------------------------------------------------------------------------------- - function privCheckFormat($p_level=0) - { - $v_result = true; - - // ----- Reset the file system cache - clearstatcache(); - - // ----- Reset the error handler - $this->privErrorReset(); - - // ----- Look if the file exits - if (!is_file($this->zipname)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); - return(false); + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privParseOptions() + // Description : + // This internal methods reads the variable list of arguments ($p_options_list, + // $p_size) and generate an array with the options and values ($v_result_list). + // $v_requested_options contains the options that can be present and those that + // must be present. + // $v_requested_options is an array, with the option value as key, and 'optional', + // or 'mandatory' as value. + // Parameters : + // See above. + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + public function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options = false) + { + $v_result = 1; - // ----- Check that the file is readeable - if (!is_readable($this->zipname)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); - return(false); - } + // ----- Read the options + $i = 0; + while ($i < $p_size) { + + // ----- Check if the option is supported + if (!isset($v_requested_options[$p_options_list[$i]])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '" . $p_options_list[$i] . "' for this method"); - // ----- Check the magic code - // TBC + // ----- Return + return PclZip::errorCode(); + } - // ----- Check the central header - // TBC + // ----- Look for next option + switch ($p_options_list[$i]) { + // ----- Look for options that request a path value + case PCLZIP_OPT_PATH: + case PCLZIP_OPT_REMOVE_PATH: + case PCLZIP_OPT_ADD_PATH: + // ----- Check the number of parameters + if (($i + 1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i + 1], false); + $i++; + break; + + case PCLZIP_OPT_TEMP_FILE_THRESHOLD: + // ----- Check the number of parameters + if (($i + 1) >= $p_size) { + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + return PclZip::errorCode(); + } + + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + + return PclZip::errorCode(); + } + + // ----- Check the value + $v_value = $p_options_list[$i + 1]; + if ((!is_integer($v_value)) || ($v_value < 0)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + return PclZip::errorCode(); + } + + // ----- Get the value (and convert it in bytes) + $v_result_list[$p_options_list[$i]] = $v_value * 1048576; + $i++; + break; + + case PCLZIP_OPT_TEMP_FILE_ON: + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + break; + + case PCLZIP_OPT_TEMP_FILE_OFF: + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); + + return PclZip::errorCode(); + } + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '" . PclZipUtilOptionText($p_options_list[$i]) . "' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); + + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + break; + + case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION: + // ----- Check the number of parameters + if (($i + 1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i + 1]) && ($p_options_list[$i + 1] != '')) { + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i + 1], false); + $i++; + } else { + } + break; + + // ----- Look for options that request an array of string for value + case PCLZIP_OPT_BY_NAME: + // ----- Check the number of parameters + if (($i + 1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i + 1])) { + $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i + 1]; + } elseif (is_array($p_options_list[$i + 1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1]; + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that request an EREG or PREG expression + case PCLZIP_OPT_BY_EREG: + $p_options_list[$i] = PCLZIP_OPT_BY_PREG; + // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG + // to PCLZIP_OPT_BY_PREG + case PCLZIP_OPT_BY_PREG: + //case PCLZIP_OPT_CRYPT : + // ----- Check the number of parameters + if (($i + 1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i + 1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1]; + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that takes a string + case PCLZIP_OPT_COMMENT: + case PCLZIP_OPT_ADD_COMMENT: + case PCLZIP_OPT_PREPEND_COMMENT: + // ----- Check the number of parameters + if (($i + 1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i + 1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1]; + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that request an array of index + case PCLZIP_OPT_BY_INDEX: + // ----- Check the number of parameters + if (($i + 1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_work_list = array(); + if (is_string($p_options_list[$i + 1])) { + + // ----- Remove spaces + $p_options_list[$i + 1] = strtr($p_options_list[$i + 1], ' ', ''); + + // ----- Parse items + $v_work_list = explode(",", $p_options_list[$i + 1]); + } elseif (is_integer($p_options_list[$i + 1])) { + $v_work_list[0] = $p_options_list[$i + 1] . '-' . $p_options_list[$i + 1]; + } elseif (is_array($p_options_list[$i + 1])) { + $v_work_list = $p_options_list[$i + 1]; + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Reduce the index list + // each index item in the list must be a couple with a start and + // an end value : [0,3], [5-5], [8-10], ... + // ----- Check the format of each item + $v_sort_flag = false; + $v_sort_value = 0; + for ($j = 0; $j < sizeof($v_work_list); $j++) { + // ----- Explode the item + $v_item_list = explode("-", $v_work_list[$j]); + $v_size_item_list = sizeof($v_item_list); + + // ----- TBC : Here we might check that each item is a + // real integer ... + + // ----- Look for single value + if ($v_size_item_list == 1) { + // ----- Set the option value + $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0]; + $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0]; + } elseif ($v_size_item_list == 2) { + // ----- Set the option value + $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0]; + $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1]; + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for list sort + if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) { + $v_sort_flag = true; + + // ----- TBC : An automatic sort should be writen ... + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + $v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start']; + } + + // ----- Sort the items + if ($v_sort_flag) { + // TBC : To Be Completed + } + + // ----- Next option + $i++; + break; + + // ----- Look for options that request no value + case PCLZIP_OPT_REMOVE_ALL_PATH: + case PCLZIP_OPT_EXTRACT_AS_STRING: + case PCLZIP_OPT_NO_COMPRESSION: + case PCLZIP_OPT_EXTRACT_IN_OUTPUT: + case PCLZIP_OPT_REPLACE_NEWER: + case PCLZIP_OPT_STOP_ON_ERROR: + $v_result_list[$p_options_list[$i]] = true; + break; + + // ----- Look for options that request an octal value + case PCLZIP_OPT_SET_CHMOD: + // ----- Check the number of parameters + if (($i + 1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = $p_options_list[$i + 1]; + $i++; + break; + + // ----- Look for options that request a call-back + case PCLZIP_CB_PRE_EXTRACT: + case PCLZIP_CB_POST_EXTRACT: + case PCLZIP_CB_PRE_ADD: + case PCLZIP_CB_POST_ADD: + /* for futur use + case PCLZIP_CB_PRE_DELETE : + case PCLZIP_CB_POST_DELETE : + case PCLZIP_CB_PRE_LIST : + case PCLZIP_CB_POST_LIST : + */ + // ----- Check the number of parameters + if (($i + 1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_function_name = $p_options_list[$i + 1]; + + // ----- Check that the value is a valid existing function + if (!function_exists($v_function_name)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '" . $v_function_name . "()' is not an existing function for option '" . PclZipUtilOptionText($p_options_list[$i]) . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Set the attribute + $v_result_list[$p_options_list[$i]] = $v_function_name; + $i++; + break; + + default: + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '" . $p_options_list[$i] . "'"); + + // ----- Return + return PclZip::errorCode(); + } - // ----- Check each file header - // TBC + // ----- Next options + $i++; + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privParseOptions() - // Description : - // This internal methods reads the variable list of arguments ($p_options_list, - // $p_size) and generate an array with the options and values ($v_result_list). - // $v_requested_options contains the options that can be present and those that - // must be present. - // $v_requested_options is an array, with the option value as key, and 'optional', - // or 'mandatory' as value. - // Parameters : - // See above. - // Return Values : - // 1 on success. - // 0 on failure. - // -------------------------------------------------------------------------------- - function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false) - { - $v_result=1; - - // ----- Read the options - $i=0; - while ($i<$p_size) { - - // ----- Check if the option is supported - if (!isset($v_requested_options[$p_options_list[$i]])) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key = reset($v_requested_options); $key = key($v_requested_options); $key = next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + // ----- Look if present + if (!isset($v_result_list[$key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter " . PclZipUtilOptionText($key) . "(" . $key . ")"); + + // ----- Return + return PclZip::errorCode(); + } + } + } + } + + // ----- Look for default values + if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + + } // ----- Return - return PclZip::errorCode(); - } - - // ----- Look for next option - switch ($p_options_list[$i]) { - // ----- Look for options that request a path value - case PCLZIP_OPT_PATH : - case PCLZIP_OPT_REMOVE_PATH : - case PCLZIP_OPT_ADD_PATH : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return $v_result; + } + // -------------------------------------------------------------------------------- - // ----- Return - return PclZip::errorCode(); - } + // -------------------------------------------------------------------------------- + // Function : privOptionDefaultThreshold() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privOptionDefaultThreshold(&$p_options) + { + $v_result = 1; - // ----- Get the value - $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); - $i++; - break; + if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) { + return $v_result; + } - case PCLZIP_OPT_TEMP_FILE_THRESHOLD : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - return PclZip::errorCode(); - } + // ----- Get 'memory_limit' configuration value + $v_memory_limit = ini_get('memory_limit'); + $v_memory_limit = trim($v_memory_limit); + $last = strtolower(substr($v_memory_limit, -1)); + $v_memory_limit = preg_replace('/[^0-9,.]/', '', $v_memory_limit); - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); - return PclZip::errorCode(); - } + if ($last == 'g') { + //$v_memory_limit = $v_memory_limit*1024*1024*1024; + $v_memory_limit = $v_memory_limit * 1073741824; + } + if ($last == 'm') { + //$v_memory_limit = $v_memory_limit*1024*1024; + $v_memory_limit = $v_memory_limit * 1048576; + } + if ($last == 'k') { + $v_memory_limit = $v_memory_limit * 1024; + } - // ----- Check the value - $v_value = $p_options_list[$i+1]; - if ((!is_integer($v_value)) || ($v_value<0)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); - return PclZip::errorCode(); - } + $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit * PCLZIP_TEMPORARY_FILE_RATIO); - // ----- Get the value (and convert it in bytes) - $v_result_list[$p_options_list[$i]] = $v_value*1048576; - $i++; - break; + // ----- Sanity check : No threshold if value lower than 1M + if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) { + unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]); + } - case PCLZIP_OPT_TEMP_FILE_ON : - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); - return PclZip::errorCode(); - } + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrParseAtt() + // Description : + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + public function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options = false) + { + $v_result = 1; - $v_result_list[$p_options_list[$i]] = true; - break; + // ----- For each file in the list check the attributes + foreach ($p_file_list as $v_key => $v_value) { - case PCLZIP_OPT_TEMP_FILE_OFF : - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); - return PclZip::errorCode(); - } - // ----- Check for incompatible options - if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); - return PclZip::errorCode(); - } + // ----- Check if the option is supported + if (!isset($v_requested_options[$v_key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '" . $v_key . "' for this file"); - $v_result_list[$p_options_list[$i]] = true; - break; + // ----- Return + return PclZip::errorCode(); + } - case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + // ----- Look for attribute + switch ($v_key) { + case PCLZIP_ATT_FILE_NAME: + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type " . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'"); - // ----- Return - return PclZip::errorCode(); - } + return PclZip::errorCode(); + } - // ----- Get the value - if ( is_string($p_options_list[$i+1]) - && ($p_options_list[$i+1] != '')) { - $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); - $i++; - } - else { - } - break; - - // ----- Look for options that request an array of string for value - case PCLZIP_OPT_BY_NAME : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); - // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; - } - else if (is_array($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + if ($p_filedescr['filename'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '" . PclZipUtilOptionText($v_key) . "'"); - // ----- Return - return PclZip::errorCode(); - } - $i++; - break; - - // ----- Look for options that request an EREG or PREG expression - case PCLZIP_OPT_BY_EREG : - // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG - // to PCLZIP_OPT_BY_PREG - $p_options_list[$i] = PCLZIP_OPT_BY_PREG; - case PCLZIP_OPT_BY_PREG : - //case PCLZIP_OPT_CRYPT : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); + } - // ----- Return - return PclZip::errorCode(); - } + break; - // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + case PCLZIP_ATT_FILE_NEW_SHORT_NAME: + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type " . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'"); - // ----- Return - return PclZip::errorCode(); - } - $i++; - break; - - // ----- Look for options that takes a string - case PCLZIP_OPT_COMMENT : - case PCLZIP_OPT_ADD_COMMENT : - case PCLZIP_OPT_PREPEND_COMMENT : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, - "Missing parameter value for option '" - .PclZipUtilOptionText($p_options_list[$i]) - ."'"); + return PclZip::errorCode(); + } - // ----- Return - return PclZip::errorCode(); - } + $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); - // ----- Get the value - if (is_string($p_options_list[$i+1])) { - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, - "Wrong parameter value for option '" - .PclZipUtilOptionText($p_options_list[$i]) - ."'"); + if ($p_filedescr['new_short_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '" . PclZipUtilOptionText($v_key) . "'"); - // ----- Return - return PclZip::errorCode(); - } - $i++; - break; - - // ----- Look for options that request an array of index - case PCLZIP_OPT_BY_INDEX : - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); + } + break; + case PCLZIP_ATT_FILE_NEW_FULL_NAME: + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type " . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return PclZip::errorCode(); + } + + $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['new_full_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return PclZip::errorCode(); + } + break; + + // ----- Look for options that takes a string + case PCLZIP_ATT_FILE_COMMENT: + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type " . gettype($v_value) . ". String expected for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return PclZip::errorCode(); + } + + $p_filedescr['comment'] = $v_value; + break; + + case PCLZIP_ATT_FILE_MTIME: + if (!is_integer($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type " . gettype($v_value) . ". Integer expected for attribute '" . PclZipUtilOptionText($v_key) . "'"); + + return PclZip::errorCode(); + } + + $p_filedescr['mtime'] = $v_value; + break; + + case PCLZIP_ATT_FILE_CONTENT: + $p_filedescr['content'] = $v_value; + break; + + default: + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '" . $v_key . "'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key = reset($v_requested_options); $key = key($v_requested_options); $key = next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + // ----- Look if present + if (!isset($p_file_list[$key])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter " . PclZipUtilOptionText($key) . "(" . $key . ")"); + + return PclZip::errorCode(); + } + } + } + } + + // end foreach + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrExpand() + // Description : + // This method look for each item of the list to see if its a file, a folder + // or a string to be added as file. For any other type of files (link, other) + // just ignore the item. + // Then prepare the information that will be stored for that file. + // When its a folder, expand the folder with all the files that are in that + // folder (recursively). + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + public function privFileDescrExpand(&$p_filedescr_list, &$p_options) + { + $v_result = 1; + + // ----- Create a result list + $v_result_list = array(); + + // ----- Look each entry + for ($i = 0; $i < sizeof($p_filedescr_list); $i++) { + + // ----- Get filedescr + $v_descr = $p_filedescr_list[$i]; + + // ----- Reduce the filename + $v_descr['filename'] = PclZipUtilTranslateWinPath($v_descr['filename'], false); + $v_descr['filename'] = PclZipUtilPathReduction($v_descr['filename']); + + // ----- Look for real file or folder + if (file_exists($v_descr['filename'])) { + if (@is_file($v_descr['filename'])) { + $v_descr['type'] = 'file'; + } elseif (@is_dir($v_descr['filename'])) { + $v_descr['type'] = 'folder'; + } elseif (@is_link($v_descr['filename'])) { + // skip + continue; + } else { + // skip + continue; + } + + // ----- Look for string added as file + } elseif (isset($v_descr['content'])) { + $v_descr['type'] = 'virtual_file'; + + // ----- Missing file + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '" . $v_descr['filename'] . "' does not exist"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Calculate the stored filename + $this->privCalculateStoredFilename($v_descr, $p_options); + + // ----- Add the descriptor in result list + $v_result_list[sizeof($v_result_list)] = $v_descr; + + // ----- Look for folder + if ($v_descr['type'] == 'folder') { + // ----- List of items in folder + $v_dirlist_descr = array(); + $v_dirlist_nb = 0; + if ($v_folder_handler = @opendir($v_descr['filename'])) { + while (($v_item_handler = @readdir($v_folder_handler)) !== false) { + + // ----- Skip '.' and '..' + if (($v_item_handler == '.') || ($v_item_handler == '..')) { + continue; + } + + // ----- Compose the full filename + $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'] . '/' . $v_item_handler; + + // ----- Look for different stored filename + // Because the name of the folder was changed, the name of the + // files/sub-folders also change + if (($v_descr['stored_filename'] != $v_descr['filename']) && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) { + if ($v_descr['stored_filename'] != '') { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'] . '/' . $v_item_handler; + } else { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler; + } + } + + $v_dirlist_nb++; + } + + @closedir($v_folder_handler); + } else { + // TBC : unable to open folder in read mode + } + + // ----- Expand each element of the list + if ($v_dirlist_nb != 0) { + // ----- Expand + if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) { + return $v_result; + } + + // ----- Concat the resulting list + $v_result_list = array_merge($v_result_list, $v_dirlist_descr); + } else { + } + + // ----- Free local array + unset($v_dirlist_descr); + } + } + + // ----- Get the result list + $p_filedescr_list = $v_result_list; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCreate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privCreate($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result = 1; + $v_list_detail = array(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the file in write mode + if (($v_result = $this->privOpenFd('wb')) != 1) { // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - $v_work_list = array(); - if (is_string($p_options_list[$i+1])) { - - // ----- Remove spaces - $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); - - // ----- Parse items - $v_work_list = explode(",", $p_options_list[$i+1]); - } - else if (is_integer($p_options_list[$i+1])) { - $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; - } - else if (is_array($p_options_list[$i+1])) { - $v_work_list = $p_options_list[$i+1]; - } - else { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return $v_result; + } + + // ----- Add the list of files + $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options); + + // ----- Close + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAdd() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privAdd($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result = 1; + $v_list_detail = array(); + + // ----- Look if the archive exists or is empty + if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) { + + // ----- Do a create + $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options); // ----- Return - return PclZip::errorCode(); - } - - // ----- Reduce the index list - // each index item in the list must be a couple with a start and - // an end value : [0,3], [5-5], [8-10], ... - // ----- Check the format of each item - $v_sort_flag=false; - $v_sort_value=0; - for ($j=0; $j= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return $v_result; + } + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + if (($v_result = $this->privOpenFd('rb')) != 1) { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); // ----- Return - return PclZip::errorCode(); - } - - // ----- Get the value - $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; - $i++; - break; - - // ----- Look for options that request a call-back - case PCLZIP_CB_PRE_EXTRACT : - case PCLZIP_CB_POST_EXTRACT : - case PCLZIP_CB_PRE_ADD : - case PCLZIP_CB_POST_ADD : - /* for futur use - case PCLZIP_CB_PRE_DELETE : - case PCLZIP_CB_POST_DELETE : - case PCLZIP_CB_PRE_LIST : - case PCLZIP_CB_POST_LIST : - */ - // ----- Check the number of parameters - if (($i+1) >= $p_size) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.tmp'; + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_zip_temp_name . '\' in binary write mode'); // ----- Return return PclZip::errorCode(); - } + } - // ----- Get the value - $v_function_name = $p_options_list[$i+1]; + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } - // ----- Check that the value is a valid existing function - if (!function_exists($v_function_name)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); // ----- Return - return PclZip::errorCode(); - } + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } - // ----- Set the attribute - $v_result_list[$p_options_list[$i]] = $v_function_name; - $i++; - break; + // ----- Create the Central Dir files header + for ($i = 0, $v_count = 0; $i < sizeof($v_header_list); $i++) { + // ----- Create the file header + if ($v_header_list[$i]['status'] == 'ok') { + if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = $v_central_dir['comment']; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { + $v_comment = $v_comment . $p_options[PCLZIP_OPT_ADD_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT] . $v_comment; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd) - $v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count + $v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); - default : - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, - "Unknown parameter '" - .$p_options_list[$i]."'"); + // ----- Close the temporary file + @fclose($v_zip_temp_fd); - // ----- Return - return PclZip::errorCode(); - } + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); - // ----- Next options - $i++; + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOpenFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function privOpenFd($p_mode) + { + $v_result = 1; - // ----- Look for mandatory options - if ($v_requested_options !== false) { - for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { - // ----- Look for mandatory option - if ($v_requested_options[$key] == 'mandatory') { - // ----- Look if present - if (!isset($v_result_list[$key])) { + // ----- Look if already open + if ($this->zip_fd != 0) { // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \'' . $this->zipname . '\' already open'); // ----- Return return PclZip::errorCode(); - } } - } - } - // ----- Look for default values - if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \'' . $this->zipname . '\' in ' . $p_mode . ' mode'); + // ----- Return + return PclZip::errorCode(); + } + + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privOptionDefaultThreshold() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privOptionDefaultThreshold(&$p_options) - { - $v_result=1; - - if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) - || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) { - return $v_result; + // -------------------------------------------------------------------------------- + // Function : privCloseFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function privCloseFd() + { + $v_result = 1; + + if ($this->zip_fd != 0) { + @fclose($this->zip_fd); + } + $this->zip_fd = 0; + + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddList() + // Description : + // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is + // different from the real path of the file. This is usefull if you want to have PclTar + // running in any directory, and memorize relative path from an other directory. + // Parameters : + // $p_list : An array containing the file or directory names to add in the tar + // $p_result_list : list of added files with their properties (specially the status field) + // $p_add_dir : Path to add in the filename path archived + // $p_remove_dir : Path to remove in the filename path archived + // Return Values : + // -------------------------------------------------------------------------------- + // function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) + public function privAddList($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result = 1; - // ----- Get 'memory_limit' configuration value - $v_memory_limit = ini_get('memory_limit'); - $v_memory_limit = trim($v_memory_limit); - $last = strtolower(substr($v_memory_limit, -1)); + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) { + // ----- Return + return $v_result; + } - if($last == 'g') - //$v_memory_limit = $v_memory_limit*1024*1024*1024; - $v_memory_limit = $v_memory_limit*1073741824; - if($last == 'm') - //$v_memory_limit = $v_memory_limit*1024*1024; - $v_memory_limit = $v_memory_limit*1048576; - if($last == 'k') - $v_memory_limit = $v_memory_limit*1024; + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); - $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO); + // ----- Create the Central Dir files header + for ($i = 0, $v_count = 0; $i < sizeof($v_header_list); $i++) { + // ----- Create the file header + if ($v_header_list[$i]['status'] == 'ok') { + if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) { + // ----- Return + return $v_result; + } + $v_count++; + } + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } - // ----- Sanity check : No threshold if value lower than 1M - if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) { - unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]); - } + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privFileDescrParseAtt() - // Description : - // Parameters : - // Return Values : - // 1 on success. - // 0 on failure. - // -------------------------------------------------------------------------------- - function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false) - { - $v_result=1; - - // ----- For each file in the list check the attributes - foreach ($p_file_list as $v_key => $v_value) { - - // ----- Check if the option is supported - if (!isset($v_requested_options[$v_key])) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file"); + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd) - $v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + return $v_result; + } // ----- Return - return PclZip::errorCode(); - } - - // ----- Look for attribute - switch ($v_key) { - case PCLZIP_ATT_FILE_NAME : - if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileList() + // Description : + // Parameters : + // $p_filedescr_list : An array containing the file description + // or directory names to add in the zip + // $p_result_list : list of added files with their properties (specially the status field) + // Return Values : + // -------------------------------------------------------------------------------- + public function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result = 1; + $v_header = array(); - $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); + // ----- Recuperate the current number of elt in list + $v_nb = sizeof($p_result_list); - if ($p_filedescr['filename'] == '') { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } + // ----- Loop on the files + for ($j = 0; ($j < sizeof($p_filedescr_list)) && ($v_result == 1); $j++) { + // ----- Format the filename + $p_filedescr_list[$j]['filename'] = PclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false); - break; + // ----- Skip empty file names + // TBC : Can this be possible ? not checked in DescrParseAtt ? + if ($p_filedescr_list[$j]['filename'] == "") { + continue; + } - case PCLZIP_ATT_FILE_NEW_SHORT_NAME : - if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } + // ----- Check the filename + if (($p_filedescr_list[$j]['type'] != 'virtual_file') && (!file_exists($p_filedescr_list[$j]['filename']))) { + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '" . $p_filedescr_list[$j]['filename'] . "' does not exist"); - $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); + return PclZip::errorCode(); + } - if ($p_filedescr['new_short_name'] == '') { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } - break; + // ----- Look if it is a file or a dir with no all path remove option + // or a dir with all its path removed + // if ( (is_file($p_filedescr_list[$j]['filename'])) + // || ( is_dir($p_filedescr_list[$j]['filename']) + if (($p_filedescr_list[$j]['type'] == 'file') || ($p_filedescr_list[$j]['type'] == 'virtual_file') || (($p_filedescr_list[$j]['type'] == 'folder') && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]) || !$p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) { - case PCLZIP_ATT_FILE_NEW_FULL_NAME : - if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } + // ----- Add the file + $v_result = $this->privAddFile($p_filedescr_list[$j], $v_header, $p_options); + if ($v_result != 1) { + return $v_result; + } - $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); + // ----- Store the file infos + $p_result_list[$v_nb++] = $v_header; + } + } - if ($p_filedescr['new_full_name'] == '') { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } - break; + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- - // ----- Look for options that takes a string - case PCLZIP_ATT_FILE_COMMENT : - if (!is_string($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); - return PclZip::errorCode(); - } + // -------------------------------------------------------------------------------- + // Function : privAddFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privAddFile($p_filedescr, &$p_header, &$p_options) + { + $v_result = 1; - $p_filedescr['comment'] = $v_value; - break; + // ----- Working variable + $p_filename = $p_filedescr['filename']; - case PCLZIP_ATT_FILE_MTIME : - if (!is_integer($v_value)) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'"); + // TBC : Already done in the fileAtt check ... ? + if ($p_filename == "") { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); + + // ----- Return return PclZip::errorCode(); - } - - $p_filedescr['mtime'] = $v_value; - break; - - case PCLZIP_ATT_FILE_CONTENT : - $p_filedescr['content'] = $v_value; - break; - - default : - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, - "Unknown parameter '".$v_key."'"); - - // ----- Return - return PclZip::errorCode(); - } - - // ----- Look for mandatory options - if ($v_requested_options !== false) { - for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { - // ----- Look for mandatory option - if ($v_requested_options[$key] == 'mandatory') { - // ----- Look if present - if (!isset($p_file_list[$key])) { - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); - return PclZip::errorCode(); - } - } } - } - // end foreach - } + // ----- Look for a stored different filename + /* TBC : Removed + if (isset($p_filedescr['stored_filename'])) { + $v_stored_filename = $p_filedescr['stored_filename']; + } else { + $v_stored_filename = $p_filedescr['stored_filename']; + } + */ - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privFileDescrExpand() - // Description : - // This method look for each item of the list to see if its a file, a folder - // or a string to be added as file. For any other type of files (link, other) - // just ignore the item. - // Then prepare the information that will be stored for that file. - // When its a folder, expand the folder with all the files that are in that - // folder (recursively). - // Parameters : - // Return Values : - // 1 on success. - // 0 on failure. - // -------------------------------------------------------------------------------- - function privFileDescrExpand(&$p_filedescr_list, &$p_options) - { - $v_result=1; - - // ----- Create a result list - $v_result_list = array(); - - // ----- Look each entry - for ($i=0; $iprivCalculateStoredFilename($v_descr, $p_options); + // ------ Look for file comment + if (isset($p_filedescr['comment'])) { + $p_header['comment_len'] = strlen($p_filedescr['comment']); + $p_header['comment'] = $p_filedescr['comment']; + } else { + $p_header['comment_len'] = 0; + $p_header['comment'] = ''; + } - // ----- Add the descriptor in result list - $v_result_list[sizeof($v_result_list)] = $v_descr; + // ----- Look for pre-add callback + if (isset($p_options[PCLZIP_CB_PRE_ADD])) { - // ----- Look for folder - if ($v_descr['type'] == 'folder') { - // ----- List of items in folder - $v_dirlist_descr = array(); - $v_dirlist_nb = 0; - if ($v_folder_handler = @opendir($v_descr['filename'])) { - while (($v_item_handler = @readdir($v_folder_handler)) !== false) { + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_header['status'] = "skipped"; + $v_result = 1; + } - // ----- Skip '.' and '..' - if (($v_item_handler == '.') || ($v_item_handler == '..')) { - continue; + // ----- Update the informations + // Only some fields can be modified + if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { + $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']); } + } + + // ----- Look for empty stored filename + if ($p_header['stored_filename'] == "") { + $p_header['status'] = "filtered"; + } + + // ----- Check the path length + if (strlen($p_header['stored_filename']) > 0xFF) { + $p_header['status'] = 'filename_too_long'; + } + + // ----- Look if no error, or file not skipped + if ($p_header['status'] == 'ok') { - // ----- Compose the full filename - $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler; - - // ----- Look for different stored filename - // Because the name of the folder was changed, the name of the - // files/sub-folders also change - if (($v_descr['stored_filename'] != $v_descr['filename']) - && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) { - if ($v_descr['stored_filename'] != '') { - $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler; - } - else { - $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler; - } + // ----- Look for a file + if ($p_filedescr['type'] == 'file') { + // ----- Look for using temporary file to zip + if ((!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])))) { + $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + + // ----- Use "in memory" zip algo + } else { + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + + return PclZip::errorCode(); + } + + // ----- Read the file content + $v_content = @fread($v_file, $p_header['size']); + + // ----- Close the file + @fclose($v_file); + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + + // ----- Look for normal compression + } else { + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + + } + + // ----- Look for a virtual file (a file from string) + } elseif ($p_filedescr['type'] == 'virtual_file') { + + $v_content = $p_filedescr['content']; + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + + // ----- Look for normal compression + } else { + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + + // ----- Look for a directory + } elseif ($p_filedescr['type'] == 'folder') { + // ----- Look for directory last '/' + if (@substr($p_header['stored_filename'], -1) != '/') { + $p_header['stored_filename'] .= '/'; + } + + // ----- Set the file properties + $p_header['size'] = 0; + //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked + $p_header['external'] = 0x00000010; // Value for a folder : to be checked + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + return $v_result; + } } + } - $v_dirlist_nb++; - } + // ----- Look for post-add callback + if (isset($p_options[PCLZIP_CB_POST_ADD])) { - @closedir($v_folder_handler); + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header); + if ($v_result == 0) { + // ----- Ignored + $v_result = 1; + } + + // ----- Update the informations + // Nothing can be modified } - else { - // TBC : unable to open folder in read mode + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options) + { + $v_result = PCLZIP_ERR_NO_ERROR; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + + return PclZip::errorCode(); } - // ----- Expand each element of the list - if ($v_dirlist_nb != 0) { - // ----- Expand - if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) { - return $v_result; - } + // ----- Creates a compressed temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.gz'; + if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary write mode'); - // ----- Concat the resulting list - $v_result_list = array_merge($v_result_list, $v_dirlist_descr); + return PclZip::errorCode(); } - else { + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = filesize($p_filename); + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @gzputs($v_file_compressed, $v_buffer, $v_read_size); + $v_size -= $v_read_size; } - // ----- Free local array - unset($v_dirlist_descr); - } - } + // ----- Close the file + @fclose($v_file); + @gzclose($v_file_compressed); - // ----- Get the result list - $p_filedescr_list = $v_result_list; + // ----- Check the minimum file size + if (filesize($v_gzip_temp_name) < 18) { + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \'' . $v_gzip_temp_name . '\' has invalid filesize - should be minimum 18 bytes'); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privCreate() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privCreate($p_filedescr_list, &$p_result_list, &$p_options) - { - $v_result=1; - $v_list_detail = array(); - - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); - - // ----- Open the file in write mode - if (($v_result = $this->privOpenFd('wb')) != 1) - { - // ----- Return - return $v_result; - } + return PclZip::errorCode(); + } - // ----- Add the list of files - $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options); + // ----- Extract the compressed attributes + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary read mode'); - // ----- Close - $this->privCloseFd(); + return PclZip::errorCode(); + } - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); + // ----- Read the gzip file header + $v_binary_data = @fread($v_file_compressed, 10); + $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privAdd() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privAdd($p_filedescr_list, &$p_result_list, &$p_options) - { - $v_result=1; - $v_list_detail = array(); - - // ----- Look if the archive exists or is empty - if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) - { + // ----- Check some parameters + $v_data_header['os'] = bin2hex($v_data_header['os']); - // ----- Do a create - $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options); + // ----- Read the gzip file footer + @fseek($v_file_compressed, filesize($v_gzip_temp_name) - 8); + $v_binary_data = @fread($v_file_compressed, 8); + $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data); - // ----- Return - return $v_result; - } - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); + // ----- Set the attributes + $p_header['compression'] = ord($v_data_header['cm']); + //$p_header['mtime'] = $v_data_header['mtime']; + $p_header['crc'] = $v_data_footer['crc']; + $p_header['compressed_size'] = filesize($v_gzip_temp_name) - 18; - // ----- Open the zip file - if (($v_result=$this->privOpenFd('rb')) != 1) - { - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); + // ----- Close the file + @fclose($v_file_compressed); - // ----- Return - return $v_result; - } + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + return $v_result; + } - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result; - } + // ----- Add the compressed data + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary read mode'); - // ----- Go to beginning of File - @rewind($this->zip_fd); + return PclZip::errorCode(); + } - // ----- Creates a temporay file - $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + fseek($v_file_compressed, 10); + $v_size = $p_header['compressed_size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_file_compressed, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) - { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); + // ----- Close the file + @fclose($v_file_compressed); - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + // ----- Unlink the temporary file + @unlink($v_gzip_temp_name); - // ----- Return - return PclZip::errorCode(); + // ----- Return + return $v_result; } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the central dir - $v_size = $v_central_dir['offset']; - while ($v_size != 0) + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCalculateStoredFilename() + // Description : + // Based on file descriptor properties and global options, this method + // calculate the filename that will be stored in the archive. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privCalculateStoredFilename(&$p_filedescr, &$p_options) { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } + $v_result = 1; - // ----- Swap the file descriptor - // Here is a trick : I swap the temporary fd with the zip fd, in order to use - // the following methods on the temporary fil and not the real archive - $v_swap = $this->zip_fd; - $this->zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; + // ----- Working variables + $p_filename = $p_filedescr['filename']; + if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { + $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; + } else { + $p_add_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { + $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; + } else { + $p_remove_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } else { + $p_remove_all_dir = 0; + } - // ----- Add the files - $v_header_list = array(); - if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) - { - fclose($v_zip_temp_fd); - $this->privCloseFd(); - @unlink($v_zip_temp_name); - $this->privSwapBackMagicQuotes(); + // ----- Look for full name change + if (isset($p_filedescr['new_full_name'])) { + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); + + // ----- Look for path and/or short name change + } else { + + // ----- Look for short name change + // Its when we cahnge just the filename but not the path + if (isset($p_filedescr['new_short_name'])) { + $v_path_info = pathinfo($p_filename); + $v_dir = ''; + if ($v_path_info['dirname'] != '') { + $v_dir = $v_path_info['dirname'] . '/'; + } + $v_stored_filename = $v_dir . $p_filedescr['new_short_name']; + } else { + // ----- Calculate the stored filename + $v_stored_filename = $p_filename; + } - // ----- Return - return $v_result; - } + // ----- Look for all path to remove + if ($p_remove_all_dir) { + $v_stored_filename = basename($p_filename); + + // ----- Look for partial path remove + } elseif ($p_remove_dir != "") { + if (substr($p_remove_dir, -1) != '/') { + $p_remove_dir .= "/"; + } + + if ((substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) { + + if ((substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) { + $p_remove_dir = "./" . $p_remove_dir; + } + if ((substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) { + $p_remove_dir = substr($p_remove_dir, 2); + } + } + + $v_compare = PclZipUtilPathInclusion($p_remove_dir, $v_stored_filename); + if ($v_compare > 0) { + if ($v_compare == 2) { + $v_stored_filename = ""; + } else { + $v_stored_filename = substr($v_stored_filename, strlen($p_remove_dir)); + } + } + } - // ----- Store the offset of the central dir - $v_offset = @ftell($this->zip_fd); + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); - // ----- Copy the block of file headers from the old archive - $v_size = $v_central_dir['size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($v_zip_temp_fd, $v_read_size); - @fwrite($this->zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; + // ----- Look for path to add + if ($p_add_dir != "") { + if (substr($p_add_dir, -1) == "/") { + $v_stored_filename = $p_add_dir . $v_stored_filename; + } else { + $v_stored_filename = $p_add_dir . "/" . $v_stored_filename; + } + } + } + + // ----- Filename (reduce the path of stored name) + $v_stored_filename = PclZipUtilPathReduction($v_stored_filename); + $p_filedescr['stored_filename'] = $v_stored_filename; + + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- - // ----- Create the Central Dir files header - for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { - fclose($v_zip_temp_fd); - $this->privCloseFd(); - @unlink($v_zip_temp_name); - $this->privSwapBackMagicQuotes(); - - // ----- Return - return $v_result; - } - $v_count++; - } - - // ----- Transform the header to a 'usable' info - $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); - } + $v_result = 1; - // ----- Zip file comment - $v_comment = $v_central_dir['comment']; - if (isset($p_options[PCLZIP_OPT_COMMENT])) { - $v_comment = $p_options[PCLZIP_OPT_COMMENT]; - } - if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { - $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT]; - } - if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { - $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment; - } + // ----- Store the offset position of the file + $p_header['offset'] = ftell($this->zip_fd); - // ----- Calculate the size of the central header - $v_size = @ftell($this->zip_fd)-$v_offset; + // ----- Transform UNIX mtime to DOS format mdate/mtime + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours'] << 11) + ($v_date['minutes'] << 5) + $v_date['seconds'] / 2; + $v_mdate = (($v_date['year'] - 1980) << 9) + ($v_date['mon'] << 5) + $v_date['mday']; - // ----- Create the central dir footer - if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) - { - // ----- Reset the file list - unset($v_header_list); - $this->privSwapBackMagicQuotes(); + // ----- Packed data + $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len']); - // ----- Return - return $v_result; - } + // ----- Write the first 148 bytes of the header in the archive + fputs($this->zip_fd, $v_binary_data, 30); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } - // ----- Swap back the file descriptor - $v_swap = $this->zip_fd; - $this->zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- - // ----- Close - $this->privCloseFd(); + // -------------------------------------------------------------------------------- + // Function : privWriteCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privWriteCentralFileHeader(&$p_header) + { + $v_result = 1; - // ----- Close the temporary file - @fclose($v_zip_temp_fd); + // TBC + //for (reset($p_header); $key = key($p_header); next($p_header)) { + //} - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); + // ----- Transform UNIX mtime to DOS format mdate/mtime + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours'] << 11) + ($v_date['minutes'] << 5) + $v_date['seconds'] / 2; + $v_mdate = (($v_date['year'] - 1980) << 9) + ($v_date['mon'] << 5) + $v_date['mday']; - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->zipname); + // ----- Packed data + $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, $p_header['version'], $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len'], $p_header['comment_len'], $p_header['disk'], $p_header['internal'], $p_header['external'], $p_header['offset']); - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->zipname); - PclZipUtilRename($v_zip_temp_name, $this->zipname); + // ----- Write the 42 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 46); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privOpenFd() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function privOpenFd($p_mode) - { - $v_result=1; - - // ----- Look if already open - if ($this->zip_fd != 0) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open'); + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + if ($p_header['comment_len'] != 0) { + fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); + } - // ----- Return - return PclZip::errorCode(); + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- - // ----- Open the zip file - if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) + // -------------------------------------------------------------------------------- + // Function : privWriteCentralHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode'); + $v_result = 1; - // ----- Return - return PclZip::errorCode(); - } + // ----- Packed data + $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, $p_nb_entries, $p_size, $p_offset, strlen($p_comment)); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privCloseFd() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function privCloseFd() - { - $v_result=1; - - if ($this->zip_fd != 0) - @fclose($this->zip_fd); - $this->zip_fd = 0; + // ----- Write the 22 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 22); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privAddList() - // Description : - // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is - // different from the real path of the file. This is usefull if you want to have PclTar - // running in any directory, and memorize relative path from an other directory. - // Parameters : - // $p_list : An array containing the file or directory names to add in the tar - // $p_result_list : list of added files with their properties (specially the status field) - // $p_add_dir : Path to add in the filename path archived - // $p_remove_dir : Path to remove in the filename path archived - // Return Values : - // -------------------------------------------------------------------------------- -// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) - function privAddList($p_filedescr_list, &$p_result_list, &$p_options) - { - $v_result=1; - - // ----- Add the files - $v_header_list = array(); - if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) - { - // ----- Return - return $v_result; - } + // ----- Write the variable fields + if (strlen($p_comment) != 0) { + fputs($this->zip_fd, $p_comment, strlen($p_comment)); + } - // ----- Store the offset of the central dir - $v_offset = @ftell($this->zip_fd); + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- - // ----- Create the Central Dir files header - for ($i=0,$v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { - // ----- Return - return $v_result; - } - $v_count++; - } + $v_result = 1; - // ----- Transform the header to a 'usable' info - $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); - } + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); - // ----- Zip file comment - $v_comment = ''; - if (isset($p_options[PCLZIP_OPT_COMMENT])) { - $v_comment = $p_options[PCLZIP_OPT_COMMENT]; - } + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); - // ----- Calculate the size of the central header - $v_size = @ftell($this->zip_fd)-$v_offset; + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \'' . $this->zipname . '\' in binary read mode'); - // ----- Create the central dir footer - if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) - { - // ----- Reset the file list - unset($v_header_list); + // ----- Return + return PclZip::errorCode(); + } - // ----- Return - return $v_result; - } + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + $this->privSwapBackMagicQuotes(); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privAddFileList() - // Description : - // Parameters : - // $p_filedescr_list : An array containing the file description - // or directory names to add in the zip - // $p_result_list : list of added files with their properties (specially the status field) - // Return Values : - // -------------------------------------------------------------------------------- - function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) - { - $v_result=1; - $v_header = array(); - - // ----- Recuperate the current number of elt in list - $v_nb = sizeof($p_result_list); - - // ----- Loop on the files - for ($j=0; ($jprivAddFile($p_filedescr_list[$j], $v_header, - $p_options); - if ($v_result != 1) { - return $v_result; + return $v_result; } - // ----- Store the file infos - $p_result_list[$v_nb++] = $v_header; - } - } + // ----- Go to beginning of Central Dir + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_central_dir['offset'])) { + $this->privSwapBackMagicQuotes(); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privAddFile() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privAddFile($p_filedescr, &$p_header, &$p_options) - { - $v_result=1; - - // ----- Working variable - $p_filename = $p_filedescr['filename']; - - // TBC : Already done in the fileAtt check ... ? - if ($p_filename == "") { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); - - // ----- Return - return PclZip::errorCode(); - } + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - // ----- Look for a stored different filename - /* TBC : Removed - if (isset($p_filedescr['stored_filename'])) { - $v_stored_filename = $p_filedescr['stored_filename']; - } - else { - $v_stored_filename = $p_filedescr['stored_filename']; - } - */ - - // ----- Set the file properties - clearstatcache(); - $p_header['version'] = 20; - $p_header['version_extracted'] = 10; - $p_header['flag'] = 0; - $p_header['compression'] = 0; - $p_header['crc'] = 0; - $p_header['compressed_size'] = 0; - $p_header['filename_len'] = strlen($p_filename); - $p_header['extra_len'] = 0; - $p_header['disk'] = 0; - $p_header['internal'] = 0; - $p_header['offset'] = 0; - $p_header['filename'] = $p_filename; -// TBC : Removed $p_header['stored_filename'] = $v_stored_filename; - $p_header['stored_filename'] = $p_filedescr['stored_filename']; - $p_header['extra'] = ''; - $p_header['status'] = 'ok'; - $p_header['index'] = -1; - - // ----- Look for regular file - if ($p_filedescr['type']=='file') { - $p_header['external'] = 0x00000000; - $p_header['size'] = filesize($p_filename); - } + // ----- Return + return PclZip::errorCode(); + } - // ----- Look for regular folder - else if ($p_filedescr['type']=='folder') { - $p_header['external'] = 0x00000010; - $p_header['mtime'] = filemtime($p_filename); - $p_header['size'] = filesize($p_filename); - } + // ----- Read each entry + for ($i = 0; $i < $v_central_dir['entries']; $i++) { + // ----- Read the file header + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) { + $this->privSwapBackMagicQuotes(); - // ----- Look for virtual file - else if ($p_filedescr['type'] == 'virtual_file') { - $p_header['external'] = 0x00000000; - $p_header['size'] = strlen($p_filedescr['content']); - } + return $v_result; + } + $v_header['index'] = $i; + // ----- Get the only interesting attributes + $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); + unset($v_header); + } - // ----- Look for filetime - if (isset($p_filedescr['mtime'])) { - $p_header['mtime'] = $p_filedescr['mtime']; - } - else if ($p_filedescr['type'] == 'virtual_file') { - $p_header['mtime'] = time(); - } - else { - $p_header['mtime'] = filemtime($p_filename); - } + // ----- Close the zip file + $this->privCloseFd(); - // ------ Look for file comment - if (isset($p_filedescr['comment'])) { - $p_header['comment_len'] = strlen($p_filedescr['comment']); - $p_header['comment'] = $p_filedescr['comment']; - } - else { - $p_header['comment_len'] = 0; - $p_header['comment'] = ''; - } + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); - // ----- Look for pre-add callback - if (isset($p_options[PCLZIP_CB_PRE_ADD])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_header, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header); - if ($v_result == 0) { - // ----- Change the file status - $p_header['status'] = "skipped"; + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privConvertHeader2FileInfo() + // Description : + // This function takes the file informations from the central directory + // entries and extract the interesting parameters that will be given back. + // The resulting file infos are set in the array $p_info + // $p_info['filename'] : Filename with full path. Given by user (add), + // extracted in the filesystem (extract). + // $p_info['stored_filename'] : Stored filename in the archive. + // $p_info['size'] = Size of the file. + // $p_info['compressed_size'] = Compressed size of the file. + // $p_info['mtime'] = Last modification date of the file. + // $p_info['comment'] = Comment associated with the file. + // $p_info['folder'] = true/false : indicates if the entry is a folder or not. + // $p_info['status'] = status of the action on the file. + // $p_info['crc'] = CRC of the file content. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privConvertHeader2FileInfo($p_header, &$p_info) + { $v_result = 1; - } - // ----- Update the informations - // Only some fields can be modified - if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { - $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']); - } - } + // ----- Get the interesting attributes + $v_temp_path = PclZipUtilPathReduction($p_header['filename']); + $p_info['filename'] = $v_temp_path; + $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); + $p_info['stored_filename'] = $v_temp_path; + $p_info['size'] = $p_header['size']; + $p_info['compressed_size'] = $p_header['compressed_size']; + $p_info['mtime'] = $p_header['mtime']; + $p_info['comment'] = $p_header['comment']; + $p_info['folder'] = (($p_header['external'] & 0x00000010) == 0x00000010); + $p_info['index'] = $p_header['index']; + $p_info['status'] = $p_header['status']; + $p_info['crc'] = $p_header['crc']; - // ----- Look for empty stored filename - if ($p_header['stored_filename'] == "") { - $p_header['status'] = "filtered"; + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractByRule() + // Description : + // Extract a file or directory depending of rules (by index, by name, ...) + // Parameters : + // $p_file_list : An array where will be placed the properties of each + // extracted file + // $p_path : Path to add while writing the extracted files + // $p_remove_path : Path to remove (from the file memorized path) while writing the + // extracted files. If the path does not match the file path, + // the file is extracted with its memorized path. + // $p_remove_path does not apply to 'list' mode. + // $p_path and $p_remove_path are commulative. + // Return Values : + // 1 on success,0 or less on error (see error code list) + // -------------------------------------------------------------------------------- + public function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + $v_result = 1; - // ----- Check the path length - if (strlen($p_header['stored_filename']) > 0xFF) { - $p_header['status'] = 'filename_too_long'; - } + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); - // ----- Look if no error, or file not skipped - if ($p_header['status'] == 'ok') { - - // ----- Look for a file - if ($p_filedescr['type'] == 'file') { - // ----- Look for using temporary file to zip - if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) - && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) - || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) - && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) { - $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options); - if ($v_result < PCLZIP_ERR_NO_ERROR) { - return $v_result; - } + // ----- Check the path + if (($p_path == "") || ((substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../") && (substr($p_path, 1, 2) != ":/"))) { + $p_path = "./" . $p_path; } - // ----- Use "in memory" zip algo - else { - - // ----- Open the source file - if (($v_file = @fopen($p_filename, "rb")) == 0) { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); - return PclZip::errorCode(); + // ----- Reduce the path last (and duplicated) '/' + if (($p_path != "./") && ($p_path != "/")) { + // ----- Look for the path end '/' + while (substr($p_path, -1) == "/") { + $p_path = substr($p_path, 0, strlen($p_path) - 1); + } } - // ----- Read the file content - $v_content = @fread($v_file, $p_header['size']); - - // ----- Close the file - @fclose($v_file); - - // ----- Calculate the CRC - $p_header['crc'] = @crc32($v_content); - - // ----- Look for no compression - if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { - // ----- Set header parameters - $p_header['compressed_size'] = $p_header['size']; - $p_header['compression'] = 0; + // ----- Look for path to remove format (should end by /) + if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) { + $p_remove_path .= '/'; } + $p_remove_path_size = strlen($p_remove_path); - // ----- Look for normal compression - else { - // ----- Compress the content - $v_content = @gzdeflate($v_content); - - // ----- Set header parameters - $p_header['compressed_size'] = strlen($v_content); - $p_header['compression'] = 8; - } + // ----- Open the zip file + if (($v_result = $this->privOpenFd('rb')) != 1) { + $this->privSwapBackMagicQuotes(); - // ----- Call the header generation - if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { - @fclose($v_file); - return $v_result; + return $v_result; } - // ----- Write the compressed (or not) content - @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; } - } + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; - // ----- Look for a virtual file (a file from string) - else if ($p_filedescr['type'] == 'virtual_file') { + // ----- Read each entry + $j_start = 0; + for ($i = 0, $v_nb_extracted = 0; $i < $v_central_dir['entries']; $i++) { - $v_content = $p_filedescr['content']; + // ----- Read next Central dir entry + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_pos_entry)) { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); - // ----- Calculate the CRC - $p_header['crc'] = @crc32($v_content); + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - // ----- Look for no compression - if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { - // ----- Set header parameters - $p_header['compressed_size'] = $p_header['size']; - $p_header['compression'] = 0; - } + // ----- Return + return PclZip::errorCode(); + } - // ----- Look for normal compression - else { - // ----- Compress the content - $v_content = @gzdeflate($v_content); + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); - // ----- Set header parameters - $p_header['compressed_size'] = strlen($v_content); - $p_header['compression'] = 8; - } + return $v_result; + } - // ----- Call the header generation - if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { - @fclose($v_file); - return $v_result; - } + // ----- Store the index + $v_header['index'] = $i; - // ----- Write the compressed (or not) content - @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); - } + // ----- Store the file position + $v_pos_entry = ftell($this->zip_fd); - // ----- Look for a directory - else if ($p_filedescr['type'] == 'folder') { - // ----- Look for directory last '/' - if (@substr($p_header['stored_filename'], -1) != '/') { - $p_header['stored_filename'] .= '/'; - } + // ----- Look for the specific extract rules + $v_extract = false; - // ----- Set the file properties - $p_header['size'] = 0; - //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked - $p_header['external'] = 0x00000010; // Value for a folder : to be checked + // ----- Look for extract by name rule + if ((isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { - // ----- Call the header generation - if (($v_result = $this->privWriteFileHeader($p_header)) != 1) - { - return $v_result; - } - } - } + // ----- Look if the filename is in the list + for ($j = 0; ($j < sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) { - // ----- Look for post-add callback - if (isset($p_options[PCLZIP_CB_POST_ADD])) { + // ----- Look for a directory + if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") { - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_header, $v_local_header); + // ----- Look if the directory is in the filename path + if ((strlen($v_header['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_extract = true; + } - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header); - if ($v_result == 0) { - // ----- Ignored - $v_result = 1; - } + // ----- Look for a filename + } elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + $v_extract = true; + } + } + // ----- Look for extract by ereg rule + // ereg() is deprecated with PHP 5.3 + /* + elseif ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { - // ----- Update the informations - // Nothing can be modified - } + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { + $v_extract = true; + } + } + */ - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privAddFileUsingTempFile() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options) - { - $v_result=PCLZIP_ERR_NO_ERROR; - - // ----- Working variable - $p_filename = $p_filedescr['filename']; - - - // ----- Open the source file - if (($v_file = @fopen($p_filename, "rb")) == 0) { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); - return PclZip::errorCode(); - } + // ----- Look for extract by preg rule + } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { - // ----- Creates a compressed temporary file - $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; - if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) { - fclose($v_file); - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); - return PclZip::errorCode(); - } + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { + $v_extract = true; + } - // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks - $v_size = filesize($p_filename); - while ($v_size != 0) { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($v_file, $v_read_size); - //$v_binary_data = pack('a'.$v_read_size, $v_buffer); - @gzputs($v_file_compressed, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } + // ----- Look for extract by index rule + } elseif ((isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { - // ----- Close the file - @fclose($v_file); - @gzclose($v_file_compressed); + // ----- Look if the index is in the list + for ($j = $j_start; ($j < sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) { - // ----- Check the minimum file size - if (filesize($v_gzip_temp_name) < 18) { - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes'); - return PclZip::errorCode(); - } + if (($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i <= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_extract = true; + } + if ($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j + 1; + } - // ----- Extract the compressed attributes - if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); - return PclZip::errorCode(); - } + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start'] > $i) { + break; + } + } - // ----- Read the gzip file header - $v_binary_data = @fread($v_file_compressed, 10); - $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data); + // ----- Look for no rule, which means extract all the archive + } else { + $v_extract = true; + } - // ----- Check some parameters - $v_data_header['os'] = bin2hex($v_data_header['os']); + // ----- Check compression method + if (($v_extract) && (($v_header['compression'] != 8) && ($v_header['compression'] != 0))) { + $v_header['status'] = 'unsupported_compression'; - // ----- Read the gzip file footer - @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8); - $v_binary_data = @fread($v_file_compressed, 8); - $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data); + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { - // ----- Set the attributes - $p_header['compression'] = ord($v_data_header['cm']); - //$p_header['mtime'] = $v_data_header['mtime']; - $p_header['crc'] = $v_data_footer['crc']; - $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18; + $this->privSwapBackMagicQuotes(); - // ----- Close the file - @fclose($v_file_compressed); + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, "Filename '" . $v_header['stored_filename'] . "' is " . "compressed by an unsupported compression " . "method (" . $v_header['compression'] . ") "); - // ----- Call the header generation - if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { - return $v_result; - } + return PclZip::errorCode(); + } + } - // ----- Add the compressed data - if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) - { - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); - return PclZip::errorCode(); - } + // ----- Check encrypted files + if (($v_extract) && (($v_header['flag'] & 1) == 1)) { + $v_header['status'] = 'unsupported_encryption'; - // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks - fseek($v_file_compressed, 10); - $v_size = $p_header['compressed_size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($v_file_compressed, $v_read_size); - //$v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($this->zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { - // ----- Close the file - @fclose($v_file_compressed); + $this->privSwapBackMagicQuotes(); - // ----- Unlink the temporary file - @unlink($v_gzip_temp_name); + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, "Unsupported encryption for " . " filename '" . $v_header['stored_filename'] . "'"); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privCalculateStoredFilename() - // Description : - // Based on file descriptor properties and global options, this method - // calculate the filename that will be stored in the archive. - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privCalculateStoredFilename(&$p_filedescr, &$p_options) - { - $v_result=1; - - // ----- Working variables - $p_filename = $p_filedescr['filename']; - if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { - $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; - } - else { - $p_add_dir = ''; - } - if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { - $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; - } - else { - $p_remove_dir = ''; - } - if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { - $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; - } - else { - $p_remove_all_dir = 0; - } + return PclZip::errorCode(); + } + } + // ----- Look for real extraction + if (($v_extract) && ($v_header['status'] != 'ok')) { + $v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++]); + if ($v_result != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); - // ----- Look for full name change - if (isset($p_filedescr['new_full_name'])) { - // ----- Remove drive letter if any - $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); - } + return $v_result; + } - // ----- Look for path and/or short name change - else { - - // ----- Look for short name change - // Its when we cahnge just the filename but not the path - if (isset($p_filedescr['new_short_name'])) { - $v_path_info = pathinfo($p_filename); - $v_dir = ''; - if ($v_path_info['dirname'] != '') { - $v_dir = $v_path_info['dirname'].'/'; - } - $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; - } - else { - // ----- Calculate the stored filename - $v_stored_filename = $p_filename; - } - - // ----- Look for all path to remove - if ($p_remove_all_dir) { - $v_stored_filename = basename($p_filename); - } - // ----- Look for partial path remove - else if ($p_remove_dir != "") { - if (substr($p_remove_dir, -1) != '/') - $p_remove_dir .= "/"; - - if ( (substr($p_filename, 0, 2) == "./") - || (substr($p_remove_dir, 0, 2) == "./")) { - - if ( (substr($p_filename, 0, 2) == "./") - && (substr($p_remove_dir, 0, 2) != "./")) { - $p_remove_dir = "./".$p_remove_dir; - } - if ( (substr($p_filename, 0, 2) != "./") - && (substr($p_remove_dir, 0, 2) == "./")) { - $p_remove_dir = substr($p_remove_dir, 2); - } - } - - $v_compare = PclZipUtilPathInclusion($p_remove_dir, - $v_stored_filename); - if ($v_compare > 0) { - if ($v_compare == 2) { - $v_stored_filename = ""; - } - else { - $v_stored_filename = substr($v_stored_filename, - strlen($p_remove_dir)); - } - } - } - - // ----- Remove drive letter if any - $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); - - // ----- Look for path to add - if ($p_add_dir != "") { - if (substr($p_add_dir, -1) == "/") - $v_stored_filename = $p_add_dir.$v_stored_filename; - else - $v_stored_filename = $p_add_dir."/".$v_stored_filename; - } - } + $v_extract = false; + } - // ----- Filename (reduce the path of stored name) - $v_stored_filename = PclZipUtilPathReduction($v_stored_filename); - $p_filedescr['stored_filename'] = $v_stored_filename; + // ----- Look for real extraction + if ($v_extract) { + + // ----- Go to the file position + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_header['offset'])) { + // ----- Close the zip file + $this->privCloseFd(); + + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for extraction as string + if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { + + $v_string = ''; + + // ----- Extracting the file + $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Set the file content + $p_file_list[$v_nb_extracted]['content'] = $v_string; + + // ----- Next extracted file + $v_nb_extracted++; + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + + // ----- Look for extraction in standard output + } elseif ((isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { + // ----- Extracting the file in standard output + $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + + // ----- Look for normal extraction + } else { + // ----- Extracting the file + $v_result1 = $this->privExtractFile($v_header, $p_path, $p_remove_path, $p_remove_all_path, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + } + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privWriteFileHeader() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privWriteFileHeader(&$p_header) - { - $v_result=1; - - // ----- Store the offset position of the file - $p_header['offset'] = ftell($this->zip_fd); - - // ----- Transform UNIX mtime to DOS format mdate/mtime - $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - - // ----- Packed data - $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, - $p_header['version_extracted'], $p_header['flag'], - $p_header['compression'], $v_mtime, $v_mdate, - $p_header['crc'], $p_header['compressed_size'], - $p_header['size'], - strlen($p_header['stored_filename']), - $p_header['extra_len']); - - // ----- Write the first 148 bytes of the header in the archive - fputs($this->zip_fd, $v_binary_data, 30); - - // ----- Write the variable fields - if (strlen($p_header['stored_filename']) != 0) - { - fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); - } - if ($p_header['extra_len'] != 0) - { - fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); - } + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privWriteCentralFileHeader() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privWriteCentralFileHeader(&$p_header) - { - $v_result=1; - - // TBC - //for(reset($p_header); $key = key($p_header); next($p_header)) { - //} - - // ----- Transform UNIX mtime to DOS format mdate/mtime - $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - - - // ----- Packed data - $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, - $p_header['version'], $p_header['version_extracted'], - $p_header['flag'], $p_header['compression'], - $v_mtime, $v_mdate, $p_header['crc'], - $p_header['compressed_size'], $p_header['size'], - strlen($p_header['stored_filename']), - $p_header['extra_len'], $p_header['comment_len'], - $p_header['disk'], $p_header['internal'], - $p_header['external'], $p_header['offset']); - - // ----- Write the 42 bytes of the header in the zip file - fputs($this->zip_fd, $v_binary_data, 46); - - // ----- Write the variable fields - if (strlen($p_header['stored_filename']) != 0) - { - fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); - } - if ($p_header['extra_len'] != 0) - { - fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + // ----- Return + return $v_result; } - if ($p_header['comment_len'] != 0) + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFile() + // Description : + // Parameters : + // Return Values : + // + // 1 : ... ? + // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback + // -------------------------------------------------------------------------------- + public function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) { - fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); - } + $v_result = 1; - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privWriteCentralHeader() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) - { - $v_result=1; - - // ----- Packed data - $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, - $p_nb_entries, $p_size, - $p_offset, strlen($p_comment)); - - // ----- Write the 22 bytes of the header in the zip file - fputs($this->zip_fd, $v_binary_data, 22); - - // ----- Write the variable fields - if (strlen($p_comment) != 0) - { - fputs($this->zip_fd, $p_comment, strlen($p_comment)); - } + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + // ----- Return + return $v_result; + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privList() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privList(&$p_list) - { - $v_result=1; - - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); - - // ----- Open the zip file - if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) - { - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + // ----- Look for all path to remove + if ($p_remove_all_path == true) { + // ----- Look for folder entry that not need to be extracted + if (($p_entry['external'] & 0x00000010) == 0x00000010) { - // ----- Return - return PclZip::errorCode(); - } + $p_entry['status'] = "filtered"; - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - $this->privSwapBackMagicQuotes(); - return $v_result; - } + return $v_result; + } - // ----- Go to beginning of Central Dir - @rewind($this->zip_fd); - if (@fseek($this->zip_fd, $v_central_dir['offset'])) - { - $this->privSwapBackMagicQuotes(); + // ----- Get the basename of the path + $p_entry['filename'] = basename($p_entry['filename']); - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + // ----- Look for path to remove + } elseif ($p_remove_path != "") { + if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) { - // ----- Return - return PclZip::errorCode(); - } + // ----- Change the file status + $p_entry['status'] = "filtered"; - // ----- Read each entry - for ($i=0; $i<$v_central_dir['entries']; $i++) - { - // ----- Read the file header - if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) - { - $this->privSwapBackMagicQuotes(); - return $v_result; - } - $v_header['index'] = $i; + // ----- Return + return $v_result; + } - // ----- Get the only interesting attributes - $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); - unset($v_header); - } + $p_remove_path_size = strlen($p_remove_path); + if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) { - // ----- Close the zip file - $this->privCloseFd(); + // ----- Remove the path + $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); - // ----- Magic quotes trick - $this->privSwapBackMagicQuotes(); + } + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privConvertHeader2FileInfo() - // Description : - // This function takes the file informations from the central directory - // entries and extract the interesting parameters that will be given back. - // The resulting file infos are set in the array $p_info - // $p_info['filename'] : Filename with full path. Given by user (add), - // extracted in the filesystem (extract). - // $p_info['stored_filename'] : Stored filename in the archive. - // $p_info['size'] = Size of the file. - // $p_info['compressed_size'] = Compressed size of the file. - // $p_info['mtime'] = Last modification date of the file. - // $p_info['comment'] = Comment associated with the file. - // $p_info['folder'] = true/false : indicates if the entry is a folder or not. - // $p_info['status'] = status of the action on the file. - // $p_info['crc'] = CRC of the file content. - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privConvertHeader2FileInfo($p_header, &$p_info) - { - $v_result=1; - - // ----- Get the interesting attributes - $v_temp_path = PclZipUtilPathReduction($p_header['filename']); - $p_info['filename'] = $v_temp_path; - $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); - $p_info['stored_filename'] = $v_temp_path; - $p_info['size'] = $p_header['size']; - $p_info['compressed_size'] = $p_header['compressed_size']; - $p_info['mtime'] = $p_header['mtime']; - $p_info['comment'] = $p_header['comment']; - $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); - $p_info['index'] = $p_header['index']; - $p_info['status'] = $p_header['status']; - $p_info['crc'] = $p_header['crc']; + // ----- Add the path + if ($p_path != '') { + $p_entry['filename'] = $p_path . "/" . $p_entry['filename']; + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privExtractByRule() - // Description : - // Extract a file or directory depending of rules (by index, by name, ...) - // Parameters : - // $p_file_list : An array where will be placed the properties of each - // extracted file - // $p_path : Path to add while writing the extracted files - // $p_remove_path : Path to remove (from the file memorized path) while writing the - // extracted files. If the path does not match the file path, - // the file is extracted with its memorized path. - // $p_remove_path does not apply to 'list' mode. - // $p_path and $p_remove_path are commulative. - // Return Values : - // 1 on success,0 or less on error (see error code list) - // -------------------------------------------------------------------------------- - function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) - { - $v_result=1; - - // ----- Magic quotes trick - $this->privDisableMagicQuotes(); - - // ----- Check the path - if ( ($p_path == "") - || ( (substr($p_path, 0, 1) != "/") - && (substr($p_path, 0, 3) != "../") - && (substr($p_path,1,2)!=":/"))) - $p_path = "./".$p_path; - - // ----- Reduce the path last (and duplicated) '/' - if (($p_path != "./") && ($p_path != "/")) - { - // ----- Look for the path end '/' - while (substr($p_path, -1) == "/") - { - $p_path = substr($p_path, 0, strlen($p_path)-1); - } - } + // ----- Check a base_dir_restriction + if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { + $v_inclusion = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], $p_entry['filename']); + if ($v_inclusion == 0) { - // ----- Look for path to remove format (should end by /) - if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) - { - $p_remove_path .= '/'; - } - $p_remove_path_size = strlen($p_remove_path); + PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, "Filename '" . $p_entry['filename'] . "' is " . "outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); - // ----- Open the zip file - if (($v_result = $this->privOpenFd('rb')) != 1) - { - $this->privSwapBackMagicQuotes(); - return $v_result; - } + return PclZip::errorCode(); + } + } - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - return $v_result; - } + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } - // ----- Start at beginning of Central Dir - $v_pos_entry = $v_central_dir['offset']; + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } - // ----- Read each entry - $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) - { + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } - // ----- Read next Central dir entry - @rewind($this->zip_fd); - if (@fseek($this->zip_fd, $v_pos_entry)) - { - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + // ----- Look for specific actions while the file exist + if (file_exists($p_entry['filename'])) { - // ----- Return - return PclZip::errorCode(); - } + // ----- Look if file is a directory + if (is_dir($p_entry['filename'])) { - // ----- Read the file header - $v_header = array(); - if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); + // ----- Change the file status + $p_entry['status'] = "already_a_directory"; - return $v_result; - } - - // ----- Store the index - $v_header['index'] = $i; - - // ----- Store the file position - $v_pos_entry = ftell($this->zip_fd); - - // ----- Look for the specific extract rules - $v_extract = false; - - // ----- Look for extract by name rule - if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) - && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) - && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { - $v_extract = true; - } - } - // ----- Look for a filename - elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { - $v_extract = true; - } - } - } - - // ----- Look for extract by ereg rule - // ereg() is deprecated with PHP 5.3 - /* - else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) - && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { - - if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - */ - - // ----- Look for extract by preg rule - else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) - && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { - - if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - - // ----- Look for extract by index rule - else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) - && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { - $v_extract = true; - } - if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { - $j_start = $j+1; - } - - if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { - break; - } - } - } - - // ----- Look for no rule, which means extract all the archive - else { - $v_extract = true; - } - - // ----- Check compression method - if ( ($v_extract) - && ( ($v_header['compression'] != 8) - && ($v_header['compression'] != 0))) { - $v_header['status'] = 'unsupported_compression'; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - - $this->privSwapBackMagicQuotes(); - - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, - "Filename '".$v_header['stored_filename']."' is " - ."compressed by an unsupported compression " - ."method (".$v_header['compression'].") "); - - return PclZip::errorCode(); - } - } - - // ----- Check encrypted files - if (($v_extract) && (($v_header['flag'] & 1) == 1)) { - $v_header['status'] = 'unsupported_encryption'; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - - $this->privSwapBackMagicQuotes(); - - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, - "Unsupported encryption for " - ." filename '".$v_header['stored_filename'] - ."'"); - - return PclZip::errorCode(); - } - } + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { - // ----- Look for real extraction - if (($v_extract) && ($v_header['status'] != 'ok')) { - $v_result = $this->privConvertHeader2FileInfo($v_header, - $p_file_list[$v_nb_extracted++]); - if ($v_result != 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result; - } + PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, "Filename '" . $p_entry['filename'] . "' is " . "already used by an existing directory"); - $v_extract = false; - } + return PclZip::errorCode(); + } - // ----- Look for real extraction - if ($v_extract) - { + // ----- Look if file is write protected + } elseif (!is_writeable($p_entry['filename'])) { - // ----- Go to the file position - @rewind($this->zip_fd); - if (@fseek($this->zip_fd, $v_header['offset'])) - { - // ----- Close the zip file - $this->privCloseFd(); + // ----- Change the file status + $p_entry['status'] = "write_protected"; - $this->privSwapBackMagicQuotes(); + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Filename '" . $p_entry['filename'] . "' exists " . "and is write protected"); - // ----- Return - return PclZip::errorCode(); - } + return PclZip::errorCode(); + } - // ----- Look for extraction as string - if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { + // ----- Look if the extracted file is older + } elseif (filemtime($p_entry['filename']) > $p_entry['mtime']) { + // ----- Change the file status + if ((isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) && ($p_options[PCLZIP_OPT_REPLACE_NEWER] === true)) { + } else { + $p_entry['status'] = "newer_exist"; - $v_string = ''; + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { - // ----- Extracting the file - $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); - if ($v_result1 < 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result1; - } + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Newer version of '" . $p_entry['filename'] . "' exists " . "and option PCLZIP_OPT_REPLACE_NEWER is not selected"); - // ----- Get the only interesting attributes - if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); + return PclZip::errorCode(); + } + } + } else { + } - return $v_result; - } + // ----- Check the directory availability and create it if necessary + } else { + if ((($p_entry['external'] & 0x00000010) == 0x00000010) || (substr($p_entry['filename'], -1) == '/')) { + $v_dir_to_check = $p_entry['filename']; + } elseif (!strstr($p_entry['filename'], "/")) { + $v_dir_to_check = ""; + } else { + $v_dir_to_check = dirname($p_entry['filename']); + } - // ----- Set the file content - $p_file_list[$v_nb_extracted]['content'] = $v_string; + if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external'] & 0x00000010) == 0x00000010))) != 1) { - // ----- Next extracted file - $v_nb_extracted++; + // ----- Change the file status + $p_entry['status'] = "path_creation_fail"; - // ----- Look for user callback abort - if ($v_result1 == 2) { - break; - } + // ----- Return + //return $v_result; + $v_result = 1; + } + } } - // ----- Look for extraction in standard output - elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) - && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { - // ----- Extracting the file in standard output - $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); - if ($v_result1 < 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result1; - } - // ----- Get the only interesting attributes - if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result; - } - - // ----- Look for user callback abort - if ($v_result1 == 2) { - break; - } - } - // ----- Look for normal extraction - else { - // ----- Extracting the file - $v_result1 = $this->privExtractFile($v_header, - $p_path, $p_remove_path, - $p_remove_all_path, - $p_options); - if ($v_result1 < 1) { - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); - return $v_result1; - } + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { - // ----- Get the only interesting attributes - if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external'] & 0x00000010) == 0x00000010)) { + // ----- Look for not compressed file + if ($p_entry['compression'] == 0) { - return $v_result; - } + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { - // ----- Look for user callback abort - if ($v_result1 == 2) { - break; - } - } - } - } + // ----- Change the file status + $p_entry['status'] = "write_error"; - // ----- Close the zip file - $this->privCloseFd(); - $this->privSwapBackMagicQuotes(); + // ----- Return + return $v_result; + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privExtractFile() - // Description : - // Parameters : - // Return Values : - // - // 1 : ... ? - // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback - // -------------------------------------------------------------------------------- - function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) - { - $v_result=1; - - // ----- Read the file header - if (($v_result = $this->privReadFileHeader($v_header)) != 1) - { - // ----- Return - return $v_result; - } + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + /* Try to speed up the code + $v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_binary_data, $v_read_size); + */ + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + // ----- Closing the destination file + fclose($v_dest_file); - // ----- Check that the file header is coherent with $p_entry info - if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { - // TBC - } + // ----- Change the file mtime + touch($p_entry['filename'], $p_entry['mtime']); - // ----- Look for all path to remove - if ($p_remove_all_path == true) { - // ----- Look for folder entry that not need to be extracted - if (($p_entry['external']&0x00000010)==0x00000010) { + } else { + // ----- TBC + // Need to be finished + if (($p_entry['flag'] & 1) == 1) { + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \'' . $p_entry['filename'] . '\' is encrypted. Encrypted files are not supported.'); - $p_entry['status'] = "filtered"; + return PclZip::errorCode(); + } - return $v_result; - } + // ----- Look for using temporary file to unzip + if ((!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])))) { + $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } - // ----- Get the basename of the path - $p_entry['filename'] = basename($p_entry['filename']); - } + // ----- Look for extract in memory + } else { - // ----- Look for path to remove - else if ($p_remove_path != "") - { - if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) - { + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); - // ----- Change the file status - $p_entry['status'] = "filtered"; + // ----- Decompress the file + $v_file_content = @gzinflate($v_buffer); + unset($v_buffer); + if ($v_file_content === false) { - // ----- Return - return $v_result; - } + // ----- Change the file status + // TBC + $p_entry['status'] = "error"; - $p_remove_path_size = strlen($p_remove_path); - if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) - { + return $v_result; + } - // ----- Remove the path - $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { - } - } + // ----- Change the file status + $p_entry['status'] = "write_error"; - // ----- Add the path - if ($p_path != '') { - $p_entry['filename'] = $p_path."/".$p_entry['filename']; - } + return $v_result; + } - // ----- Check a base_dir_restriction - if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { - $v_inclusion - = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], - $p_entry['filename']); - if ($v_inclusion == 0) { + // ----- Write the uncompressed data + @fwrite($v_dest_file, $v_file_content, $p_entry['size']); + unset($v_file_content); - PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, - "Filename '".$p_entry['filename']."' is " - ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); + // ----- Closing the destination file + @fclose($v_dest_file); - return PclZip::errorCode(); - } - } + } - // ----- Look for pre-extract callback - if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; - $v_result = 1; - } - - // ----- Look for abort result - if ($v_result == 2) { - // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; - $v_result = PCLZIP_ERR_USER_ABORTED; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; - } + // ----- Change the file mtime + @touch($p_entry['filename'], $p_entry['mtime']); + } + // ----- Look for chmod option + if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { + // ----- Change the mode of the file + @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); + } - // ----- Look for specific actions while the file exist - if (file_exists($p_entry['filename'])) - { + } + } - // ----- Look if file is a directory - if (is_dir($p_entry['filename'])) - { + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; - // ----- Change the file status - $p_entry['status'] = "already_a_directory"; + // ----- Look for post-extract callback + } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - // For historical reason first PclZip implementation does not stop - // when this kind of error occurs. - if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, - "Filename '".$p_entry['filename']."' is " - ."already used by an existing directory"); + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); - return PclZip::errorCode(); + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; } - } - // ----- Look if file is write protected - else if (!is_writeable($p_entry['filename'])) - { + } - // ----- Change the file status - $p_entry['status'] = "write_protected"; + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - // For historical reason first PclZip implementation does not stop - // when this kind of error occurs. - if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + // -------------------------------------------------------------------------------- + // Function : privExtractFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privExtractFileUsingTempFile(&$p_entry, &$p_options) + { + $v_result = 1; - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, - "Filename '".$p_entry['filename']."' exists " - ."and is write protected"); + // ----- Creates a temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.gz'; + if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary write mode'); return PclZip::errorCode(); - } - } - - // ----- Look if the extracted file is older - else if (filemtime($p_entry['filename']) > $p_entry['mtime']) - { - // ----- Change the file status - if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) - && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) { - } - else { - $p_entry['status'] = "newer_exist"; - - // ----- Look for PCLZIP_OPT_STOP_ON_ERROR - // For historical reason first PclZip implementation does not stop - // when this kind of error occurs. - if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) - && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { - - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, - "Newer version of '".$p_entry['filename']."' exists " - ."and option PCLZIP_OPT_REPLACE_NEWER is not selected"); - - return PclZip::errorCode(); - } - } - } - else { - } - } - - // ----- Check the directory availability and create it if necessary - else { - if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) - $v_dir_to_check = $p_entry['filename']; - else if (!strstr($p_entry['filename'], "/")) - $v_dir_to_check = ""; - else - $v_dir_to_check = dirname($p_entry['filename']); - - if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { + } - // ----- Change the file status - $p_entry['status'] = "path_creation_fail"; + // ----- Write gz file format header + $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); + @fwrite($v_dest_file, $v_binary_data, 10); - // ----- Return - //return $v_result; - $v_result = 1; + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; } - } - } - - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) - { - // ----- Look for not compressed file - if ($p_entry['compression'] == 0) { + // ----- Write gz file format footer + $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); + @fwrite($v_dest_file, $v_binary_data, 8); - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) - { + // ----- Close the temporary file + @fclose($v_dest_file); - // ----- Change the file status + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { $p_entry['status'] = "write_error"; - // ----- Return return $v_result; - } + } + // ----- Open the temporary gz file + if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { + @fclose($v_dest_file); + $p_entry['status'] = "read_error"; + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_gzip_temp_name . '\' in binary read mode'); + + return PclZip::errorCode(); + } - // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks - $v_size = $p_entry['compressed_size']; - while ($v_size != 0) - { + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['size']; + while ($v_size != 0) { $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->zip_fd, $v_read_size); - /* Try to speed up the code - $v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_binary_data, $v_read_size); - */ + $v_buffer = @gzread($v_src_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); @fwrite($v_dest_file, $v_buffer, $v_read_size); $v_size -= $v_read_size; - } + } + @fclose($v_dest_file); + @gzclose($v_src_file); - // ----- Closing the destination file - fclose($v_dest_file); + // ----- Delete the temporary file + @unlink($v_gzip_temp_name); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- - // ----- Change the file mtime - touch($p_entry['filename'], $p_entry['mtime']); + // -------------------------------------------------------------------------------- + // Function : privExtractFileInOutput() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privExtractFileInOutput(&$p_entry, &$p_options) + { + $v_result = 1; + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + return $v_result; + } + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC } - else { - // ----- TBC - // Need to be finished - if (($p_entry['flag'] & 1) == 1) { - PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); - return PclZip::errorCode(); - } + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - // ----- Look for using temporary file to unzip - if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) - && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) - || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) - && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) { - $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); - if ($v_result < PCLZIP_ERR_NO_ERROR) { - return $v_result; + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; } - } - // ----- Look for extract in memory - else { + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } - // ----- Read the compressed file in a buffer (one shot) - $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + // ----- Trace - // ----- Decompress the file - $v_file_content = @gzinflate($v_buffer); - unset($v_buffer); - if ($v_file_content === FALSE) { + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { - // ----- Change the file status - // TBC - $p_entry['status'] = "error"; + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external'] & 0x00000010) == 0x00000010)) { + // ----- Look for not compressed file + if ($p_entry['compressed_size'] == $p_entry['size']) { - return $v_result; - } + // ----- Read the file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + // ----- Send the file to the output + echo $v_buffer; + unset($v_buffer); + } else { - // ----- Change the file status - $p_entry['status'] = "write_error"; + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); - return $v_result; + // ----- Decompress the file + $v_file_content = gzinflate($v_buffer); + unset($v_buffer); + + // ----- Send the file to the output + echo $v_file_content; + unset($v_file_content); + } } + } - // ----- Write the uncompressed data - @fwrite($v_dest_file, $v_file_content, $p_entry['size']); - unset($v_file_content); + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; - // ----- Closing the destination file - @fclose($v_dest_file); + // ----- Look for post-extract callback + } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + return $v_result; + } + // -------------------------------------------------------------------------------- - } + // -------------------------------------------------------------------------------- + // Function : privExtractFileAsString() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) + { + $v_result = 1; - // ----- Change the file mtime - @touch($p_entry['filename'], $p_entry['mtime']); + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + // ----- Return + return $v_result; } - // ----- Look for chmod option - if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { - - // ----- Change the mode of the file - @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC } - } - } - - // ----- Change abort status - if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; - } + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - // ----- Look for post-extract callback - elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } - // ----- Look for abort result - if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; - } - } + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privExtractFileUsingTempFile() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privExtractFileUsingTempFile(&$p_entry, &$p_options) - { - $v_result=1; - - // ----- Creates a temporary file - $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; - if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { - fclose($v_file); - PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); - return PclZip::errorCode(); - } + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external'] & 0x00000010) == 0x00000010)) { + // ----- Look for not compressed file + // if ($p_entry['compressed_size'] == $p_entry['size']) + if ($p_entry['compression'] == 0) { + // ----- Reading the file + $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); + } else { - // ----- Write gz file format header - $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); - @fwrite($v_dest_file, $v_binary_data, 10); + // ----- Reading the file + $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); - // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks - $v_size = $p_entry['compressed_size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->zip_fd, $v_read_size); - //$v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } + // ----- Decompress the file + if (($p_string = @gzinflate($v_data)) === false) { + // TBC + } + } - // ----- Write gz file format footer - $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); - @fwrite($v_dest_file, $v_binary_data, 8); + // ----- Trace + } else { + // TBC : error : can not extract a folder in a string + } - // ----- Close the temporary file - @fclose($v_dest_file); + } - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { - $p_entry['status'] = "write_error"; - return $v_result; - } + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; - // ----- Open the temporary gz file - if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { - @fclose($v_dest_file); - $p_entry['status'] = "read_error"; - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); - return PclZip::errorCode(); - } + // ----- Look for post-extract callback + } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks - $v_size = $p_entry['size']; - while ($v_size != 0) { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($v_src_file, $v_read_size); - //$v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - @fclose($v_dest_file); - @gzclose($v_src_file); + // ----- Swap the content to header + $v_local_header['content'] = $p_string; + $p_string = ''; - // ----- Delete the temporary file - @unlink($v_gzip_temp_name); + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privExtractFileInOutput() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privExtractFileInOutput(&$p_entry, &$p_options) - { - $v_result=1; - - // ----- Read the file header - if (($v_result = $this->privReadFileHeader($v_header)) != 1) { - return $v_result; - } + // ----- Swap back the content to header + $p_string = $v_local_header['content']; + unset($v_local_header['content']); + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } - // ----- Check that the file header is coherent with $p_entry info - if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { - // TBC + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- - // ----- Look for pre-extract callback - if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; + // -------------------------------------------------------------------------------- + // Function : privReadFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privReadFileHeader(&$p_header) + { $v_result = 1; - } - - // ----- Look for abort result - if ($v_result == 2) { - // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; - $v_result = PCLZIP_ERR_USER_ABORTED; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; - } - // ----- Trace + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = unpack('Vid', $v_binary_data); - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { + // ----- Check signature + if ($v_data['id'] != 0x04034b50) { - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) { - // ----- Look for not compressed file - if ($p_entry['compressed_size'] == $p_entry['size']) { - - // ----- Read the file in a buffer (one shot) - $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - // ----- Send the file to the output - echo $v_buffer; - unset($v_buffer); + // ----- Return + return PclZip::errorCode(); } - else { - // ----- Read the compressed file in a buffer (one shot) - $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 26); - // ----- Decompress the file - $v_file_content = gzinflate($v_buffer); - unset($v_buffer); + // ----- Look for invalid block size + if (strlen($v_binary_data) != 26) { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : " . strlen($v_binary_data)); - // ----- Send the file to the output - echo $v_file_content; - unset($v_file_content); + // ----- Return + return PclZip::errorCode(); } - } - } - // ----- Change abort status - if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; - } + // ----- Extract the values + $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); - // ----- Look for post-extract callback - elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + // ----- Get filename + $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + // ----- Get extra_fields + if ($v_data['extra_len'] != 0) { + $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); + } else { + $p_header['extra'] = ''; + } - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + // ----- Extract properties + $p_header['version_extracted'] = $v_data['version']; + $p_header['compression'] = $v_data['compression']; + $p_header['size'] = $v_data['size']; + $p_header['compressed_size'] = $v_data['compressed_size']; + $p_header['crc'] = $v_data['crc']; + $p_header['flag'] = $v_data['flag']; + $p_header['filename_len'] = $v_data['filename_len']; + + // ----- Recuperate date in UNIX format + $p_header['mdate'] = $v_data['mdate']; + $p_header['mtime'] = $v_data['mtime']; + if ($p_header['mdate'] && $p_header['mtime']) { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F) * 2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + } else { + $p_header['mtime'] = time(); + } - // ----- Look for abort result - if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; - } - } + // TBC + //for (reset($v_data); $key = key($v_data); next($v_data)) { + //} - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privExtractFileAsString() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) - { - $v_result=1; - - // ----- Read the file header - $v_header = array(); - if (($v_result = $this->privReadFileHeader($v_header)) != 1) - { - // ----- Return - return $v_result; - } + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + // ----- Set the status field + $p_header['status'] = "ok"; - // ----- Check that the file header is coherent with $p_entry info - if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { - // TBC + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- - // ----- Look for pre-extract callback - if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { - - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; + // -------------------------------------------------------------------------------- + // Function : privReadCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privReadCentralFileHeader(&$p_header) + { $v_result = 1; - } - - // ----- Look for abort result - if ($v_result == 2) { - // ----- This status is internal and will be changed in 'skipped' - $p_entry['status'] = "aborted"; - $v_result = PCLZIP_ERR_USER_ABORTED; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; - } + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = unpack('Vid', $v_binary_data); - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { + // ----- Check signature + if ($v_data['id'] != 0x02014b50) { - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) { - // ----- Look for not compressed file - // if ($p_entry['compressed_size'] == $p_entry['size']) - if ($p_entry['compression'] == 0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - // ----- Reading the file - $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); + // ----- Return + return PclZip::errorCode(); } - else { - - // ----- Reading the file - $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); - // ----- Decompress the file - if (($p_string = @gzinflate($v_data)) === FALSE) { - // TBC - } - } + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 42); - // ----- Trace - } - else { - // TBC : error : can not extract a folder in a string - } + // ----- Look for invalid block size + if (strlen($v_binary_data) != 42) { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; - } + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : " . strlen($v_binary_data)); - // ----- Change abort status - if ($p_entry['status'] == "aborted") { - $p_entry['status'] = "skipped"; - } + // ----- Return + return PclZip::errorCode(); + } - // ----- Look for post-extract callback - elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + // ----- Extract the values + $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); - // ----- Generate a local information - $v_local_header = array(); - $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + // ----- Get filename + if ($p_header['filename_len'] != 0) { + $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); + } else { + $p_header['filename'] = ''; + } - // ----- Swap the content to header - $v_local_header['content'] = $p_string; - $p_string = ''; + // ----- Get extra + if ($p_header['extra_len'] != 0) { + $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); + } else { + $p_header['extra'] = ''; + } - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. -// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); - $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + // ----- Get comment + if ($p_header['comment_len'] != 0) { + $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); + } else { + $p_header['comment'] = ''; + } - // ----- Swap back the content to header - $p_string = $v_local_header['content']; - unset($v_local_header['content']); + // ----- Extract properties - // ----- Look for abort result - if ($v_result == 2) { - $v_result = PCLZIP_ERR_USER_ABORTED; - } - } + // ----- Recuperate date in UNIX format + //if ($p_header['mdate'] && $p_header['mtime']) + // TBC : bug : this was ignoring time with 0/0/0 + if (1) { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F) * 2; - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privReadFileHeader() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privReadFileHeader(&$p_header) - { - $v_result=1; - - // ----- Read the 4 bytes signature - $v_binary_data = @fread($this->zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] != 0x04034b50) - { + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); - // ----- Return - return PclZip::errorCode(); - } + } else { + $p_header['mtime'] = time(); + } - // ----- Read the first 42 bytes of the header - $v_binary_data = fread($this->zip_fd, 26); + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; - // ----- Look for invalid block size - if (strlen($v_binary_data) != 26) - { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; + // ----- Set default status to ok + $p_header['status'] = 'ok'; - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + // ----- Look if it is a directory + if (substr($p_header['filename'], -1) == '/') { + //$p_header['external'] = 0x41FF0010; + $p_header['external'] = 0x00000010; + } - // ----- Return - return PclZip::errorCode(); + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCheckFileHeaders() + // Description : + // Parameters : + // Return Values : + // 1 on success, + // 0 on error; + // -------------------------------------------------------------------------------- + public function privCheckFileHeaders(&$p_local_header, &$p_central_header) + { + $v_result = 1; - // ----- Extract the values - $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); + // ----- Check the static values + // TBC + if ($p_local_header['filename'] != $p_central_header['filename']) { + } + if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { + } + if ($p_local_header['flag'] != $p_central_header['flag']) { + } + if ($p_local_header['compression'] != $p_central_header['compression']) { + } + if ($p_local_header['mtime'] != $p_central_header['mtime']) { + } + if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { + } - // ----- Get filename - $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); + // ----- Look for flag bit 3 + if (($p_local_header['flag'] & 8) == 8) { + $p_local_header['size'] = $p_central_header['size']; + $p_local_header['compressed_size'] = $p_central_header['compressed_size']; + $p_local_header['crc'] = $p_central_header['crc']; + } - // ----- Get extra_fields - if ($v_data['extra_len'] != 0) { - $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); - } - else { - $p_header['extra'] = ''; + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- - // ----- Extract properties - $p_header['version_extracted'] = $v_data['version']; - $p_header['compression'] = $v_data['compression']; - $p_header['size'] = $v_data['size']; - $p_header['compressed_size'] = $v_data['compressed_size']; - $p_header['crc'] = $v_data['crc']; - $p_header['flag'] = $v_data['flag']; - $p_header['filename_len'] = $v_data['filename_len']; - - // ----- Recuperate date in UNIX format - $p_header['mdate'] = $v_data['mdate']; - $p_header['mtime'] = $v_data['mtime']; - if ($p_header['mdate'] && $p_header['mtime']) + // -------------------------------------------------------------------------------- + // Function : privReadEndCentralDir() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privReadEndCentralDir(&$p_central_dir) { - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; - - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; - - // ----- Get UNIX date format - $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + $v_result = 1; - } - else - { - $p_header['mtime'] = time(); - } + // ----- Go to the end of the zip file + $v_size = filesize($this->zipname); + @fseek($this->zip_fd, $v_size); + if (@ftell($this->zip_fd) != $v_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \'' . $this->zipname . '\''); - // TBC - //for(reset($v_data); $key = key($v_data); next($v_data)) { - //} + // ----- Return + return PclZip::errorCode(); + } - // ----- Set the stored filename - $p_header['stored_filename'] = $p_header['filename']; + // ----- First try : look if this is an archive with no commentaries (most of the time) + // in this case the end of central dir is at 22 bytes of the file end + $v_found = 0; + if ($v_size > 26) { + @fseek($this->zip_fd, $v_size - 22); + if (($v_pos = @ftell($this->zip_fd)) != ($v_size - 22)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \'' . $this->zipname . '\''); - // ----- Set the status field - $p_header['status'] = "ok"; + // ----- Return + return PclZip::errorCode(); + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privReadCentralFileHeader() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privReadCentralFileHeader(&$p_header) - { - $v_result=1; - - // ----- Read the 4 bytes signature - $v_binary_data = @fread($this->zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] != 0x02014b50) - { + // ----- Read for bytes + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = @unpack('Vid', $v_binary_data); - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + // ----- Check signature + if ($v_data['id'] == 0x06054b50) { + $v_found = 1; + } - // ----- Return - return PclZip::errorCode(); - } + $v_pos = ftell($this->zip_fd); + } - // ----- Read the first 42 bytes of the header - $v_binary_data = fread($this->zip_fd, 42); + // ----- Go back to the maximum possible size of the Central Dir End Record + if (!$v_found) { + $v_maximum_size = 65557; // 0xFFFF + 22; + if ($v_maximum_size > $v_size) { + $v_maximum_size = $v_size; + } + @fseek($this->zip_fd, $v_size - $v_maximum_size); + if (@ftell($this->zip_fd) != ($v_size - $v_maximum_size)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \'' . $this->zipname . '\''); - // ----- Look for invalid block size - if (strlen($v_binary_data) != 42) - { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; + // ----- Return + return PclZip::errorCode(); + } - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + // ----- Read byte per byte in order to find the signature + $v_pos = ftell($this->zip_fd); + $v_bytes = 0x00000000; + while ($v_pos < $v_size) { + // ----- Read a byte + $v_byte = @fread($this->zip_fd, 1); + + // ----- Add the byte + //$v_bytes = ($v_bytes << 8) | Ord($v_byte); + // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number + // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. + $v_bytes = (($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); + + // ----- Compare the bytes + if ($v_bytes == 0x504b0506) { + $v_pos++; + break; + } + + $v_pos++; + } - // ----- Return - return PclZip::errorCode(); - } + // ----- Look if not found end of central dir + if ($v_pos == $v_size) { - // ----- Extract the values - $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); - - // ----- Get filename - if ($p_header['filename_len'] != 0) - $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); - else - $p_header['filename'] = ''; - - // ----- Get extra - if ($p_header['extra_len'] != 0) - $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); - else - $p_header['extra'] = ''; - - // ----- Get comment - if ($p_header['comment_len'] != 0) - $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); - else - $p_header['comment'] = ''; - - // ----- Extract properties - - // ----- Recuperate date in UNIX format - //if ($p_header['mdate'] && $p_header['mtime']) - // TBC : bug : this was ignoring time with 0/0/0 - if (1) - { - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; + // ----- Return + return PclZip::errorCode(); + } + } - // ----- Get UNIX date format - $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + // ----- Read the first 18 bytes of the header + $v_binary_data = fread($this->zip_fd, 18); - } - else - { - $p_header['mtime'] = time(); - } + // ----- Look for invalid block size + if (strlen($v_binary_data) != 18) { - // ----- Set the stored filename - $p_header['stored_filename'] = $p_header['filename']; + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : " . strlen($v_binary_data)); - // ----- Set default status to ok - $p_header['status'] = 'ok'; + // ----- Return + return PclZip::errorCode(); + } - // ----- Look if it is a directory - if (substr($p_header['filename'], -1) == '/') { - //$p_header['external'] = 0x41FF0010; - $p_header['external'] = 0x00000010; - } + // ----- Extract the values + $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); + // ----- Check the global size + if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privCheckFileHeaders() - // Description : - // Parameters : - // Return Values : - // 1 on success, - // 0 on error; - // -------------------------------------------------------------------------------- - function privCheckFileHeaders(&$p_local_header, &$p_central_header) - { - $v_result=1; - - // ----- Check the static values - // TBC - if ($p_local_header['filename'] != $p_central_header['filename']) { - } - if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { - } - if ($p_local_header['flag'] != $p_central_header['flag']) { - } - if ($p_local_header['compression'] != $p_central_header['compression']) { - } - if ($p_local_header['mtime'] != $p_central_header['mtime']) { - } - if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { - } + // ----- Removed in release 2.2 see readme file + // The check of the file size is a little too strict. + // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. + // While decrypted, zip has training 0 bytes + if (0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'The central dir is not at the end of the archive.' . ' Some trailing bytes exists after the archive.'); - // ----- Look for flag bit 3 - if (($p_local_header['flag'] & 8) == 8) { - $p_local_header['size'] = $p_central_header['size']; - $p_local_header['compressed_size'] = $p_central_header['compressed_size']; - $p_local_header['crc'] = $p_central_header['crc']; - } + // ----- Return + return PclZip::errorCode(); + } + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privReadEndCentralDir() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privReadEndCentralDir(&$p_central_dir) - { - $v_result=1; - - // ----- Go to the end of the zip file - $v_size = filesize($this->zipname); - @fseek($this->zip_fd, $v_size); - if (@ftell($this->zip_fd) != $v_size) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); + // ----- Get comment + if ($v_data['comment_size'] != 0) { + $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); + } else { + $p_central_dir['comment'] = ''; + } - // ----- Return - return PclZip::errorCode(); - } + $p_central_dir['entries'] = $v_data['entries']; + $p_central_dir['disk_entries'] = $v_data['disk_entries']; + $p_central_dir['offset'] = $v_data['offset']; + $p_central_dir['size'] = $v_data['size']; + $p_central_dir['disk'] = $v_data['disk']; + $p_central_dir['disk_start'] = $v_data['disk_start']; - // ----- First try : look if this is an archive with no commentaries (most of the time) - // in this case the end of central dir is at 22 bytes of the file end - $v_found = 0; - if ($v_size > 26) { - @fseek($this->zip_fd, $v_size-22); - if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + // TBC + //for (reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { + //} // ----- Return - return PclZip::errorCode(); - } + return $v_result; + } + // -------------------------------------------------------------------------------- - // ----- Read for bytes - $v_binary_data = @fread($this->zip_fd, 4); - $v_data = @unpack('Vid', $v_binary_data); + // -------------------------------------------------------------------------------- + // Function : privDeleteByRule() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privDeleteByRule(&$p_result_list, &$p_options) + { + $v_result = 1; + $v_list_detail = array(); - // ----- Check signature - if ($v_data['id'] == 0x06054b50) { - $v_found = 1; - } + // ----- Open the zip file + if (($v_result = $this->privOpenFd('rb')) != 1) { + // ----- Return + return $v_result; + } - $v_pos = ftell($this->zip_fd); - } + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + $this->privCloseFd(); - // ----- Go back to the maximum possible size of the Central Dir End Record - if (!$v_found) { - $v_maximum_size = 65557; // 0xFFFF + 22; - if ($v_maximum_size > $v_size) - $v_maximum_size = $v_size; - @fseek($this->zip_fd, $v_size-$v_maximum_size); - if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + return $v_result; + } - // ----- Return - return PclZip::errorCode(); - } + // ----- Go to beginning of File + @rewind($this->zip_fd); - // ----- Read byte per byte in order to find the signature - $v_pos = ftell($this->zip_fd); - $v_bytes = 0x00000000; - while ($v_pos < $v_size) - { - // ----- Read a byte - $v_byte = @fread($this->zip_fd, 1); + // ----- Scan all the files + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_pos_entry)) { + // ----- Close the zip file + $this->privCloseFd(); - // ----- Add the byte - //$v_bytes = ($v_bytes << 8) | Ord($v_byte); - // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number - // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. - $v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - // ----- Compare the bytes - if ($v_bytes == 0x504b0506) - { - $v_pos++; - break; + // ----- Return + return PclZip::errorCode(); } - $v_pos++; - } + // ----- Read each entry + $v_header_list = array(); + $j_start = 0; + for ($i = 0, $v_nb_extracted = 0; $i < $v_central_dir['entries']; $i++) { - // ----- Look if not found end of central dir - if ($v_pos == $v_size) - { + // ----- Read the file header + $v_header_list[$v_nb_extracted] = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); + return $v_result; + } - // ----- Return - return PclZip::errorCode(); - } - } + // ----- Store the index + $v_header_list[$v_nb_extracted]['index'] = $i; - // ----- Read the first 18 bytes of the header - $v_binary_data = fread($this->zip_fd, 18); + // ----- Look for the specific extract rules + $v_found = false; - // ----- Look for invalid block size - if (strlen($v_binary_data) != 18) - { + // ----- Look for extract by name rule + if ((isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); + // ----- Look if the filename is in the list + for ($j = 0; ($j < sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_found); $j++) { - // ----- Return - return PclZip::errorCode(); - } + // ----- Look for a directory + if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") { - // ----- Extract the values - $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); - - // ----- Check the global size - if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { - - // ----- Removed in release 2.2 see readme file - // The check of the file size is a little too strict. - // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. - // While decrypted, zip has training 0 bytes - if (0) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, - 'The central dir is not at the end of the archive.' - .' Some trailing bytes exists after the archive.'); - - // ----- Return - return PclZip::errorCode(); - } - } + // ----- Look if the directory is in the filename path + if ((strlen($v_header_list[$v_nb_extracted]['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } elseif ((($v_header_list[$v_nb_extracted]['external'] & 0x00000010) == 0x00000010) /* Indicates a folder */ && ($v_header_list[$v_nb_extracted]['stored_filename'] . '/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } - // ----- Get comment - if ($v_data['comment_size'] != 0) { - $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); - } - else - $p_central_dir['comment'] = ''; + // ----- Look for a filename + } elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + $v_found = true; + } + } - $p_central_dir['entries'] = $v_data['entries']; - $p_central_dir['disk_entries'] = $v_data['disk_entries']; - $p_central_dir['offset'] = $v_data['offset']; - $p_central_dir['size'] = $v_data['size']; - $p_central_dir['disk'] = $v_data['disk']; - $p_central_dir['disk_start'] = $v_data['disk_start']; + // ----- Look for extract by ereg rule + // ereg() is deprecated with PHP 5.3 + /* + elseif ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { - // TBC - //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { - //} + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + $v_found = true; + } + } + */ - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privDeleteByRule() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privDeleteByRule(&$p_result_list, &$p_options) - { - $v_result=1; - $v_list_detail = array(); - - // ----- Open the zip file - if (($v_result=$this->privOpenFd('rb')) != 1) - { - // ----- Return - return $v_result; - } + // ----- Look for extract by preg rule + } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - $this->privCloseFd(); - return $v_result; - } + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + $v_found = true; + } - // ----- Go to beginning of File - @rewind($this->zip_fd); + // ----- Look for extract by index rule + } elseif ((isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { - // ----- Scan all the files - // ----- Start at beginning of Central Dir - $v_pos_entry = $v_central_dir['offset']; - @rewind($this->zip_fd); - if (@fseek($this->zip_fd, $v_pos_entry)) - { - // ----- Close the zip file - $this->privCloseFd(); + // ----- Look if the index is in the list + for ($j = $j_start; ($j < sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_found); $j++) { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + if (($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i <= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_found = true; + } + if ($i >= $p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j + 1; + } - // ----- Return - return PclZip::errorCode(); - } + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start'] > $i) { + break; + } + } + } else { + $v_found = true; + } - // ----- Read each entry - $v_header_list = array(); - $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) - { + // ----- Look for deletion + if ($v_found) { + unset($v_header_list[$v_nb_extracted]); + } else { + $v_nb_extracted++; + } + } - // ----- Read the file header - $v_header_list[$v_nb_extracted] = array(); - if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) - { - // ----- Close the zip file - $this->privCloseFd(); + // ----- Look if something need to be deleted + if ($v_nb_extracted > 0) { - return $v_result; - } - - - // ----- Store the index - $v_header_list[$v_nb_extracted]['index'] = $i; - - // ----- Look for the specific extract rules - $v_found = false; - - // ----- Look for extract by name rule - if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) - && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) - && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { - $v_found = true; - } - elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ - && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { - $v_found = true; - } - } - // ----- Look for a filename - elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { - $v_found = true; - } - } - } - - // ----- Look for extract by ereg rule - // ereg() is deprecated with PHP 5.3 - /* - else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) - && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { - - if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - */ - - // ----- Look for extract by preg rule - else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) - && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { - - if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - - // ----- Look for extract by index rule - else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) - && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { - $v_found = true; - } - if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { - $j_start = $j+1; - } - - if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { - break; - } - } - } - else { - $v_found = true; - } - - // ----- Look for deletion - if ($v_found) - { - unset($v_header_list[$v_nb_extracted]); - } - else - { - $v_nb_extracted++; - } - } + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.tmp'; - // ----- Look if something need to be deleted - if ($v_nb_extracted > 0) { + // ----- Creates a temporary zip archive + $v_temp_zip = new PclZip($v_zip_temp_name); - // ----- Creates a temporay file - $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + // ----- Open the temporary zip file in write mode + if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { + $this->privCloseFd(); - // ----- Creates a temporary zip archive - $v_temp_zip = new PclZip($v_zip_temp_name); + // ----- Return + return $v_result; + } - // ----- Open the temporary zip file in write mode - if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { - $this->privCloseFd(); + // ----- Look which file need to be kept + for ($i = 0; $i < sizeof($v_header_list); $i++) { + + // ----- Calculate the position of the header + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the file header + $v_local_header = array(); + if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Check that local file header is same as central file header + if ($this->privCheckFileHeaders($v_local_header, $v_header_list[$i]) != 1) { + // TBC + } + unset($v_local_header); + + // ----- Write the file header + if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Read/write the data block + if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + } - // ----- Return - return $v_result; - } + // ----- Store the offset of the central dir + $v_offset = @ftell($v_temp_zip->zip_fd); - // ----- Look which file need to be kept - for ($i=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); - // ----- Calculate the position of the header - @rewind($this->zip_fd); - if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { - // ----- Close the zip file - $this->privCloseFd(); - $v_temp_zip->privCloseFd(); - @unlink($v_zip_temp_name); + // ----- Return + return $v_result; + } - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + // ----- Transform the header to a 'usable' info + $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } - // ----- Return - return PclZip::errorCode(); + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; } - // ----- Read the file header - $v_local_header = array(); - if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { - // ----- Close the zip file - $this->privCloseFd(); + // ----- Calculate the size of the central header + $v_size = @ftell($v_temp_zip->zip_fd) - $v_offset; + + // ----- Create the central dir footer + if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); $v_temp_zip->privCloseFd(); + $this->privCloseFd(); @unlink($v_zip_temp_name); // ----- Return return $v_result; } - // ----- Check that local file header is same as central file header - if ($this->privCheckFileHeaders($v_local_header, - $v_header_list[$i]) != 1) { - // TBC - } - unset($v_local_header); + // ----- Close + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); - // ----- Write the file header - if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { - // ----- Close the zip file - $this->privCloseFd(); - $v_temp_zip->privCloseFd(); - @unlink($v_zip_temp_name); + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); - // ----- Return + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Destroy the temporary archive + unset($v_temp_zip); + + // ----- Remove every files : reset the file + } elseif ($v_central_dir['entries'] != 0) { + $this->privCloseFd(); + + if (($v_result = $this->privOpenFd('wb')) != 1) { return $v_result; } - // ----- Read/write the data block - if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { - // ----- Close the zip file - $this->privCloseFd(); - $v_temp_zip->privCloseFd(); - @unlink($v_zip_temp_name); - - // ----- Return + if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { return $v_result; } - } - // ----- Store the offset of the central dir - $v_offset = @ftell($v_temp_zip->zip_fd); + $this->privCloseFd(); + } - // ----- Re-Create the Central Dir files header - for ($i=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { - $v_temp_zip->privCloseFd(); - $this->privCloseFd(); - @unlink($v_zip_temp_name); + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDirCheck() + // Description : + // Check if a directory exists, if not it creates it and all the parents directory + // which may be useful. + // Parameters : + // $p_dir : Directory path to check. + // Return Values : + // 1 : OK + // -1 : Unable to create directory + // -------------------------------------------------------------------------------- + public function privDirCheck($p_dir, $p_is_dir = false) + { + $v_result = 1; - // ----- Return - return $v_result; - } + // ----- Remove the final '/' + if (($p_is_dir) && (substr($p_dir, -1) == '/')) { + $p_dir = substr($p_dir, 0, strlen($p_dir) - 1); + } - // ----- Transform the header to a 'usable' info - $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + // ----- Check the directory availability + if ((is_dir($p_dir)) || ($p_dir == "")) { + return 1; } + // ----- Extract parent directory + $p_parent_dir = dirname($p_dir); - // ----- Zip file comment - $v_comment = ''; - if (isset($p_options[PCLZIP_OPT_COMMENT])) { - $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + // ----- Just a check + if ($p_parent_dir != $p_dir) { + // ----- Look for parent directory + if ($p_parent_dir != "") { + if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) { + return $v_result; + } + } } - // ----- Calculate the size of the central header - $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; - - // ----- Create the central dir footer - if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { - // ----- Reset the file list - unset($v_header_list); - $v_temp_zip->privCloseFd(); - $this->privCloseFd(); - @unlink($v_zip_temp_name); + // ----- Create the directory + if (!@mkdir($p_dir, 0777)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); // ----- Return - return $v_result; + return PclZip::errorCode(); } - // ----- Close - $v_temp_zip->privCloseFd(); - $this->privCloseFd(); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->zipname); + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->zipname); - PclZipUtilRename($v_zip_temp_name, $this->zipname); + // -------------------------------------------------------------------------------- + // Function : privMerge() + // Description : + // If $p_archive_to_add does not exist, the function exit with a success result. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privMerge(&$p_archive_to_add) + { + $v_result = 1; - // ----- Destroy the temporary archive - unset($v_temp_zip); - } + // ----- Look if the archive_to_add exists + if (!is_file($p_archive_to_add->zipname)) { - // ----- Remove every files : reset the file - else if ($v_central_dir['entries'] != 0) { - $this->privCloseFd(); + // ----- Nothing to merge, so merge is a success + $v_result = 1; - if (($v_result = $this->privOpenFd('wb')) != 1) { - return $v_result; + // ----- Return + return $v_result; } - if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { - return $v_result; - } + // ----- Look if the archive exists + if (!is_file($this->zipname)) { - $this->privCloseFd(); - } + // ----- Do a duplicate + $v_result = $this->privDuplicate($p_archive_to_add->zipname); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privDirCheck() - // Description : - // Check if a directory exists, if not it creates it and all the parents directory - // which may be useful. - // Parameters : - // $p_dir : Directory path to check. - // Return Values : - // 1 : OK - // -1 : Unable to create directory - // -------------------------------------------------------------------------------- - function privDirCheck($p_dir, $p_is_dir=false) - { - $v_result = 1; + // ----- Return + return $v_result; + } + // ----- Open the zip file + if (($v_result = $this->privOpenFd('rb')) != 1) { + // ----- Return + return $v_result; + } - // ----- Remove the final '/' - if (($p_is_dir) && (substr($p_dir, -1)=='/')) - { - $p_dir = substr($p_dir, 0, strlen($p_dir)-1); - } + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + $this->privCloseFd(); - // ----- Check the directory availability - if ((is_dir($p_dir)) || ($p_dir == "")) - { - return 1; - } + return $v_result; + } - // ----- Extract parent directory - $p_parent_dir = dirname($p_dir); + // ----- Go to beginning of File + @rewind($this->zip_fd); - // ----- Just a check - if ($p_parent_dir != $p_dir) - { - // ----- Look for parent directory - if ($p_parent_dir != "") - { - if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) - { - return $v_result; - } - } - } + // ----- Open the archive_to_add file + if (($v_result = $p_archive_to_add->privOpenFd('rb')) != 1) { + $this->privCloseFd(); - // ----- Create the directory - if (!@mkdir($p_dir, 0777)) - { - // ----- Error log - PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); + // ----- Return + return $v_result; + } - // ----- Return - return PclZip::errorCode(); - } + // ----- Read the central directory informations + $v_central_dir_to_add = array(); + if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privMerge() - // Description : - // If $p_archive_to_add does not exist, the function exit with a success result. - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privMerge(&$p_archive_to_add) - { - $v_result=1; - - // ----- Look if the archive_to_add exists - if (!is_file($p_archive_to_add->zipname)) - { + return $v_result; + } - // ----- Nothing to merge, so merge is a success - $v_result = 1; + // ----- Go to beginning of File + @rewind($p_archive_to_add->zip_fd); - // ----- Return - return $v_result; - } + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.tmp'; - // ----- Look if the archive exists - if (!is_file($this->zipname)) - { + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); - // ----- Do a duplicate - $v_result = $this->privDuplicate($p_archive_to_add->zipname); + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_zip_temp_name . '\' in binary write mode'); - // ----- Return - return $v_result; - } + // ----- Return + return PclZip::errorCode(); + } - // ----- Open the zip file - if (($v_result=$this->privOpenFd('rb')) != 1) - { - // ----- Return - return $v_result; - } + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) - { - $this->privCloseFd(); - return $v_result; - } + // ----- Copy the files from the archive_to_add into the temporary file + $v_size = $v_central_dir_to_add['offset']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } - // ----- Go to beginning of File - @rewind($this->zip_fd); + // ----- Store the offset of the central dir + $v_offset = @ftell($v_zip_temp_fd); - // ----- Open the archive_to_add file - if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) - { - $this->privCloseFd(); + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } - // ----- Return - return $v_result; - } + // ----- Copy the block of file headers from the archive_to_add + $v_size = $v_central_dir_to_add['size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } - // ----- Read the central directory informations - $v_central_dir_to_add = array(); - if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) - { - $this->privCloseFd(); - $p_archive_to_add->privCloseFd(); + // ----- Merge the file comments + $v_comment = $v_central_dir['comment'] . ' ' . $v_central_dir_to_add['comment']; - return $v_result; - } + // ----- Calculate the size of the (new) central header + $v_size = @ftell($v_zip_temp_fd) - $v_offset; - // ----- Go to beginning of File - @rewind($p_archive_to_add->zip_fd); + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive fd + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; - // ----- Creates a temporay file - $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries'] + $v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + @fclose($v_zip_temp_fd); + $this->zip_fd = null; - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) - { - $this->privCloseFd(); - $p_archive_to_add->privCloseFd(); + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + return $v_result; + } - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; - // ----- Return - return PclZip::errorCode(); - } + // ----- Close + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the central dir - $v_size = $v_central_dir['offset']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } + // ----- Close the temporary file + @fclose($v_zip_temp_fd); - // ----- Copy the files from the archive_to_add into the temporary file - $v_size = $v_central_dir_to_add['offset']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); - // ----- Store the offset of the central dir - $v_offset = @ftell($v_zip_temp_fd); + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); - // ----- Copy the block of file headers from the old archive - $v_size = $v_central_dir['size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- - // ----- Copy the block of file headers from the archive_to_add - $v_size = $v_central_dir_to_add['size']; - while ($v_size != 0) + // -------------------------------------------------------------------------------- + // Function : privDuplicate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privDuplicate($p_archive_filename) { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } + $v_result = 1; - // ----- Merge the file comments - $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; + // ----- Look if the $p_archive_filename exists + if (!is_file($p_archive_filename)) { - // ----- Calculate the size of the (new) central header - $v_size = @ftell($v_zip_temp_fd)-$v_offset; + // ----- Nothing to duplicate, so duplicate is a success. + $v_result = 1; - // ----- Swap the file descriptor - // Here is a trick : I swap the temporary fd with the zip fd, in order to use - // the following methods on the temporary fil and not the real archive fd - $v_swap = $this->zip_fd; - $this->zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; + // ----- Return + return $v_result; + } - // ----- Create the central dir footer - if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) - { - $this->privCloseFd(); - $p_archive_to_add->privCloseFd(); - @fclose($v_zip_temp_fd); - $this->zip_fd = null; + // ----- Open the zip file + if (($v_result = $this->privOpenFd('wb')) != 1) { + // ----- Return + return $v_result; + } - // ----- Reset the file list - unset($v_header_list); + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) { + $this->privCloseFd(); - // ----- Return - return $v_result; - } + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \'' . $p_archive_filename . '\' in binary write mode'); - // ----- Swap back the file descriptor - $v_swap = $this->zip_fd; - $this->zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; + // ----- Return + return PclZip::errorCode(); + } - // ----- Close - $this->privCloseFd(); - $p_archive_to_add->privCloseFd(); + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = filesize($p_archive_filename); + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } - // ----- Close the temporary file - @fclose($v_zip_temp_fd); + // ----- Close + $this->privCloseFd(); - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->zipname); + // ----- Close the temporary file + @fclose($v_zip_temp_fd); - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->zipname); - PclZipUtilRename($v_zip_temp_name, $this->zipname); + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privDuplicate() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privDuplicate($p_archive_filename) - { - $v_result=1; - - // ----- Look if the $p_archive_filename exists - if (!is_file($p_archive_filename)) + // -------------------------------------------------------------------------------- + // Function : privErrorLog() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function privErrorLog($p_error_code = 0, $p_error_string = '') { - - // ----- Nothing to duplicate, so duplicate is a success. - $v_result = 1; - - // ----- Return - return $v_result; + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclError($p_error_code, $p_error_string); + } else { + $this->error_code = $p_error_code; + $this->error_string = $p_error_string; + } } + // -------------------------------------------------------------------------------- - // ----- Open the zip file - if (($v_result=$this->privOpenFd('wb')) != 1) + // -------------------------------------------------------------------------------- + // Function : privErrorReset() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function privErrorReset() { - // ----- Return - return $v_result; + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclErrorReset(); + } else { + $this->error_code = 0; + $this->error_string = ''; + } } + // -------------------------------------------------------------------------------- - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) + // -------------------------------------------------------------------------------- + // Function : privDisableMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privDisableMagicQuotes() { - $this->privCloseFd(); - - PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); + $v_result = 1; - // ----- Return - return PclZip::errorCode(); - } + // ----- Look if function exists + if ((!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; + } - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the central dir - $v_size = filesize($p_archive_filename); - while ($v_size != 0) - { - $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = fread($v_zip_temp_fd, $v_read_size); - @fwrite($this->zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } + // ----- Look if already done + if ($this->magic_quotes_status != -1) { + return $v_result; + } - // ----- Close - $this->privCloseFd(); + // ----- Get and memorize the magic_quote value + $this->magic_quotes_status = @get_magic_quotes_runtime(); - // ----- Close the temporary file - @fclose($v_zip_temp_fd); + // ----- Disable magic_quotes + if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime(0); + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privErrorLog() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function privErrorLog($p_error_code=0, $p_error_string='') - { - if (PCLZIP_ERROR_EXTERNAL == 1) { - PclError($p_error_code, $p_error_string); - } - else { - $this->error_code = $p_error_code; - $this->error_string = $p_error_string; - } - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privErrorReset() - // Description : - // Parameters : - // -------------------------------------------------------------------------------- - function privErrorReset() - { - if (PCLZIP_ERROR_EXTERNAL == 1) { - PclErrorReset(); - } - else { - $this->error_code = 0; - $this->error_string = ''; - } - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privDisableMagicQuotes() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privDisableMagicQuotes() - { - $v_result=1; - - // ----- Look if function exists - if ( (!function_exists("get_magic_quotes_runtime")) - || (!function_exists("set_magic_quotes_runtime"))) { - return $v_result; + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- - // ----- Look if already done - if ($this->magic_quotes_status != -1) { - return $v_result; - } + // -------------------------------------------------------------------------------- + // Function : privSwapBackMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privSwapBackMagicQuotes() + { + $v_result = 1; - // ----- Get and memorize the magic_quote value - $this->magic_quotes_status = @get_magic_quotes_runtime(); + // ----- Look if function exists + if ((!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; + } - // ----- Disable magic_quotes - if ($this->magic_quotes_status == 1) { - @set_magic_quotes_runtime(0); - } + // ----- Look if something to do + if ($this->magic_quotes_status != -1) { + return $v_result; + } - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : privSwapBackMagicQuotes() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function privSwapBackMagicQuotes() - { - $v_result=1; - - // ----- Look if function exists - if ( (!function_exists("get_magic_quotes_runtime")) - || (!function_exists("set_magic_quotes_runtime"))) { - return $v_result; - } + // ----- Swap back magic_quotes + if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime($this->magic_quotes_status); + } - // ----- Look if something to do - if ($this->magic_quotes_status != -1) { - return $v_result; + // ----- Return + return $v_result; } + // -------------------------------------------------------------------------------- +} - // ----- Swap back magic_quotes - if ($this->magic_quotes_status == 1) { - @set_magic_quotes_runtime($this->magic_quotes_status); - } +// End of class +// -------------------------------------------------------------------------------- - // ----- Return - return $v_result; - } - // -------------------------------------------------------------------------------- - - } - // End of class - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : PclZipUtilPathReduction() - // Description : - // Parameters : - // Return Values : - // -------------------------------------------------------------------------------- - function PclZipUtilPathReduction($p_dir) - { +// -------------------------------------------------------------------------------- +// Function : PclZipUtilPathReduction() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function PclZipUtilPathReduction($p_dir) +{ $v_result = ""; // ----- Look for not empty path if ($p_dir != "") { - // ----- Explode path by directory names - $v_list = explode("/", $p_dir); - - // ----- Study directories from last to first - $v_skip = 0; - for ($i=sizeof($v_list)-1; $i>=0; $i--) { - // ----- Look for current path - if ($v_list[$i] == ".") { - // ----- Ignore this directory - // Should be the first $i=0, but no check is done - } - else if ($v_list[$i] == "..") { - $v_skip++; - } - else if ($v_list[$i] == "") { - // ----- First '/' i.e. root slash - if ($i == 0) { - $v_result = "/".$v_result; - if ($v_skip > 0) { - // ----- It is an invalid path, so the path is not modified - // TBC - $v_result = $p_dir; - $v_skip = 0; + // ----- Explode path by directory names + $v_list = explode("/", $p_dir); + + // ----- Study directories from last to first + $v_skip = 0; + for ($i = sizeof($v_list) - 1; $i >= 0; $i--) { + // ----- Look for current path + if ($v_list[$i] == ".") { + // ----- Ignore this directory + // Should be the first $i=0, but no check is done + } elseif ($v_list[$i] == "..") { + $v_skip++; + } elseif ($v_list[$i] == "") { + // ----- First '/' i.e. root slash + if ($i == 0) { + $v_result = "/" . $v_result; + if ($v_skip > 0) { + // ----- It is an invalid path, so the path is not modified + // TBC + $v_result = $p_dir; + $v_skip = 0; + } + + // ----- Last '/' i.e. indicates a directory + } elseif ($i == (sizeof($v_list) - 1)) { + $v_result = $v_list[$i]; + + // ----- Double '/' inside the path + } else { + // ----- Ignore only the double '//' in path, + // but not the first and last '/' + } + } else { + // ----- Look for item to skip + if ($v_skip > 0) { + $v_skip--; + } else { + $v_result = $v_list[$i] . ($i != (sizeof($v_list) - 1) ? "/" . $v_result : ""); + } + } + } + + // ----- Look for skip + if ($v_skip > 0) { + while ($v_skip > 0) { + $v_result = '../' . $v_result; + $v_skip--; } - } - // ----- Last '/' i.e. indicates a directory - else if ($i == (sizeof($v_list)-1)) { - $v_result = $v_list[$i]; - } - // ----- Double '/' inside the path - else { - // ----- Ignore only the double '//' in path, - // but not the first and last '/' - } - } - else { - // ----- Look for item to skip - if ($v_skip > 0) { - $v_skip--; - } - else { - $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); - } - } - } - - // ----- Look for skip - if ($v_skip > 0) { - while ($v_skip > 0) { - $v_result = '../'.$v_result; - $v_skip--; - } - } + } } // ----- Return return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : PclZipUtilPathInclusion() - // Description : - // This function indicates if the path $p_path is under the $p_dir tree. Or, - // said in an other way, if the file or sub-dir $p_path is inside the dir - // $p_dir. - // The function indicates also if the path is exactly the same as the dir. - // This function supports path with duplicated '/' like '//', but does not - // support '.' or '..' statements. - // Parameters : - // Return Values : - // 0 if $p_path is not inside directory $p_dir - // 1 if $p_path is inside directory $p_dir - // 2 if $p_path is exactly the same as $p_dir - // -------------------------------------------------------------------------------- - function PclZipUtilPathInclusion($p_dir, $p_path) - { +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilPathInclusion() +// Description : +// This function indicates if the path $p_path is under the $p_dir tree. Or, +// said in an other way, if the file or sub-dir $p_path is inside the dir +// $p_dir. +// The function indicates also if the path is exactly the same as the dir. +// This function supports path with duplicated '/' like '//', but does not +// support '.' or '..' statements. +// Parameters : +// Return Values : +// 0 if $p_path is not inside directory $p_dir +// 1 if $p_path is inside directory $p_dir +// 2 if $p_path is exactly the same as $p_dir +// -------------------------------------------------------------------------------- +function PclZipUtilPathInclusion($p_dir, $p_path) +{ $v_result = 1; // ----- Look for path beginning by ./ - if ( ($p_dir == '.') - || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { - $p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1); + if (($p_dir == '.') || ((strlen($p_dir) >= 2) && (substr($p_dir, 0, 2) == './'))) { + $p_dir = PclZipUtilTranslateWinPath(getcwd(), false) . '/' . substr($p_dir, 1); } - if ( ($p_path == '.') - || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { - $p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1); + if (($p_path == '.') || ((strlen($p_path) >= 2) && (substr($p_path, 0, 2) == './'))) { + $p_path = PclZipUtilTranslateWinPath(getcwd(), false) . '/' . substr($p_path, 1); } // ----- Explode dir and path by directory separator - $v_list_dir = explode("/", $p_dir); - $v_list_dir_size = sizeof($v_list_dir); - $v_list_path = explode("/", $p_path); + $v_list_dir = explode("/", $p_dir); + $v_list_dir_size = sizeof($v_list_dir); + $v_list_path = explode("/", $p_path); $v_list_path_size = sizeof($v_list_path); // ----- Study directories paths @@ -5499,193 +5234,182 @@ function PclZipUtilPathInclusion($p_dir, $p_path) $j = 0; while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { - // ----- Look for empty dir (path reduction) - if ($v_list_dir[$i] == '') { - $i++; - continue; - } - if ($v_list_path[$j] == '') { - $j++; - continue; - } + // ----- Look for empty dir (path reduction) + if ($v_list_dir[$i] == '') { + $i++; + continue; + } + if ($v_list_path[$j] == '') { + $j++; + continue; + } - // ----- Compare the items - if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) { - $v_result = 0; - } + // ----- Compare the items + if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ($v_list_path[$j] != '')) { + $v_result = 0; + } - // ----- Next items - $i++; - $j++; + // ----- Next items + $i++; + $j++; } // ----- Look if everything seems to be the same if ($v_result) { - // ----- Skip all the empty items - while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; - while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; - - if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { - // ----- There are exactly the same - $v_result = 2; - } - else if ($i < $v_list_dir_size) { - // ----- The path is shorter than the dir - $v_result = 0; - } + // ----- Skip all the empty items + while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) { + $j++; + } + while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) { + $i++; + } + + if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { + // ----- There are exactly the same + $v_result = 2; + } elseif ($i < $v_list_dir_size) { + // ----- The path is shorter than the dir + $v_result = 0; + } } // ----- Return return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : PclZipUtilCopyBlock() - // Description : - // Parameters : - // $p_mode : read/write compression mode - // 0 : src & dest normal - // 1 : src gzip, dest normal - // 2 : src normal, dest gzip - // 3 : src & dest gzip - // Return Values : - // -------------------------------------------------------------------------------- - function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0) - { +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilCopyBlock() +// Description : +// Parameters : +// $p_mode : read/write compression mode +// 0 : src & dest normal +// 1 : src gzip, dest normal +// 2 : src normal, dest gzip +// 3 : src & dest gzip +// Return Values : +// -------------------------------------------------------------------------------- +function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode = 0) +{ $v_result = 1; - if ($p_mode==0) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==1) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==2) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==3) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } + if ($p_mode == 0) { + while ($p_size != 0) { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } elseif ($p_mode == 1) { + while ($p_size != 0) { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } elseif ($p_mode == 2) { + while ($p_size != 0) { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } elseif ($p_mode == 3) { + while ($p_size != 0) { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } } // ----- Return return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : PclZipUtilRename() - // Description : - // This function tries to do a simple rename() function. If it fails, it - // tries to copy the $p_src file in a new $p_dest file and then unlink the - // first one. - // Parameters : - // $p_src : Old filename - // $p_dest : New filename - // Return Values : - // 1 on success, 0 on failure. - // -------------------------------------------------------------------------------- - function PclZipUtilRename($p_src, $p_dest) - { +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilRename() +// Description : +// This function tries to do a simple rename() function. If it fails, it +// tries to copy the $p_src file in a new $p_dest file and then unlink the +// first one. +// Parameters : +// $p_src : Old filename +// $p_dest : New filename +// Return Values : +// 1 on success, 0 on failure. +// -------------------------------------------------------------------------------- +function PclZipUtilRename($p_src, $p_dest) +{ $v_result = 1; // ----- Try to rename the files if (!@rename($p_src, $p_dest)) { - // ----- Try to copy & unlink the src - if (!@copy($p_src, $p_dest)) { - $v_result = 0; - } - else if (!@unlink($p_src)) { - $v_result = 0; - } + // ----- Try to copy & unlink the src + if (!@copy($p_src, $p_dest)) { + $v_result = 0; + } elseif (!@unlink($p_src)) { + $v_result = 0; + } } // ----- Return return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : PclZipUtilOptionText() - // Description : - // Translate option value in text. Mainly for debug purpose. - // Parameters : - // $p_option : the option value. - // Return Values : - // The option text value. - // -------------------------------------------------------------------------------- - function PclZipUtilOptionText($p_option) - { +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilOptionText() +// Description : +// Translate option value in text. Mainly for debug purpose. +// Parameters : +// $p_option : the option value. +// Return Values : +// The option text value. +// -------------------------------------------------------------------------------- +function PclZipUtilOptionText($p_option) +{ $v_list = get_defined_constants(); for (reset($v_list); $v_key = key($v_list); next($v_list)) { $v_prefix = substr($v_key, 0, 10); - if (( ($v_prefix == 'PCLZIP_OPT') - || ($v_prefix == 'PCLZIP_CB_') - || ($v_prefix == 'PCLZIP_ATT')) - && ($v_list[$v_key] == $p_option)) { - return $v_key; + if ((($v_prefix == 'PCLZIP_OPT') || ($v_prefix == 'PCLZIP_CB_') || ($v_prefix == 'PCLZIP_ATT')) && ($v_list[$v_key] == $p_option)) { + return $v_key; } } $v_result = 'Unknown'; return $v_result; - } - // -------------------------------------------------------------------------------- - - // -------------------------------------------------------------------------------- - // Function : PclZipUtilTranslateWinPath() - // Description : - // Translate windows path by replacing '\' by '/' and optionally removing - // drive letter. - // Parameters : - // $p_path : path to translate. - // $p_remove_disk_letter : true | false - // Return Values : - // The path translated. - // -------------------------------------------------------------------------------- - function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true) - { +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilTranslateWinPath() +// Description : +// Translate windows path by replacing '\' by '/' and optionally removing +// drive letter. +// Parameters : +// $p_path : path to translate. +// $p_remove_disk_letter : true | false +// Return Values : +// The path translated. +// -------------------------------------------------------------------------------- +function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter = true) +{ if (stristr(php_uname(), 'windows')) { - // ----- Look for potential disk letter - if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { - $p_path = substr($p_path, $v_position+1); - } - // ----- Change potential windows directory separator - if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { - $p_path = strtr($p_path, '\\', '/'); - } + // ----- Look for potential disk letter + if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { + $p_path = substr($p_path, $v_position + 1); + } + // ----- Change potential windows directory separator + if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0, 1) == '\\')) { + $p_path = strtr($p_path, '\\', '/'); + } } + return $p_path; - } - // -------------------------------------------------------------------------------- +} +// -------------------------------------------------------------------------------- From 157f325db52aed4b8349cf03e2b334d99cef6f36 Mon Sep 17 00:00:00 2001 From: Nilton Date: Mon, 11 Dec 2017 16:45:06 +0100 Subject: [PATCH 72/74] Change syntax to please new Travis rules --- src/PhpWord/TemplateProcessor.php | 127 +++++------- tests/PhpWord/TemplateProcessorTest.php | 263 +++++++++++------------- 2 files changed, 177 insertions(+), 213 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index bf2fddd4ca..d64fa3c44f 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -150,11 +150,10 @@ protected function transformXml($xml, $xsltProcessor) foreach ($xml as &$item) { $item = $this->transformSingleXml($item, $xsltProcessor); } - return (array)$xml; - } else { - $xml = $this->transformSingleXml($xml, $xsltProcessor); - return (string)$xml; + return (array) $xml; } + $xml = $this->transformSingleXml($xml, $xsltProcessor); + return (string) $xml; } /** @@ -178,9 +177,9 @@ public function applyXslStyleSheet($xslDomDocument, $xslOptions = array(), $xslO throw new Exception('Could not set values for the given XSL style sheet parameters.'); } - $this->tempDocumentHeaders = (array)$this->transformXml($this->tempDocumentHeaders, $xsltProcessor); - $this->tempDocumentMainPart = (string)$this->transformXml($this->tempDocumentMainPart, $xsltProcessor); - $this->tempDocumentFooters = (array)$this->transformXml($this->tempDocumentFooters, $xsltProcessor); + $this->tempDocumentHeaders = (array) $this->transformXml($this->tempDocumentHeaders, $xsltProcessor); + $this->tempDocumentMainPart = (string) $this->transformXml($this->tempDocumentMainPart, $xsltProcessor); + $this->tempDocumentFooters = (array) $this->transformXml($this->tempDocumentFooters, $xsltProcessor); } /** @@ -215,7 +214,7 @@ protected static function ensureUtf8Encoded($subject) /** * @param mixed $search macro name you want to replace (or an array of these) * @param mixed $replace replace string (or an array of these) - * @param int $limit How many times it will have to replace the same variable all over the document. + * @param int $limit How many times it will have to replace the same variable all over the document */ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_DEFAULT) { @@ -242,22 +241,22 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ $replace = $xmlEscaper->escape($replace); } - $this->tempDocumentHeaders = (array)$this->setValueForPart( + $this->tempDocumentHeaders = (array) $this->setValueForPart( $search, $replace, - (array)$this->tempDocumentHeaders, + (array) $this->tempDocumentHeaders, $limit ); - $this->tempDocumentMainPart = (string)$this->setValueForPart( + $this->tempDocumentMainPart = (string) $this->setValueForPart( $search, $replace, - (string)$this->tempDocumentMainPart, + (string) $this->tempDocumentMainPart, $limit ); - $this->tempDocumentFooters = (array)$this->setValueForPart( + $this->tempDocumentFooters = (array) $this->setValueForPart( $search, $replace, - (array)$this->tempDocumentFooters, + (array) $this->tempDocumentFooters, $limit ); } @@ -266,10 +265,8 @@ public function setValue($search, $replace, $limit = self::MAXIMUM_REPLACEMENTS_ * Replaces a closed block with text * * @param string $blockname The blockname without '${}'. Your macro must end with slash, i.e.: ${value/} - * @param mixed $replace Array or the text can be multiline (contain \n). It will cloneBlock(). + * @param mixed $replace Array or the text can be multiline (contain \n); It will then cloneBlock() * @param int $limit - * - * @return void */ public function setBlock($blockname, $replace, $limit = self::MAXIMUM_REPLACEMENTS_DEFAULT) { @@ -287,17 +284,17 @@ public function setBlock($blockname, $replace, $limit = self::MAXIMUM_REPLACEMEN } /** - * Updates a file inside the document, from a string (with binary data) - * To replace an image: $templateProcessor->zipAddFromString("word/media/image1.jpg", file_get_contents($file)); + * Expose zip class * - * @param string $localname The path and name inside the docx/zip file - * @param mixed $contents Text or Binary data + * To replace an image: $templateProcessor->zip()->AddFromString("word/media/image1.jpg", file_get_contents($file)); + * (note that to add an image you also need to add some xml in the document, and a relation from Id to zip-filename) + * To read a file: $templateProcessor->zip()->getFromName("word/media/image1.jpg"); * - * @return bool + * @return object */ - public function zipAddFromString($localname, $contents) + public function zip() { - return $this->zipClass->AddFromString($localname, $contents); + return $this->zipClass; } /** @@ -308,16 +305,13 @@ public function zipAddFromString($localname, $contents) * @param mixed $elseReturn * * @return mixed - * - * @throws \PhpOffice\PhpWord\Exception\Exception */ private function failGraciously($exceptionText, $throwException, $elseReturn) { if ($throwException) { throw new Exception($exceptionText); - } else { - return $elseReturn; } + return $elseReturn; } /** @@ -371,9 +365,8 @@ protected static function cloneSlice(&$text, $numberOfClones = 1, $incrementVari * @param bool $incrementVariables * @param bool $throwException * - * @return string|false Returns the row cloned or false if the $search macro is not found - * * @throws \PhpOffice\PhpWord\Exception\Exception + * @return string|false Returns the row cloned or false if the $search macro is not found */ private function processRow( $search, @@ -426,9 +419,8 @@ function (&$xmlSegment, &$segmentStart, &$segmentEnd, &$part) use (&$replace) { * @param bool $incrementVariables * @param bool $throwException * - * @return mixed Returns true if row cloned succesfully or or false if the $search macro is not found - * * @throws \PhpOffice\PhpWord\Exception\Exception + * @return mixed Returns true if row cloned succesfully or or false if the $search macro is not found */ public function cloneRow( $search, @@ -457,13 +449,13 @@ public function getRow($search, $throwException = false) * * @param string $search a macro name in a table row * @param string $replacement The replacement xml string. Be careful and keep the xml uncorrupted. - * @param bool $throwException false by default (it then returns false or null on errors). + * @param bool $throwException false by default (it then returns false or null on errors) * * @return mixed true (replaced), false ($search not found) or null (no tags found around $search) */ public function replaceRow($search, $replacement = '', $throwException = false) { - return $this->processRow($search, 1, (string)$replacement, false, $throwException); + return $this->processRow($search, 1, (string) $replacement, false, $throwException); } /** @@ -471,7 +463,7 @@ public function replaceRow($search, $replacement = '', $throwException = false) * * @param string $search * - * @return boolean + * @return bool */ public function deleteRow($search) { @@ -487,9 +479,8 @@ public function deleteRow($search) * @param bool $incrementVariables * @param bool $throwException * - * @return mixed The cloned string if successful, false ($blockname not found) or Null (no paragraph found) - * * @throws \PhpOffice\PhpWord\Exception\Exception + * @return mixed The cloned string if successful, false ($blockname not found) or Null (no paragraph found) */ private function processBlock( $blockname, @@ -576,11 +567,10 @@ private function processBlock( * @param string $blockname The blockname without '${}', it will search for '${BLOCKNAME}' and '${/BLOCKNAME} * @param int $clones How many times the block needs to be cloned * @param bool $incrementVariables true by default (variables get appended #1, #2 inside the cloned blocks) - * @param bool $throwException false by default (it then returns false or null on errors). - * - * @return mixed True if successful, false ($blockname not found) or null (no paragraph found) + * @param bool $throwException false by default (it then returns false or null on errors) * * @throws \PhpOffice\PhpWord\Exception\Exception + * @return mixed True if successful, false ($blockname not found) or null (no paragraph found) */ public function cloneBlock( $blockname, @@ -609,13 +599,13 @@ public function getBlock($blockname, $throwException = false) * * @param string $blockname The name of the macro start and end (without the macro marker ${}) * @param string $replacement The replacement xml - * @param bool $throwException false by default. + * @param bool $throwException false by default * * @return mixed false-ish on no replacement, true-ish on replacement */ public function replaceBlock($blockname, $replacement = '', $throwException = false) { - return $this->processBlock($blockname, 0, (string)$replacement, false, $throwException); + return $this->processBlock($blockname, 0, (string) $replacement, false, $throwException); } /** @@ -623,7 +613,7 @@ public function replaceBlock($blockname, $replacement = '', $throwException = fa * * @param string $blockname * - * @return mixed true-ish on block found and deleted, falseish on block not found. + * @return mixed true-ish on block found and deleted, falseish on block not found */ public function deleteBlock($blockname) { @@ -633,14 +623,14 @@ public function deleteBlock($blockname) /** * process a segment. * - * @param string $needle If this is a macro, you need to add the ${} around it yourself. + * @param string $needle If this is a macro, you need to add the ${} around it yourself * @param string $xmltag an xml tag without brackets, for example: w:p * @param int $direction in which direction should be searched. -1 left, 1 right. Default 0: around * @param int $clones How many times the segment needs to be cloned * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) * @param mixed $replace true (default/cloneSegment) false(getSegment) string(replaceSegment) function(callback) * @param bool $incrementVariables true by default (variables get appended #1, #2 inside the cloned blocks) - * @param bool $throwException false by default (it then returns false or null on errors). + * @param bool $throwException false by default (it then returns false or null on errors) * * @return mixed The segment(getSegment), false (no $needle), null (no tags), true (clone/replace) */ @@ -656,9 +646,9 @@ public function processSegment( ) { $docPart = preg_split('/:/', $docPart); if (count($docPart)>1) { - $part = &$this->{"tempDocument".$docPart[0]}[$docPart[1]]; + $part = &$this->{'tempDocument' . $docPart[0]}[$docPart[1]]; } else { - $part = &$this->{"tempDocument".$docPart[0]}; + $part = &$this->{'tempDocument' . $docPart[0]}; } $needlePos = strpos($part, $needle); @@ -713,13 +703,13 @@ public function processSegment( /** * Clone a segment. * - * @param string $needle If this is a macro, you need to add the ${} around it yourself. + * @param string $needle If this is a macro, you need to add the ${} around it yourself * @param string $xmltag an xml tag without brackets, for example: w:p * @param int $direction in which direction should be searched. -1 left, 1 right. Default 0: around * @param int $clones How many times the segment needs to be cloned * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) * @param bool $incrementVariables true by default (variables get appended #1, #2 inside the cloned blocks) - * @param bool $throwException false by default (it then returns false or null on errors). + * @param bool $throwException false by default (it then returns false or null on errors) * * @return mixed Returns true when succesfully cloned, false (no $needle found), null (no tags found) */ @@ -747,11 +737,11 @@ public function cloneSegment( /** * Get a segment. (first segment found) * - * @param string $needle If this is a macro, you need to add the ${} around it yourself. + * @param string $needle If this is a macro, you need to add the ${} around it yourself * @param string $xmltag an xml tag without brackets, for example: w:p * @param int $direction in which direction should be searched. -1 left, 1 right. Default 0: around * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (first header) - * @param bool $throwException false by default (it then returns false or null on errors). + * @param bool $throwException false by default (it then returns false or null on errors) * * @return mixed Segment String, false ($needle not found) or null (no tags found around $needle) */ @@ -763,12 +753,12 @@ public function getSegment($needle, $xmltag, $direction = 0, $docPart = 'MainPar /** * Replace a segment. * - * @param string $needle If this is a macro, you need to add the ${} around it yourself. + * @param string $needle If this is a macro, you need to add the ${} around it yourself * @param string $xmltag an xml tag without brackets, for example: w:p * @param int $direction in which direction should be searched. -1 left, 1 right. Default 0: around * @param string $replacement The replacement xml string. Be careful and keep the xml uncorrupted. * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:2' (second header) - * @param bool $throwException false by default (it then returns false or null on errors). + * @param bool $throwException false by default (it then returns false or null on errors) * * @return mixed true (replaced), false ($needle not found) or null (no tags found around $needle) */ @@ -786,7 +776,7 @@ public function replaceSegment( $direction, 0, $docPart, - (string)$replacement, + (string) $replacement, false, $throwException ); @@ -795,9 +785,9 @@ public function replaceSegment( /** * Delete a segment. * - * @param string $needle If this is a macro, you need to add the ${} yourself. + * @param string $needle If this is a macro, you need to add the ${} yourself * @param string $xmltag an xml tag without brackets, for example: w:p - * @param integer $direction in which direction should be searched. -1 left, 1 right. Default 0: around + * @param int $direction in which direction should be searched. -1 left, 1 right. Default 0: around * @param string $docPart 'MainPart' (default) 'Footers:1' (first footer) or 'Headers:1' (second header) * * @return mixed true (segment deleted), false ($needle not found) or null (no tags found around $needle) @@ -807,7 +797,7 @@ public function deleteSegment($needle, $xmltag, $direction = self::SEARCH_AROUND return $this->replaceSegment($needle, $xmltag, $direction, '', $docPart, false); } - /** + /** * Saves the result document. * * @throws \PhpOffice\PhpWord\Exception\Exception @@ -974,9 +964,8 @@ protected function getFooterName($index) * @param int $offset Do not look from the beginning, but starting at $offset * @param bool $throwException * - * @return int Zero if not found (due to the nature of xml, your document never starts at 0) - * * @throws \PhpOffice\PhpWord\Exception\Exception + * @return int Zero if not found (due to the nature of xml, your document never starts at 0) */ protected function findOpenTagLeft(&$searchString, $tag, $offset = 0, $throwException = false) { @@ -995,7 +984,7 @@ protected function findOpenTagLeft(&$searchString, $tag, $offset = 0, $throwExce if ($tagStart === false) { return $this->failGraciously( - "Can not find the start position of the item to clone.", + 'Can not find the start position of the item to clone.', $throwException, 0 ); @@ -1010,12 +999,11 @@ protected function findOpenTagLeft(&$searchString, $tag, $offset = 0, $throwExce * * @param string $searchString The string we are searching in (the mainbody or an array element of Footers/Headers) * @param string $tag Fully qualified tag, for example: '' (with brackets!) - * @param integer $offset Do not look from the beginning, but starting at $offset + * @param int $offset Do not look from the beginning, but starting at $offset * @param boolean $throwException * - * @return integer Zero if not found (due to the nature of xml, your document never starts at 0) - * * @throws \PhpOffice\PhpWord\Exception\Exception + * @return int Zero if not found (due to the nature of xml, your document never starts at 0) */ protected function findOpenTagRight(&$searchString, $tag, $offset = 0, $throwException = false) @@ -1035,7 +1023,7 @@ protected function findOpenTagRight(&$searchString, $tag, $offset = 0, $throwExc if ($tagStart === false) { return $this->failGraciously( - "Can not find the start position of the item to clone.", + 'Can not find the start position of the item to clone.', $throwException, 0 ); @@ -1060,20 +1048,18 @@ protected function findCloseTagLeft(&$searchString, $tag, $offset = 0) if ($pos !== false) { return $pos + strlen($tag); - } else { - return 0; } + return 0; } - /** * Find the end position of the nearest $tag after $offset. * * @param string $searchString The string we are searching in (the MainPart or an array element of Footers/Headers) * @param string $tag Fully qualified tag, for example: '' - * @param integer $offset Do not look from the beginning, but starting at $offset + * @param int $offset Do not look from the beginning, but starting at $offset * - * @return integer Zero if not found + * @return int Zero if not found */ protected function findCloseTagRight(&$searchString, $tag, $offset = 0) { @@ -1081,9 +1067,8 @@ protected function findCloseTagRight(&$searchString, $tag, $offset = 0) if ($pos !== false) { return $pos + strlen($tag); - } else { - return 0; } + return 0; } /** diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index a86ebeb2bb..308979eddb 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -30,6 +30,7 @@ public function poke(&$object, $property, $newValue = null) $refObject = new \ReflectionObject($object); $refProperty = $refObject->getProperty($property); $refProperty->setAccessible(true); + if ($newValue !== null) { $refProperty->setValue($object, $newValue); } @@ -41,6 +42,7 @@ public function peek(&$object, $property) $refObject = new \ReflectionObject($object); $refProperty = $refObject->getProperty($property); $refProperty->setAccessible(true); + return $refProperty->getValue($object); } @@ -78,7 +80,7 @@ public function testTheConstruct() * Template can be saved in temporary location. * * @covers ::save - * @covers ::zipAddFromString + * @covers ::zip * @test */ final public function testTemplateCanBeSavedInTemporaryLocation() @@ -92,8 +94,8 @@ final public function testTemplateCanBeSavedInTemporaryLocation() $templateProcessor->applyXslStyleSheet($xslDomDocument, array('needle' => $needle)); } - $embeddingText = "The quick Brown Fox jumped over the lazy^H^H^H^Htired unitTester"; - $templateProcessor->zipAddFromString('word/embeddings/fox.bin', $embeddingText); + $embeddingText = 'The quick Brown Fox jumped over the lazy^H^H^H^Htired unitTester'; + $templateProcessor->zip()->AddFromString('word/embeddings/fox.bin', $embeddingText); $documentFqfn = $templateProcessor->save(); $this->assertNotEmpty($documentFqfn, 'FQFN of the saved document is empty.'); @@ -104,7 +106,6 @@ final public function testTemplateCanBeSavedInTemporaryLocation() $templateHeaderXml = $templateZip->getFromName('word/header1.xml'); $templateMainPartXml = $templateZip->getFromName('word/document.xml'); $templateFooterXml = $templateZip->getFromName('word/footer1.xml'); - $templateFooterXml = $templateZip->getFromName('word/footer1.xml'); if (false === $templateZip->close()) { throw new \Exception("Could not close zip file \"{$templateZip}\"."); } @@ -244,8 +245,7 @@ public function testCloneRow() $docFound = file_exists($docName); unlink($docName); $this->assertTrue($docFound); - $this->assertEquals( - null, + $this->assertNull( $templateProcessor->cloneRow('userId', 2, false, true) ); } @@ -264,13 +264,13 @@ public function testGetRow() $initialArray = array('tableHeader', 'userId', 'userName', 'userLocation'); $midArray = array( 'tableHeader', - 'userId', 'userName', 'foo', 'userLocation' + 'userId', 'userName', 'foo', 'userLocation', ); $finalArray = array( 'tableHeader', 'userId#1', 'userName#1', 'foo#1', 'userId#2', 'userName#2', 'foo#2', - 'userId', 'userName', 'userLocation' + 'userId', 'userName', 'userLocation', ); $row = $templateProcessor->getRow('userId'); $this->assertNotEmpty($row); @@ -287,7 +287,7 @@ public function testGetRow() $this->assertEquals( $midArray, array_values($templateProcessor->getVariables()), - implode("|", $templateProcessor->getVariables()) + implode('|', $templateProcessor->getVariables()) ); $row = $templateProcessor->cloneRow('userId', 2, true, false); $this->assertEquals( @@ -306,7 +306,7 @@ public function testGetRow() $templateProcessorNewFile->getVariables() ); $row = $templateProcessorNewFile->getRow('userId'); - $this->assertTrue(strlen($row)>10); + $this->assertTrue(strlen($row) > 10); $this->assertTrue( $templateProcessorNewFile->replaceRow('userId#1', $row) ); @@ -370,22 +370,22 @@ public function testCloneDeleteBlock() $templateProcessor->saveAs($docName); $docFound = file_exists($docName); if ($docFound) { - # Great, so we saved the replaced document, so we open that new document - # note that we need to access private variables, so we use a sub-class + // Great, so we saved the replaced document, so we open that new document + // note that we need to access private variables, so we use a sub-class $templateProcessorNewFile = new TemplateProcessor($docName); - # We test that all Block variables have been replaced (thus, getVariables() is empty) + // We test that all Block variables have been replaced (thus, getVariables() is empty) $this->assertEquals( array(), $templateProcessorNewFile->getVariables(), "All block variables should have been replaced" ); - # we cloned block CLONEME $cloneTimes times, so let's count to $cloneTimes + // we cloned block CLONEME $cloneTimes times, so let's count to $cloneTimes $this->assertEquals( $cloneTimes, substr_count($this->peek($templateProcessorNewFile, 'tempDocumentMainPart'), $xmlblock), "Block should be present $cloneTimes in the document" ); - unlink($docName); # delete generated file + unlink($docName); // delete generated file } $this->assertTrue($docFound); @@ -403,7 +403,7 @@ public function testCloneDeleteBlock() public function testCloneIndexedBlock() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); - # we will fake a block with a variable inside it, as there is no template document yet. + // we will fake a block with a variable inside it, as there is no template document yet. $xmlTxt = 'This ${repeats} a few times'; $xmlStr = '${MYBLOCK}' . $xmlTxt . '${/MYBLOCK}'; $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); @@ -411,14 +411,14 @@ public function testCloneIndexedBlock() $this->assertEquals( $xmlTxt, $templateProcessor->getBlock('MYBLOCK'), - "Block should be cut at the right place (using findOpenTagLeft/findCloseTagRight)" + 'Block should be cut at the right place (using findOpenTagLeft/findCloseTagRight)' ); - # detects variables + // detects variables $this->assertEquals( array('MYBLOCK', 'repeats', '/MYBLOCK'), $templateProcessor->getVariables(), - "Injected document should contain the right initial variables, in the right order" + 'Injected document should contain the right initial variables, in the right order' ); $templateProcessor->cloneBlock('MYBLOCK', 4); @@ -426,23 +426,23 @@ public function testCloneIndexedBlock() $this->assertEquals( array('repeats#1', 'repeats#2', 'repeats#3', 'repeats#4'), $templateProcessor->getVariables(), - "Injected document should contain the right cloned variables, in the right order" + 'Injected document should contain the right cloned variables, in the right order' ); $variablesArray = array( 'repeats#1' => 'ONE', 'repeats#2' => 'TWO', 'repeats#3' => 'THREE', - 'repeats#4' => 'FOUR' + 'repeats#4' => 'FOUR', ); $templateProcessor->setValue(array_keys($variablesArray), array_values($variablesArray)); $this->assertEquals( array(), $templateProcessor->getVariables(), - "Variables have been replaced and should not be present anymore" + 'Variables have been replaced and should not be present anymore' ); - # now we test the order of replacement: ONE,TWO,THREE then FOUR + // now we test the order of replacement: ONE,TWO,THREE then FOUR $tmpStr = ""; foreach ($variablesArray as $variable) { $tmpStr .= str_replace('${repeats}', $variable, $xmlTxt); @@ -450,31 +450,34 @@ public function testCloneIndexedBlock() $this->assertEquals( 1, substr_count($this->peek($templateProcessor, 'tempDocumentMainPart'), $tmpStr), - "order of replacement should be: ONE,TWO,THREE then FOUR" + 'order of replacement should be: ONE,TWO,THREE then FOUR' ); - # Now we try again, but without variable incrementals (old behavior) + // Now we try again, but without variable incrementals (old behavior) $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); $templateProcessor->cloneBlock('MYBLOCK', 4, false); - # detects new variable + // detects new variable $this->assertEquals( array('repeats'), $templateProcessor->getVariables(), 'new variable $repeats should be present' ); - # we cloned block CLONEME 4 times, so let's count + // we cloned block CLONEME 4 times, so let's count $this->assertEquals( 4, substr_count($this->peek($templateProcessor, 'tempDocumentMainPart'), $xmlTxt), 'detects new variable $repeats to be present 4 times' ); - # we cloned block CLONEME 4 times, so let's see that there is no space between these blocks + // we cloned block CLONEME 4 times, so let's see that there is no space between these blocks $this->assertEquals( 1, - substr_count($this->peek($templateProcessor, 'tempDocumentMainPart'), $xmlTxt.$xmlTxt.$xmlTxt.$xmlTxt), + substr_count( + $this->peek($templateProcessor, 'tempDocumentMainPart'), + $xmlTxt . $xmlTxt . $xmlTxt . $xmlTxt + ), "The four times cloned block should be the same as four times the block" ); } @@ -498,32 +501,32 @@ public function testClosedBlock() $this->assertEquals( $xmlTxt, $templateProcessor->getBlock('BLOCKCLOSE/'), - "Block should be cut at the right place (using findOpenTagLeft/findCloseTagRight)" + 'Block should be cut at the right place (using findOpenTagLeft/findCloseTagRight)' ); - # detects variables + // detects variables $this->assertEquals( array('BEFORE', 'BLOCKCLOSE/', 'AFTER'), $templateProcessor->getVariables(), - "Injected document should contain the right initial variables, in the right order" + 'Injected document should contain the right initial variables, in the right order' ); - # inserting itself should result in no change + // inserting itself should result in no change $oldvalue = $this->peek($templateProcessor, 'tempDocumentMainPart'); $block = $templateProcessor->getBlock('BLOCKCLOSE/'); $templateProcessor->replaceBlock('BLOCKCLOSE/', $block); $this->assertEquals( $oldvalue, $this->peek($templateProcessor, 'tempDocumentMainPart'), - "ReplaceBlock should replace at the right position" + 'ReplaceBlock should replace at the right position' ); $templateProcessor->cloneBlock('BLOCKCLOSE/', 4); - # detects new variables + // detects new variables $this->assertEquals( array('BEFORE', 'BLOCKCLOSE#1/', 'BLOCKCLOSE#2/', 'BLOCKCLOSE#3/', 'BLOCKCLOSE#4/', 'AFTER'), $templateProcessor->getVariables(), - "Injected document should contain the right cloned variables, in the right order" + 'Injected document should contain the right cloned variables, in the right order' ); $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); @@ -575,22 +578,22 @@ public function testSetValueMultiline() $docFound = file_exists($docName); $this->assertTrue($docFound); if ($docFound) { - # We open that new document (and use the OpenTemplateProcessor to access private variables) + // We open that new document (and use the OpenTemplateProcessor to access private variables) $templateProcessorNewFile = new TemplateProcessor($docName); - # We test that all Block variables have been replaced (thus, getVariables() is empty) + // We test that all Block variables have been replaced (thus, getVariables() is empty) $this->assertEquals( 0, substr_count($this->peek($templateProcessorNewFile, 'tempDocumentMainPart'), $helloworld), - "there should be a multiline" + 'there should be a multiline' ); - # The block it should be turned into: + // The block it should be turned into: $xmlblock = 'helloworld'; $this->assertEquals( 1, substr_count($this->peek($templateProcessorNewFile, 'tempDocumentMainPart'), $xmlblock), - "multiline should be present 1 in the document" + 'multiline should be present 1 in the document' ); - unlink($docName); # delete generated file + unlink($docName); // delete generated file } } @@ -604,32 +607,32 @@ public function testSetValueMultiline() public function testInlineBlock() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); - $xmlStr = ''. - 'This'. - '${inline}'. - ' has been'. - '${/inline}'. + $xmlStr = '' . + 'This' . + '${inline}' . + ' has been' . + '${/inline}' . ' block'; $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); $this->assertEquals( $templateProcessor->getBlock('inline'), - ''. + '' . ' has been', - "When inside the same , cut inside the paragraph" + 'When inside the same , cut inside the paragraph' ); $templateProcessor->replaceBlock('inline', 'shows'); $this->assertEquals( $this->peek($templateProcessor, 'tempDocumentMainPart'), - ''. - ''. - 'This'. - 'shows'. + '' . + '' . + 'This' . + 'shows' . ' block', - "InlineBlock replace is malformed" + 'InlineBlock replace is malformed' ); } @@ -642,13 +645,13 @@ public function testInlineBlock() public function testSetBlock() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); - $xmlStr = ''. - ''. - ''. - 'BEFORE'. - '${inline/}'. - 'AFTER'. - ''. + $xmlStr = '' . + '' . + '' . + 'BEFORE' . + '${inline/}' . + 'AFTER' . + '' . ''; $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); @@ -657,32 +660,32 @@ public function testSetBlock() // XMLReader::xml($templateProcessor->tempDocumentMainPart)->isValid() $this->assertEquals( - ''. - ''. - ''. - 'BEFORE'. - 'one'. - 'AFTER'. - ''. - ''. - 'BEFORE'. - 'two'. - 'AFTER'. - ''. + '' . + '' . + '' . + 'BEFORE' . + 'one' . + 'AFTER' . + '' . + '' . + 'BEFORE' . + 'two' . + 'AFTER' . + '' . '', $this->peek($templateProcessor, 'tempDocumentMainPart') ); $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); - $templateProcessor->setBlock('inline/', "simplé`"); + $templateProcessor->setBlock('inline/', 'simplé`'); $this->assertEquals( - ''. - ''. - ''. - 'BEFORE'. - 'simplé`'. - 'AFTER'. - ''. + '' . + '' . + '' . + 'BEFORE' . + 'simplé`' . + 'AFTER' . + '' . '', $this->peek($templateProcessor, 'tempDocumentMainPart') ); @@ -699,21 +702,21 @@ public function testSetBlock() public function testReplaceBlock() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); - $xmlStr = ''. - '${/nostart}'. - ''. - '${malformedblock}'. - '${notABlock}'. - ''. + $xmlStr = '' . + '${/nostart}' . + '' . + '${malformedblock}' . + '${notABlock}' . + '' . '${/malformedblock}'; $this->poke($templateProcessor, 'tempDocumentMainPart', $xmlStr); $this->assertFalse( - $templateProcessor->replaceBlock('notABlock', "") + $templateProcessor->replaceBlock('notABlock', '') ); $this->assertFalse( - $templateProcessor->cloneBlock('notABlock', "", 10) + $templateProcessor->cloneBlock('notABlock', '', 10) ); $this->assertNull( $templateProcessor->cloneBlock('malformedblock', 11) @@ -721,10 +724,8 @@ public function testReplaceBlock() $this->assertNull( $templateProcessor->cloneBlock('nostart', 11) ); - $this->assertEquals( - null, - $got = $templateProcessor->replaceBlock('malformedblock', "", true), - $got + $this->assertNull( + $templateProcessor->replaceBlock('malformedblock', '', true) ); } @@ -740,45 +741,37 @@ public function testFailGraciously() $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); $around = TemplateProcessor::SEARCH_AROUND; - $this->assertEquals( - null, + $this->assertFalse( $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', $around, 'MainPart', false) ); - $this->assertEquals( - null, + $this->assertFalse( $templateProcessor->cloneSegment('I-DO-NOT-EXIST', 'w:p', $around, 1, 'MainPart', true, false) ); - $this->assertEquals( - false, + $this->assertNull( $templateProcessor->cloneSegment('tableHeader', 'DESPACITO', $around, 1, 'MainPart', true, false) ); - $this->assertEquals( - null, + $this->assertFalse( $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', $around, 'IOU', 'Footer:1', false) ); - $this->assertEquals( - false, + $this->assertNull( $templateProcessor->replaceSegment('tableHeader', 'we:be', $around, 'BodyMoving', 'MainPart', false) ); - $this->assertEquals( - false, + $this->assertFalse( $templateProcessor->deleteSegment('tableHeader', '>sabotage<', 'MainPart', $around, 1, true, true, false) ); $left = TemplateProcessor::SEARCH_LEFT; $right = TemplateProcessor::SEARCH_RIGHT; - $this->assertEquals( - false, + $this->assertFalse( $templateProcessor->deleteSegment('tableHeader', '>sabotage<', 'MainPart', $right, 1, true, true, false) ); - $this->assertEquals( - false, + $this->assertFalse( $templateProcessor->deleteSegment('tableHeader', '>sabotage<', 'MainPart', $left, 1, true, true, false) ); } @@ -804,7 +797,7 @@ public function testCloneSegment() $zipFile->open($testDocument); $originalFooterXml = $zipFile->getFromName('word/footer1.xml'); if (false === $zipFile->close()) { - throw new \Exception("Could not close zip file"); + throw new \Exception('Could not close zip file'); } $around = TemplateProcessor::SEARCH_AROUND; @@ -823,7 +816,7 @@ public function testCloneSegment() $zipFile->open($docName); $updatedFooterXml = $zipFile->getFromName('word/footer1.xml'); if (false === $zipFile->close()) { - throw new \Exception("Could not close zip file"); + throw new \Exception('Could not close zip file'); } $this->assertNotEquals( @@ -851,8 +844,7 @@ public function testCloneSegment() final public function testThrowFailGraciously() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); - $this->assertEquals( - null, + $this->assertNull( $templateProcessor->cloneSegment( 'I-DO-NOT-EXIST', 'w:p', @@ -876,8 +868,7 @@ final public function testAnotherThrowFailGraciously() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); $around = TemplateProcessor::SEARCH_AROUND; - $this->assertEquals( - null, + $this->assertNull( $templateProcessor->replaceSegment('I-DO-NOT-EXIST', 'w:p', $around, 'IOU', 'MainPart', true) ); } @@ -891,23 +882,17 @@ public function testSaveAs() { $testDocument = __DIR__ . '/_files/templates/header-footer.docx'; $templateProcessor = new TemplateProcessor($testDocument); - $tempFileName = "tempfilename.docx"; - $this->assertEquals( - null, + $tempFileName = 'tempfilename.docx'; + $this->assertNull( $templateProcessor->saveAs($tempFileName) ); - $this->assertTrue( - file_exists($tempFileName) - ); + $this->assertFileExists($tempFileName); $templateProcessor = new TemplateProcessor($tempFileName); - $this->assertEquals( - null, + $this->assertNull( $templateProcessor->saveAs($tempFileName), 'Second save should succeed, but does not' ); - $this->assertTrue( - file_exists($tempFileName) - ); + $this->assertFileExists($tempFileName); unlink($tempFileName); } @@ -926,9 +911,7 @@ public function testSave() 'Do not clobber the original file' ); - $this->assertTrue( - file_exists($tempFileName) - ); + $this->assertFileExists($tempFileName); unlink($tempFileName); } @@ -941,8 +924,7 @@ public function testSave() final public function testReplaceBlockThrow() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); - $this->assertEquals( - null, + $this->assertNull( $templateProcessor->replaceBlock('I-DO-NOT-EXIST', 'IOU', true) ); } @@ -956,8 +938,7 @@ final public function testReplaceBlockThrow() final public function testgetSegmentThrow() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); - $this->assertEquals( - null, + $this->assertNull( $templateProcessor->getSegment('I-DO-NOT-EXIST', 'w:p', TemplateProcessor::SEARCH_AROUND, 'MainPart', true) ); } @@ -971,8 +952,7 @@ final public function testgetSegmentThrow() final public function testCloneBlockThrow() { $templateProcessor = new TemplateProcessor(__DIR__ . '/_files/templates/clone-merge.docx'); - $this->assertEquals( - null, + $this->assertNull( $templateProcessor->cloneBlock('I-DO-NOT-EXIST', 'replace', 1, true, true) ); } @@ -992,7 +972,6 @@ public function testfindTagRightAndLeft() $stub = $this->getMockForAbstractClass('\PhpOffice\PhpWord\TemplateProcessor', array($testDocument)); $str = '...abcd${dream}efg...'; - $this->assertEquals(true, self::callProtectedMethod($stub, 'findCloseTagRight', array(&$str, '', 0))); $this->assertEquals(26, self::callProtectedMethod($stub, 'findCloseTagRight', array(&$str, '', 0))); $this->assertEquals(7, self::callProtectedMethod($stub, 'findOpenTagRight', array(&$str, '', 0))); $this->assertEquals(07, self::callProtectedMethod($stub, 'findOpenTagLeft', array(&$str, '', 20))); @@ -1022,7 +1001,7 @@ public function testfindTagRightAndLeft() // now throw an exception - $snipStart = self::callProtectedMethod($stub, 'findOpenTagRight', array(&$str, '', $snipStart+1, true)); + $snipStart = self::callProtectedMethod($stub, 'findOpenTagRight', array(&$str, '', $snipStart + 1, true)); } /** * testing grabbing segments left and right @@ -1035,11 +1014,11 @@ public function testfindTagRightAndLeft() public function testGetSegment() { $template = new TemplateProcessor(__DIR__ . '/_files/templates/blank.docx'); - $xmlStr = ''. - 'before'. - ''. - '${middle}'. - ''. + $xmlStr = '' . + 'before' . + '' . + '${middle}' . + '' . 'after'; $this->poke($template, 'tempDocumentMainPart', $xmlStr); From 602fecf58fe1dc92548801b77a2088a7dbd70dc3 Mon Sep 17 00:00:00 2001 From: Nilton Date: Tue, 12 Dec 2017 11:47:49 +0100 Subject: [PATCH 73/74] a return must be preceded by an empty line. Quotes are preferred to be single-quoted. --- src/PhpWord/TemplateProcessor.php | 13 +++++++++++-- tests/PhpWord/TemplateProcessorTest.php | 12 +++++++----- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index d64fa3c44f..d5ad904977 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -150,9 +150,11 @@ protected function transformXml($xml, $xsltProcessor) foreach ($xml as &$item) { $item = $this->transformSingleXml($item, $xsltProcessor); } + return (array) $xml; } $xml = $this->transformSingleXml($xml, $xsltProcessor); + return (string) $xml; } @@ -311,6 +313,7 @@ private function failGraciously($exceptionText, $throwException, $elseReturn) if ($throwException) { throw new Exception($exceptionText); } + return $elseReturn; } @@ -353,6 +356,7 @@ protected static function cloneSlice(&$text, $numberOfClones = 1, $incrementVari $result .= $text; } } + return $result; } @@ -404,6 +408,7 @@ function (&$xmlSegment, &$segmentStart, &$segmentEnd, &$part) use (&$replace) { } $xmlSegment = substr($part, $segmentStart, ($segmentEnd - $segmentStart)); } + return $replace; }, $incrementVariables, @@ -555,6 +560,7 @@ private function processBlock( $this->getSlice($this->tempDocumentMainPart, 0, $startBlockStart) . $replace . $this->getSlice($this->tempDocumentMainPart, $endBlockEnd); + return true; } @@ -645,7 +651,7 @@ public function processSegment( $throwException = false ) { $docPart = preg_split('/:/', $docPart); - if (count($docPart)>1) { + if (count($docPart) > 1) { $part = &$this->{'tempDocument' . $docPart[0]}[$docPart[1]]; } else { $part = &$this->{'tempDocument' . $docPart[0]}; @@ -694,6 +700,7 @@ public function processSegment( $this->getSlice($part, 0, $segmentStart) . $replace . $this->getSlice($part, $segmentEnd); + return true; } @@ -1000,7 +1007,7 @@ protected function findOpenTagLeft(&$searchString, $tag, $offset = 0, $throwExce * @param string $searchString The string we are searching in (the mainbody or an array element of Footers/Headers) * @param string $tag Fully qualified tag, for example: '' (with brackets!) * @param int $offset Do not look from the beginning, but starting at $offset - * @param boolean $throwException + * @param bool $throwException * * @throws \PhpOffice\PhpWord\Exception\Exception * @return int Zero if not found (due to the nature of xml, your document never starts at 0) @@ -1049,6 +1056,7 @@ protected function findCloseTagLeft(&$searchString, $tag, $offset = 0) if ($pos !== false) { return $pos + strlen($tag); } + return 0; } @@ -1068,6 +1076,7 @@ protected function findCloseTagRight(&$searchString, $tag, $offset = 0) if ($pos !== false) { return $pos + strlen($tag); } + return 0; } diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index 308979eddb..af8cf07c46 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -34,6 +34,7 @@ public function poke(&$object, $property, $newValue = null) if ($newValue !== null) { $refProperty->setValue($object, $newValue); } + return $refProperty; } @@ -58,6 +59,7 @@ public static function callProtectedMethod($object, $method, array $args = array $class = new \ReflectionClass(get_class($object)); $method = $class->getMethod($method); $method->setAccessible(true); + return $method->invokeArgs($object, $args); } @@ -377,13 +379,13 @@ public function testCloneDeleteBlock() $this->assertEquals( array(), $templateProcessorNewFile->getVariables(), - "All block variables should have been replaced" + 'All block variables should have been replaced' ); // we cloned block CLONEME $cloneTimes times, so let's count to $cloneTimes $this->assertEquals( $cloneTimes, substr_count($this->peek($templateProcessorNewFile, 'tempDocumentMainPart'), $xmlblock), - "Block should be present $cloneTimes in the document" + 'Block should be present $cloneTimes in the document' ); unlink($docName); // delete generated file } @@ -422,7 +424,7 @@ public function testCloneIndexedBlock() ); $templateProcessor->cloneBlock('MYBLOCK', 4); - # detects new variables + // detects new variables $this->assertEquals( array('repeats#1', 'repeats#2', 'repeats#3', 'repeats#4'), $templateProcessor->getVariables(), @@ -443,7 +445,7 @@ public function testCloneIndexedBlock() ); // now we test the order of replacement: ONE,TWO,THREE then FOUR - $tmpStr = ""; + $tmpStr = ''; foreach ($variablesArray as $variable) { $tmpStr .= str_replace('${repeats}', $variable, $xmlTxt); } @@ -478,7 +480,7 @@ public function testCloneIndexedBlock() $this->peek($templateProcessor, 'tempDocumentMainPart'), $xmlTxt . $xmlTxt . $xmlTxt . $xmlTxt ), - "The four times cloned block should be the same as four times the block" + 'The four times cloned block should be the same as four times the block' ); } From a8290f7ae5a96b1634947d1fbe141b9a088decdc Mon Sep 17 00:00:00 2001 From: Nilton Date: Thu, 14 Dec 2017 12:49:05 +0100 Subject: [PATCH 74/74] Parsed through php-cs-fixer --- src/PhpWord/TemplateProcessor.php | 3 +-- tests/PhpWord/TemplateProcessorTest.php | 4 +--- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/PhpWord/TemplateProcessor.php b/src/PhpWord/TemplateProcessor.php index d5ad904977..97057f405c 100644 --- a/src/PhpWord/TemplateProcessor.php +++ b/src/PhpWord/TemplateProcessor.php @@ -831,7 +831,6 @@ public function save() return $this->tempDocumentFilename; } - /** * Saves the result document to the user defined file. * @@ -883,6 +882,7 @@ function ($match) { $paragraph ); } + return implode('', $paragraphs); } @@ -1012,7 +1012,6 @@ protected function findOpenTagLeft(&$searchString, $tag, $offset = 0, $throwExce * @throws \PhpOffice\PhpWord\Exception\Exception * @return int Zero if not found (due to the nature of xml, your document never starts at 0) */ - protected function findOpenTagRight(&$searchString, $tag, $offset = 0, $throwException = false) { $tagStart = strpos( diff --git a/tests/PhpWord/TemplateProcessorTest.php b/tests/PhpWord/TemplateProcessorTest.php index af8cf07c46..01804d877b 100644 --- a/tests/PhpWord/TemplateProcessorTest.php +++ b/tests/PhpWord/TemplateProcessorTest.php @@ -540,7 +540,6 @@ public function testClosedBlock() ); } - /** * @covers ::setValue * @test @@ -693,7 +692,6 @@ public function testSetBlock() ); } - /** * @covers ::replaceBlock * @covers ::cloneBlock @@ -1001,10 +999,10 @@ public function testfindTagRightAndLeft() self::callProtectedMethod($stub, 'getSlice', array(&$str, $snipStart, $snipEnd)) ); - // now throw an exception $snipStart = self::callProtectedMethod($stub, 'findOpenTagRight', array(&$str, '', $snipStart + 1, true)); } + /** * testing grabbing segments left and right *