From c1b4b2e4a572777cb450bf0c6a2bc12face7adc5 Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Mon, 10 Mar 2014 22:41:41 +0700 Subject: [PATCH 01/17] Skeleton copied from PHPExcel :) --- Classes/PHPWord/IOFactory.php | 27 +- Classes/PHPWord/Reader/Abstract.php | 106 ++ Classes/PHPWord/Reader/IReader.php | 48 + Classes/PHPWord/Reader/Word2007.php | 2065 +++++++++++++++++++++++++++ 4 files changed, 2245 insertions(+), 1 deletion(-) create mode 100644 Classes/PHPWord/Reader/Abstract.php create mode 100644 Classes/PHPWord/Reader/IReader.php create mode 100644 Classes/PHPWord/Reader/Word2007.php diff --git a/Classes/PHPWord/IOFactory.php b/Classes/PHPWord/IOFactory.php index a9eae570..5b955fac 100755 --- a/Classes/PHPWord/IOFactory.php +++ b/Classes/PHPWord/IOFactory.php @@ -37,7 +37,8 @@ class PHPWord_IOFactory * @var array */ private static $_searchLocations = array( - array('type' => 'IWriter', 'path' => 'PHPWord/Writer/{0}.php', 'class' => 'PHPWord_Writer_{0}') + array('type' => 'IWriter', 'path' => 'PHPWord/Writer/{0}.php', 'class' => 'PHPWord_Writer_{0}'), + array( 'type' => 'IReader', 'path' => 'PHPWord/Reader/{0}.php', 'class' => 'PHPWord_Reader_{0}' ), ); /** @@ -118,4 +119,28 @@ class PHPWord_IOFactory throw new Exception("No $searchType found for type $writerType"); } + + /** + * Create PHPWord_Reader_IReader + * + * @param string $readerType Example: Word2007 + * @return PHPWord_Reader_IReader + */ + public static function createReader($readerType = '') { + $searchType = 'IReader'; + + foreach (self::$_searchLocations as $searchLocation) { + if ($searchLocation['type'] == $searchType) { + $className = str_replace('{0}', $readerType, $searchLocation['class']); + + $instance = new $className(); + if ($instance !== NULL) { + return $instance; + } + } + } + + throw new PHPExcel_Reader_Exception("No $searchType found for type $readerType"); + } + } diff --git a/Classes/PHPWord/Reader/Abstract.php b/Classes/PHPWord/Reader/Abstract.php new file mode 100644 index 00000000..55481a32 --- /dev/null +++ b/Classes/PHPWord/Reader/Abstract.php @@ -0,0 +1,106 @@ +_readDataOnly; + } + + /** + * Set read data only + * + * @param boolean $pValue + * @return PHPWord_Reader_IReader + */ + public function setReadDataOnly($pValue = FALSE) { + $this->_readDataOnly = $pValue; + return $this; + } + + /** + * Open file for reading + * + * @param string $pFilename + * @throws PHPWord_Reader_Exception + * @return resource + */ + protected function _openFile($pFilename) + { + // Check if file exists + if (!file_exists($pFilename) || !is_readable($pFilename)) { + throw new PHPWord_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + // Open file + $this->_fileHandle = fopen($pFilename, 'r'); + if ($this->_fileHandle === FALSE) { + throw new PHPWord_Reader_Exception("Could not open file " . $pFilename . " for reading."); + } + } + + /** + * Can the current PHPWord_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPWord_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + try { + $this->_openFile($pFilename); + } catch (Exception $e) { + return FALSE; + } + + $readable = $this->_isValidFormat(); + fclose ($this->_fileHandle); + return $readable; + } + +} diff --git a/Classes/PHPWord/Reader/IReader.php b/Classes/PHPWord/Reader/IReader.php new file mode 100644 index 00000000..e2ecc4b3 --- /dev/null +++ b/Classes/PHPWord/Reader/IReader.php @@ -0,0 +1,48 @@ +_readFilter = new PHPWord_Reader_DefaultReadFilter(); + $this->_referenceHelper = PHPWord_ReferenceHelper::getInstance(); + } + + + /** + * Can the current PHPWord_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPWord_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPWord_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $zipClass = PHPWord_Settings::getZipClass(); + + // Check if zip class exists +// if (!class_exists($zipClass, FALSE)) { +// throw new PHPWord_Reader_Exception($zipClass . " library is not enabled"); +// } + + $xl = false; + // Load file + $zip = new $zipClass; + if ($zip->open($pFilename) === true) { + // check if it is an OOXML archive + $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); + if ($rels !== false) { + foreach ($rels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": + if (basename($rel["Target"]) == 'workbook.xml') { + $xl = true; + } + break; + + } + } + } + $zip->close(); + } + + return $xl; + } + + + /** + * Reads names of the worksheets from a file, without parsing the whole file to a PHPWord object + * + * @param string $pFilename + * @throws PHPWord_Reader_Exception + */ + public function listWorksheetNames($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPWord_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetNames = array(); + + $zipClass = PHPWord_Settings::getZipClass(); + + $zip = new $zipClass; + $zip->open($pFilename); + + // The files we're looking at here are small enough that simpleXML is more efficient than XMLReader + $rels = simplexml_load_string( + $this->_getFromZipArchive($zip, "_rels/.rels") + ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($rels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": + $xmlWorkbook = simplexml_load_string( + $this->_getFromZipArchive($zip, "{$rel['Target']}") + ); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + + if ($xmlWorkbook->sheets) { + foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + // Check if sheet should be skipped + $worksheetNames[] = (string) $eleSheet["name"]; + } + } + } + } + + $zip->close(); + + return $worksheetNames; + } + + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPWord_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPWord_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetInfo = array(); + + $zipClass = PHPWord_Settings::getZipClass(); + + $zip = new $zipClass; + $zip->open($pFilename); + + $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($rels->Relationship as $rel) { + if ($rel["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument") { + $dir = dirname($rel["Target"]); + $relsWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); + + $worksheets = array(); + foreach ($relsWorkbook->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet") { + $worksheets[(string) $ele["Id"]] = $ele["Target"]; + } + } + + $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + if ($xmlWorkbook->sheets) { + $dir = dirname($rel["Target"]); + foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + $tmpInfo = array( + 'worksheetName' => (string) $eleSheet["name"], + 'lastColumnLetter' => 'A', + 'lastColumnIndex' => 0, + 'totalRows' => 0, + 'totalColumns' => 0, + ); + + $fileWorksheet = $worksheets[(string) self::array_item($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + + $xml = new XMLReader(); + $res = $xml->open('zip://'.PHPWord_Shared_File::realpath($pFilename).'#'."$dir/$fileWorksheet"); + $xml->setParserProperty(2,true); + + $currCells = 0; + while ($xml->read()) { + if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) { + $row = $xml->getAttribute('r'); + $tmpInfo['totalRows'] = $row; + $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'],$currCells); + $currCells = 0; + } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) { + $currCells++; + } + } + $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'],$currCells); + $xml->close(); + + $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; + $tmpInfo['lastColumnLetter'] = PHPWord_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); + + $worksheetInfo[] = $tmpInfo; + } + } + } + } + + $zip->close(); + + return $worksheetInfo; + } + + + private static function _castToBool($c) { +// echo 'Initial Cast to Boolean
'; + $value = isset($c->v) ? (string) $c->v : NULL; + if ($value == '0') { + return FALSE; + } elseif ($value == '1') { + return TRUE; + } else { + return (bool)$c->v; + } + return $value; + } // function _castToBool() + + + private static function _castToError($c) { +// echo 'Initial Cast to Error
'; + return isset($c->v) ? (string) $c->v : NULL; + } // function _castToError() + + + private static function _castToString($c) { +// echo 'Initial Cast to String
'; + return isset($c->v) ? (string) $c->v : NULL; + } // function _castToString() + + + private function _castToFormula($c,$r,&$cellDataType,&$value,&$calculatedValue,&$sharedFormulas,$castBaseType) { +// echo 'Formula',PHP_EOL; +// echo '$c->f is '.$c->f.PHP_EOL; + $cellDataType = 'f'; + $value = "={$c->f}"; + $calculatedValue = self::$castBaseType($c); + + // Shared formula? + if (isset($c->f['t']) && strtolower((string)$c->f['t']) == 'shared') { +// echo 'SHARED FORMULA'.PHP_EOL; + $instance = (string)$c->f['si']; + +// echo 'Instance ID = '.$instance.PHP_EOL; +// +// echo 'Shared Formula Array:'.PHP_EOL; +// print_r($sharedFormulas); + if (!isset($sharedFormulas[(string)$c->f['si']])) { +// echo 'SETTING NEW SHARED FORMULA'.PHP_EOL; +// echo 'Master is '.$r.PHP_EOL; +// echo 'Formula is '.$value.PHP_EOL; + $sharedFormulas[$instance] = array( 'master' => $r, + 'formula' => $value + ); +// echo 'New Shared Formula Array:'.PHP_EOL; +// print_r($sharedFormulas); + } else { +// echo 'GETTING SHARED FORMULA'.PHP_EOL; +// echo 'Master is '.$sharedFormulas[$instance]['master'].PHP_EOL; +// echo 'Formula is '.$sharedFormulas[$instance]['formula'].PHP_EOL; + $master = PHPWord_Cell::coordinateFromString($sharedFormulas[$instance]['master']); + $current = PHPWord_Cell::coordinateFromString($r); + + $difference = array(0, 0); + $difference[0] = PHPWord_Cell::columnIndexFromString($current[0]) - PHPWord_Cell::columnIndexFromString($master[0]); + $difference[1] = $current[1] - $master[1]; + + $value = $this->_referenceHelper->updateFormulaReferences( $sharedFormulas[$instance]['formula'], + 'A1', + $difference[0], + $difference[1] + ); +// echo 'Adjusted Formula is '.$value.PHP_EOL; + } + } + } + + + public function _getFromZipArchive($archive, $fileName = '') + { + // Root-relative paths + if (strpos($fileName, '//') !== false) + { + $fileName = substr($fileName, strpos($fileName, '//') + 1); + } + $fileName = PHPWord_Shared_File::realpath($fileName); + + // Apache POI fixes + $contents = $archive->getFromName($fileName); + if ($contents === false) + { + $contents = $archive->getFromName(substr($fileName, 1)); + } + + return $contents; + } + + + /** + * Loads PHPWord from file + * + * @param string $pFilename + * @throws PHPWord_Reader_Exception + */ + public function load($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPWord_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + // Initialisations + $excel = new PHPWord; + $excel->removeSheetByIndex(0); + if (!$this->_readDataOnly) { + $excel->removeCellStyleXfByIndex(0); // remove the default style + $excel->removeCellXfByIndex(0); // remove the default style + } + + $zipClass = PHPWord_Settings::getZipClass(); + + $zip = new $zipClass; + $zip->open($pFilename); + + // Read the theme first, because we need the colour scheme when reading the styles + $wbRels = simplexml_load_string($this->_getFromZipArchive($zip, "xl/_rels/workbook.xml.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($wbRels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme": + $themeOrderArray = array('lt1','dk1','lt2','dk2'); + $themeOrderAdditional = count($themeOrderArray); + + $xmlTheme = simplexml_load_string($this->_getFromZipArchive($zip, "xl/{$rel['Target']}")); + if (is_object($xmlTheme)) { + $xmlThemeName = $xmlTheme->attributes(); + $xmlTheme = $xmlTheme->children("http://schemas.openxmlformats.org/drawingml/2006/main"); + $themeName = (string)$xmlThemeName['name']; + + $colourScheme = $xmlTheme->themeElements->clrScheme->attributes(); + $colourSchemeName = (string)$colourScheme['name']; + $colourScheme = $xmlTheme->themeElements->clrScheme->children("http://schemas.openxmlformats.org/drawingml/2006/main"); + + $themeColours = array(); + foreach ($colourScheme as $k => $xmlColour) { + $themePos = array_search($k,$themeOrderArray); + if ($themePos === false) { + $themePos = $themeOrderAdditional++; + } + if (isset($xmlColour->sysClr)) { + $xmlColourData = $xmlColour->sysClr->attributes(); + $themeColours[$themePos] = $xmlColourData['lastClr']; + } elseif (isset($xmlColour->srgbClr)) { + $xmlColourData = $xmlColour->srgbClr->attributes(); + $themeColours[$themePos] = $xmlColourData['val']; + } + } + self::$_theme = new PHPWord_Reader_Word2007_Theme($themeName,$colourSchemeName,$themeColours); + } + break; + } + } + + $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($rels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties": + $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); + if (is_object($xmlCore)) { + $xmlCore->registerXPathNamespace("dc", "http://purl.org/dc/elements/1.1/"); + $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/"); + $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); + $docProps = $excel->getProperties(); + $docProps->setCreator((string) self::array_item($xmlCore->xpath("dc:creator"))); + $docProps->setLastModifiedBy((string) self::array_item($xmlCore->xpath("cp:lastModifiedBy"))); + $docProps->setCreated(strtotime(self::array_item($xmlCore->xpath("dcterms:created")))); //! respect xsi:type + $docProps->setModified(strtotime(self::array_item($xmlCore->xpath("dcterms:modified")))); //! respect xsi:type + $docProps->setTitle((string) self::array_item($xmlCore->xpath("dc:title"))); + $docProps->setDescription((string) self::array_item($xmlCore->xpath("dc:description"))); + $docProps->setSubject((string) self::array_item($xmlCore->xpath("dc:subject"))); + $docProps->setKeywords((string) self::array_item($xmlCore->xpath("cp:keywords"))); + $docProps->setCategory((string) self::array_item($xmlCore->xpath("cp:category"))); + } + break; + + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties": + $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); + if (is_object($xmlCore)) { + $docProps = $excel->getProperties(); + if (isset($xmlCore->Company)) + $docProps->setCompany((string) $xmlCore->Company); + if (isset($xmlCore->Manager)) + $docProps->setManager((string) $xmlCore->Manager); + } + break; + + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties": + $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); + if (is_object($xmlCore)) { + $docProps = $excel->getProperties(); + foreach ($xmlCore as $xmlProperty) { + $cellDataOfficeAttributes = $xmlProperty->attributes(); + if (isset($cellDataOfficeAttributes['name'])) { + $propertyName = (string) $cellDataOfficeAttributes['name']; + $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + $attributeType = $cellDataOfficeChildren->getName(); + $attributeValue = (string) $cellDataOfficeChildren->{$attributeType}; + $attributeValue = PHPWord_DocumentProperties::convertProperty($attributeValue,$attributeType); + $attributeType = PHPWord_DocumentProperties::convertPropertyType($attributeType); + $docProps->setCustomProperty($propertyName,$attributeValue,$attributeType); + } + } + } + break; + //Ribbon + case "http://schemas.microsoft.com/office/2006/relationships/ui/extensibility": + $customUI = $rel['Target']; + if(!is_null($customUI)){ + $this->_readRibbon($excel, $customUI, $zip); + } + break; + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": + $dir = dirname($rel["Target"]); + $relsWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); + + $sharedStrings = array(); + $xpath = self::array_item($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']")); + $xmlStrings = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$xpath[Target]")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + if (isset($xmlStrings) && isset($xmlStrings->si)) { + foreach ($xmlStrings->si as $val) { + if (isset($val->t)) { + $sharedStrings[] = PHPWord_Shared_String::ControlCharacterOOXML2PHP( (string) $val->t ); + } elseif (isset($val->r)) { + $sharedStrings[] = $this->_parseRichText($val); + } + } + } + + $worksheets = array(); + $macros = $customUI = NULL; + foreach ($relsWorkbook->Relationship as $ele) { + switch($ele['Type']){ + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet": + $worksheets[(string) $ele["Id"]] = $ele["Target"]; + break; + // a vbaProject ? (: some macros) + case "http://schemas.microsoft.com/office/2006/relationships/vbaProject": + $macros = $ele["Target"]; + break; + } + } + + if(!is_null($macros)){ + $macrosCode = $this->_getFromZipArchive($zip, 'xl/vbaProject.bin');//vbaProject.bin always in 'xl' dir and always named vbaProject.bin + if($macrosCode !== false){ + $excel->setMacrosCode($macrosCode); + $excel->setHasMacros(true); + //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir + $Certificate = $this->_getFromZipArchive($zip, 'xl/vbaProjectSignature.bin'); + if($Certificate !== false) + $excel->setMacrosCertificate($Certificate); + } + } + $styles = array(); + $cellStyles = array(); + $xpath = self::array_item($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); + $xmlStyles = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$xpath[Target]")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + $numFmts = null; + if ($xmlStyles && $xmlStyles->numFmts[0]) { + $numFmts = $xmlStyles->numFmts[0]; + } + if (isset($numFmts) && ($numFmts !== NULL)) { + $numFmts->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + } + if (!$this->_readDataOnly && $xmlStyles) { + foreach ($xmlStyles->cellXfs->xf as $xf) { + $numFmt = PHPWord_Style_NumberFormat::FORMAT_GENERAL; + + if ($xf["numFmtId"]) { + if (isset($numFmts)) { + $tmpNumFmt = self::array_item($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); + + if (isset($tmpNumFmt["formatCode"])) { + $numFmt = (string) $tmpNumFmt["formatCode"]; + } + } + + if ((int)$xf["numFmtId"] < 164) { + $numFmt = PHPWord_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]); + } + } + $quotePrefix = false; + if (isset($xf["quotePrefix"])) { + $quotePrefix = (boolean) $xf["quotePrefix"]; + } + //$numFmt = str_replace('mm', 'i', $numFmt); + //$numFmt = str_replace('h', 'H', $numFmt); + + $style = (object) array( + "numFmt" => $numFmt, + "font" => $xmlStyles->fonts->font[intval($xf["fontId"])], + "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])], + "border" => $xmlStyles->borders->border[intval($xf["borderId"])], + "alignment" => $xf->alignment, + "protection" => $xf->protection, + "quotePrefix" => $quotePrefix, + ); + $styles[] = $style; + + // add style to cellXf collection + $objStyle = new PHPWord_Style; + self::_readStyle($objStyle, $style); + $excel->addCellXf($objStyle); + } + + foreach ($xmlStyles->cellStyleXfs->xf as $xf) { + $numFmt = PHPWord_Style_NumberFormat::FORMAT_GENERAL; + if ($numFmts && $xf["numFmtId"]) { + $tmpNumFmt = self::array_item($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); + if (isset($tmpNumFmt["formatCode"])) { + $numFmt = (string) $tmpNumFmt["formatCode"]; + } else if ((int)$xf["numFmtId"] < 165) { + $numFmt = PHPWord_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]); + } + } + + $cellStyle = (object) array( + "numFmt" => $numFmt, + "font" => $xmlStyles->fonts->font[intval($xf["fontId"])], + "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])], + "border" => $xmlStyles->borders->border[intval($xf["borderId"])], + "alignment" => $xf->alignment, + "protection" => $xf->protection, + "quotePrefix" => $quotePrefix, + ); + $cellStyles[] = $cellStyle; + + // add style to cellStyleXf collection + $objStyle = new PHPWord_Style; + self::_readStyle($objStyle, $cellStyle); + $excel->addCellStyleXf($objStyle); + } + } + + $dxfs = array(); + if (!$this->_readDataOnly && $xmlStyles) { + // Conditional Styles + if ($xmlStyles->dxfs) { + foreach ($xmlStyles->dxfs->dxf as $dxf) { + $style = new PHPWord_Style(FALSE, TRUE); + self::_readStyle($style, $dxf); + $dxfs[] = $style; + } + } + // Cell Styles + if ($xmlStyles->cellStyles) { + foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) { + if (intval($cellStyle['builtinId']) == 0) { + if (isset($cellStyles[intval($cellStyle['xfId'])])) { + // Set default style + $style = new PHPWord_Style; + self::_readStyle($style, $cellStyles[intval($cellStyle['xfId'])]); + + // normal style, currently not using it for anything + } + } + } + } + } + + $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + + // Set base date + if ($xmlWorkbook->workbookPr) { + PHPWord_Shared_Date::setExcelCalendar(PHPWord_Shared_Date::CALENDAR_WINDOWS_1900); + if (isset($xmlWorkbook->workbookPr['date1904'])) { + if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) { + PHPWord_Shared_Date::setExcelCalendar(PHPWord_Shared_Date::CALENDAR_MAC_1904); + } + } + } + + $sheetId = 0; // keep track of new sheet id in final workbook + $oldSheetId = -1; // keep track of old sheet id in final workbook + $countSkippedSheets = 0; // keep track of number of skipped sheets + $mapSheetId = array(); // mapping of sheet ids from old to new + + + $charts = $chartDetails = array(); + + if ($xmlWorkbook->sheets) { + foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + ++$oldSheetId; + + // Check if sheet should be skipped + if (isset($this->_loadSheetsOnly) && !in_array((string) $eleSheet["name"], $this->_loadSheetsOnly)) { + ++$countSkippedSheets; + $mapSheetId[$oldSheetId] = null; + continue; + } + + // Map old sheet id in original workbook to new sheet id. + // They will differ if loadSheetsOnly() is being used + $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets; + + // Load sheet + $docSheet = $excel->createSheet(); + // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet + // references in formula cells... during the load, all formulae should be correct, + // and we're simply bringing the worksheet name in line with the formula, not the + // reverse + $docSheet->setTitle((string) $eleSheet["name"],false); + $fileWorksheet = $worksheets[(string) self::array_item($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + $xmlSheet = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$fileWorksheet")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + + $sharedFormulas = array(); + + if (isset($eleSheet["state"]) && (string) $eleSheet["state"] != '') { + $docSheet->setSheetState( (string) $eleSheet["state"] ); + } + + if (isset($xmlSheet->sheetViews) && isset($xmlSheet->sheetViews->sheetView)) { + if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) { + $docSheet->getSheetView()->setZoomScale( intval($xmlSheet->sheetViews->sheetView['zoomScale']) ); + } + + if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) { + $docSheet->getSheetView()->setZoomScaleNormal( intval($xmlSheet->sheetViews->sheetView['zoomScaleNormal']) ); + } + + if (isset($xmlSheet->sheetViews->sheetView['view'])) { + $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']); + } + + if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) { + $docSheet->setShowGridLines(self::boolean((string)$xmlSheet->sheetViews->sheetView['showGridLines'])); + } + + if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) { + $docSheet->setShowRowColHeaders(self::boolean((string)$xmlSheet->sheetViews->sheetView['showRowColHeaders'])); + } + + if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) { + $docSheet->setRightToLeft(self::boolean((string)$xmlSheet->sheetViews->sheetView['rightToLeft'])); + } + + if (isset($xmlSheet->sheetViews->sheetView->pane)) { + if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) { + $docSheet->freezePane( (string)$xmlSheet->sheetViews->sheetView->pane['topLeftCell'] ); + } else { + $xSplit = 0; + $ySplit = 0; + + if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) { + $xSplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['xSplit']); + } + + if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) { + $ySplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['ySplit']); + } + + $docSheet->freezePaneByColumnAndRow($xSplit, $ySplit); + } + } + + if (isset($xmlSheet->sheetViews->sheetView->selection)) { + if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) { + $sqref = (string)$xmlSheet->sheetViews->sheetView->selection['sqref']; + $sqref = explode(' ', $sqref); + $sqref = $sqref[0]; + $docSheet->setSelectedCells($sqref); + } + } + + } + + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->tabColor)) { + if (isset($xmlSheet->sheetPr->tabColor['rgb'])) { + $docSheet->getTabColor()->setARGB( (string)$xmlSheet->sheetPr->tabColor['rgb'] ); + } + } + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr['codeName'])) { + $docSheet->setCodeName((string) $xmlSheet->sheetPr['codeName']); + } + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->outlinePr)) { + if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) && + !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryRight'])) { + $docSheet->setShowSummaryRight(FALSE); + } else { + $docSheet->setShowSummaryRight(TRUE); + } + + if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) && + !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryBelow'])) { + $docSheet->setShowSummaryBelow(FALSE); + } else { + $docSheet->setShowSummaryBelow(TRUE); + } + } + + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->pageSetUpPr)) { + if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) && + !self::boolean((string) $xmlSheet->sheetPr->pageSetUpPr['fitToPage'])) { + $docSheet->getPageSetup()->setFitToPage(FALSE); + } else { + $docSheet->getPageSetup()->setFitToPage(TRUE); + } + } + + if (isset($xmlSheet->sheetFormatPr)) { + if (isset($xmlSheet->sheetFormatPr['customHeight']) && + self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) && + isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) { + $docSheet->getDefaultRowDimension()->setRowHeight( (float)$xmlSheet->sheetFormatPr['defaultRowHeight'] ); + } + if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) { + $docSheet->getDefaultColumnDimension()->setWidth( (float)$xmlSheet->sheetFormatPr['defaultColWidth'] ); + } + if (isset($xmlSheet->sheetFormatPr['zeroHeight']) && + ((string)$xmlSheet->sheetFormatPr['zeroHeight'] == '1')) { + $docSheet->getDefaultRowDimension()->setzeroHeight(true); + } + } + + if (isset($xmlSheet->cols) && !$this->_readDataOnly) { + foreach ($xmlSheet->cols->col as $col) { + for ($i = intval($col["min"]) - 1; $i < intval($col["max"]); ++$i) { + if ($col["style"] && !$this->_readDataOnly) { + $docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setXfIndex(intval($col["style"])); + } + if (self::boolean($col["bestFit"])) { + //$docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setAutoSize(TRUE); + } + if (self::boolean($col["hidden"])) { + $docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setVisible(FALSE); + } + if (self::boolean($col["collapsed"])) { + $docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setCollapsed(TRUE); + } + if ($col["outlineLevel"] > 0) { + $docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setOutlineLevel(intval($col["outlineLevel"])); + } + $docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setWidth(floatval($col["width"])); + + if (intval($col["max"]) == 16384) { + break; + } + } + } + } + + if (isset($xmlSheet->printOptions) && !$this->_readDataOnly) { + if (self::boolean((string) $xmlSheet->printOptions['gridLinesSet'])) { + $docSheet->setShowGridlines(TRUE); + } + + if (self::boolean((string) $xmlSheet->printOptions['gridLines'])) { + $docSheet->setPrintGridlines(TRUE); + } + + if (self::boolean((string) $xmlSheet->printOptions['horizontalCentered'])) { + $docSheet->getPageSetup()->setHorizontalCentered(TRUE); + } + if (self::boolean((string) $xmlSheet->printOptions['verticalCentered'])) { + $docSheet->getPageSetup()->setVerticalCentered(TRUE); + } + } + + if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) { + foreach ($xmlSheet->sheetData->row as $row) { + if ($row["ht"] && !$this->_readDataOnly) { + $docSheet->getRowDimension(intval($row["r"]))->setRowHeight(floatval($row["ht"])); + } + if (self::boolean($row["hidden"]) && !$this->_readDataOnly) { + $docSheet->getRowDimension(intval($row["r"]))->setVisible(FALSE); + } + if (self::boolean($row["collapsed"])) { + $docSheet->getRowDimension(intval($row["r"]))->setCollapsed(TRUE); + } + if ($row["outlineLevel"] > 0) { + $docSheet->getRowDimension(intval($row["r"]))->setOutlineLevel(intval($row["outlineLevel"])); + } + if ($row["s"] && !$this->_readDataOnly) { + $docSheet->getRowDimension(intval($row["r"]))->setXfIndex(intval($row["s"])); + } + + foreach ($row->c as $c) { + $r = (string) $c["r"]; + $cellDataType = (string) $c["t"]; + $value = null; + $calculatedValue = null; + + // Read cell? + if ($this->getReadFilter() !== NULL) { + $coordinates = PHPWord_Cell::coordinateFromString($r); + + if (!$this->getReadFilter()->readCell($coordinates[0], $coordinates[1], $docSheet->getTitle())) { + continue; + } + } + + // echo 'Reading cell '.$coordinates[0].$coordinates[1].'
'; + // print_r($c); + // echo '
'; + // echo 'Cell Data Type is '.$cellDataType.': '; + // + // Read cell! + switch ($cellDataType) { + case "s": + // echo 'String
'; + if ((string)$c->v != '') { + $value = $sharedStrings[intval($c->v)]; + + if ($value instanceof PHPWord_RichText) { + $value = clone $value; + } + } else { + $value = ''; + } + + break; + case "b": + // echo 'Boolean
'; + if (!isset($c->f)) { + $value = self::_castToBool($c); + } else { + // Formula + $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToBool'); + if (isset($c->f['t'])) { + $att = array(); + $att = $c->f; + $docSheet->getCell($r)->setFormulaAttributes($att); + } + // echo '$calculatedValue = '.$calculatedValue.'
'; + } + break; + case "inlineStr": + // echo 'Inline String
'; + $value = $this->_parseRichText($c->is); + + break; + case "e": + // echo 'Error
'; + if (!isset($c->f)) { + $value = self::_castToError($c); + } else { + // Formula + $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToError'); + // echo '$calculatedValue = '.$calculatedValue.'
'; + } + + break; + + default: + // echo 'Default
'; + if (!isset($c->f)) { + // echo 'Not a Formula
'; + $value = self::_castToString($c); + } else { + // echo 'Treat as Formula
'; + // Formula + $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToString'); + // echo '$calculatedValue = '.$calculatedValue.'
'; + } + + break; + } + // echo 'Value is '.$value.'
'; + + // Check for numeric values + if (is_numeric($value) && $cellDataType != 's') { + if ($value == (int)$value) $value = (int)$value; + elseif ($value == (float)$value) $value = (float)$value; + elseif ($value == (double)$value) $value = (double)$value; + } + + // Rich text? + if ($value instanceof PHPWord_RichText && $this->_readDataOnly) { + $value = $value->getPlainText(); + } + + $cell = $docSheet->getCell($r); + // Assign value + if ($cellDataType != '') { + $cell->setValueExplicit($value, $cellDataType); + } else { + $cell->setValue($value); + } + if ($calculatedValue !== NULL) { + $cell->setCalculatedValue($calculatedValue); + } + + // Style information? + if ($c["s"] && !$this->_readDataOnly) { + // no style index means 0, it seems + $cell->setXfIndex(isset($styles[intval($c["s"])]) ? + intval($c["s"]) : 0); + } + } + } + } + + $conditionals = array(); + if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) { + foreach ($xmlSheet->conditionalFormatting as $conditional) { + foreach ($conditional->cfRule as $cfRule) { + if ( + ( + (string)$cfRule["type"] == PHPWord_Style_Conditional::CONDITION_NONE || + (string)$cfRule["type"] == PHPWord_Style_Conditional::CONDITION_CELLIS || + (string)$cfRule["type"] == PHPWord_Style_Conditional::CONDITION_CONTAINSTEXT || + (string)$cfRule["type"] == PHPWord_Style_Conditional::CONDITION_EXPRESSION + ) && isset($dxfs[intval($cfRule["dxfId"])]) + ) { + $conditionals[(string) $conditional["sqref"]][intval($cfRule["priority"])] = $cfRule; + } + } + } + + foreach ($conditionals as $ref => $cfRules) { + ksort($cfRules); + $conditionalStyles = array(); + foreach ($cfRules as $cfRule) { + $objConditional = new PHPWord_Style_Conditional(); + $objConditional->setConditionType((string)$cfRule["type"]); + $objConditional->setOperatorType((string)$cfRule["operator"]); + + if ((string)$cfRule["text"] != '') { + $objConditional->setText((string)$cfRule["text"]); + } + + if (count($cfRule->formula) > 1) { + foreach ($cfRule->formula as $formula) { + $objConditional->addCondition((string)$formula); + } + } else { + $objConditional->addCondition((string)$cfRule->formula); + } + $objConditional->setStyle(clone $dxfs[intval($cfRule["dxfId"])]); + $conditionalStyles[] = $objConditional; + } + + // Extract all cell references in $ref + $aReferences = PHPWord_Cell::extractAllCellReferencesInRange($ref); + foreach ($aReferences as $reference) { + $docSheet->getStyle($reference)->setConditionalStyles($conditionalStyles); + } + } + } + + $aKeys = array("sheet", "objects", "scenarios", "formatCells", "formatColumns", "formatRows", "insertColumns", "insertRows", "insertHyperlinks", "deleteColumns", "deleteRows", "selectLockedCells", "sort", "autoFilter", "pivotTables", "selectUnlockedCells"); + if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { + foreach ($aKeys as $key) { + $method = "set" . ucfirst($key); + $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key])); + } + } + + if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { + $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection["password"], TRUE); + if ($xmlSheet->protectedRanges->protectedRange) { + foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) { + $docSheet->protectCells((string) $protectedRange["sqref"], (string) $protectedRange["password"], true); + } + } + } + + if ($xmlSheet && $xmlSheet->autoFilter && !$this->_readDataOnly) { + $autoFilter = $docSheet->getAutoFilter(); + $autoFilter->setRange((string) $xmlSheet->autoFilter["ref"]); + foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) { + $column = $autoFilter->getColumnByOffset((integer) $filterColumn["colId"]); + // Check for standard filters + if ($filterColumn->filters) { + $column->setFilterType(PHPWord_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER); + $filters = $filterColumn->filters; + if ((isset($filters["blank"])) && ($filters["blank"] == 1)) { + $column->createRule()->setRule( + NULL, // Operator is undefined, but always treated as EQUAL + '' + ) + ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER); + } + // Standard filters are always an OR join, so no join rule needs to be set + // Entries can be either filter elements + foreach ($filters->filter as $filterRule) { + $column->createRule()->setRule( + NULL, // Operator is undefined, but always treated as EQUAL + (string) $filterRule["val"] + ) + ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER); + } + // Or Date Group elements + foreach ($filters->dateGroupItem as $dateGroupItem) { + $column->createRule()->setRule( + NULL, // Operator is undefined, but always treated as EQUAL + array( + 'year' => (string) $dateGroupItem["year"], + 'month' => (string) $dateGroupItem["month"], + 'day' => (string) $dateGroupItem["day"], + 'hour' => (string) $dateGroupItem["hour"], + 'minute' => (string) $dateGroupItem["minute"], + 'second' => (string) $dateGroupItem["second"], + ), + (string) $dateGroupItem["dateTimeGrouping"] + ) + ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP); + } + } + // Check for custom filters + if ($filterColumn->customFilters) { + $column->setFilterType(PHPWord_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER); + $customFilters = $filterColumn->customFilters; + // Custom filters can an AND or an OR join; + // and there should only ever be one or two entries + if ((isset($customFilters["and"])) && ($customFilters["and"] == 1)) { + $column->setJoin(PHPWord_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND); + } + foreach ($customFilters->customFilter as $filterRule) { + $column->createRule()->setRule( + (string) $filterRule["operator"], + (string) $filterRule["val"] + ) + ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); + } + } + // Check for dynamic filters + if ($filterColumn->dynamicFilter) { + $column->setFilterType(PHPWord_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + // We should only ever have one dynamic filter + foreach ($filterColumn->dynamicFilter as $filterRule) { + $column->createRule()->setRule( + NULL, // Operator is undefined, but always treated as EQUAL + (string) $filterRule["val"], + (string) $filterRule["type"] + ) + ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); + if (isset($filterRule["val"])) { + $column->setAttribute('val',(string) $filterRule["val"]); + } + if (isset($filterRule["maxVal"])) { + $column->setAttribute('maxVal',(string) $filterRule["maxVal"]); + } + } + } + // Check for dynamic filters + if ($filterColumn->top10) { + $column->setFilterType(PHPWord_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER); + // We should only ever have one top10 filter + foreach ($filterColumn->top10 as $filterRule) { + $column->createRule()->setRule( + (((isset($filterRule["percent"])) && ($filterRule["percent"] == 1)) + ? PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT + : PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE + ), + (string) $filterRule["val"], + (((isset($filterRule["top"])) && ($filterRule["top"] == 1)) + ? PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP + : PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM + ) + ) + ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER); + } + } + } + } + + if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->_readDataOnly) { + foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) { + $mergeRef = (string) $mergeCell["ref"]; + if (strpos($mergeRef,':') !== FALSE) { + $docSheet->mergeCells((string) $mergeCell["ref"]); + } + } + } + + if ($xmlSheet && $xmlSheet->pageMargins && !$this->_readDataOnly) { + $docPageMargins = $docSheet->getPageMargins(); + $docPageMargins->setLeft(floatval($xmlSheet->pageMargins["left"])); + $docPageMargins->setRight(floatval($xmlSheet->pageMargins["right"])); + $docPageMargins->setTop(floatval($xmlSheet->pageMargins["top"])); + $docPageMargins->setBottom(floatval($xmlSheet->pageMargins["bottom"])); + $docPageMargins->setHeader(floatval($xmlSheet->pageMargins["header"])); + $docPageMargins->setFooter(floatval($xmlSheet->pageMargins["footer"])); + } + + if ($xmlSheet && $xmlSheet->pageSetup && !$this->_readDataOnly) { + $docPageSetup = $docSheet->getPageSetup(); + + if (isset($xmlSheet->pageSetup["orientation"])) { + $docPageSetup->setOrientation((string) $xmlSheet->pageSetup["orientation"]); + } + if (isset($xmlSheet->pageSetup["paperSize"])) { + $docPageSetup->setPaperSize(intval($xmlSheet->pageSetup["paperSize"])); + } + if (isset($xmlSheet->pageSetup["scale"])) { + $docPageSetup->setScale(intval($xmlSheet->pageSetup["scale"]), FALSE); + } + if (isset($xmlSheet->pageSetup["fitToHeight"]) && intval($xmlSheet->pageSetup["fitToHeight"]) >= 0) { + $docPageSetup->setFitToHeight(intval($xmlSheet->pageSetup["fitToHeight"]), FALSE); + } + if (isset($xmlSheet->pageSetup["fitToWidth"]) && intval($xmlSheet->pageSetup["fitToWidth"]) >= 0) { + $docPageSetup->setFitToWidth(intval($xmlSheet->pageSetup["fitToWidth"]), FALSE); + } + if (isset($xmlSheet->pageSetup["firstPageNumber"]) && isset($xmlSheet->pageSetup["useFirstPageNumber"]) && + self::boolean((string) $xmlSheet->pageSetup["useFirstPageNumber"])) { + $docPageSetup->setFirstPageNumber(intval($xmlSheet->pageSetup["firstPageNumber"])); + } + } + + if ($xmlSheet && $xmlSheet->headerFooter && !$this->_readDataOnly) { + $docHeaderFooter = $docSheet->getHeaderFooter(); + + if (isset($xmlSheet->headerFooter["differentOddEven"]) && + self::boolean((string)$xmlSheet->headerFooter["differentOddEven"])) { + $docHeaderFooter->setDifferentOddEven(TRUE); + } else { + $docHeaderFooter->setDifferentOddEven(FALSE); + } + if (isset($xmlSheet->headerFooter["differentFirst"]) && + self::boolean((string)$xmlSheet->headerFooter["differentFirst"])) { + $docHeaderFooter->setDifferentFirst(TRUE); + } else { + $docHeaderFooter->setDifferentFirst(FALSE); + } + if (isset($xmlSheet->headerFooter["scaleWithDoc"]) && + !self::boolean((string)$xmlSheet->headerFooter["scaleWithDoc"])) { + $docHeaderFooter->setScaleWithDocument(FALSE); + } else { + $docHeaderFooter->setScaleWithDocument(TRUE); + } + if (isset($xmlSheet->headerFooter["alignWithMargins"]) && + !self::boolean((string)$xmlSheet->headerFooter["alignWithMargins"])) { + $docHeaderFooter->setAlignWithMargins(FALSE); + } else { + $docHeaderFooter->setAlignWithMargins(TRUE); + } + + $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader); + $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter); + $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader); + $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter); + $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader); + $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter); + } + + if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->_readDataOnly) { + foreach ($xmlSheet->rowBreaks->brk as $brk) { + if ($brk["man"]) { + $docSheet->setBreak("A$brk[id]", PHPWord_Worksheet::BREAK_ROW); + } + } + } + if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->_readDataOnly) { + foreach ($xmlSheet->colBreaks->brk as $brk) { + if ($brk["man"]) { + $docSheet->setBreak(PHPWord_Cell::stringFromColumnIndex((string) $brk["id"]) . "1", PHPWord_Worksheet::BREAK_COLUMN); + } + } + } + + if ($xmlSheet && $xmlSheet->dataValidations && !$this->_readDataOnly) { + foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) { + // Uppercase coordinate + $range = strtoupper($dataValidation["sqref"]); + $rangeSet = explode(' ',$range); + foreach($rangeSet as $range) { + $stRange = $docSheet->shrinkRangeToFit($range); + + // Extract all cell references in $range + $aReferences = PHPWord_Cell::extractAllCellReferencesInRange($stRange); + foreach ($aReferences as $reference) { + // Create validation + $docValidation = $docSheet->getCell($reference)->getDataValidation(); + $docValidation->setType((string) $dataValidation["type"]); + $docValidation->setErrorStyle((string) $dataValidation["errorStyle"]); + $docValidation->setOperator((string) $dataValidation["operator"]); + $docValidation->setAllowBlank($dataValidation["allowBlank"] != 0); + $docValidation->setShowDropDown($dataValidation["showDropDown"] == 0); + $docValidation->setShowInputMessage($dataValidation["showInputMessage"] != 0); + $docValidation->setShowErrorMessage($dataValidation["showErrorMessage"] != 0); + $docValidation->setErrorTitle((string) $dataValidation["errorTitle"]); + $docValidation->setError((string) $dataValidation["error"]); + $docValidation->setPromptTitle((string) $dataValidation["promptTitle"]); + $docValidation->setPrompt((string) $dataValidation["prompt"]); + $docValidation->setFormula1((string) $dataValidation->formula1); + $docValidation->setFormula2((string) $dataValidation->formula2); + } + } + } + } + + // Add hyperlinks + $hyperlinks = array(); + if (!$this->_readDataOnly) { + // Locate hyperlink relations + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink") { + $hyperlinks[(string)$ele["Id"]] = (string)$ele["Target"]; + } + } + } + + // Loop through hyperlinks + if ($xmlSheet && $xmlSheet->hyperlinks) { + foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) { + // Link url + $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + + foreach (PHPWord_Cell::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) { + $cell = $docSheet->getCell( $cellReference ); + if (isset($linkRel['id'])) { + $hyperlinkUrl = $hyperlinks[ (string)$linkRel['id'] ]; + if (isset($hyperlink['location'])) { + $hyperlinkUrl .= '#' . (string) $hyperlink['location']; + } + $cell->getHyperlink()->setUrl($hyperlinkUrl); + } elseif (isset($hyperlink['location'])) { + $cell->getHyperlink()->setUrl( 'sheet://' . (string)$hyperlink['location'] ); + } + + // Tooltip + if (isset($hyperlink['tooltip'])) { + $cell->getHyperlink()->setTooltip( (string)$hyperlink['tooltip'] ); + } + } + } + } + } + + // Add comments + $comments = array(); + $vmlComments = array(); + if (!$this->_readDataOnly) { + // Locate comment relations + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments") { + $comments[(string)$ele["Id"]] = (string)$ele["Target"]; + } + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") { + $vmlComments[(string)$ele["Id"]] = (string)$ele["Target"]; + } + } + } + + // Loop through comments + foreach ($comments as $relName => $relPath) { + // Load comments file + $relPath = PHPWord_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath); + $commentsFile = simplexml_load_string($this->_getFromZipArchive($zip, $relPath) ); + + // Utility variables + $authors = array(); + + // Loop through authors + foreach ($commentsFile->authors->author as $author) { + $authors[] = (string)$author; + } + + // Loop through contents + foreach ($commentsFile->commentList->comment as $comment) { + $docSheet->getComment( (string)$comment['ref'] )->setAuthor( $authors[(string)$comment['authorId']] ); + $docSheet->getComment( (string)$comment['ref'] )->setText( $this->_parseRichText($comment->text) ); + } + } + + // Loop through VML comments + foreach ($vmlComments as $relName => $relPath) { + // Load VML comments file + $relPath = PHPWord_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath); + $vmlCommentsFile = simplexml_load_string( $this->_getFromZipArchive($zip, $relPath) ); + $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + + $shapes = $vmlCommentsFile->xpath('//v:shape'); + foreach ($shapes as $shape) { + $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + + if (isset($shape['style'])) { + $style = (string)$shape['style']; + $fillColor = strtoupper( substr( (string)$shape['fillcolor'], 1 ) ); + $column = null; + $row = null; + + $clientData = $shape->xpath('.//x:ClientData'); + if (is_array($clientData) && !empty($clientData)) { + $clientData = $clientData[0]; + + if ( isset($clientData['ObjectType']) && (string)$clientData['ObjectType'] == 'Note' ) { + $temp = $clientData->xpath('.//x:Row'); + if (is_array($temp)) $row = $temp[0]; + + $temp = $clientData->xpath('.//x:Column'); + if (is_array($temp)) $column = $temp[0]; + } + } + + if (($column !== NULL) && ($row !== NULL)) { + // Set comment properties + $comment = $docSheet->getCommentByColumnAndRow((string) $column, $row + 1); + $comment->getFillColor()->setRGB( $fillColor ); + + // Parse style + $styleArray = explode(';', str_replace(' ', '', $style)); + foreach ($styleArray as $stylePair) { + $stylePair = explode(':', $stylePair); + + if ($stylePair[0] == 'margin-left') $comment->setMarginLeft($stylePair[1]); + if ($stylePair[0] == 'margin-top') $comment->setMarginTop($stylePair[1]); + if ($stylePair[0] == 'width') $comment->setWidth($stylePair[1]); + if ($stylePair[0] == 'height') $comment->setHeight($stylePair[1]); + if ($stylePair[0] == 'visibility') $comment->setVisible( $stylePair[1] == 'visible' ); + + } + } + } + } + } + + // Header/footer images + if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->_readDataOnly) { + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $vmlRelationship = ''; + + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") { + $vmlRelationship = self::dir_add("$dir/$fileWorksheet", $ele["Target"]); + } + } + + if ($vmlRelationship != '') { + // Fetch linked images + $relsVML = simplexml_load_string($this->_getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels' )); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $drawings = array(); + foreach ($relsVML->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") { + $drawings[(string) $ele["Id"]] = self::dir_add($vmlRelationship, $ele["Target"]); + } + } + + // Fetch VML document + $vmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $vmlRelationship)); + $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + + $hfImages = array(); + + $shapes = $vmlDrawing->xpath('//v:shape'); + foreach ($shapes as $idx => $shape) { + $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + $imageData = $shape->xpath('//v:imagedata'); + $imageData = $imageData[$idx]; + + $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office'); + $style = self::toCSSArray( (string)$shape['style'] ); + + $hfImages[ (string)$shape['id'] ] = new PHPWord_Worksheet_HeaderFooterDrawing(); + if (isset($imageData['title'])) { + $hfImages[ (string)$shape['id'] ]->setName( (string)$imageData['title'] ); + } + + $hfImages[ (string)$shape['id'] ]->setPath("zip://".PHPWord_Shared_File::realpath($pFilename)."#" . $drawings[(string)$imageData['relid']], false); + $hfImages[ (string)$shape['id'] ]->setResizeProportional(false); + $hfImages[ (string)$shape['id'] ]->setWidth($style['width']); + $hfImages[ (string)$shape['id'] ]->setHeight($style['height']); + if (isset($style['margin-left'])) { + $hfImages[ (string)$shape['id'] ]->setOffsetX($style['margin-left']); + } + $hfImages[ (string)$shape['id'] ]->setOffsetY($style['margin-top']); + $hfImages[ (string)$shape['id'] ]->setResizeProportional(true); + } + + $docSheet->getHeaderFooter()->setImages($hfImages); + } + } + } + + } + + // TODO: Autoshapes from twoCellAnchors! + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $drawings = array(); + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing") { + $drawings[(string) $ele["Id"]] = self::dir_add("$dir/$fileWorksheet", $ele["Target"]); + } + } + if ($xmlSheet->drawing && !$this->_readDataOnly) { + foreach ($xmlSheet->drawing as $drawing) { + $fileDrawing = $drawings[(string) self::array_item($drawing->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + $relsDrawing = simplexml_load_string($this->_getFromZipArchive($zip, dirname($fileDrawing) . "/_rels/" . basename($fileDrawing) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $images = array(); + + if ($relsDrawing && $relsDrawing->Relationship) { + foreach ($relsDrawing->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") { + $images[(string) $ele["Id"]] = self::dir_add($fileDrawing, $ele["Target"]); + } elseif ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart") { + if ($this->_includeCharts) { + $charts[self::dir_add($fileDrawing, $ele["Target"])] = array('id' => (string) $ele["Id"], + 'sheet' => $docSheet->getTitle() + ); + } + } + } + } + $xmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $fileDrawing))->children("http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"); + + if ($xmlDrawing->oneCellAnchor) { + foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) { + if ($oneCellAnchor->pic->blipFill) { + $blip = $oneCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip; + $xfrm = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm; + $outerShdw = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw; + $objDrawing = new PHPWord_Worksheet_Drawing; + $objDrawing->setName((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name")); + $objDrawing->setDescription((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr")); + $objDrawing->setPath("zip://".PHPWord_Shared_File::realpath($pFilename)."#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false); + $objDrawing->setCoordinates(PHPWord_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1)); + $objDrawing->setOffsetX(PHPWord_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff)); + $objDrawing->setOffsetY(PHPWord_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff)); + $objDrawing->setResizeProportional(false); + $objDrawing->setWidth(PHPWord_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cx"))); + $objDrawing->setHeight(PHPWord_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cy"))); + if ($xfrm) { + $objDrawing->setRotation(PHPWord_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot"))); + } + if ($outerShdw) { + $shadow = $objDrawing->getShadow(); + $shadow->setVisible(true); + $shadow->setBlurRadius(PHPWord_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad"))); + $shadow->setDistance(PHPWord_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist"))); + $shadow->setDirection(PHPWord_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir"))); + $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn")); + $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val")); + $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000); + } + $objDrawing->setWorksheet($docSheet); + } else { + // ? Can charts be positioned with a oneCellAnchor ? + $coordinates = PHPWord_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1); + $offsetX = PHPWord_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff); + $offsetY = PHPWord_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff); + $width = PHPWord_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cx")); + $height = PHPWord_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cy")); + } + } + } + if ($xmlDrawing->twoCellAnchor) { + foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) { + if ($twoCellAnchor->pic->blipFill) { + $blip = $twoCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip; + $xfrm = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm; + $outerShdw = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw; + $objDrawing = new PHPWord_Worksheet_Drawing; + $objDrawing->setName((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name")); + $objDrawing->setDescription((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr")); + $objDrawing->setPath("zip://".PHPWord_Shared_File::realpath($pFilename)."#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false); + $objDrawing->setCoordinates(PHPWord_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1)); + $objDrawing->setOffsetX(PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff)); + $objDrawing->setOffsetY(PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff)); + $objDrawing->setResizeProportional(false); + + $objDrawing->setWidth(PHPWord_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cx"))); + $objDrawing->setHeight(PHPWord_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cy"))); + + if ($xfrm) { + $objDrawing->setRotation(PHPWord_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot"))); + } + if ($outerShdw) { + $shadow = $objDrawing->getShadow(); + $shadow->setVisible(true); + $shadow->setBlurRadius(PHPWord_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad"))); + $shadow->setDistance(PHPWord_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist"))); + $shadow->setDirection(PHPWord_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir"))); + $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn")); + $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val")); + $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000); + } + $objDrawing->setWorksheet($docSheet); + } elseif(($this->_includeCharts) && ($twoCellAnchor->graphicFrame)) { + $fromCoordinate = PHPWord_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1); + $fromOffsetX = PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff); + $fromOffsetY = PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff); + $toCoordinate = PHPWord_Cell::stringFromColumnIndex((string) $twoCellAnchor->to->col) . ($twoCellAnchor->to->row + 1); + $toOffsetX = PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->to->colOff); + $toOffsetY = PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->to->rowOff); + $graphic = $twoCellAnchor->graphicFrame->children("http://schemas.openxmlformats.org/drawingml/2006/main")->graphic; + $chartRef = $graphic->graphicData->children("http://schemas.openxmlformats.org/drawingml/2006/chart")->chart; + $thisChart = (string) $chartRef->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"); + + $chartDetails[$docSheet->getTitle().'!'.$thisChart] = + array( 'fromCoordinate' => $fromCoordinate, + 'fromOffsetX' => $fromOffsetX, + 'fromOffsetY' => $fromOffsetY, + 'toCoordinate' => $toCoordinate, + 'toOffsetX' => $toOffsetX, + 'toOffsetY' => $toOffsetY, + 'worksheetTitle' => $docSheet->getTitle() + ); + } + } + } + + } + } + } + + // Loop through definedNames + if ($xmlWorkbook->definedNames) { + foreach ($xmlWorkbook->definedNames->definedName as $definedName) { + // Extract range + $extractedRange = (string)$definedName; + $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange); + if (($spos = strpos($extractedRange,'!')) !== false) { + $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos)); + } else { + $extractedRange = str_replace('$', '', $extractedRange); + } + + // Valid range? + if (stripos((string)$definedName, '#REF!') !== FALSE || $extractedRange == '') { + continue; + } + + // Some definedNames are only applicable if we are on the same sheet... + if ((string)$definedName['localSheetId'] != '' && (string)$definedName['localSheetId'] == $sheetId) { + // Switch on type + switch ((string)$definedName['name']) { + + case '_xlnm._FilterDatabase': + if ((string)$definedName['hidden'] !== '1') { + $docSheet->getAutoFilter()->setRange($extractedRange); + } + break; + + case '_xlnm.Print_Titles': + // Split $extractedRange + $extractedRange = explode(',', $extractedRange); + + // Set print titles + foreach ($extractedRange as $range) { + $matches = array(); + $range = str_replace('$', '', $range); + + // check for repeating columns, e g. 'A:A' or 'A:D' + if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) { + $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($matches[1], $matches[2])); + } + // check for repeating rows, e.g. '1:1' or '1:5' + elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) { + $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($matches[1], $matches[2])); + } + } + break; + + case '_xlnm.Print_Area': + $rangeSets = explode(',', $extractedRange); // FIXME: what if sheetname contains comma? + $newRangeSets = array(); + foreach($rangeSets as $rangeSet) { + $range = explode('!', $rangeSet); // FIXME: what if sheetname contains exclamation mark? + $rangeSet = isset($range[1]) ? $range[1] : $range[0]; + if (strpos($rangeSet, ':') === FALSE) { + $rangeSet = $rangeSet . ':' . $rangeSet; + } + $newRangeSets[] = str_replace('$', '', $rangeSet); + } + $docSheet->getPageSetup()->setPrintArea(implode(',',$newRangeSets)); + break; + + default: + break; + } + } + } + } + + // Next sheet id + ++$sheetId; + } + + // Loop through definedNames + if ($xmlWorkbook->definedNames) { + foreach ($xmlWorkbook->definedNames->definedName as $definedName) { + // Extract range + $extractedRange = (string)$definedName; + $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange); + if (($spos = strpos($extractedRange,'!')) !== false) { + $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos)); + } else { + $extractedRange = str_replace('$', '', $extractedRange); + } + + // Valid range? + if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') { + continue; + } + + // Some definedNames are only applicable if we are on the same sheet... + if ((string)$definedName['localSheetId'] != '') { + // Local defined name + // Switch on type + switch ((string)$definedName['name']) { + + case '_xlnm._FilterDatabase': + case '_xlnm.Print_Titles': + case '_xlnm.Print_Area': + break; + + default: + if ($mapSheetId[(integer) $definedName['localSheetId']] !== null) { + $range = explode('!', (string)$definedName); + if (count($range) == 2) { + $range[0] = str_replace("''", "'", $range[0]); + $range[0] = str_replace("'", "", $range[0]); + if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) { + $extractedRange = str_replace('$', '', $range[1]); + $scope = $docSheet->getParent()->getSheet($mapSheetId[(integer) $definedName['localSheetId']]); + $excel->addNamedRange( new PHPWord_NamedRange((string)$definedName['name'], $worksheet, $extractedRange, true, $scope) ); + } + } + } + break; + } + } else if (!isset($definedName['localSheetId'])) { + // "Global" definedNames + $locatedSheet = null; + $extractedSheetName = ''; + if (strpos( (string)$definedName, '!' ) !== false) { + // Extract sheet name + $extractedSheetName = PHPWord_Worksheet::extractSheetTitle( (string)$definedName, true ); + $extractedSheetName = $extractedSheetName[0]; + + // Locate sheet + $locatedSheet = $excel->getSheetByName($extractedSheetName); + + // Modify range + $range = explode('!', $extractedRange); + $extractedRange = isset($range[1]) ? $range[1] : $range[0]; + } + + if ($locatedSheet !== NULL) { + $excel->addNamedRange( new PHPWord_NamedRange((string)$definedName['name'], $locatedSheet, $extractedRange, false) ); + } + } + } + } + } + + if ((!$this->_readDataOnly) || (!empty($this->_loadSheetsOnly))) { + // active sheet index + $activeTab = intval($xmlWorkbook->bookViews->workbookView["activeTab"]); // refers to old sheet index + + // keep active sheet index if sheet is still loaded, else first sheet is set as the active + if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) { + $excel->setActiveSheetIndex($mapSheetId[$activeTab]); + } else { + if ($excel->getSheetCount() == 0) { + $excel->createSheet(); + } + $excel->setActiveSheetIndex(0); + } + } + break; + } + + } + + + if (!$this->_readDataOnly) { + $contentTypes = simplexml_load_string($this->_getFromZipArchive($zip, "[Content_Types].xml")); + foreach ($contentTypes->Override as $contentType) { + switch ($contentType["ContentType"]) { + case "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": + if ($this->_includeCharts) { + $chartEntryRef = ltrim($contentType['PartName'],'/'); + $chartElements = simplexml_load_string($this->_getFromZipArchive($zip, $chartEntryRef)); + $objChart = PHPWord_Reader_Word2007_Chart::readChart($chartElements,basename($chartEntryRef,'.xml')); + +// echo 'Chart ',$chartEntryRef,'
'; +// var_dump($charts[$chartEntryRef]); +// + if (isset($charts[$chartEntryRef])) { + $chartPositionRef = $charts[$chartEntryRef]['sheet'].'!'.$charts[$chartEntryRef]['id']; +// echo 'Position Ref ',$chartPositionRef,'
'; + if (isset($chartDetails[$chartPositionRef])) { +// var_dump($chartDetails[$chartPositionRef]); + + $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); + $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet'])); + $objChart->setTopLeftPosition( $chartDetails[$chartPositionRef]['fromCoordinate'], + $chartDetails[$chartPositionRef]['fromOffsetX'], + $chartDetails[$chartPositionRef]['fromOffsetY'] + ); + $objChart->setBottomRightPosition( $chartDetails[$chartPositionRef]['toCoordinate'], + $chartDetails[$chartPositionRef]['toOffsetX'], + $chartDetails[$chartPositionRef]['toOffsetY'] + ); + } + } + } + } + } + } + + $zip->close(); + + return $excel; + } + + + private static function _readColor($color, $background=FALSE) { + if (isset($color["rgb"])) { + return (string)$color["rgb"]; + } else if (isset($color["indexed"])) { + return PHPWord_Style_Color::indexedColor($color["indexed"]-7,$background)->getARGB(); + } else if (isset($color["theme"])) { + if (self::$_theme !== NULL) { + $returnColour = self::$_theme->getColourByIndex((int)$color["theme"]); + if (isset($color["tint"])) { + $tintAdjust = (float) $color["tint"]; + $returnColour = PHPWord_Style_Color::changeBrightness($returnColour, $tintAdjust); + } + return 'FF'.$returnColour; + } + } + + if ($background) { + return 'FFFFFFFF'; + } + return 'FF000000'; + } + + + private static function _readStyle($docStyle, $style) { + // format code +// if (isset($style->numFmt)) { +// if (isset($style->numFmt['formatCode'])) { +// $docStyle->getNumberFormat()->setFormatCode((string) $style->numFmt['formatCode']); +// } else { + $docStyle->getNumberFormat()->setFormatCode($style->numFmt); +// } +// } + + // font + if (isset($style->font)) { + $docStyle->getFont()->setName((string) $style->font->name["val"]); + $docStyle->getFont()->setSize((string) $style->font->sz["val"]); + if (isset($style->font->b)) { + $docStyle->getFont()->setBold(!isset($style->font->b["val"]) || self::boolean((string) $style->font->b["val"])); + } + if (isset($style->font->i)) { + $docStyle->getFont()->setItalic(!isset($style->font->i["val"]) || self::boolean((string) $style->font->i["val"])); + } + if (isset($style->font->strike)) { + $docStyle->getFont()->setStrikethrough(!isset($style->font->strike["val"]) || self::boolean((string) $style->font->strike["val"])); + } + $docStyle->getFont()->getColor()->setARGB(self::_readColor($style->font->color)); + + if (isset($style->font->u) && !isset($style->font->u["val"])) { + $docStyle->getFont()->setUnderline(PHPWord_Style_Font::UNDERLINE_SINGLE); + } else if (isset($style->font->u) && isset($style->font->u["val"])) { + $docStyle->getFont()->setUnderline((string)$style->font->u["val"]); + } + + if (isset($style->font->vertAlign) && isset($style->font->vertAlign["val"])) { + $vertAlign = strtolower((string)$style->font->vertAlign["val"]); + if ($vertAlign == 'superscript') { + $docStyle->getFont()->setSuperScript(true); + } + if ($vertAlign == 'subscript') { + $docStyle->getFont()->setSubScript(true); + } + } + } + + // fill + if (isset($style->fill)) { + if ($style->fill->gradientFill) { + $gradientFill = $style->fill->gradientFill[0]; + if(!empty($gradientFill["type"])) { + $docStyle->getFill()->setFillType((string) $gradientFill["type"]); + } + $docStyle->getFill()->setRotation(floatval($gradientFill["degree"])); + $gradientFill->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + $docStyle->getFill()->getStartColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=0]"))->color) ); + $docStyle->getFill()->getEndColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=1]"))->color) ); + } elseif ($style->fill->patternFill) { + $patternType = (string)$style->fill->patternFill["patternType"] != '' ? (string)$style->fill->patternFill["patternType"] : 'solid'; + $docStyle->getFill()->setFillType($patternType); + if ($style->fill->patternFill->fgColor) { + $docStyle->getFill()->getStartColor()->setARGB(self::_readColor($style->fill->patternFill->fgColor,true)); + } else { + $docStyle->getFill()->getStartColor()->setARGB('FF000000'); + } + if ($style->fill->patternFill->bgColor) { + $docStyle->getFill()->getEndColor()->setARGB(self::_readColor($style->fill->patternFill->bgColor,true)); + } + } + } + + // border + if (isset($style->border)) { + $diagonalUp = self::boolean((string) $style->border["diagonalUp"]); + $diagonalDown = self::boolean((string) $style->border["diagonalDown"]); + if (!$diagonalUp && !$diagonalDown) { + $docStyle->getBorders()->setDiagonalDirection(PHPWord_Style_Borders::DIAGONAL_NONE); + } elseif ($diagonalUp && !$diagonalDown) { + $docStyle->getBorders()->setDiagonalDirection(PHPWord_Style_Borders::DIAGONAL_UP); + } elseif (!$diagonalUp && $diagonalDown) { + $docStyle->getBorders()->setDiagonalDirection(PHPWord_Style_Borders::DIAGONAL_DOWN); + } else { + $docStyle->getBorders()->setDiagonalDirection(PHPWord_Style_Borders::DIAGONAL_BOTH); + } + self::_readBorder($docStyle->getBorders()->getLeft(), $style->border->left); + self::_readBorder($docStyle->getBorders()->getRight(), $style->border->right); + self::_readBorder($docStyle->getBorders()->getTop(), $style->border->top); + self::_readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom); + self::_readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal); + } + + // alignment + if (isset($style->alignment)) { + $docStyle->getAlignment()->setHorizontal((string) $style->alignment["horizontal"]); + $docStyle->getAlignment()->setVertical((string) $style->alignment["vertical"]); + + $textRotation = 0; + if ((int)$style->alignment["textRotation"] <= 90) { + $textRotation = (int)$style->alignment["textRotation"]; + } else if ((int)$style->alignment["textRotation"] > 90) { + $textRotation = 90 - (int)$style->alignment["textRotation"]; + } + + $docStyle->getAlignment()->setTextRotation(intval($textRotation)); + $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment["wrapText"])); + $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment["shrinkToFit"])); + $docStyle->getAlignment()->setIndent( intval((string)$style->alignment["indent"]) > 0 ? intval((string)$style->alignment["indent"]) : 0 ); + } + + // protection + if (isset($style->protection)) { + if (isset($style->protection['locked'])) { + if (self::boolean((string) $style->protection['locked'])) { + $docStyle->getProtection()->setLocked(PHPWord_Style_Protection::PROTECTION_PROTECTED); + } else { + $docStyle->getProtection()->setLocked(PHPWord_Style_Protection::PROTECTION_UNPROTECTED); + } + } + + if (isset($style->protection['hidden'])) { + if (self::boolean((string) $style->protection['hidden'])) { + $docStyle->getProtection()->setHidden(PHPWord_Style_Protection::PROTECTION_PROTECTED); + } else { + $docStyle->getProtection()->setHidden(PHPWord_Style_Protection::PROTECTION_UNPROTECTED); + } + } + } + + // top-level style settings + if (isset($style->quotePrefix)) { + $docStyle->setQuotePrefix($style->quotePrefix); + } + } + + + private static function _readBorder($docBorder, $eleBorder) { + if (isset($eleBorder["style"])) { + $docBorder->setBorderStyle((string) $eleBorder["style"]); + } + if (isset($eleBorder->color)) { + $docBorder->getColor()->setARGB(self::_readColor($eleBorder->color)); + } + } + + + private function _parseRichText($is = null) { + $value = new PHPWord_RichText(); + + if (isset($is->t)) { + $value->createText( PHPWord_Shared_String::ControlCharacterOOXML2PHP( (string) $is->t ) ); + } else { + foreach ($is->r as $run) { + if (!isset($run->rPr)) { + $objText = $value->createText( PHPWord_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) ); + + } else { + $objText = $value->createTextRun( PHPWord_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) ); + + if (isset($run->rPr->rFont["val"])) { + $objText->getFont()->setName((string) $run->rPr->rFont["val"]); + } + + if (isset($run->rPr->sz["val"])) { + $objText->getFont()->setSize((string) $run->rPr->sz["val"]); + } + + if (isset($run->rPr->color)) { + $objText->getFont()->setColor( new PHPWord_Style_Color( self::_readColor($run->rPr->color) ) ); + } + + if ((isset($run->rPr->b["val"]) && self::boolean((string) $run->rPr->b["val"])) || + (isset($run->rPr->b) && !isset($run->rPr->b["val"]))) { + $objText->getFont()->setBold(TRUE); + } + + if ((isset($run->rPr->i["val"]) && self::boolean((string) $run->rPr->i["val"])) || + (isset($run->rPr->i) && !isset($run->rPr->i["val"]))) { + $objText->getFont()->setItalic(TRUE); + } + + if (isset($run->rPr->vertAlign) && isset($run->rPr->vertAlign["val"])) { + $vertAlign = strtolower((string)$run->rPr->vertAlign["val"]); + if ($vertAlign == 'superscript') { + $objText->getFont()->setSuperScript(TRUE); + } + if ($vertAlign == 'subscript') { + $objText->getFont()->setSubScript(TRUE); + } + } + + if (isset($run->rPr->u) && !isset($run->rPr->u["val"])) { + $objText->getFont()->setUnderline(PHPWord_Style_Font::UNDERLINE_SINGLE); + } else if (isset($run->rPr->u) && isset($run->rPr->u["val"])) { + $objText->getFont()->setUnderline((string)$run->rPr->u["val"]); + } + + if ((isset($run->rPr->strike["val"]) && self::boolean((string) $run->rPr->strike["val"])) || + (isset($run->rPr->strike) && !isset($run->rPr->strike["val"]))) { + $objText->getFont()->setStrikethrough(TRUE); + } + } + } + } + + return $value; + } + + private function _readRibbon($excel, $customUITarget, $zip) + { + $baseDir = dirname($customUITarget); + $nameCustomUI = basename($customUITarget); + // get the xml file (ribbon) + $localRibbon = $this->_getFromZipArchive($zip, $customUITarget); + $customUIImagesNames = array(); + $customUIImagesBinaries = array(); + // something like customUI/_rels/customUI.xml.rels + $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels'; + $dataRels = $this->_getFromZipArchive($zip, $pathRels); + if ($dataRels) { + // exists and not empty if the ribbon have some pictures (other than internal MSO) + $UIRels = simplexml_load_string($dataRels); + if ($UIRels) { + // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image + foreach ($UIRels->Relationship as $ele) { + if ($ele["Type"] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { + // an image ? + $customUIImagesNames[(string) $ele['Id']] = (string)$ele['Target']; + $customUIImagesBinaries[(string)$ele['Target']] = $this->_getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']); + } + } + } + } + if ($localRibbon) { + $excel->setRibbonXMLData($customUITarget, $localRibbon); + if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) { + $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries); + } else { + $excel->setRibbonBinObjects(NULL); + } + } else { + $excel->setRibbonXMLData(NULL); + $excel->setRibbonBinObjects(NULL); + } + } + + private static function array_item($array, $key = 0) { + return (isset($array[$key]) ? $array[$key] : null); + } + + + private static function dir_add($base, $add) { + return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add"); + } + + + private static function toCSSArray($style) { + $style = str_replace(array("\r","\n"), "", $style); + + $temp = explode(';', $style); + $style = array(); + foreach ($temp as $item) { + $item = explode(':', $item); + + if (strpos($item[1], 'px') !== false) { + $item[1] = str_replace('px', '', $item[1]); + } + if (strpos($item[1], 'pt') !== false) { + $item[1] = str_replace('pt', '', $item[1]); + $item[1] = PHPWord_Shared_Font::fontSizeToPixels($item[1]); + } + if (strpos($item[1], 'in') !== false) { + $item[1] = str_replace('in', '', $item[1]); + $item[1] = PHPWord_Shared_Font::inchSizeToPixels($item[1]); + } + if (strpos($item[1], 'cm') !== false) { + $item[1] = str_replace('cm', '', $item[1]); + $item[1] = PHPWord_Shared_Font::centimeterSizeToPixels($item[1]); + } + + $style[$item[0]] = $item[1]; + } + + return $style; + } + + private static function boolean($value = NULL) + { + if (is_numeric($value) || is_object($value)) { + return (bool) $value; + } + return ($value === 'true' || $value === 'TRUE') ? TRUE : FALSE; + } +} From cf790b9f98ecf7979bdb7296e1a1142d70015461 Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Tue, 11 Mar 2014 02:43:04 +0700 Subject: [PATCH 02/17] Minimum working sample for text, textrun, and textbreak --- Classes/PHPWord/IOFactory.php | 11 + Classes/PHPWord/Reader/Abstract.php | 31 +- Classes/PHPWord/Reader/Word2007.php | 1963 +-------------------------- samples/Sample_10_ReadWord2007.php | 78 ++ 4 files changed, 169 insertions(+), 1914 deletions(-) create mode 100644 samples/Sample_10_ReadWord2007.php diff --git a/Classes/PHPWord/IOFactory.php b/Classes/PHPWord/IOFactory.php index 5b955fac..649bcb06 100755 --- a/Classes/PHPWord/IOFactory.php +++ b/Classes/PHPWord/IOFactory.php @@ -143,4 +143,15 @@ class PHPWord_IOFactory throw new PHPExcel_Reader_Exception("No $searchType found for type $readerType"); } + /** + * Loads PHPWord from file + * + * @param string $pFilename The name of the file + * @return PHPWord + */ + public static function load($pFilename, $readerType = 'Word2007') { + $reader = self::createReader($readerType); + return $reader->load($pFilename); + } + } diff --git a/Classes/PHPWord/Reader/Abstract.php b/Classes/PHPWord/Reader/Abstract.php index 55481a32..bf3eb374 100644 --- a/Classes/PHPWord/Reader/Abstract.php +++ b/Classes/PHPWord/Reader/Abstract.php @@ -36,9 +36,9 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader * * @var boolean */ - protected $_readDataOnly = FALSE; + protected $readDataOnly = TRUE; - protected $_fileHandle = NULL; + protected $fileHandle = NULL; /** @@ -47,7 +47,8 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader * @return boolean */ public function getReadDataOnly() { - return $this->_readDataOnly; + // return $this->readDataOnly; + return TRUE; } /** @@ -56,8 +57,8 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader * @param boolean $pValue * @return PHPWord_Reader_IReader */ - public function setReadDataOnly($pValue = FALSE) { - $this->_readDataOnly = $pValue; + public function setReadDataOnly($pValue = TRUE) { + $this->readDataOnly = $pValue; return $this; } @@ -65,20 +66,20 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader * Open file for reading * * @param string $pFilename - * @throws PHPWord_Reader_Exception + * @throws PHPWord_Exception * @return resource */ - protected function _openFile($pFilename) + protected function openFile($pFilename) { // Check if file exists if (!file_exists($pFilename) || !is_readable($pFilename)) { - throw new PHPWord_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + throw new PHPWord_Exception("Could not open " . $pFilename . " for reading! File does not exist."); } // Open file - $this->_fileHandle = fopen($pFilename, 'r'); - if ($this->_fileHandle === FALSE) { - throw new PHPWord_Reader_Exception("Could not open file " . $pFilename . " for reading."); + $this->fileHandle = fopen($pFilename, 'r'); + if ($this->fileHandle === FALSE) { + throw new PHPWord_Exception("Could not open file " . $pFilename . " for reading."); } } @@ -87,19 +88,17 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader * * @param string $pFilename * @return boolean - * @throws PHPWord_Reader_Exception + * @throws PHPWord_Exception */ public function canRead($pFilename) { // Check if file exists try { - $this->_openFile($pFilename); + $this->openFile($pFilename); } catch (Exception $e) { return FALSE; } - - $readable = $this->_isValidFormat(); - fclose ($this->_fileHandle); + fclose ($this->fileHandle); return $readable; } diff --git a/Classes/PHPWord/Reader/Word2007.php b/Classes/PHPWord/Reader/Word2007.php index fbaf5426..5cc11566 100644 --- a/Classes/PHPWord/Reader/Word2007.php +++ b/Classes/PHPWord/Reader/Word2007.php @@ -28,79 +28,48 @@ /** PHPWord root directory */ if (!defined('PHPWORD_BASE_PATH')) { - /** - * @ignore - */ define('PHPWORD_BASE_PATH', dirname(__FILE__) . '/../../'); require(PHPWORD_BASE_PATH . 'PHPWord/Autoloader.php'); } /** * PHPWord_Reader_Word2007 - * - * @category PHPWord - * @package PHPWord_Reader - * @copyright Copyright (c) 2006 - 2014 PHPWord (http://www.codeplex.com/PHPWord) */ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord_Reader_IReader { - /** - * PHPWord_ReferenceHelper instance - * - * @var PHPWord_ReferenceHelper - */ - private $_referenceHelper = NULL; - - /** - * PHPWord_Reader_Word2007_Theme instance - * - * @var PHPWord_Reader_Word2007_Theme - */ - private static $_theme = NULL; - /** * Create a new PHPWord_Reader_Word2007 instance */ public function __construct() { - $this->_readFilter = new PHPWord_Reader_DefaultReadFilter(); - $this->_referenceHelper = PHPWord_ReferenceHelper::getInstance(); } - /** * Can the current PHPWord_Reader_IReader read the file? * * @param string $pFilename * @return boolean - * @throws PHPWord_Reader_Exception + * @throws PHPWord_Exception */ public function canRead($pFilename) { // Check if file exists if (!file_exists($pFilename)) { - throw new PHPWord_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + throw new PHPWord_Exception("Could not open " . $pFilename . " for reading! File does not exist."); } - $zipClass = PHPWord_Settings::getZipClass(); - - // Check if zip class exists -// if (!class_exists($zipClass, FALSE)) { -// throw new PHPWord_Reader_Exception($zipClass . " library is not enabled"); -// } - - $xl = false; + $return = false; // Load file - $zip = new $zipClass; + $zip = new ZipArchive; if ($zip->open($pFilename) === true) { // check if it is an OOXML archive - $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); + $rels = simplexml_load_string($this->getFromZipArchive($zip, "_rels/.rels")); if ($rels !== false) { foreach ($rels->Relationship as $rel) { switch ($rel["Type"]) { case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": - if (basename($rel["Target"]) == 'workbook.xml') { - $xl = true; + if (basename($rel["Target"]) == 'document.xml') { + $return = true; } break; @@ -110,211 +79,16 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord $zip->close(); } - return $xl; + return $return; } - /** - * Reads names of the worksheets from a file, without parsing the whole file to a PHPWord object + * Get from zip archive * - * @param string $pFilename - * @throws PHPWord_Reader_Exception + * @param ZipArchive $archive + * @param string $fileName */ - public function listWorksheetNames($pFilename) - { - // Check if file exists - if (!file_exists($pFilename)) { - throw new PHPWord_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); - } - - $worksheetNames = array(); - - $zipClass = PHPWord_Settings::getZipClass(); - - $zip = new $zipClass; - $zip->open($pFilename); - - // The files we're looking at here are small enough that simpleXML is more efficient than XMLReader - $rels = simplexml_load_string( - $this->_getFromZipArchive($zip, "_rels/.rels") - ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); - foreach ($rels->Relationship as $rel) { - switch ($rel["Type"]) { - case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": - $xmlWorkbook = simplexml_load_string( - $this->_getFromZipArchive($zip, "{$rel['Target']}") - ); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); - - if ($xmlWorkbook->sheets) { - foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { - // Check if sheet should be skipped - $worksheetNames[] = (string) $eleSheet["name"]; - } - } - } - } - - $zip->close(); - - return $worksheetNames; - } - - - /** - * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) - * - * @param string $pFilename - * @throws PHPWord_Reader_Exception - */ - public function listWorksheetInfo($pFilename) - { - // Check if file exists - if (!file_exists($pFilename)) { - throw new PHPWord_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); - } - - $worksheetInfo = array(); - - $zipClass = PHPWord_Settings::getZipClass(); - - $zip = new $zipClass; - $zip->open($pFilename); - - $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); - foreach ($rels->Relationship as $rel) { - if ($rel["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument") { - $dir = dirname($rel["Target"]); - $relsWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); - $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); - - $worksheets = array(); - foreach ($relsWorkbook->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet") { - $worksheets[(string) $ele["Id"]] = $ele["Target"]; - } - } - - $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); - if ($xmlWorkbook->sheets) { - $dir = dirname($rel["Target"]); - foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { - $tmpInfo = array( - 'worksheetName' => (string) $eleSheet["name"], - 'lastColumnLetter' => 'A', - 'lastColumnIndex' => 0, - 'totalRows' => 0, - 'totalColumns' => 0, - ); - - $fileWorksheet = $worksheets[(string) self::array_item($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; - - $xml = new XMLReader(); - $res = $xml->open('zip://'.PHPWord_Shared_File::realpath($pFilename).'#'."$dir/$fileWorksheet"); - $xml->setParserProperty(2,true); - - $currCells = 0; - while ($xml->read()) { - if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) { - $row = $xml->getAttribute('r'); - $tmpInfo['totalRows'] = $row; - $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'],$currCells); - $currCells = 0; - } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) { - $currCells++; - } - } - $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'],$currCells); - $xml->close(); - - $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; - $tmpInfo['lastColumnLetter'] = PHPWord_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); - - $worksheetInfo[] = $tmpInfo; - } - } - } - } - - $zip->close(); - - return $worksheetInfo; - } - - - private static function _castToBool($c) { -// echo 'Initial Cast to Boolean
'; - $value = isset($c->v) ? (string) $c->v : NULL; - if ($value == '0') { - return FALSE; - } elseif ($value == '1') { - return TRUE; - } else { - return (bool)$c->v; - } - return $value; - } // function _castToBool() - - - private static function _castToError($c) { -// echo 'Initial Cast to Error
'; - return isset($c->v) ? (string) $c->v : NULL; - } // function _castToError() - - - private static function _castToString($c) { -// echo 'Initial Cast to String
'; - return isset($c->v) ? (string) $c->v : NULL; - } // function _castToString() - - - private function _castToFormula($c,$r,&$cellDataType,&$value,&$calculatedValue,&$sharedFormulas,$castBaseType) { -// echo 'Formula',PHP_EOL; -// echo '$c->f is '.$c->f.PHP_EOL; - $cellDataType = 'f'; - $value = "={$c->f}"; - $calculatedValue = self::$castBaseType($c); - - // Shared formula? - if (isset($c->f['t']) && strtolower((string)$c->f['t']) == 'shared') { -// echo 'SHARED FORMULA'.PHP_EOL; - $instance = (string)$c->f['si']; - -// echo 'Instance ID = '.$instance.PHP_EOL; -// -// echo 'Shared Formula Array:'.PHP_EOL; -// print_r($sharedFormulas); - if (!isset($sharedFormulas[(string)$c->f['si']])) { -// echo 'SETTING NEW SHARED FORMULA'.PHP_EOL; -// echo 'Master is '.$r.PHP_EOL; -// echo 'Formula is '.$value.PHP_EOL; - $sharedFormulas[$instance] = array( 'master' => $r, - 'formula' => $value - ); -// echo 'New Shared Formula Array:'.PHP_EOL; -// print_r($sharedFormulas); - } else { -// echo 'GETTING SHARED FORMULA'.PHP_EOL; -// echo 'Master is '.$sharedFormulas[$instance]['master'].PHP_EOL; -// echo 'Formula is '.$sharedFormulas[$instance]['formula'].PHP_EOL; - $master = PHPWord_Cell::coordinateFromString($sharedFormulas[$instance]['master']); - $current = PHPWord_Cell::coordinateFromString($r); - - $difference = array(0, 0); - $difference[0] = PHPWord_Cell::columnIndexFromString($current[0]) - PHPWord_Cell::columnIndexFromString($master[0]); - $difference[1] = $current[1] - $master[1]; - - $value = $this->_referenceHelper->updateFormulaReferences( $sharedFormulas[$instance]['formula'], - 'A1', - $difference[0], - $difference[1] - ); -// echo 'Adjusted Formula is '.$value.PHP_EOL; - } - } - } - - - public function _getFromZipArchive($archive, $fileName = '') + public function getFromZipArchive($archive, $fileName = '') { // Root-relative paths if (strpos($fileName, '//') !== false) @@ -330,6 +104,11 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord $contents = $archive->getFromName(substr($fileName, 1)); } + // Stupid hack for namespace + if ($contents != '' && $fileName = 'word/document.xml') { + $contents = preg_replace('~(removeSheetByIndex(0); - if (!$this->_readDataOnly) { - $excel->removeCellStyleXfByIndex(0); // remove the default style - $excel->removeCellXfByIndex(0); // remove the default style - } - - $zipClass = PHPWord_Settings::getZipClass(); - - $zip = new $zipClass; + $word = new PHPWord; + $zip = new ZipArchive; $zip->open($pFilename); - // Read the theme first, because we need the colour scheme when reading the styles - $wbRels = simplexml_load_string($this->_getFromZipArchive($zip, "xl/_rels/workbook.xml.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); - foreach ($wbRels->Relationship as $rel) { - switch ($rel["Type"]) { - case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme": - $themeOrderArray = array('lt1','dk1','lt2','dk2'); - $themeOrderAdditional = count($themeOrderArray); - - $xmlTheme = simplexml_load_string($this->_getFromZipArchive($zip, "xl/{$rel['Target']}")); - if (is_object($xmlTheme)) { - $xmlThemeName = $xmlTheme->attributes(); - $xmlTheme = $xmlTheme->children("http://schemas.openxmlformats.org/drawingml/2006/main"); - $themeName = (string)$xmlThemeName['name']; - - $colourScheme = $xmlTheme->themeElements->clrScheme->attributes(); - $colourSchemeName = (string)$colourScheme['name']; - $colourScheme = $xmlTheme->themeElements->clrScheme->children("http://schemas.openxmlformats.org/drawingml/2006/main"); - - $themeColours = array(); - foreach ($colourScheme as $k => $xmlColour) { - $themePos = array_search($k,$themeOrderArray); - if ($themePos === false) { - $themePos = $themeOrderAdditional++; - } - if (isset($xmlColour->sysClr)) { - $xmlColourData = $xmlColour->sysClr->attributes(); - $themeColours[$themePos] = $xmlColourData['lastClr']; - } elseif (isset($xmlColour->srgbClr)) { - $xmlColourData = $xmlColour->srgbClr->attributes(); - $themeColours[$themePos] = $xmlColourData['val']; - } - } - self::$_theme = new PHPWord_Reader_Word2007_Theme($themeName,$colourSchemeName,$themeColours); - } - break; - } - } - - $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + // Read relationships + $rels = simplexml_load_string($this->getFromZipArchive($zip, "_rels/.rels")); foreach ($rels->Relationship as $rel) { switch ($rel["Type"]) { - case "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties": - $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); + // Core properties + case "http://schemas.openxmlformats.org/package/2006//relationships/metadata/core-properties": + $xmlCore = simplexml_load_string($this->getFromZipArchive($zip, "{$rel['Target']}")); if (is_object($xmlCore)) { $xmlCore->registerXPathNamespace("dc", "http://purl.org/dc/elements/1.1/"); $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/"); - $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); - $docProps = $excel->getProperties(); + $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006//metadata/core-properties"); + $docProps = $word->getProperties(); $docProps->setCreator((string) self::array_item($xmlCore->xpath("dc:creator"))); $docProps->setLastModifiedBy((string) self::array_item($xmlCore->xpath("cp:lastModifiedBy"))); - $docProps->setCreated(strtotime(self::array_item($xmlCore->xpath("dcterms:created")))); //! respect xsi:type - $docProps->setModified(strtotime(self::array_item($xmlCore->xpath("dcterms:modified")))); //! respect xsi:type + $docProps->setCreated(strtotime(self::array_item($xmlCore->xpath("dcterms:created")))); + $docProps->setModified(strtotime(self::array_item($xmlCore->xpath("dcterms:modified")))); $docProps->setTitle((string) self::array_item($xmlCore->xpath("dc:title"))); $docProps->setDescription((string) self::array_item($xmlCore->xpath("dc:description"))); $docProps->setSubject((string) self::array_item($xmlCore->xpath("dc:subject"))); $docProps->setKeywords((string) self::array_item($xmlCore->xpath("cp:keywords"))); $docProps->setCategory((string) self::array_item($xmlCore->xpath("cp:category"))); } - break; - + break; + // Extended properties case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties": - $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); + $xmlCore = simplexml_load_string($this->getFromZipArchive($zip, "{$rel['Target']}")); if (is_object($xmlCore)) { - $docProps = $excel->getProperties(); + $docProps = $word->getProperties(); if (isset($xmlCore->Company)) $docProps->setCompany((string) $xmlCore->Company); if (isset($xmlCore->Manager)) $docProps->setManager((string) $xmlCore->Manager); } - break; - + break; + // Custom properties case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties": - $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); + $xmlCore = simplexml_load_string($this->getFromZipArchive($zip, "{$rel['Target']}")); if (is_object($xmlCore)) { - $docProps = $excel->getProperties(); + $docProps = $word->getProperties(); foreach ($xmlCore as $xmlProperty) { $cellDataOfficeAttributes = $xmlProperty->attributes(); if (isset($cellDataOfficeAttributes['name'])) { $propertyName = (string) $cellDataOfficeAttributes['name']; - $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + $cellDataOfficeChildren = $xmlProperty->children("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); $attributeType = $cellDataOfficeChildren->getName(); $attributeValue = (string) $cellDataOfficeChildren->{$attributeType}; $attributeValue = PHPWord_DocumentProperties::convertProperty($attributeValue,$attributeType); @@ -448,1618 +182,51 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord } } } - break; - //Ribbon - case "http://schemas.microsoft.com/office/2006/relationships/ui/extensibility": - $customUI = $rel['Target']; - if(!is_null($customUI)){ - $this->_readRibbon($excel, $customUI, $zip); - } - break; + break; + // Document case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": $dir = dirname($rel["Target"]); - $relsWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels")); //~ http://schemas.openxmlformats.org/package/2006/relationships"); - $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); - - $sharedStrings = array(); - $xpath = self::array_item($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']")); - $xmlStrings = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$xpath[Target]")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); - if (isset($xmlStrings) && isset($xmlStrings->si)) { - foreach ($xmlStrings->si as $val) { - if (isset($val->t)) { - $sharedStrings[] = PHPWord_Shared_String::ControlCharacterOOXML2PHP( (string) $val->t ); - } elseif (isset($val->r)) { - $sharedStrings[] = $this->_parseRichText($val); - } - } - } - - $worksheets = array(); - $macros = $customUI = NULL; - foreach ($relsWorkbook->Relationship as $ele) { - switch($ele['Type']){ - case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet": - $worksheets[(string) $ele["Id"]] = $ele["Target"]; - break; - // a vbaProject ? (: some macros) - case "http://schemas.microsoft.com/office/2006/relationships/vbaProject": - $macros = $ele["Target"]; - break; - } - } - - if(!is_null($macros)){ - $macrosCode = $this->_getFromZipArchive($zip, 'xl/vbaProject.bin');//vbaProject.bin always in 'xl' dir and always named vbaProject.bin - if($macrosCode !== false){ - $excel->setMacrosCode($macrosCode); - $excel->setHasMacros(true); - //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir - $Certificate = $this->_getFromZipArchive($zip, 'xl/vbaProjectSignature.bin'); - if($Certificate !== false) - $excel->setMacrosCertificate($Certificate); - } - } - $styles = array(); - $cellStyles = array(); - $xpath = self::array_item($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); - $xmlStyles = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$xpath[Target]")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); - $numFmts = null; - if ($xmlStyles && $xmlStyles->numFmts[0]) { - $numFmts = $xmlStyles->numFmts[0]; - } - if (isset($numFmts) && ($numFmts !== NULL)) { - $numFmts->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); - } - if (!$this->_readDataOnly && $xmlStyles) { - foreach ($xmlStyles->cellXfs->xf as $xf) { - $numFmt = PHPWord_Style_NumberFormat::FORMAT_GENERAL; - - if ($xf["numFmtId"]) { - if (isset($numFmts)) { - $tmpNumFmt = self::array_item($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); - - if (isset($tmpNumFmt["formatCode"])) { - $numFmt = (string) $tmpNumFmt["formatCode"]; - } - } - - if ((int)$xf["numFmtId"] < 164) { - $numFmt = PHPWord_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]); - } - } - $quotePrefix = false; - if (isset($xf["quotePrefix"])) { - $quotePrefix = (boolean) $xf["quotePrefix"]; - } - //$numFmt = str_replace('mm', 'i', $numFmt); - //$numFmt = str_replace('h', 'H', $numFmt); - - $style = (object) array( - "numFmt" => $numFmt, - "font" => $xmlStyles->fonts->font[intval($xf["fontId"])], - "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])], - "border" => $xmlStyles->borders->border[intval($xf["borderId"])], - "alignment" => $xf->alignment, - "protection" => $xf->protection, - "quotePrefix" => $quotePrefix, - ); - $styles[] = $style; - - // add style to cellXf collection - $objStyle = new PHPWord_Style; - self::_readStyle($objStyle, $style); - $excel->addCellXf($objStyle); - } - - foreach ($xmlStyles->cellStyleXfs->xf as $xf) { - $numFmt = PHPWord_Style_NumberFormat::FORMAT_GENERAL; - if ($numFmts && $xf["numFmtId"]) { - $tmpNumFmt = self::array_item($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); - if (isset($tmpNumFmt["formatCode"])) { - $numFmt = (string) $tmpNumFmt["formatCode"]; - } else if ((int)$xf["numFmtId"] < 165) { - $numFmt = PHPWord_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]); - } - } - - $cellStyle = (object) array( - "numFmt" => $numFmt, - "font" => $xmlStyles->fonts->font[intval($xf["fontId"])], - "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])], - "border" => $xmlStyles->borders->border[intval($xf["borderId"])], - "alignment" => $xf->alignment, - "protection" => $xf->protection, - "quotePrefix" => $quotePrefix, - ); - $cellStyles[] = $cellStyle; - - // add style to cellStyleXf collection - $objStyle = new PHPWord_Style; - self::_readStyle($objStyle, $cellStyle); - $excel->addCellStyleXf($objStyle); - } - } - - $dxfs = array(); - if (!$this->_readDataOnly && $xmlStyles) { - // Conditional Styles - if ($xmlStyles->dxfs) { - foreach ($xmlStyles->dxfs->dxf as $dxf) { - $style = new PHPWord_Style(FALSE, TRUE); - self::_readStyle($style, $dxf); - $dxfs[] = $style; - } - } - // Cell Styles - if ($xmlStyles->cellStyles) { - foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) { - if (intval($cellStyle['builtinId']) == 0) { - if (isset($cellStyles[intval($cellStyle['xfId'])])) { - // Set default style - $style = new PHPWord_Style; - self::_readStyle($style, $cellStyles[intval($cellStyle['xfId'])]); - - // normal style, currently not using it for anything - } - } - } - } - } - - $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); - - // Set base date - if ($xmlWorkbook->workbookPr) { - PHPWord_Shared_Date::setExcelCalendar(PHPWord_Shared_Date::CALENDAR_WINDOWS_1900); - if (isset($xmlWorkbook->workbookPr['date1904'])) { - if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) { - PHPWord_Shared_Date::setExcelCalendar(PHPWord_Shared_Date::CALENDAR_MAC_1904); - } - } - } - - $sheetId = 0; // keep track of new sheet id in final workbook - $oldSheetId = -1; // keep track of old sheet id in final workbook - $countSkippedSheets = 0; // keep track of number of skipped sheets - $mapSheetId = array(); // mapping of sheet ids from old to new - - - $charts = $chartDetails = array(); - - if ($xmlWorkbook->sheets) { - foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { - ++$oldSheetId; - - // Check if sheet should be skipped - if (isset($this->_loadSheetsOnly) && !in_array((string) $eleSheet["name"], $this->_loadSheetsOnly)) { - ++$countSkippedSheets; - $mapSheetId[$oldSheetId] = null; - continue; - } - - // Map old sheet id in original workbook to new sheet id. - // They will differ if loadSheetsOnly() is being used - $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets; - - // Load sheet - $docSheet = $excel->createSheet(); - // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet - // references in formula cells... during the load, all formulae should be correct, - // and we're simply bringing the worksheet name in line with the formula, not the - // reverse - $docSheet->setTitle((string) $eleSheet["name"],false); - $fileWorksheet = $worksheets[(string) self::array_item($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; - $xmlSheet = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$fileWorksheet")); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); - - $sharedFormulas = array(); - - if (isset($eleSheet["state"]) && (string) $eleSheet["state"] != '') { - $docSheet->setSheetState( (string) $eleSheet["state"] ); - } - - if (isset($xmlSheet->sheetViews) && isset($xmlSheet->sheetViews->sheetView)) { - if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) { - $docSheet->getSheetView()->setZoomScale( intval($xmlSheet->sheetViews->sheetView['zoomScale']) ); - } - - if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) { - $docSheet->getSheetView()->setZoomScaleNormal( intval($xmlSheet->sheetViews->sheetView['zoomScaleNormal']) ); - } - - if (isset($xmlSheet->sheetViews->sheetView['view'])) { - $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']); - } - - if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) { - $docSheet->setShowGridLines(self::boolean((string)$xmlSheet->sheetViews->sheetView['showGridLines'])); - } - - if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) { - $docSheet->setShowRowColHeaders(self::boolean((string)$xmlSheet->sheetViews->sheetView['showRowColHeaders'])); - } - - if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) { - $docSheet->setRightToLeft(self::boolean((string)$xmlSheet->sheetViews->sheetView['rightToLeft'])); - } - - if (isset($xmlSheet->sheetViews->sheetView->pane)) { - if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) { - $docSheet->freezePane( (string)$xmlSheet->sheetViews->sheetView->pane['topLeftCell'] ); - } else { - $xSplit = 0; - $ySplit = 0; - - if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) { - $xSplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['xSplit']); - } - - if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) { - $ySplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['ySplit']); - } - - $docSheet->freezePaneByColumnAndRow($xSplit, $ySplit); - } - } - - if (isset($xmlSheet->sheetViews->sheetView->selection)) { - if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) { - $sqref = (string)$xmlSheet->sheetViews->sheetView->selection['sqref']; - $sqref = explode(' ', $sqref); - $sqref = $sqref[0]; - $docSheet->setSelectedCells($sqref); - } - } - - } - - if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->tabColor)) { - if (isset($xmlSheet->sheetPr->tabColor['rgb'])) { - $docSheet->getTabColor()->setARGB( (string)$xmlSheet->sheetPr->tabColor['rgb'] ); - } - } - if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr['codeName'])) { - $docSheet->setCodeName((string) $xmlSheet->sheetPr['codeName']); - } - if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->outlinePr)) { - if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) && - !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryRight'])) { - $docSheet->setShowSummaryRight(FALSE); - } else { - $docSheet->setShowSummaryRight(TRUE); - } - - if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) && - !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryBelow'])) { - $docSheet->setShowSummaryBelow(FALSE); - } else { - $docSheet->setShowSummaryBelow(TRUE); - } - } - - if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->pageSetUpPr)) { - if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) && - !self::boolean((string) $xmlSheet->sheetPr->pageSetUpPr['fitToPage'])) { - $docSheet->getPageSetup()->setFitToPage(FALSE); - } else { - $docSheet->getPageSetup()->setFitToPage(TRUE); - } - } - - if (isset($xmlSheet->sheetFormatPr)) { - if (isset($xmlSheet->sheetFormatPr['customHeight']) && - self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) && - isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) { - $docSheet->getDefaultRowDimension()->setRowHeight( (float)$xmlSheet->sheetFormatPr['defaultRowHeight'] ); - } - if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) { - $docSheet->getDefaultColumnDimension()->setWidth( (float)$xmlSheet->sheetFormatPr['defaultColWidth'] ); - } - if (isset($xmlSheet->sheetFormatPr['zeroHeight']) && - ((string)$xmlSheet->sheetFormatPr['zeroHeight'] == '1')) { - $docSheet->getDefaultRowDimension()->setzeroHeight(true); - } - } - - if (isset($xmlSheet->cols) && !$this->_readDataOnly) { - foreach ($xmlSheet->cols->col as $col) { - for ($i = intval($col["min"]) - 1; $i < intval($col["max"]); ++$i) { - if ($col["style"] && !$this->_readDataOnly) { - $docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setXfIndex(intval($col["style"])); - } - if (self::boolean($col["bestFit"])) { - //$docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setAutoSize(TRUE); - } - if (self::boolean($col["hidden"])) { - $docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setVisible(FALSE); - } - if (self::boolean($col["collapsed"])) { - $docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setCollapsed(TRUE); - } - if ($col["outlineLevel"] > 0) { - $docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setOutlineLevel(intval($col["outlineLevel"])); - } - $docSheet->getColumnDimension(PHPWord_Cell::stringFromColumnIndex($i))->setWidth(floatval($col["width"])); - - if (intval($col["max"]) == 16384) { - break; - } - } - } - } - - if (isset($xmlSheet->printOptions) && !$this->_readDataOnly) { - if (self::boolean((string) $xmlSheet->printOptions['gridLinesSet'])) { - $docSheet->setShowGridlines(TRUE); - } - - if (self::boolean((string) $xmlSheet->printOptions['gridLines'])) { - $docSheet->setPrintGridlines(TRUE); - } - - if (self::boolean((string) $xmlSheet->printOptions['horizontalCentered'])) { - $docSheet->getPageSetup()->setHorizontalCentered(TRUE); - } - if (self::boolean((string) $xmlSheet->printOptions['verticalCentered'])) { - $docSheet->getPageSetup()->setVerticalCentered(TRUE); - } - } - - if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) { - foreach ($xmlSheet->sheetData->row as $row) { - if ($row["ht"] && !$this->_readDataOnly) { - $docSheet->getRowDimension(intval($row["r"]))->setRowHeight(floatval($row["ht"])); - } - if (self::boolean($row["hidden"]) && !$this->_readDataOnly) { - $docSheet->getRowDimension(intval($row["r"]))->setVisible(FALSE); - } - if (self::boolean($row["collapsed"])) { - $docSheet->getRowDimension(intval($row["r"]))->setCollapsed(TRUE); - } - if ($row["outlineLevel"] > 0) { - $docSheet->getRowDimension(intval($row["r"]))->setOutlineLevel(intval($row["outlineLevel"])); - } - if ($row["s"] && !$this->_readDataOnly) { - $docSheet->getRowDimension(intval($row["r"]))->setXfIndex(intval($row["s"])); - } - - foreach ($row->c as $c) { - $r = (string) $c["r"]; - $cellDataType = (string) $c["t"]; - $value = null; - $calculatedValue = null; - - // Read cell? - if ($this->getReadFilter() !== NULL) { - $coordinates = PHPWord_Cell::coordinateFromString($r); - - if (!$this->getReadFilter()->readCell($coordinates[0], $coordinates[1], $docSheet->getTitle())) { - continue; - } - } - - // echo 'Reading cell '.$coordinates[0].$coordinates[1].'
'; - // print_r($c); - // echo '
'; - // echo 'Cell Data Type is '.$cellDataType.': '; - // - // Read cell! - switch ($cellDataType) { - case "s": - // echo 'String
'; - if ((string)$c->v != '') { - $value = $sharedStrings[intval($c->v)]; - - if ($value instanceof PHPWord_RichText) { - $value = clone $value; - } - } else { - $value = ''; - } - - break; - case "b": - // echo 'Boolean
'; - if (!isset($c->f)) { - $value = self::_castToBool($c); - } else { - // Formula - $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToBool'); - if (isset($c->f['t'])) { - $att = array(); - $att = $c->f; - $docSheet->getCell($r)->setFormulaAttributes($att); - } - // echo '$calculatedValue = '.$calculatedValue.'
'; - } - break; - case "inlineStr": - // echo 'Inline String
'; - $value = $this->_parseRichText($c->is); - - break; - case "e": - // echo 'Error
'; - if (!isset($c->f)) { - $value = self::_castToError($c); - } else { - // Formula - $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToError'); - // echo '$calculatedValue = '.$calculatedValue.'
'; - } - - break; - - default: - // echo 'Default
'; - if (!isset($c->f)) { - // echo 'Not a Formula
'; - $value = self::_castToString($c); - } else { - // echo 'Treat as Formula
'; - // Formula - $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToString'); - // echo '$calculatedValue = '.$calculatedValue.'
'; - } - - break; - } - // echo 'Value is '.$value.'
'; - - // Check for numeric values - if (is_numeric($value) && $cellDataType != 's') { - if ($value == (int)$value) $value = (int)$value; - elseif ($value == (float)$value) $value = (float)$value; - elseif ($value == (double)$value) $value = (double)$value; - } - - // Rich text? - if ($value instanceof PHPWord_RichText && $this->_readDataOnly) { - $value = $value->getPlainText(); - } - - $cell = $docSheet->getCell($r); - // Assign value - if ($cellDataType != '') { - $cell->setValueExplicit($value, $cellDataType); - } else { - $cell->setValue($value); - } - if ($calculatedValue !== NULL) { - $cell->setCalculatedValue($calculatedValue); - } - - // Style information? - if ($c["s"] && !$this->_readDataOnly) { - // no style index means 0, it seems - $cell->setXfIndex(isset($styles[intval($c["s"])]) ? - intval($c["s"]) : 0); - } - } - } - } - - $conditionals = array(); - if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) { - foreach ($xmlSheet->conditionalFormatting as $conditional) { - foreach ($conditional->cfRule as $cfRule) { - if ( - ( - (string)$cfRule["type"] == PHPWord_Style_Conditional::CONDITION_NONE || - (string)$cfRule["type"] == PHPWord_Style_Conditional::CONDITION_CELLIS || - (string)$cfRule["type"] == PHPWord_Style_Conditional::CONDITION_CONTAINSTEXT || - (string)$cfRule["type"] == PHPWord_Style_Conditional::CONDITION_EXPRESSION - ) && isset($dxfs[intval($cfRule["dxfId"])]) - ) { - $conditionals[(string) $conditional["sqref"]][intval($cfRule["priority"])] = $cfRule; - } - } - } - - foreach ($conditionals as $ref => $cfRules) { - ksort($cfRules); - $conditionalStyles = array(); - foreach ($cfRules as $cfRule) { - $objConditional = new PHPWord_Style_Conditional(); - $objConditional->setConditionType((string)$cfRule["type"]); - $objConditional->setOperatorType((string)$cfRule["operator"]); - - if ((string)$cfRule["text"] != '') { - $objConditional->setText((string)$cfRule["text"]); - } - - if (count($cfRule->formula) > 1) { - foreach ($cfRule->formula as $formula) { - $objConditional->addCondition((string)$formula); - } - } else { - $objConditional->addCondition((string)$cfRule->formula); - } - $objConditional->setStyle(clone $dxfs[intval($cfRule["dxfId"])]); - $conditionalStyles[] = $objConditional; - } - - // Extract all cell references in $ref - $aReferences = PHPWord_Cell::extractAllCellReferencesInRange($ref); - foreach ($aReferences as $reference) { - $docSheet->getStyle($reference)->setConditionalStyles($conditionalStyles); - } - } - } - - $aKeys = array("sheet", "objects", "scenarios", "formatCells", "formatColumns", "formatRows", "insertColumns", "insertRows", "insertHyperlinks", "deleteColumns", "deleteRows", "selectLockedCells", "sort", "autoFilter", "pivotTables", "selectUnlockedCells"); - if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { - foreach ($aKeys as $key) { - $method = "set" . ucfirst($key); - $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key])); - } - } - - if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { - $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection["password"], TRUE); - if ($xmlSheet->protectedRanges->protectedRange) { - foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) { - $docSheet->protectCells((string) $protectedRange["sqref"], (string) $protectedRange["password"], true); - } - } - } - - if ($xmlSheet && $xmlSheet->autoFilter && !$this->_readDataOnly) { - $autoFilter = $docSheet->getAutoFilter(); - $autoFilter->setRange((string) $xmlSheet->autoFilter["ref"]); - foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) { - $column = $autoFilter->getColumnByOffset((integer) $filterColumn["colId"]); - // Check for standard filters - if ($filterColumn->filters) { - $column->setFilterType(PHPWord_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER); - $filters = $filterColumn->filters; - if ((isset($filters["blank"])) && ($filters["blank"] == 1)) { - $column->createRule()->setRule( - NULL, // Operator is undefined, but always treated as EQUAL - '' - ) - ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER); - } - // Standard filters are always an OR join, so no join rule needs to be set - // Entries can be either filter elements - foreach ($filters->filter as $filterRule) { - $column->createRule()->setRule( - NULL, // Operator is undefined, but always treated as EQUAL - (string) $filterRule["val"] - ) - ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER); - } - // Or Date Group elements - foreach ($filters->dateGroupItem as $dateGroupItem) { - $column->createRule()->setRule( - NULL, // Operator is undefined, but always treated as EQUAL - array( - 'year' => (string) $dateGroupItem["year"], - 'month' => (string) $dateGroupItem["month"], - 'day' => (string) $dateGroupItem["day"], - 'hour' => (string) $dateGroupItem["hour"], - 'minute' => (string) $dateGroupItem["minute"], - 'second' => (string) $dateGroupItem["second"], - ), - (string) $dateGroupItem["dateTimeGrouping"] - ) - ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP); - } - } - // Check for custom filters - if ($filterColumn->customFilters) { - $column->setFilterType(PHPWord_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER); - $customFilters = $filterColumn->customFilters; - // Custom filters can an AND or an OR join; - // and there should only ever be one or two entries - if ((isset($customFilters["and"])) && ($customFilters["and"] == 1)) { - $column->setJoin(PHPWord_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND); - } - foreach ($customFilters->customFilter as $filterRule) { - $column->createRule()->setRule( - (string) $filterRule["operator"], - (string) $filterRule["val"] - ) - ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); - } - } - // Check for dynamic filters - if ($filterColumn->dynamicFilter) { - $column->setFilterType(PHPWord_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); - // We should only ever have one dynamic filter - foreach ($filterColumn->dynamicFilter as $filterRule) { - $column->createRule()->setRule( - NULL, // Operator is undefined, but always treated as EQUAL - (string) $filterRule["val"], - (string) $filterRule["type"] - ) - ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); - if (isset($filterRule["val"])) { - $column->setAttribute('val',(string) $filterRule["val"]); - } - if (isset($filterRule["maxVal"])) { - $column->setAttribute('maxVal',(string) $filterRule["maxVal"]); - } - } - } - // Check for dynamic filters - if ($filterColumn->top10) { - $column->setFilterType(PHPWord_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER); - // We should only ever have one top10 filter - foreach ($filterColumn->top10 as $filterRule) { - $column->createRule()->setRule( - (((isset($filterRule["percent"])) && ($filterRule["percent"] == 1)) - ? PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT - : PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE - ), - (string) $filterRule["val"], - (((isset($filterRule["top"])) && ($filterRule["top"] == 1)) - ? PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP - : PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM - ) - ) - ->setRuleType(PHPWord_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER); - } - } - } - } - - if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->_readDataOnly) { - foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) { - $mergeRef = (string) $mergeCell["ref"]; - if (strpos($mergeRef,':') !== FALSE) { - $docSheet->mergeCells((string) $mergeCell["ref"]); - } - } - } - - if ($xmlSheet && $xmlSheet->pageMargins && !$this->_readDataOnly) { - $docPageMargins = $docSheet->getPageMargins(); - $docPageMargins->setLeft(floatval($xmlSheet->pageMargins["left"])); - $docPageMargins->setRight(floatval($xmlSheet->pageMargins["right"])); - $docPageMargins->setTop(floatval($xmlSheet->pageMargins["top"])); - $docPageMargins->setBottom(floatval($xmlSheet->pageMargins["bottom"])); - $docPageMargins->setHeader(floatval($xmlSheet->pageMargins["header"])); - $docPageMargins->setFooter(floatval($xmlSheet->pageMargins["footer"])); - } - - if ($xmlSheet && $xmlSheet->pageSetup && !$this->_readDataOnly) { - $docPageSetup = $docSheet->getPageSetup(); - - if (isset($xmlSheet->pageSetup["orientation"])) { - $docPageSetup->setOrientation((string) $xmlSheet->pageSetup["orientation"]); - } - if (isset($xmlSheet->pageSetup["paperSize"])) { - $docPageSetup->setPaperSize(intval($xmlSheet->pageSetup["paperSize"])); - } - if (isset($xmlSheet->pageSetup["scale"])) { - $docPageSetup->setScale(intval($xmlSheet->pageSetup["scale"]), FALSE); - } - if (isset($xmlSheet->pageSetup["fitToHeight"]) && intval($xmlSheet->pageSetup["fitToHeight"]) >= 0) { - $docPageSetup->setFitToHeight(intval($xmlSheet->pageSetup["fitToHeight"]), FALSE); - } - if (isset($xmlSheet->pageSetup["fitToWidth"]) && intval($xmlSheet->pageSetup["fitToWidth"]) >= 0) { - $docPageSetup->setFitToWidth(intval($xmlSheet->pageSetup["fitToWidth"]), FALSE); - } - if (isset($xmlSheet->pageSetup["firstPageNumber"]) && isset($xmlSheet->pageSetup["useFirstPageNumber"]) && - self::boolean((string) $xmlSheet->pageSetup["useFirstPageNumber"])) { - $docPageSetup->setFirstPageNumber(intval($xmlSheet->pageSetup["firstPageNumber"])); - } - } - - if ($xmlSheet && $xmlSheet->headerFooter && !$this->_readDataOnly) { - $docHeaderFooter = $docSheet->getHeaderFooter(); - - if (isset($xmlSheet->headerFooter["differentOddEven"]) && - self::boolean((string)$xmlSheet->headerFooter["differentOddEven"])) { - $docHeaderFooter->setDifferentOddEven(TRUE); - } else { - $docHeaderFooter->setDifferentOddEven(FALSE); - } - if (isset($xmlSheet->headerFooter["differentFirst"]) && - self::boolean((string)$xmlSheet->headerFooter["differentFirst"])) { - $docHeaderFooter->setDifferentFirst(TRUE); - } else { - $docHeaderFooter->setDifferentFirst(FALSE); - } - if (isset($xmlSheet->headerFooter["scaleWithDoc"]) && - !self::boolean((string)$xmlSheet->headerFooter["scaleWithDoc"])) { - $docHeaderFooter->setScaleWithDocument(FALSE); - } else { - $docHeaderFooter->setScaleWithDocument(TRUE); - } - if (isset($xmlSheet->headerFooter["alignWithMargins"]) && - !self::boolean((string)$xmlSheet->headerFooter["alignWithMargins"])) { - $docHeaderFooter->setAlignWithMargins(FALSE); - } else { - $docHeaderFooter->setAlignWithMargins(TRUE); - } - - $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader); - $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter); - $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader); - $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter); - $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader); - $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter); - } - - if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->_readDataOnly) { - foreach ($xmlSheet->rowBreaks->brk as $brk) { - if ($brk["man"]) { - $docSheet->setBreak("A$brk[id]", PHPWord_Worksheet::BREAK_ROW); - } - } - } - if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->_readDataOnly) { - foreach ($xmlSheet->colBreaks->brk as $brk) { - if ($brk["man"]) { - $docSheet->setBreak(PHPWord_Cell::stringFromColumnIndex((string) $brk["id"]) . "1", PHPWord_Worksheet::BREAK_COLUMN); - } - } - } - - if ($xmlSheet && $xmlSheet->dataValidations && !$this->_readDataOnly) { - foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) { - // Uppercase coordinate - $range = strtoupper($dataValidation["sqref"]); - $rangeSet = explode(' ',$range); - foreach($rangeSet as $range) { - $stRange = $docSheet->shrinkRangeToFit($range); - - // Extract all cell references in $range - $aReferences = PHPWord_Cell::extractAllCellReferencesInRange($stRange); - foreach ($aReferences as $reference) { - // Create validation - $docValidation = $docSheet->getCell($reference)->getDataValidation(); - $docValidation->setType((string) $dataValidation["type"]); - $docValidation->setErrorStyle((string) $dataValidation["errorStyle"]); - $docValidation->setOperator((string) $dataValidation["operator"]); - $docValidation->setAllowBlank($dataValidation["allowBlank"] != 0); - $docValidation->setShowDropDown($dataValidation["showDropDown"] == 0); - $docValidation->setShowInputMessage($dataValidation["showInputMessage"] != 0); - $docValidation->setShowErrorMessage($dataValidation["showErrorMessage"] != 0); - $docValidation->setErrorTitle((string) $dataValidation["errorTitle"]); - $docValidation->setError((string) $dataValidation["error"]); - $docValidation->setPromptTitle((string) $dataValidation["promptTitle"]); - $docValidation->setPrompt((string) $dataValidation["prompt"]); - $docValidation->setFormula1((string) $dataValidation->formula1); - $docValidation->setFormula2((string) $dataValidation->formula2); - } - } - } - } - - // Add hyperlinks - $hyperlinks = array(); - if (!$this->_readDataOnly) { - // Locate hyperlink relations - if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { - $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); - foreach ($relsWorksheet->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink") { - $hyperlinks[(string)$ele["Id"]] = (string)$ele["Target"]; - } - } - } - - // Loop through hyperlinks - if ($xmlSheet && $xmlSheet->hyperlinks) { - foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) { - // Link url - $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - - foreach (PHPWord_Cell::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) { - $cell = $docSheet->getCell( $cellReference ); - if (isset($linkRel['id'])) { - $hyperlinkUrl = $hyperlinks[ (string)$linkRel['id'] ]; - if (isset($hyperlink['location'])) { - $hyperlinkUrl .= '#' . (string) $hyperlink['location']; - } - $cell->getHyperlink()->setUrl($hyperlinkUrl); - } elseif (isset($hyperlink['location'])) { - $cell->getHyperlink()->setUrl( 'sheet://' . (string)$hyperlink['location'] ); - } - - // Tooltip - if (isset($hyperlink['tooltip'])) { - $cell->getHyperlink()->setTooltip( (string)$hyperlink['tooltip'] ); - } - } - } - } - } - - // Add comments - $comments = array(); - $vmlComments = array(); - if (!$this->_readDataOnly) { - // Locate comment relations - if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { - $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); - foreach ($relsWorksheet->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments") { - $comments[(string)$ele["Id"]] = (string)$ele["Target"]; - } - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") { - $vmlComments[(string)$ele["Id"]] = (string)$ele["Target"]; - } - } - } - - // Loop through comments - foreach ($comments as $relName => $relPath) { - // Load comments file - $relPath = PHPWord_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath); - $commentsFile = simplexml_load_string($this->_getFromZipArchive($zip, $relPath) ); - - // Utility variables - $authors = array(); - - // Loop through authors - foreach ($commentsFile->authors->author as $author) { - $authors[] = (string)$author; - } - - // Loop through contents - foreach ($commentsFile->commentList->comment as $comment) { - $docSheet->getComment( (string)$comment['ref'] )->setAuthor( $authors[(string)$comment['authorId']] ); - $docSheet->getComment( (string)$comment['ref'] )->setText( $this->_parseRichText($comment->text) ); - } - } - - // Loop through VML comments - foreach ($vmlComments as $relName => $relPath) { - // Load VML comments file - $relPath = PHPWord_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath); - $vmlCommentsFile = simplexml_load_string( $this->_getFromZipArchive($zip, $relPath) ); - $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); - - $shapes = $vmlCommentsFile->xpath('//v:shape'); - foreach ($shapes as $shape) { - $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); - - if (isset($shape['style'])) { - $style = (string)$shape['style']; - $fillColor = strtoupper( substr( (string)$shape['fillcolor'], 1 ) ); - $column = null; - $row = null; - - $clientData = $shape->xpath('.//x:ClientData'); - if (is_array($clientData) && !empty($clientData)) { - $clientData = $clientData[0]; - - if ( isset($clientData['ObjectType']) && (string)$clientData['ObjectType'] == 'Note' ) { - $temp = $clientData->xpath('.//x:Row'); - if (is_array($temp)) $row = $temp[0]; - - $temp = $clientData->xpath('.//x:Column'); - if (is_array($temp)) $column = $temp[0]; - } - } - - if (($column !== NULL) && ($row !== NULL)) { - // Set comment properties - $comment = $docSheet->getCommentByColumnAndRow((string) $column, $row + 1); - $comment->getFillColor()->setRGB( $fillColor ); - - // Parse style - $styleArray = explode(';', str_replace(' ', '', $style)); - foreach ($styleArray as $stylePair) { - $stylePair = explode(':', $stylePair); - - if ($stylePair[0] == 'margin-left') $comment->setMarginLeft($stylePair[1]); - if ($stylePair[0] == 'margin-top') $comment->setMarginTop($stylePair[1]); - if ($stylePair[0] == 'width') $comment->setWidth($stylePair[1]); - if ($stylePair[0] == 'height') $comment->setHeight($stylePair[1]); - if ($stylePair[0] == 'visibility') $comment->setVisible( $stylePair[1] == 'visible' ); - - } - } - } - } - } - - // Header/footer images - if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->_readDataOnly) { - if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { - $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); - $vmlRelationship = ''; - - foreach ($relsWorksheet->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") { - $vmlRelationship = self::dir_add("$dir/$fileWorksheet", $ele["Target"]); - } - } - - if ($vmlRelationship != '') { - // Fetch linked images - $relsVML = simplexml_load_string($this->_getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels' )); //~ http://schemas.openxmlformats.org/package/2006/relationships"); - $drawings = array(); - foreach ($relsVML->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") { - $drawings[(string) $ele["Id"]] = self::dir_add($vmlRelationship, $ele["Target"]); - } - } - - // Fetch VML document - $vmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $vmlRelationship)); - $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); - - $hfImages = array(); - - $shapes = $vmlDrawing->xpath('//v:shape'); - foreach ($shapes as $idx => $shape) { - $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); - $imageData = $shape->xpath('//v:imagedata'); - $imageData = $imageData[$idx]; - - $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office'); - $style = self::toCSSArray( (string)$shape['style'] ); - - $hfImages[ (string)$shape['id'] ] = new PHPWord_Worksheet_HeaderFooterDrawing(); - if (isset($imageData['title'])) { - $hfImages[ (string)$shape['id'] ]->setName( (string)$imageData['title'] ); - } - - $hfImages[ (string)$shape['id'] ]->setPath("zip://".PHPWord_Shared_File::realpath($pFilename)."#" . $drawings[(string)$imageData['relid']], false); - $hfImages[ (string)$shape['id'] ]->setResizeProportional(false); - $hfImages[ (string)$shape['id'] ]->setWidth($style['width']); - $hfImages[ (string)$shape['id'] ]->setHeight($style['height']); - if (isset($style['margin-left'])) { - $hfImages[ (string)$shape['id'] ]->setOffsetX($style['margin-left']); - } - $hfImages[ (string)$shape['id'] ]->setOffsetY($style['margin-top']); - $hfImages[ (string)$shape['id'] ]->setResizeProportional(true); - } - - $docSheet->getHeaderFooter()->setImages($hfImages); - } - } - } - - } - - // TODO: Autoshapes from twoCellAnchors! - if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { - $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); - $drawings = array(); - foreach ($relsWorksheet->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing") { - $drawings[(string) $ele["Id"]] = self::dir_add("$dir/$fileWorksheet", $ele["Target"]); - } - } - if ($xmlSheet->drawing && !$this->_readDataOnly) { - foreach ($xmlSheet->drawing as $drawing) { - $fileDrawing = $drawings[(string) self::array_item($drawing->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; - $relsDrawing = simplexml_load_string($this->_getFromZipArchive($zip, dirname($fileDrawing) . "/_rels/" . basename($fileDrawing) . ".rels") ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); - $images = array(); - - if ($relsDrawing && $relsDrawing->Relationship) { - foreach ($relsDrawing->Relationship as $ele) { - if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") { - $images[(string) $ele["Id"]] = self::dir_add($fileDrawing, $ele["Target"]); - } elseif ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart") { - if ($this->_includeCharts) { - $charts[self::dir_add($fileDrawing, $ele["Target"])] = array('id' => (string) $ele["Id"], - 'sheet' => $docSheet->getTitle() - ); - } - } - } - } - $xmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $fileDrawing))->children("http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"); - - if ($xmlDrawing->oneCellAnchor) { - foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) { - if ($oneCellAnchor->pic->blipFill) { - $blip = $oneCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip; - $xfrm = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm; - $outerShdw = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw; - $objDrawing = new PHPWord_Worksheet_Drawing; - $objDrawing->setName((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name")); - $objDrawing->setDescription((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr")); - $objDrawing->setPath("zip://".PHPWord_Shared_File::realpath($pFilename)."#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false); - $objDrawing->setCoordinates(PHPWord_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1)); - $objDrawing->setOffsetX(PHPWord_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff)); - $objDrawing->setOffsetY(PHPWord_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff)); - $objDrawing->setResizeProportional(false); - $objDrawing->setWidth(PHPWord_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cx"))); - $objDrawing->setHeight(PHPWord_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cy"))); - if ($xfrm) { - $objDrawing->setRotation(PHPWord_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot"))); - } - if ($outerShdw) { - $shadow = $objDrawing->getShadow(); - $shadow->setVisible(true); - $shadow->setBlurRadius(PHPWord_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad"))); - $shadow->setDistance(PHPWord_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist"))); - $shadow->setDirection(PHPWord_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir"))); - $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn")); - $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val")); - $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000); - } - $objDrawing->setWorksheet($docSheet); - } else { - // ? Can charts be positioned with a oneCellAnchor ? - $coordinates = PHPWord_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1); - $offsetX = PHPWord_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff); - $offsetY = PHPWord_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff); - $width = PHPWord_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cx")); - $height = PHPWord_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cy")); - } - } - } - if ($xmlDrawing->twoCellAnchor) { - foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) { - if ($twoCellAnchor->pic->blipFill) { - $blip = $twoCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip; - $xfrm = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm; - $outerShdw = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw; - $objDrawing = new PHPWord_Worksheet_Drawing; - $objDrawing->setName((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name")); - $objDrawing->setDescription((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr")); - $objDrawing->setPath("zip://".PHPWord_Shared_File::realpath($pFilename)."#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false); - $objDrawing->setCoordinates(PHPWord_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1)); - $objDrawing->setOffsetX(PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff)); - $objDrawing->setOffsetY(PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff)); - $objDrawing->setResizeProportional(false); - - $objDrawing->setWidth(PHPWord_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cx"))); - $objDrawing->setHeight(PHPWord_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cy"))); - - if ($xfrm) { - $objDrawing->setRotation(PHPWord_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot"))); - } - if ($outerShdw) { - $shadow = $objDrawing->getShadow(); - $shadow->setVisible(true); - $shadow->setBlurRadius(PHPWord_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad"))); - $shadow->setDistance(PHPWord_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist"))); - $shadow->setDirection(PHPWord_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir"))); - $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn")); - $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val")); - $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000); - } - $objDrawing->setWorksheet($docSheet); - } elseif(($this->_includeCharts) && ($twoCellAnchor->graphicFrame)) { - $fromCoordinate = PHPWord_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1); - $fromOffsetX = PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff); - $fromOffsetY = PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff); - $toCoordinate = PHPWord_Cell::stringFromColumnIndex((string) $twoCellAnchor->to->col) . ($twoCellAnchor->to->row + 1); - $toOffsetX = PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->to->colOff); - $toOffsetY = PHPWord_Shared_Drawing::EMUToPixels($twoCellAnchor->to->rowOff); - $graphic = $twoCellAnchor->graphicFrame->children("http://schemas.openxmlformats.org/drawingml/2006/main")->graphic; - $chartRef = $graphic->graphicData->children("http://schemas.openxmlformats.org/drawingml/2006/chart")->chart; - $thisChart = (string) $chartRef->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"); - - $chartDetails[$docSheet->getTitle().'!'.$thisChart] = - array( 'fromCoordinate' => $fromCoordinate, - 'fromOffsetX' => $fromOffsetX, - 'fromOffsetY' => $fromOffsetY, - 'toCoordinate' => $toCoordinate, - 'toOffsetX' => $toOffsetX, - 'toOffsetY' => $toOffsetY, - 'worksheetTitle' => $docSheet->getTitle() - ); - } - } - } - - } - } - } - - // Loop through definedNames - if ($xmlWorkbook->definedNames) { - foreach ($xmlWorkbook->definedNames->definedName as $definedName) { - // Extract range - $extractedRange = (string)$definedName; - $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange); - if (($spos = strpos($extractedRange,'!')) !== false) { - $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos)); - } else { - $extractedRange = str_replace('$', '', $extractedRange); - } - - // Valid range? - if (stripos((string)$definedName, '#REF!') !== FALSE || $extractedRange == '') { + $archive = "$dir/_rels/" . basename($rel["Target"]) . ".rels"; + $relsDoc = simplexml_load_string($this->getFromZipArchive($zip, $archive)); + $relsDoc->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006//relationships"); + $xpath = self::array_item($relsDoc->xpath("rel:Relationship[@Type='" . "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); + $xmlDoc = simplexml_load_string($this->getFromZipArchive($zip, "{$rel['Target']}")); + if ($xmlDoc->body) { + $section = $word->createSection(); + foreach ($xmlDoc->body->children() as $element) { + switch ($element->getName()) { + case 'p': + if ($element->pPr->sectPr) { + $section = $word->createSection(); continue; } - - // Some definedNames are only applicable if we are on the same sheet... - if ((string)$definedName['localSheetId'] != '' && (string)$definedName['localSheetId'] == $sheetId) { - // Switch on type - switch ((string)$definedName['name']) { - - case '_xlnm._FilterDatabase': - if ((string)$definedName['hidden'] !== '1') { - $docSheet->getAutoFilter()->setRange($extractedRange); - } - break; - - case '_xlnm.Print_Titles': - // Split $extractedRange - $extractedRange = explode(',', $extractedRange); - - // Set print titles - foreach ($extractedRange as $range) { - $matches = array(); - $range = str_replace('$', '', $range); - - // check for repeating columns, e g. 'A:A' or 'A:D' - if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) { - $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($matches[1], $matches[2])); - } - // check for repeating rows, e.g. '1:1' or '1:5' - elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) { - $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($matches[1], $matches[2])); - } - } - break; - - case '_xlnm.Print_Area': - $rangeSets = explode(',', $extractedRange); // FIXME: what if sheetname contains comma? - $newRangeSets = array(); - foreach($rangeSets as $rangeSet) { - $range = explode('!', $rangeSet); // FIXME: what if sheetname contains exclamation mark? - $rangeSet = isset($range[1]) ? $range[1] : $range[0]; - if (strpos($rangeSet, ':') === FALSE) { - $rangeSet = $rangeSet . ':' . $rangeSet; - } - $newRangeSets[] = str_replace('$', '', $rangeSet); - } - $docSheet->getPageSetup()->setPrintArea(implode(',',$newRangeSets)); - break; - - default: - break; - } - } - } - } - - // Next sheet id - ++$sheetId; - } - - // Loop through definedNames - if ($xmlWorkbook->definedNames) { - foreach ($xmlWorkbook->definedNames->definedName as $definedName) { - // Extract range - $extractedRange = (string)$definedName; - $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange); - if (($spos = strpos($extractedRange,'!')) !== false) { - $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos)); - } else { - $extractedRange = str_replace('$', '', $extractedRange); - } - - // Valid range? - if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') { - continue; - } - - // Some definedNames are only applicable if we are on the same sheet... - if ((string)$definedName['localSheetId'] != '') { - // Local defined name - // Switch on type - switch ((string)$definedName['name']) { - - case '_xlnm._FilterDatabase': - case '_xlnm.Print_Titles': - case '_xlnm.Print_Area': - break; - - default: - if ($mapSheetId[(integer) $definedName['localSheetId']] !== null) { - $range = explode('!', (string)$definedName); - if (count($range) == 2) { - $range[0] = str_replace("''", "'", $range[0]); - $range[0] = str_replace("'", "", $range[0]); - if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) { - $extractedRange = str_replace('$', '', $range[1]); - $scope = $docSheet->getParent()->getSheet($mapSheetId[(integer) $definedName['localSheetId']]); - $excel->addNamedRange( new PHPWord_NamedRange((string)$definedName['name'], $worksheet, $extractedRange, true, $scope) ); - } - } + if ($element->r) { + if (count($element->r) == 1) { + $section->addText($element->r->t); + } else { + $textRun = $section->createTextRun(); + foreach ($element->r as $r) { + $textRun->addText($r->t); } - break; + } + } else { + $section->addTextBreak(); } - } else if (!isset($definedName['localSheetId'])) { - // "Global" definedNames - $locatedSheet = null; - $extractedSheetName = ''; - if (strpos( (string)$definedName, '!' ) !== false) { - // Extract sheet name - $extractedSheetName = PHPWord_Worksheet::extractSheetTitle( (string)$definedName, true ); - $extractedSheetName = $extractedSheetName[0]; - - // Locate sheet - $locatedSheet = $excel->getSheetByName($extractedSheetName); - - // Modify range - $range = explode('!', $extractedRange); - $extractedRange = isset($range[1]) ? $range[1] : $range[0]; - } - - if ($locatedSheet !== NULL) { - $excel->addNamedRange( new PHPWord_NamedRange((string)$definedName['name'], $locatedSheet, $extractedRange, false) ); - } - } + break; } } } - - if ((!$this->_readDataOnly) || (!empty($this->_loadSheetsOnly))) { - // active sheet index - $activeTab = intval($xmlWorkbook->bookViews->workbookView["activeTab"]); // refers to old sheet index - - // keep active sheet index if sheet is still loaded, else first sheet is set as the active - if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) { - $excel->setActiveSheetIndex($mapSheetId[$activeTab]); - } else { - if ($excel->getSheetCount() == 0) { - $excel->createSheet(); - } - $excel->setActiveSheetIndex(0); - } - } - break; - } - - } - - - if (!$this->_readDataOnly) { - $contentTypes = simplexml_load_string($this->_getFromZipArchive($zip, "[Content_Types].xml")); - foreach ($contentTypes->Override as $contentType) { - switch ($contentType["ContentType"]) { - case "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": - if ($this->_includeCharts) { - $chartEntryRef = ltrim($contentType['PartName'],'/'); - $chartElements = simplexml_load_string($this->_getFromZipArchive($zip, $chartEntryRef)); - $objChart = PHPWord_Reader_Word2007_Chart::readChart($chartElements,basename($chartEntryRef,'.xml')); - -// echo 'Chart ',$chartEntryRef,'
'; -// var_dump($charts[$chartEntryRef]); -// - if (isset($charts[$chartEntryRef])) { - $chartPositionRef = $charts[$chartEntryRef]['sheet'].'!'.$charts[$chartEntryRef]['id']; -// echo 'Position Ref ',$chartPositionRef,'
'; - if (isset($chartDetails[$chartPositionRef])) { -// var_dump($chartDetails[$chartPositionRef]); - - $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); - $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet'])); - $objChart->setTopLeftPosition( $chartDetails[$chartPositionRef]['fromCoordinate'], - $chartDetails[$chartPositionRef]['fromOffsetX'], - $chartDetails[$chartPositionRef]['fromOffsetY'] - ); - $objChart->setBottomRightPosition( $chartDetails[$chartPositionRef]['toCoordinate'], - $chartDetails[$chartPositionRef]['toOffsetX'], - $chartDetails[$chartPositionRef]['toOffsetY'] - ); - } - } - } - } + break; } } $zip->close(); - return $excel; - } - - - private static function _readColor($color, $background=FALSE) { - if (isset($color["rgb"])) { - return (string)$color["rgb"]; - } else if (isset($color["indexed"])) { - return PHPWord_Style_Color::indexedColor($color["indexed"]-7,$background)->getARGB(); - } else if (isset($color["theme"])) { - if (self::$_theme !== NULL) { - $returnColour = self::$_theme->getColourByIndex((int)$color["theme"]); - if (isset($color["tint"])) { - $tintAdjust = (float) $color["tint"]; - $returnColour = PHPWord_Style_Color::changeBrightness($returnColour, $tintAdjust); - } - return 'FF'.$returnColour; - } - } - - if ($background) { - return 'FFFFFFFF'; - } - return 'FF000000'; - } - - - private static function _readStyle($docStyle, $style) { - // format code -// if (isset($style->numFmt)) { -// if (isset($style->numFmt['formatCode'])) { -// $docStyle->getNumberFormat()->setFormatCode((string) $style->numFmt['formatCode']); -// } else { - $docStyle->getNumberFormat()->setFormatCode($style->numFmt); -// } -// } - - // font - if (isset($style->font)) { - $docStyle->getFont()->setName((string) $style->font->name["val"]); - $docStyle->getFont()->setSize((string) $style->font->sz["val"]); - if (isset($style->font->b)) { - $docStyle->getFont()->setBold(!isset($style->font->b["val"]) || self::boolean((string) $style->font->b["val"])); - } - if (isset($style->font->i)) { - $docStyle->getFont()->setItalic(!isset($style->font->i["val"]) || self::boolean((string) $style->font->i["val"])); - } - if (isset($style->font->strike)) { - $docStyle->getFont()->setStrikethrough(!isset($style->font->strike["val"]) || self::boolean((string) $style->font->strike["val"])); - } - $docStyle->getFont()->getColor()->setARGB(self::_readColor($style->font->color)); - - if (isset($style->font->u) && !isset($style->font->u["val"])) { - $docStyle->getFont()->setUnderline(PHPWord_Style_Font::UNDERLINE_SINGLE); - } else if (isset($style->font->u) && isset($style->font->u["val"])) { - $docStyle->getFont()->setUnderline((string)$style->font->u["val"]); - } - - if (isset($style->font->vertAlign) && isset($style->font->vertAlign["val"])) { - $vertAlign = strtolower((string)$style->font->vertAlign["val"]); - if ($vertAlign == 'superscript') { - $docStyle->getFont()->setSuperScript(true); - } - if ($vertAlign == 'subscript') { - $docStyle->getFont()->setSubScript(true); - } - } - } - - // fill - if (isset($style->fill)) { - if ($style->fill->gradientFill) { - $gradientFill = $style->fill->gradientFill[0]; - if(!empty($gradientFill["type"])) { - $docStyle->getFill()->setFillType((string) $gradientFill["type"]); - } - $docStyle->getFill()->setRotation(floatval($gradientFill["degree"])); - $gradientFill->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); - $docStyle->getFill()->getStartColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=0]"))->color) ); - $docStyle->getFill()->getEndColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=1]"))->color) ); - } elseif ($style->fill->patternFill) { - $patternType = (string)$style->fill->patternFill["patternType"] != '' ? (string)$style->fill->patternFill["patternType"] : 'solid'; - $docStyle->getFill()->setFillType($patternType); - if ($style->fill->patternFill->fgColor) { - $docStyle->getFill()->getStartColor()->setARGB(self::_readColor($style->fill->patternFill->fgColor,true)); - } else { - $docStyle->getFill()->getStartColor()->setARGB('FF000000'); - } - if ($style->fill->patternFill->bgColor) { - $docStyle->getFill()->getEndColor()->setARGB(self::_readColor($style->fill->patternFill->bgColor,true)); - } - } - } - - // border - if (isset($style->border)) { - $diagonalUp = self::boolean((string) $style->border["diagonalUp"]); - $diagonalDown = self::boolean((string) $style->border["diagonalDown"]); - if (!$diagonalUp && !$diagonalDown) { - $docStyle->getBorders()->setDiagonalDirection(PHPWord_Style_Borders::DIAGONAL_NONE); - } elseif ($diagonalUp && !$diagonalDown) { - $docStyle->getBorders()->setDiagonalDirection(PHPWord_Style_Borders::DIAGONAL_UP); - } elseif (!$diagonalUp && $diagonalDown) { - $docStyle->getBorders()->setDiagonalDirection(PHPWord_Style_Borders::DIAGONAL_DOWN); - } else { - $docStyle->getBorders()->setDiagonalDirection(PHPWord_Style_Borders::DIAGONAL_BOTH); - } - self::_readBorder($docStyle->getBorders()->getLeft(), $style->border->left); - self::_readBorder($docStyle->getBorders()->getRight(), $style->border->right); - self::_readBorder($docStyle->getBorders()->getTop(), $style->border->top); - self::_readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom); - self::_readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal); - } - - // alignment - if (isset($style->alignment)) { - $docStyle->getAlignment()->setHorizontal((string) $style->alignment["horizontal"]); - $docStyle->getAlignment()->setVertical((string) $style->alignment["vertical"]); - - $textRotation = 0; - if ((int)$style->alignment["textRotation"] <= 90) { - $textRotation = (int)$style->alignment["textRotation"]; - } else if ((int)$style->alignment["textRotation"] > 90) { - $textRotation = 90 - (int)$style->alignment["textRotation"]; - } - - $docStyle->getAlignment()->setTextRotation(intval($textRotation)); - $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment["wrapText"])); - $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment["shrinkToFit"])); - $docStyle->getAlignment()->setIndent( intval((string)$style->alignment["indent"]) > 0 ? intval((string)$style->alignment["indent"]) : 0 ); - } - - // protection - if (isset($style->protection)) { - if (isset($style->protection['locked'])) { - if (self::boolean((string) $style->protection['locked'])) { - $docStyle->getProtection()->setLocked(PHPWord_Style_Protection::PROTECTION_PROTECTED); - } else { - $docStyle->getProtection()->setLocked(PHPWord_Style_Protection::PROTECTION_UNPROTECTED); - } - } - - if (isset($style->protection['hidden'])) { - if (self::boolean((string) $style->protection['hidden'])) { - $docStyle->getProtection()->setHidden(PHPWord_Style_Protection::PROTECTION_PROTECTED); - } else { - $docStyle->getProtection()->setHidden(PHPWord_Style_Protection::PROTECTION_UNPROTECTED); - } - } - } - - // top-level style settings - if (isset($style->quotePrefix)) { - $docStyle->setQuotePrefix($style->quotePrefix); - } - } - - - private static function _readBorder($docBorder, $eleBorder) { - if (isset($eleBorder["style"])) { - $docBorder->setBorderStyle((string) $eleBorder["style"]); - } - if (isset($eleBorder->color)) { - $docBorder->getColor()->setARGB(self::_readColor($eleBorder->color)); - } - } - - - private function _parseRichText($is = null) { - $value = new PHPWord_RichText(); - - if (isset($is->t)) { - $value->createText( PHPWord_Shared_String::ControlCharacterOOXML2PHP( (string) $is->t ) ); - } else { - foreach ($is->r as $run) { - if (!isset($run->rPr)) { - $objText = $value->createText( PHPWord_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) ); - - } else { - $objText = $value->createTextRun( PHPWord_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) ); - - if (isset($run->rPr->rFont["val"])) { - $objText->getFont()->setName((string) $run->rPr->rFont["val"]); - } - - if (isset($run->rPr->sz["val"])) { - $objText->getFont()->setSize((string) $run->rPr->sz["val"]); - } - - if (isset($run->rPr->color)) { - $objText->getFont()->setColor( new PHPWord_Style_Color( self::_readColor($run->rPr->color) ) ); - } - - if ((isset($run->rPr->b["val"]) && self::boolean((string) $run->rPr->b["val"])) || - (isset($run->rPr->b) && !isset($run->rPr->b["val"]))) { - $objText->getFont()->setBold(TRUE); - } - - if ((isset($run->rPr->i["val"]) && self::boolean((string) $run->rPr->i["val"])) || - (isset($run->rPr->i) && !isset($run->rPr->i["val"]))) { - $objText->getFont()->setItalic(TRUE); - } - - if (isset($run->rPr->vertAlign) && isset($run->rPr->vertAlign["val"])) { - $vertAlign = strtolower((string)$run->rPr->vertAlign["val"]); - if ($vertAlign == 'superscript') { - $objText->getFont()->setSuperScript(TRUE); - } - if ($vertAlign == 'subscript') { - $objText->getFont()->setSubScript(TRUE); - } - } - - if (isset($run->rPr->u) && !isset($run->rPr->u["val"])) { - $objText->getFont()->setUnderline(PHPWord_Style_Font::UNDERLINE_SINGLE); - } else if (isset($run->rPr->u) && isset($run->rPr->u["val"])) { - $objText->getFont()->setUnderline((string)$run->rPr->u["val"]); - } - - if ((isset($run->rPr->strike["val"]) && self::boolean((string) $run->rPr->strike["val"])) || - (isset($run->rPr->strike) && !isset($run->rPr->strike["val"]))) { - $objText->getFont()->setStrikethrough(TRUE); - } - } - } - } - - return $value; - } - - private function _readRibbon($excel, $customUITarget, $zip) - { - $baseDir = dirname($customUITarget); - $nameCustomUI = basename($customUITarget); - // get the xml file (ribbon) - $localRibbon = $this->_getFromZipArchive($zip, $customUITarget); - $customUIImagesNames = array(); - $customUIImagesBinaries = array(); - // something like customUI/_rels/customUI.xml.rels - $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels'; - $dataRels = $this->_getFromZipArchive($zip, $pathRels); - if ($dataRels) { - // exists and not empty if the ribbon have some pictures (other than internal MSO) - $UIRels = simplexml_load_string($dataRels); - if ($UIRels) { - // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image - foreach ($UIRels->Relationship as $ele) { - if ($ele["Type"] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { - // an image ? - $customUIImagesNames[(string) $ele['Id']] = (string)$ele['Target']; - $customUIImagesBinaries[(string)$ele['Target']] = $this->_getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']); - } - } - } - } - if ($localRibbon) { - $excel->setRibbonXMLData($customUITarget, $localRibbon); - if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) { - $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries); - } else { - $excel->setRibbonBinObjects(NULL); - } - } else { - $excel->setRibbonXMLData(NULL); - $excel->setRibbonBinObjects(NULL); - } + return $word; } private static function array_item($array, $key = 0) { return (isset($array[$key]) ? $array[$key] : null); } - - private static function dir_add($base, $add) { - return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add"); - } - - - private static function toCSSArray($style) { - $style = str_replace(array("\r","\n"), "", $style); - - $temp = explode(';', $style); - $style = array(); - foreach ($temp as $item) { - $item = explode(':', $item); - - if (strpos($item[1], 'px') !== false) { - $item[1] = str_replace('px', '', $item[1]); - } - if (strpos($item[1], 'pt') !== false) { - $item[1] = str_replace('pt', '', $item[1]); - $item[1] = PHPWord_Shared_Font::fontSizeToPixels($item[1]); - } - if (strpos($item[1], 'in') !== false) { - $item[1] = str_replace('in', '', $item[1]); - $item[1] = PHPWord_Shared_Font::inchSizeToPixels($item[1]); - } - if (strpos($item[1], 'cm') !== false) { - $item[1] = str_replace('cm', '', $item[1]); - $item[1] = PHPWord_Shared_Font::centimeterSizeToPixels($item[1]); - } - - $style[$item[0]] = $item[1]; - } - - return $style; - } - - private static function boolean($value = NULL) - { - if (is_numeric($value) || is_object($value)) { - return (bool) $value; - } - return ($value === 'true' || $value === 'TRUE') ? TRUE : FALSE; - } } diff --git a/samples/Sample_10_ReadWord2007.php b/samples/Sample_10_ReadWord2007.php new file mode 100644 index 00000000..d7f81925 --- /dev/null +++ b/samples/Sample_10_ReadWord2007.php @@ -0,0 +1,78 @@ +'); + +require_once '../Classes/PHPWord.php'; + +$files = array( + "Sample_01_SimpleText.docx", + "Sample_02_TabStops.docx", + "Sample_03_Sections.docx", + "Sample_04_Textrun.docx", + "Sample_05_Multicolumn.docx", + "Sample_06_Footnote.docx", + "Sample_07_TemplateCloneRow.docx", + "Sample_08_ParagraphPagination.docx", + "Sample_09_Tables.docx", +); + +foreach ($files as $file) { + echo '
'; + echo '

', date('H:i:s'), " Load from {$file} with contents:

"; + unset($PHPWord); + try { + $PHPWord = PHPWord_IOFactory::load($file); + } catch (Exception $e) { + echo '

Caught exception: ', $e->getMessage(), '

'; + continue; + } + $sections = $PHPWord->getSections(); + $countSections = count($sections); + $pSection = 0; + + if ($countSections > 0) { + foreach ($sections as $section) { + $pSection++; + echo "

Section {$pSection}:

"; + $elements = $section->getElements(); + foreach ($elements as $element) { + if ($element instanceof PHPWord_Section_Text) { + echo '

' . htmlspecialchars($element->getText()) . '

'; + } elseif ($element instanceof PHPWord_Section_TextRun) { + $subelements = $element->getElements(); + echo '

'; + if (count($subelements) > 0) { + foreach ($subelements as $subelement) { + if ($subelement instanceof PHPWord_Section_Text) { + echo htmlspecialchars($subelement->getText()); + } + } + } + echo '

'; + } elseif ($element instanceof PHPWord_Section_Link) { + echo '

Link not yet supported.

'; + } elseif ($element instanceof PHPWord_Section_Title) { + echo '

Title not yet supported.

'; + } elseif ($element instanceof PHPWord_Section_TextBreak) { + echo '
'; + } elseif ($element instanceof PHPWord_Section_PageBreak) { + echo '

Page break not yet supported.

'; + } elseif ($element instanceof PHPWord_Section_Table) { + echo '

Table not yet supported.

'; + } elseif ($element instanceof PHPWord_Section_ListItem) { + echo '

List item not yet supported.

'; + } elseif ($element instanceof PHPWord_Section_Image || + $element instanceof PHPWord_Section_MemoryImage + ) { + echo '

Image not yet supported.

'; + } elseif ($element instanceof PHPWord_TOC) { + echo '

TOC not yet supported.

'; + } elseif($element instanceof PHPWord_Section_Footnote) { + echo '

Footnote not yet supported.

'; + } + } + } + } +} + From fa2878e530606e495787ac261c8aea805bd7d981 Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Tue, 11 Mar 2014 03:01:12 +0700 Subject: [PATCH 03/17] Cleaning up code --- Classes/PHPWord/IOFactory.php | 4 ++-- Classes/PHPWord/Reader/Word2007.php | 15 +++++++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/Classes/PHPWord/IOFactory.php b/Classes/PHPWord/IOFactory.php index 649bcb06..7780a8ca 100755 --- a/Classes/PHPWord/IOFactory.php +++ b/Classes/PHPWord/IOFactory.php @@ -38,7 +38,7 @@ class PHPWord_IOFactory */ private static $_searchLocations = array( array('type' => 'IWriter', 'path' => 'PHPWord/Writer/{0}.php', 'class' => 'PHPWord_Writer_{0}'), - array( 'type' => 'IReader', 'path' => 'PHPWord/Reader/{0}.php', 'class' => 'PHPWord_Reader_{0}' ), + array('type' => 'IReader', 'path' => 'PHPWord/Reader/{0}.php', 'class' => 'PHPWord_Reader_{0}' ), ); /** @@ -140,7 +140,7 @@ class PHPWord_IOFactory } } - throw new PHPExcel_Reader_Exception("No $searchType found for type $readerType"); + throw new PHPWord_Exception("No $searchType found for type $readerType"); } /** diff --git a/Classes/PHPWord/Reader/Word2007.php b/Classes/PHPWord/Reader/Word2007.php index 5cc11566..c17d4074 100644 --- a/Classes/PHPWord/Reader/Word2007.php +++ b/Classes/PHPWord/Reader/Word2007.php @@ -48,8 +48,7 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord * Can the current PHPWord_Reader_IReader read the file? * * @param string $pFilename - * @return boolean - * @throws PHPWord_Exception + * @return bool */ public function canRead($pFilename) { @@ -117,6 +116,7 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord * Loads PHPWord from file * * @param string $pFilename + * @return PHPWord */ public function load($pFilename) { @@ -189,7 +189,8 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord $archive = "$dir/_rels/" . basename($rel["Target"]) . ".rels"; $relsDoc = simplexml_load_string($this->getFromZipArchive($zip, $archive)); $relsDoc->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006//relationships"); - $xpath = self::array_item($relsDoc->xpath("rel:Relationship[@Type='" . "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); + $xpath = self::array_item($relsDoc->xpath("rel:Relationship[@Type='" . + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); $xmlDoc = simplexml_load_string($this->getFromZipArchive($zip, "{$rel['Target']}")); if ($xmlDoc->body) { $section = $word->createSection(); @@ -219,12 +220,18 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord break; } } - $zip->close(); return $word; } + /** + * Get array item + * + * @param array $array + * @param mixed $key + * @return mixed|null + */ private static function array_item($array, $key = 0) { return (isset($array[$key]) ? $array[$key] : null); } From ec514f310fdad3958c30e4ddedec29722c5ea4d9 Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Tue, 11 Mar 2014 16:27:42 +0700 Subject: [PATCH 04/17] Reader: Read section settings and font/paragraph styles --- Classes/PHPWord/Reader/Word2007.php | 289 ++++++++++++++++-- Classes/PHPWord/Section.php | 9 + Classes/PHPWord/Shared/File.php | 2 +- Classes/PHPWord/Style/Paragraph.php | 2 +- Classes/PHPWord/Writer/Word2007/Base.php | 6 +- changelog.txt | 1 + samples/Sample_10_ReadWord2007.php | 91 ++---- samples/resources/Sample_10_ReadWord2007.docx | Bin 0 -> 22104 bytes samples/results/.gitkeep | 0 9 files changed, 295 insertions(+), 105 deletions(-) create mode 100644 samples/resources/Sample_10_ReadWord2007.docx create mode 100644 samples/results/.gitkeep diff --git a/Classes/PHPWord/Reader/Word2007.php b/Classes/PHPWord/Reader/Word2007.php index c17d4074..78a9875c 100644 --- a/Classes/PHPWord/Reader/Word2007.php +++ b/Classes/PHPWord/Reader/Word2007.php @@ -35,7 +35,8 @@ if (!defined('PHPWORD_BASE_PATH')) { /** * PHPWord_Reader_Word2007 */ -class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord_Reader_IReader +class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements + PHPWord_Reader_IReader { /** @@ -54,7 +55,8 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord { // Check if file exists if (!file_exists($pFilename)) { - throw new PHPWord_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + throw new PHPWord_Exception("Could not open " . $pFilename . + " for reading! File does not exist."); } $return = false; @@ -86,9 +88,13 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord * * @param ZipArchive $archive * @param string $fileName + * @param bool $removeNamespace */ - public function getFromZipArchive($archive, $fileName = '') - { + public function getFromZipArchive( + $archive, + $fileName = '', + $removeNamespace = false + ) { // Root-relative paths if (strpos($fileName, '//') !== false) { @@ -103,9 +109,9 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord $contents = $archive->getFromName(substr($fileName, 1)); } - // Stupid hack for namespace - if ($contents != '' && $fileName = 'word/document.xml') { - $contents = preg_replace('~(open($pFilename); - // Read relationships + // Read properties and documents $rels = simplexml_load_string($this->getFromZipArchive($zip, "_rels/.rels")); foreach ($rels->Relationship as $rel) { switch ($rel["Type"]) { // Core properties - case "http://schemas.openxmlformats.org/package/2006//relationships/metadata/core-properties": + case "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties": $xmlCore = simplexml_load_string($this->getFromZipArchive($zip, "{$rel['Target']}")); if (is_object($xmlCore)) { $xmlCore->registerXPathNamespace("dc", "http://purl.org/dc/elements/1.1/"); $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/"); - $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006//metadata/core-properties"); + $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); $docProps = $word->getProperties(); $docProps->setCreator((string) self::array_item($xmlCore->xpath("dc:creator"))); $docProps->setLastModifiedBy((string) self::array_item($xmlCore->xpath("cp:lastModifiedBy"))); @@ -188,32 +195,75 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord $dir = dirname($rel["Target"]); $archive = "$dir/_rels/" . basename($rel["Target"]) . ".rels"; $relsDoc = simplexml_load_string($this->getFromZipArchive($zip, $archive)); - $relsDoc->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006//relationships"); + $relsDoc->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); $xpath = self::array_item($relsDoc->xpath("rel:Relationship[@Type='" . "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); - $xmlDoc = simplexml_load_string($this->getFromZipArchive($zip, "{$rel['Target']}")); - if ($xmlDoc->body) { + $xmlDoc = simplexml_load_string($this->getFromZipArchive($zip, "{$rel['Target']}", true)); + if (is_object($xmlDoc)) { $section = $word->createSection(); - foreach ($xmlDoc->body->children() as $element) { - switch ($element->getName()) { - case 'p': - if ($element->pPr->sectPr) { - $section = $word->createSection(); - continue; - } - if ($element->r) { - if (count($element->r) == 1) { - $section->addText($element->r->t); - } else { - $textRun = $section->createTextRun(); - foreach ($element->r as $r) { - $textRun->addText($r->t); - } - } + + foreach ($xmlDoc->body->children() as $elm) { + $elmName = $elm->getName(); + if ($elmName == 'p') { // Paragraph/section + // Create new section if section section found + if ($elm->pPr->sectPr) { + $section->setSettings($this->loadSectionSettings($elm->pPr)); + $section = $word->createSection(); + continue; + } + // Has w:r? It's either text or textrun + if ($elm->r) { + // w:r = 1? It's a plain paragraph + if (count($elm->r) == 1) { + $section->addText($elm->r->t, + $this->loadFontStyle($elm->r)); + // w:r more than 1? It's a textrun } else { - $section->addTextBreak(); + $textRun = $section->createTextRun(); + foreach ($elm->r as $r) { + $textRun->addText($r->t, + $this->loadFontStyle($r)); + } } - break; + // No, it's a textbreak + } else { + $section->addTextBreak(); + } + } elseif ($elmName == 'sectPr') { + // Last section setting + $section->setSettings($this->loadSectionSettings($xmlDoc->body)); + } + } + } + break; + } + } + + // Read styles + $docRels = simplexml_load_string($this->getFromZipArchive($zip, "word/_rels/document.xml.rels")); + foreach ($docRels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles": + $xmlStyle = simplexml_load_string($this->getFromZipArchive($zip, "word/{$rel['Target']}", true)); + if (is_object($xmlStyle)) { + foreach ($xmlStyle->children() as $elm) { + if ($elm->getName() != 'style') { + continue; + } + unset($pStyle); + unset($fStyle); + $hasParagraphStyle = $elm->pPr && ($elm->pPr != ''); + $hasFontStyle = $elm->rPr && ($elm->rPr != ''); + $styleName = (string)$elm->name['val']; + if ($hasParagraphStyle) { + $pStyle = $this->loadParagraphStyle($elm); + if (!$hasFontStyle) { + $word->addParagraphStyle($styleName, $pStyle); + } + } + if ($hasFontStyle) { + $fStyle = $this->loadFontStyle($elm); + $word->addFontStyle($styleName, $fStyle, $pStyle); } } } @@ -225,6 +275,181 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord return $word; } + /** + * Load section settings from SimpleXMLElement + * + * @param SimpleXMLElement $elm + * @return array|string|null + * + * @todo Implement gutter + */ + private function loadSectionSettings($elm) + { + if ($xml = $elm->sectPr) { + $setting = array(); + if ($xml->type) { + $setting['breakType'] = (string)$xml->type['val']; + } + if ($xml->pgSz) { + if (isset($xml->pgSz['w'])) { + $setting['pageSizeW'] = (int)$xml->pgSz['w']; + } + if (isset($xml->pgSz['h'])) { + $setting['pageSizeH'] = (int)$xml->pgSz['h']; + } + if (isset($xml->pgSz['orient'])) { + $setting['orientation'] = (string)$xml->pgSz['orient']; + } + } + if ($xml->pgMar) { + if (isset($xml->pgMar['top'])) { + $setting['topMargin'] = (int)$xml->pgMar['top']; + } + if (isset($xml->pgMar['left'])) { + $setting['leftMargin'] = (int)$xml->pgMar['left']; + } + if (isset($xml->pgMar['bottom'])) { + $setting['bottomMargin'] = (int)$xml->pgMar['bottom']; + } + if (isset($xml->pgMar['right'])) { + $setting['rightMargin'] = (int)$xml->pgMar['right']; + } + if (isset($xml->pgMar['header'])) { + $setting['headerHeight'] = (int)$xml->pgMar['header']; + } + if (isset($xml->pgMar['footer'])) { + $setting['footerHeight'] = (int)$xml->pgMar['footer']; + } + if (isset($xml->pgMar['gutter'])) { + // $setting['gutter'] = (int)$xml->pgMar['gutter']; + } + } + if ($xml->cols) { + if (isset($xml->cols['num'])) { + $setting['colsNum'] = (int)$xml->cols['num']; + } + if (isset($xml->cols['space'])) { + $setting['colsSpace'] = (int)$xml->cols['space']; + } + } + return $setting; + } else { + return null; + } + } + + /** + * Load paragraph style from SimpleXMLElement + * + * @param SimpleXMLElement $elm + * @return array|string|null + */ + private function loadParagraphStyle($elm) + { + if ($xml = $elm->pPr) { + if ($xml->pStyle) { + return (string)$xml->pStyle['val']; + } + $style = array(); + if ($xml->jc) { + $style['align'] = (string)$xml->jc['val']; + } + if ($xml->ind) { + if (isset($xml->ind->left)) { + $style['indent'] = (int)$xml->ind->left; + } + if (isset($xml->ind->hanging)) { + $style['hanging'] = (int)$xml->ind->hanging; + } + if (isset($xml->ind->line)) { + $style['spacing'] = (int)$xml->ind->line; + } + } + if ($xml->spacing) { + if (isset($xml->spacing['after'])) { + $style['spaceAfter'] = (int)$xml->spacing['after']; + } + if (isset($xml->spacing['before'])) { + $style['spaceBefore'] = (int)$xml->spacing['before']; + } + if (isset($xml->spacing['line'])) { + $style['spacing'] = (int)$xml->spacing['line']; + } + } + if ($xml->basedOn) { + $style['basedOn'] = (string)$xml->basedOn['val']; + } + if ($xml->next) { + $style['next'] = (string)$xml->next['val']; + } + if ($xml->widowControl) { + $style['widowControl'] = false; + } + if ($xml->keepNext) { + $style['keepNext'] = true; + } + if ($xml->keepLines) { + $style['keepLines'] = true; + } + if ($xml->pageBreakBefore) { + $style['pageBreakBefore'] = true; + } + return $style; + } else { + return null; + } + } + + /** + * Load font style from SimpleXMLElement + * + * @param SimpleXMLElement $elm + * @return array|string|null + */ + private function loadFontStyle($elm) + { + if ($xml = $elm->rPr) { + if ($xml->rStyle) { + return (string)$xml->rStyle['val']; + } + $style = array(); + if ($xml->rFonts) { + $style['name'] = (string)$xml->rFonts['ascii']; + } + if ($xml->sz) { + $style['size'] = (int)$xml->sz['val'] / 2; + } + if ($xml->color) { + $style['color'] = (string)$xml->color['val']; + } + if ($xml->b) { + $style['bold'] = true; + } + if ($xml->i) { + $style['italic'] = true; + } + if ($xml->u) { + $style['underline'] = (string)$xml->u['val']; + } + if ($xml->strike) { + $style['strikethrough'] = true; + } + if ($xml->highlight) { + $style['fgColor'] = (string)$xml->highlight['val']; + } + if ($xml->vertAlign) { + if ($xml->vertAlign['val'] == 'superscript') { + $style['superScript'] = true; + } else { + $style['subScript'] = true; + } + } + return $style; + } else { + return null; + } + } + /** * Get array item * diff --git a/Classes/PHPWord/Section.php b/Classes/PHPWord/Section.php index c50e2d0c..3ed55ee5 100755 --- a/Classes/PHPWord/Section.php +++ b/Classes/PHPWord/Section.php @@ -77,7 +77,16 @@ class PHPWord_Section { $this->_sectionCount = $sectionCount; $this->_settings = new PHPWord_Section_Settings(); + $this->setSettings($settings); + } + /** + * Set Section Settings + * + * @param array $settings + */ + public function setSettings($settings = null) + { if (!is_null($settings) && is_array($settings)) { foreach ($settings as $key => $value) { if (substr($key, 0, 1) != '_') { diff --git a/Classes/PHPWord/Shared/File.php b/Classes/PHPWord/Shared/File.php index 7c1470fe..84cd2e84 100755 --- a/Classes/PHPWord/Shared/File.php +++ b/Classes/PHPWord/Shared/File.php @@ -76,7 +76,7 @@ class PHPWord_Shared_File // Found something? if ($returnValue == '' || is_null($returnValue)) { - $pathArray = split('/', $pFilename); + $pathArray = explode('/', $pFilename); while (in_array('..', $pathArray) && $pathArray[0] != '..') { for ($i = 0; $i < count($pathArray); ++$i) { if ($pathArray[$i] == '..' && $i > 0) { diff --git a/Classes/PHPWord/Style/Paragraph.php b/Classes/PHPWord/Style/Paragraph.php index bf0ae182..754589cb 100755 --- a/Classes/PHPWord/Style/Paragraph.php +++ b/Classes/PHPWord/Style/Paragraph.php @@ -506,4 +506,4 @@ class PHPWord_Style_Paragraph { return $this->lineHeight; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Writer/Word2007/Base.php b/Classes/PHPWord/Writer/Word2007/Base.php index 77f4d0d7..3ee0823e 100755 --- a/Classes/PHPWord/Writer/Word2007/Base.php +++ b/Classes/PHPWord/Writer/Word2007/Base.php @@ -128,8 +128,8 @@ class PHPWord_Writer_Word2007_Base extends PHPWord_Writer_Word2007_WriterPart protected function _writeParagraphStyle( PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Style_Paragraph $style, - $withoutPPR = false) - { + $withoutPPR = false + ) { $align = $style->getAlign(); $spacing = $style->getSpacing(); $spaceBefore = $style->getSpaceBefore(); @@ -926,4 +926,4 @@ class PHPWord_Writer_Word2007_Base extends PHPWord_Writer_Word2007_WriterPart $objWriter->endElement(); // w:p } } -} \ No newline at end of file +} diff --git a/changelog.txt b/changelog.txt index 2230f687..a76efb00 100755 --- a/changelog.txt +++ b/changelog.txt @@ -50,6 +50,7 @@ Changes in branch for release 0.7.1 : - Bugfix: (ivanlanin) GH-94 - General: PHPWord_Shared_Drawing::centimetersToPixels() conversion - Feature: (ivanlanin) - Paragraph: setTabs() function - Feature: (ivanlanin) GH-99 - General: Basic support for TextRun on ODT and RTF +- Feature: (ivanlanin) - Reader: Initial effort for Word2007 - QA: (Progi1984) - UnitTests Changes in branch for release 0.7.0 : diff --git a/samples/Sample_10_ReadWord2007.php b/samples/Sample_10_ReadWord2007.php index d7f81925..a837a574 100644 --- a/samples/Sample_10_ReadWord2007.php +++ b/samples/Sample_10_ReadWord2007.php @@ -5,74 +5,29 @@ define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '
'); require_once '../Classes/PHPWord.php'; -$files = array( - "Sample_01_SimpleText.docx", - "Sample_02_TabStops.docx", - "Sample_03_Sections.docx", - "Sample_04_Textrun.docx", - "Sample_05_Multicolumn.docx", - "Sample_06_Footnote.docx", - "Sample_07_TemplateCloneRow.docx", - "Sample_08_ParagraphPagination.docx", - "Sample_09_Tables.docx", -); +// Read contents +$sample = 'Sample_10_ReadWord2007'; +$source = "resources/{$sample}.docx"; +$target = "results/{$sample}"; +echo '

', date('H:i:s'), " Reading contents from `{$source}`

"; +$PHPWord = PHPWord_IOFactory::load($source); -foreach ($files as $file) { - echo '
'; - echo '

', date('H:i:s'), " Load from {$file} with contents:

"; - unset($PHPWord); - try { - $PHPWord = PHPWord_IOFactory::load($file); - } catch (Exception $e) { - echo '

Caught exception: ', $e->getMessage(), '

'; - continue; - } - $sections = $PHPWord->getSections(); - $countSections = count($sections); - $pSection = 0; +// Rewrite contents +echo date('H:i:s') , " Write to Word2007 format" , EOL; +$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007'); +$objWriter->save("{$sample}.docx"); +rename("{$sample}.docx", "{$target}.docx"); - if ($countSections > 0) { - foreach ($sections as $section) { - $pSection++; - echo "

Section {$pSection}:

"; - $elements = $section->getElements(); - foreach ($elements as $element) { - if ($element instanceof PHPWord_Section_Text) { - echo '

' . htmlspecialchars($element->getText()) . '

'; - } elseif ($element instanceof PHPWord_Section_TextRun) { - $subelements = $element->getElements(); - echo '

'; - if (count($subelements) > 0) { - foreach ($subelements as $subelement) { - if ($subelement instanceof PHPWord_Section_Text) { - echo htmlspecialchars($subelement->getText()); - } - } - } - echo '

'; - } elseif ($element instanceof PHPWord_Section_Link) { - echo '

Link not yet supported.

'; - } elseif ($element instanceof PHPWord_Section_Title) { - echo '

Title not yet supported.

'; - } elseif ($element instanceof PHPWord_Section_TextBreak) { - echo '
'; - } elseif ($element instanceof PHPWord_Section_PageBreak) { - echo '

Page break not yet supported.

'; - } elseif ($element instanceof PHPWord_Section_Table) { - echo '

Table not yet supported.

'; - } elseif ($element instanceof PHPWord_Section_ListItem) { - echo '

List item not yet supported.

'; - } elseif ($element instanceof PHPWord_Section_Image || - $element instanceof PHPWord_Section_MemoryImage - ) { - echo '

Image not yet supported.

'; - } elseif ($element instanceof PHPWord_TOC) { - echo '

TOC not yet supported.

'; - } elseif($element instanceof PHPWord_Section_Footnote) { - echo '

Footnote not yet supported.

'; - } - } - } - } -} +echo date('H:i:s') , ' Write to OpenDocumentText format' , EOL; +$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'ODText'); +$objWriter->save("{$sample}.odt"); +rename("{$sample}.odt", "{$target}.odt"); +echo date('H:i:s') , ' Write to RTF format' , EOL; +$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'RTF'); +$objWriter->save("{$sample}.rtf"); +rename("{$sample}.rtf", "{$target}.rtf"); + +// Echo memory peak usage +echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL; +echo date('H:i:s') , " Done writing file" , EOL; diff --git a/samples/resources/Sample_10_ReadWord2007.docx b/samples/resources/Sample_10_ReadWord2007.docx new file mode 100644 index 0000000000000000000000000000000000000000..fe8ec7acae8a53e80cf6219fed8b439465c7cea8 GIT binary patch literal 22104 zcmeFZgO@Hn(=R-pJ+`&Swr$(CZQHhO?6GZIdu-eGd~?70o_C$+KRBn?O06qN+}e0Db{!3fkH@8QVDND!JPkJ8ILo zSzG-s00AP)0|5Hr|9{v2#Us#|G-1#X>^mBP zqZ~eNEt^G&cU`+HCQywHw{psJ;|fOXALTA~y`hJu+4ei#$v|IDJ*Szy_w-By!t8N% z3Y_$}2p4JLM6*F_z2{dUwu^oVyqvpx+)_IdK}mFon|r`;3n#9EKp!)J%XIcH$}}IH z=)F{TQnBbZB%Vb(_o#muchCHeR(UfGEgdNkIY;_l!z#!=3@<*nM$dr2pWqWXywBH! z8hJc!;Q8}u80(vx+af?(cCSLh^j^bOFEp#y6}ORQw=tBb#rx>C3{ z){!$y+@x!@L%vgPoW%`vq8yB02i(xRW~Z)8Q!8*ZYHJ6bi=0g^MB34(*(VR74f?Qe zmp6cpI8GoInxANzzT8*HG3$d0Ca=(}<5zKcY%LuK5T^$TRGL zx7lgXEKdF`&I~~@UB+sHreJ6RiIR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w>?xn zBigR|;F9SZAy~;Pc!*f~C84oqTywJHIlm)fy7=F=G>S#Vn@q&@c8_?>pXv0L$kxN- z|2raLW_|psHPUlum11fXT<0|ja>wdLM0a^c-Ob|;*MN`bP_Me$O}`Z%e`XP?H0xXK z%0Cmnl=CUre>=b-XO93YN>JK=^^G0)rl4#F&ceSI&D}*ij%s9oZv&muI)FR)H{S!g7h%? ziNr3^f8?KX&6%U+q#C5p37u%zUO%43>8FNBanknu2`(ygjFU9$Nfk)j)h7y;;O`Uo zr+G~ZpDj_Hpk!nPw@>{7-wRfxIB8wrL;#_F{M~1&1f)D^`fK*fEk`Yq=Y&bcg g$;j%Vr>1`#Tnu!mh)a}=jGp*bC$93tyMN#P1ra)CCIA2c literal 0 HcmV?d00001 diff --git a/samples/results/.gitkeep b/samples/results/.gitkeep new file mode 100644 index 00000000..e69de29b From 4e3450e39f4c7aff40112d05be53dadc4c1389fa Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Tue, 11 Mar 2014 19:26:56 +0700 Subject: [PATCH 05/17] Code formatting for PSR1 & PSR2 - Part 1 --- Classes/PHPWord.php | 2 +- Classes/PHPWord/Autoloader.php | 2 +- Classes/PHPWord/DocumentProperties.php | 2 +- Classes/PHPWord/Exception.php | 2 +- .../Exceptions/InvalidStyleException.php | 2 +- Classes/PHPWord/Footnote.php | 160 +++++++------- Classes/PHPWord/IOFactory.php | 9 +- Classes/PHPWord/Media.php | 1 - Classes/PHPWord/Reader/Abstract.php | 19 +- Classes/PHPWord/Reader/Word2007.php | 70 +++--- Classes/PHPWord/Section.php | 15 +- Classes/PHPWord/Section/Footer.php | 2 +- Classes/PHPWord/Section/Footnote.php | 200 +++++++++--------- Classes/PHPWord/Section/Header.php | 3 +- Classes/PHPWord/Section/Image.php | 2 +- Classes/PHPWord/Section/Settings.php | 31 ++- Classes/PHPWord/Section/Table.php | 1 - Classes/PHPWord/Section/Table/Cell.php | 2 +- Classes/PHPWord/Section/Table/Row.php | 2 +- Classes/PHPWord/Section/Text.php | 2 +- Classes/PHPWord/Section/TextRun.php | 8 +- Classes/PHPWord/Shared/Font.php | 1 - Classes/PHPWord/Shared/String.php | 1 - Classes/PHPWord/Shared/XMLWriter.php | 2 +- Classes/PHPWord/Shared/ZipStreamWrapper.php | 2 +- Classes/PHPWord/Style.php | 1 - Classes/PHPWord/Style/Cell.php | 6 +- Classes/PHPWord/Style/Image.php | 2 +- Classes/PHPWord/Style/Row.php | 3 +- Classes/PHPWord/Style/Tab.php | 8 +- Classes/PHPWord/Style/Tabs.php | 4 +- Classes/PHPWord/TOC.php | 2 +- Classes/PHPWord/Template.php | 88 ++++---- Classes/PHPWord/Writer/ODText.php | 4 +- Classes/PHPWord/Writer/ODText/Content.php | 32 ++- Classes/PHPWord/Writer/ODText/Mimetype.php | 1 - Classes/PHPWord/Writer/ODText/Styles.php | 9 +- Classes/PHPWord/Writer/RTF.php | 52 +++-- Classes/PHPWord/Writer/Word2007.php | 10 +- Classes/PHPWord/Writer/Word2007/Base.php | 26 +-- .../PHPWord/Writer/Word2007/ContentTypes.php | 58 +++-- Classes/PHPWord/Writer/Word2007/Document.php | 2 +- Classes/PHPWord/Writer/Word2007/Footnotes.php | 16 +- .../PHPWord/Writer/Word2007/FootnotesRels.php | 107 +++++----- 44 files changed, 518 insertions(+), 456 deletions(-) diff --git a/Classes/PHPWord.php b/Classes/PHPWord.php index 64f9d9a2..009af98a 100755 --- a/Classes/PHPWord.php +++ b/Classes/PHPWord.php @@ -267,4 +267,4 @@ class PHPWord trigger_error('Template file ' . $strFilename . ' not found.', E_USER_ERROR); } } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Autoloader.php b/Classes/PHPWord/Autoloader.php index cf476646..74d1a500 100755 --- a/Classes/PHPWord/Autoloader.php +++ b/Classes/PHPWord/Autoloader.php @@ -82,4 +82,4 @@ class PHPWord_Autoloader } } } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/DocumentProperties.php b/Classes/PHPWord/DocumentProperties.php index 2bf44043..7c2aec24 100755 --- a/Classes/PHPWord/DocumentProperties.php +++ b/Classes/PHPWord/DocumentProperties.php @@ -343,4 +343,4 @@ class PHPWord_DocumentProperties $this->_company = $pValue; return $this; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Exception.php b/Classes/PHPWord/Exception.php index bd73d52c..91b5d54f 100755 --- a/Classes/PHPWord/Exception.php +++ b/Classes/PHPWord/Exception.php @@ -46,4 +46,4 @@ class PHPWord_Exception extends Exception $e->file = $file; throw $e; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Exceptions/InvalidStyleException.php b/Classes/PHPWord/Exceptions/InvalidStyleException.php index d624c62c..df436f3a 100644 --- a/Classes/PHPWord/Exceptions/InvalidStyleException.php +++ b/Classes/PHPWord/Exceptions/InvalidStyleException.php @@ -12,4 +12,4 @@ use InvalidArgumentException; */ class InvalidStyleException extends InvalidArgumentException { -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Footnote.php b/Classes/PHPWord/Footnote.php index 81054843..ac39de3a 100644 --- a/Classes/PHPWord/Footnote.php +++ b/Classes/PHPWord/Footnote.php @@ -33,93 +33,99 @@ * @package PHPWord * @copyright Copyright (c) 2011 PHPWord */ -class PHPWord_Footnote { +class PHPWord_Footnote +{ - /** - * Footnote Elements - * - * @var array - */ - private static $_footnoteCollection = array(); + /** + * Footnote Elements + * + * @var array + */ + private static $_footnoteCollection = array(); - /** - * Footnote Link Elements - * - * @var array - */ - private static $_footnoteLink = array(); + /** + * Footnote Link Elements + * + * @var array + */ + private static $_footnoteLink = array(); - /** - * Add new Footnote Element - * - * @param string $linkSrc - * @param string $linkName - * - * @return mixed - */ - public static function addFootnoteElement(PHPWord_Section_Footnote $footnote) { - $refID = self::countFootnoteElements() + 2; + /** + * Add new Footnote Element + * + * @param string $linkSrc + * @param string $linkName + * + * @return mixed + */ + public static function addFootnoteElement(PHPWord_Section_Footnote $footnote) + { + $refID = self::countFootnoteElements() + 2; - self::$_footnoteCollection[] = $footnote; + self::$_footnoteCollection[] = $footnote; - return $refID; - } + return $refID; + } - /** - * Get Footnote Elements - * - * @return array - */ - public static function getFootnoteElements() { - return self::$_footnoteCollection; - } + /** + * Get Footnote Elements + * + * @return array + */ + public static function getFootnoteElements() + { + return self::$_footnoteCollection; + } - /** - * Get Footnote Elements Count - * - * @return int - */ - public static function countFootnoteElements() { - return count(self::$_footnoteCollection); - } + /** + * Get Footnote Elements Count + * + * @return int + */ + public static function countFootnoteElements() + { + return count(self::$_footnoteCollection); + } - /** - * Add new Footnote Link Element - * - * @param string $src - * @param string $type - * - * @return mixed - */ - public static function addFootnoteLinkElement($linkSrc) { - $rID = self::countFootnoteLinkElements() + 1; + /** + * Add new Footnote Link Element + * + * @param string $src + * @param string $type + * + * @return mixed + */ + public static function addFootnoteLinkElement($linkSrc) + { + $rID = self::countFootnoteLinkElements() + 1; - $link = array(); - $link['target'] = $linkSrc; - $link['rID'] = $rID; - $link['type'] = 'hyperlink'; + $link = array(); + $link['target'] = $linkSrc; + $link['rID'] = $rID; + $link['type'] = 'hyperlink'; - self::$_footnoteLink[] = $link; + self::$_footnoteLink[] = $link; - return $rID; - } + return $rID; + } - /** - * Get Footnote Link Elements - * - * @return array - */ - public static function getFootnoteLinkElements() { - return self::$_footnoteLink; - } + /** + * Get Footnote Link Elements + * + * @return array + */ + public static function getFootnoteLinkElements() + { + return self::$_footnoteLink; + } - /** - * Get Footnote Link Elements Count - * - * @return int - */ - public static function countFootnoteLinkElements() { - return count(self::$_footnoteLink); - } - -} \ No newline at end of file + /** + * Get Footnote Link Elements Count + * + * @return int + */ + public static function countFootnoteLinkElements() + { + return count(self::$_footnoteLink); + } +} diff --git a/Classes/PHPWord/IOFactory.php b/Classes/PHPWord/IOFactory.php index 7780a8ca..aac0be87 100755 --- a/Classes/PHPWord/IOFactory.php +++ b/Classes/PHPWord/IOFactory.php @@ -126,7 +126,8 @@ class PHPWord_IOFactory * @param string $readerType Example: Word2007 * @return PHPWord_Reader_IReader */ - public static function createReader($readerType = '') { + public static function createReader($readerType = '') + { $searchType = 'IReader'; foreach (self::$_searchLocations as $searchLocation) { @@ -134,7 +135,7 @@ class PHPWord_IOFactory $className = str_replace('{0}', $readerType, $searchLocation['class']); $instance = new $className(); - if ($instance !== NULL) { + if ($instance !== null) { return $instance; } } @@ -149,9 +150,9 @@ class PHPWord_IOFactory * @param string $pFilename The name of the file * @return PHPWord */ - public static function load($pFilename, $readerType = 'Word2007') { + public static function load($pFilename, $readerType = 'Word2007') + { $reader = self::createReader($readerType); return $reader->load($pFilename); } - } diff --git a/Classes/PHPWord/Media.php b/Classes/PHPWord/Media.php index de913719..413b73de 100755 --- a/Classes/PHPWord/Media.php +++ b/Classes/PHPWord/Media.php @@ -330,4 +330,3 @@ class PHPWord_Media return self::$_footerMedia; } } - diff --git a/Classes/PHPWord/Reader/Abstract.php b/Classes/PHPWord/Reader/Abstract.php index bf3eb374..0d273ea8 100644 --- a/Classes/PHPWord/Reader/Abstract.php +++ b/Classes/PHPWord/Reader/Abstract.php @@ -36,9 +36,9 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader * * @var boolean */ - protected $readDataOnly = TRUE; + protected $readDataOnly = true; - protected $fileHandle = NULL; + protected $fileHandle = true; /** @@ -46,9 +46,10 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader * * @return boolean */ - public function getReadDataOnly() { + public function getReadDataOnly() + { // return $this->readDataOnly; - return TRUE; + return true; } /** @@ -57,7 +58,8 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader * @param boolean $pValue * @return PHPWord_Reader_IReader */ - public function setReadDataOnly($pValue = TRUE) { + public function setReadDataOnly($pValue = true) + { $this->readDataOnly = $pValue; return $this; } @@ -78,7 +80,7 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader // Open file $this->fileHandle = fopen($pFilename, 'r'); - if ($this->fileHandle === FALSE) { + if ($this->fileHandle === false) { throw new PHPWord_Exception("Could not open file " . $pFilename . " for reading."); } } @@ -96,10 +98,9 @@ abstract class PHPWord_Reader_Abstract implements PHPWord_Reader_IReader try { $this->openFile($pFilename); } catch (Exception $e) { - return FALSE; + return false; } - fclose ($this->fileHandle); + fclose($this->fileHandle); return $readable; } - } diff --git a/Classes/PHPWord/Reader/Word2007.php b/Classes/PHPWord/Reader/Word2007.php index 78a9875c..ebe5ef9c 100644 --- a/Classes/PHPWord/Reader/Word2007.php +++ b/Classes/PHPWord/Reader/Word2007.php @@ -42,7 +42,8 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements /** * Create a new PHPWord_Reader_Word2007 instance */ - public function __construct() { + public function __construct() + { } /** @@ -55,8 +56,10 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements { // Check if file exists if (!file_exists($pFilename)) { - throw new PHPWord_Exception("Could not open " . $pFilename . - " for reading! File does not exist."); + throw new PHPWord_Exception( + "Could not open " . $pFilename . + " for reading! File does not exist." + ); } $return = false; @@ -96,16 +99,14 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements $removeNamespace = false ) { // Root-relative paths - if (strpos($fileName, '//') !== false) - { + if (strpos($fileName, '//') !== false) { $fileName = substr($fileName, strpos($fileName, '//') + 1); } $fileName = PHPWord_Shared_File::realpath($fileName); // Apache POI fixes $contents = $archive->getFromName($fileName); - if ($contents === false) - { + if ($contents === false) { $contents = $archive->getFromName(substr($fileName, 1)); } @@ -128,8 +129,10 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements { // Check if file exists if (!file_exists($pFilename)) { - throw new PHPWord_Exception("Could not open " . $pFilename . - " for reading! File does not exist."); + throw new PHPWord_Exception( + "Could not open " . $pFilename . + " for reading! File does not exist." + ); } // Initialisations @@ -149,15 +152,15 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/"); $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); $docProps = $word->getProperties(); - $docProps->setCreator((string) self::array_item($xmlCore->xpath("dc:creator"))); - $docProps->setLastModifiedBy((string) self::array_item($xmlCore->xpath("cp:lastModifiedBy"))); - $docProps->setCreated(strtotime(self::array_item($xmlCore->xpath("dcterms:created")))); - $docProps->setModified(strtotime(self::array_item($xmlCore->xpath("dcterms:modified")))); - $docProps->setTitle((string) self::array_item($xmlCore->xpath("dc:title"))); - $docProps->setDescription((string) self::array_item($xmlCore->xpath("dc:description"))); - $docProps->setSubject((string) self::array_item($xmlCore->xpath("dc:subject"))); - $docProps->setKeywords((string) self::array_item($xmlCore->xpath("cp:keywords"))); - $docProps->setCategory((string) self::array_item($xmlCore->xpath("cp:category"))); + $docProps->setCreator((string) self::arrayItem($xmlCore->xpath("dc:creator"))); + $docProps->setLastModifiedBy((string) self::arrayItem($xmlCore->xpath("cp:lastModifiedBy"))); + $docProps->setCreated(strtotime(self::arrayItem($xmlCore->xpath("dcterms:created")))); + $docProps->setModified(strtotime(self::arrayItem($xmlCore->xpath("dcterms:modified")))); + $docProps->setTitle((string) self::arrayItem($xmlCore->xpath("dc:title"))); + $docProps->setDescription((string) self::arrayItem($xmlCore->xpath("dc:description"))); + $docProps->setSubject((string) self::arrayItem($xmlCore->xpath("dc:subject"))); + $docProps->setKeywords((string) self::arrayItem($xmlCore->xpath("cp:keywords"))); + $docProps->setCategory((string) self::arrayItem($xmlCore->xpath("cp:category"))); } break; // Extended properties @@ -165,10 +168,12 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements $xmlCore = simplexml_load_string($this->getFromZipArchive($zip, "{$rel['Target']}")); if (is_object($xmlCore)) { $docProps = $word->getProperties(); - if (isset($xmlCore->Company)) + if (isset($xmlCore->Company)) { $docProps->setCompany((string) $xmlCore->Company); - if (isset($xmlCore->Manager)) + } + if (isset($xmlCore->Manager)) { $docProps->setManager((string) $xmlCore->Manager); + } } break; // Custom properties @@ -183,9 +188,9 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements $cellDataOfficeChildren = $xmlProperty->children("http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"); $attributeType = $cellDataOfficeChildren->getName(); $attributeValue = (string) $cellDataOfficeChildren->{$attributeType}; - $attributeValue = PHPWord_DocumentProperties::convertProperty($attributeValue,$attributeType); + $attributeValue = PHPWord_DocumentProperties::convertProperty($attributeValue, $attributeType); $attributeType = PHPWord_DocumentProperties::convertPropertyType($attributeType); - $docProps->setCustomProperty($propertyName,$attributeValue,$attributeType); + $docProps->setCustomProperty($propertyName, $attributeValue, $attributeType); } } } @@ -196,8 +201,9 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements $archive = "$dir/_rels/" . basename($rel["Target"]) . ".rels"; $relsDoc = simplexml_load_string($this->getFromZipArchive($zip, $archive)); $relsDoc->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); - $xpath = self::array_item($relsDoc->xpath("rel:Relationship[@Type='" . - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); + $xpath = self::arrayItem( + $relsDoc->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']") + ); $xmlDoc = simplexml_load_string($this->getFromZipArchive($zip, "{$rel['Target']}", true)); if (is_object($xmlDoc)) { $section = $word->createSection(); @@ -215,14 +221,18 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements if ($elm->r) { // w:r = 1? It's a plain paragraph if (count($elm->r) == 1) { - $section->addText($elm->r->t, - $this->loadFontStyle($elm->r)); + $section->addText( + $elm->r->t, + $this->loadFontStyle($elm->r) + ); // w:r more than 1? It's a textrun } else { $textRun = $section->createTextRun(); foreach ($elm->r as $r) { - $textRun->addText($r->t, - $this->loadFontStyle($r)); + $textRun->addText( + $r->t, + $this->loadFontStyle($r) + ); } } // No, it's a textbreak @@ -457,8 +467,8 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements * @param mixed $key * @return mixed|null */ - private static function array_item($array, $key = 0) { + private static function arrayItem($array, $key = 0) + { return (isset($array[$key]) ? $array[$key] : null); } - } diff --git a/Classes/PHPWord/Section.php b/Classes/PHPWord/Section.php index 3ed55ee5..70dceba2 100755 --- a/Classes/PHPWord/Section.php +++ b/Classes/PHPWord/Section.php @@ -425,11 +425,12 @@ class PHPWord_Section * @param string $text * @return PHPWord_Section_Footnote */ - public function createFootnote($styleParagraph = null) { - $footnote = new PHPWord_Section_Footnote($styleParagraph); - $refID = PHPWord_Footnote::addFootnoteElement($footnote); - $footnote->setReferenceId($refID); - $this->_elementCollection[] = $footnote; - return $footnote; + public function createFootnote($styleParagraph = null) + { + $footnote = new PHPWord_Section_Footnote($styleParagraph); + $refID = PHPWord_Footnote::addFootnoteElement($footnote); + $footnote->setReferenceId($refID); + $this->_elementCollection[] = $footnote; + return $footnote; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Section/Footer.php b/Classes/PHPWord/Section/Footer.php index 56e3e95a..04d40f33 100755 --- a/Classes/PHPWord/Section/Footer.php +++ b/Classes/PHPWord/Section/Footer.php @@ -210,4 +210,4 @@ class PHPWord_Section_Footer { return $this->_footerCount; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Section/Footnote.php b/Classes/PHPWord/Section/Footnote.php index b02ee4ef..be9fb678 100644 --- a/Classes/PHPWord/Section/Footnote.php +++ b/Classes/PHPWord/Section/Footnote.php @@ -33,116 +33,124 @@ * @package PHPWord_Section * @copyright Copyright (c) 2011 PHPWord */ -class PHPWord_Section_Footnote { +class PHPWord_Section_Footnote +{ - /** - * Paragraph style - * - * @var PHPWord_Style_Font - */ - private $_styleParagraph; + /** + * Paragraph style + * + * @var PHPWord_Style_Font + */ + private $_styleParagraph; - /** - * Footnote Reference ID - * - * @var string - */ - private $_refId; + /** + * Footnote Reference ID + * + * @var string + */ + private $_refId; - /** - * Text collection - * - * @var array - */ - private $_elementCollection; + /** + * Text collection + * + * @var array + */ + private $_elementCollection; - /** - * Create a new Footnote Element - */ - public function __construct($styleParagraph = null) { - $this->_elementCollection = array(); + /** + * Create a new Footnote Element + */ + public function __construct($styleParagraph = null) + { + $this->_elementCollection = array(); - // Set paragraph style - if(is_array($styleParagraph)) { - $this->_styleParagraph = new PHPWord_Style_Paragraph(); + // Set paragraph style + if (is_array($styleParagraph)) { + $this->_styleParagraph = new PHPWord_Style_Paragraph(); - foreach($styleParagraph as $key => $value) { - if(substr($key, 0, 1) != '_') { - $key = '_'.$key; + foreach ($styleParagraph as $key => $value) { + if (substr($key, 0, 1) != '_') { + $key = '_' . $key; + } + $this->_styleParagraph->setStyleValue($key, $value); + } + } else { + $this->_styleParagraph = $styleParagraph; } - $this->_styleParagraph->setStyleValue($key, $value); - } - } else { - $this->_styleParagraph = $styleParagraph; } - } - /** - * Add a Text Element - * - * @var string $text - * @var mixed $styleFont - * @return PHPWord_Section_Text - */ - public function addText($text = null, $styleFont = null) { - $givenText = $text; - $text = new PHPWord_Section_Text($givenText, $styleFont); - $this->_elementCollection[] = $text; - return $text; - } + /** + * Add a Text Element + * + * @var string $text + * @var mixed $styleFont + * @return PHPWord_Section_Text + */ + public function addText($text = null, $styleFont = null) + { + $givenText = $text; + $text = new PHPWord_Section_Text($givenText, $styleFont); + $this->_elementCollection[] = $text; + return $text; + } - /** - * Add a Link Element - * - * @param string $linkSrc - * @param string $linkName - * @param mixed $styleFont - * @return PHPWord_Section_Link - */ - public function addLink($linkSrc, $linkName = null, $styleFont = null) { + /** + * Add a Link Element + * + * @param string $linkSrc + * @param string $linkName + * @param mixed $styleFont + * @return PHPWord_Section_Link + */ + public function addLink($linkSrc, $linkName = null, $styleFont = null) + { - $link = new PHPWord_Section_Link($linkSrc, $linkName, $styleFont); - $rID = PHPWord_Footnote::addFootnoteLinkElement($linkSrc); - $link->setRelationId($rID); + $link = new PHPWord_Section_Link($linkSrc, $linkName, $styleFont); + $rID = PHPWord_Footnote::addFootnoteLinkElement($linkSrc); + $link->setRelationId($rID); - $this->_elementCollection[] = $link; - return $link; - } + $this->_elementCollection[] = $link; + return $link; + } - /** - * Get Footnote content - * - * @return array - */ - public function getElements() { - return $this->_elementCollection; - } + /** + * Get Footnote content + * + * @return array + */ + public function getElements() + { + return $this->_elementCollection; + } - /** - * Get Paragraph style - * - * @return PHPWord_Style_Paragraph - */ - public function getParagraphStyle() { - return $this->_styleParagraph; - } + /** + * Get Paragraph style + * + * @return PHPWord_Style_Paragraph + */ + public function getParagraphStyle() + { + return $this->_styleParagraph; + } - /** - * Get Footnote Reference ID - * - * @return int - */ - public function getReferenceId() { - return $this->_refId; - } + /** + * Get Footnote Reference ID + * + * @return int + */ + public function getReferenceId() + { + return $this->_refId; + } - /** - * Set Footnote Reference ID - * - * @param int $refId - */ - public function setReferenceId($refId) { - $this->_refId = $refId; - } -} \ No newline at end of file + /** + * Set Footnote Reference ID + * + * @param int $refId + */ + public function setReferenceId($refId) + { + $this->_refId = $refId; + } +} diff --git a/Classes/PHPWord/Section/Header.php b/Classes/PHPWord/Section/Header.php index cb91e085..6c624406 100755 --- a/Classes/PHPWord/Section/Header.php +++ b/Classes/PHPWord/Section/Header.php @@ -292,5 +292,4 @@ class PHPWord_Section_Header { return $this->_type = PHPWord_Section_Header::EVEN; } - -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Section/Image.php b/Classes/PHPWord/Section/Image.php index f4ad628f..997c76f6 100755 --- a/Classes/PHPWord/Section/Image.php +++ b/Classes/PHPWord/Section/Image.php @@ -172,4 +172,4 @@ class PHPWord_Section_Image { $this->_isWatermark = $pValue; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Section/Settings.php b/Classes/PHPWord/Section/Settings.php index 67d01de4..38af6410 100755 --- a/Classes/PHPWord/Section/Settings.php +++ b/Classes/PHPWord/Section/Settings.php @@ -616,7 +616,8 @@ class PHPWord_Section_Settings * * @return int */ - public function getHeaderHeight() { + public function getHeaderHeight() + { return $this->headerHeight; } @@ -625,7 +626,8 @@ class PHPWord_Section_Settings * * @param int $pValue */ - public function setHeaderHeight($pValue = '') { + public function setHeaderHeight($pValue = '') + { if (!is_numeric($pValue)) { $pValue = 720; } @@ -638,7 +640,8 @@ class PHPWord_Section_Settings * * @return int */ - public function getFooterHeight() { + public function getFooterHeight() + { return $this->footerHeight; } @@ -647,7 +650,8 @@ class PHPWord_Section_Settings * * @param int $pValue */ - public function setFooterHeight($pValue = '') { + public function setFooterHeight($pValue = '') + { if (!is_numeric($pValue)) { $pValue = 720; } @@ -660,7 +664,8 @@ class PHPWord_Section_Settings * * @param int $pValue */ - public function setColsNum($pValue = '') { + public function setColsNum($pValue = '') + { if (!is_numeric($pValue)) { $pValue = 1; } @@ -673,7 +678,8 @@ class PHPWord_Section_Settings * * @return int */ - public function getColsNum() { + public function getColsNum() + { return $this->_colsNum; } @@ -682,7 +688,8 @@ class PHPWord_Section_Settings * * @param int $pValue */ - public function setColsSpace($pValue = '') { + public function setColsSpace($pValue = '') + { if (!is_numeric($pValue)) { $pValue = 720; } @@ -695,7 +702,8 @@ class PHPWord_Section_Settings * * @return int */ - public function getColsSpace() { + public function getColsSpace() + { return $this->_colsSpace; } @@ -704,7 +712,8 @@ class PHPWord_Section_Settings * * @param string $pValue */ - public function setBreakType($pValue = null) { + public function setBreakType($pValue = null) + { $this->_breakType = $pValue; return $this; } @@ -714,8 +723,8 @@ class PHPWord_Section_Settings * * @return string */ - public function getBreakType() { + public function getBreakType() + { return $this->_breakType; } - } diff --git a/Classes/PHPWord/Section/Table.php b/Classes/PHPWord/Section/Table.php index 081b6484..dd93c95e 100755 --- a/Classes/PHPWord/Section/Table.php +++ b/Classes/PHPWord/Section/Table.php @@ -160,5 +160,4 @@ class PHPWord_Section_Table { return $this->_width; } - } diff --git a/Classes/PHPWord/Section/Table/Cell.php b/Classes/PHPWord/Section/Table/Cell.php index b4bc8242..4f8f78fe 100755 --- a/Classes/PHPWord/Section/Table/Cell.php +++ b/Classes/PHPWord/Section/Table/Cell.php @@ -333,4 +333,4 @@ class PHPWord_Section_Table_Cell { return $this->_width; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Section/Table/Row.php b/Classes/PHPWord/Section/Table/Row.php index c2db614b..d174ef8f 100644 --- a/Classes/PHPWord/Section/Table/Row.php +++ b/Classes/PHPWord/Section/Table/Row.php @@ -138,4 +138,4 @@ class PHPWord_Section_Table_Row { return $this->_height; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Section/Text.php b/Classes/PHPWord/Section/Text.php index 5d628d2c..296084e6 100755 --- a/Classes/PHPWord/Section/Text.php +++ b/Classes/PHPWord/Section/Text.php @@ -149,4 +149,4 @@ class PHPWord_Section_Text { return $this->text; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Section/TextRun.php b/Classes/PHPWord/Section/TextRun.php index 7c03138b..cb23f9ce 100755 --- a/Classes/PHPWord/Section/TextRun.php +++ b/Classes/PHPWord/Section/TextRun.php @@ -116,7 +116,8 @@ class PHPWord_Section_TextRun * @param mixed $styleFont * @return PHPWord_Section_Image */ - public function addImage($imageSrc, $style = null) { + public function addImage($imageSrc, $style = null) + { $image = new PHPWord_Section_Image($imageSrc, $style); if (!is_null($image->getSource())) { @@ -136,7 +137,8 @@ class PHPWord_Section_TextRun * @param string $text * @return PHPWord_Section_Footnote */ - public function createFootnote($styleParagraph = null) { + public function createFootnote($styleParagraph = null) + { $footnote = new PHPWord_Section_Footnote($styleParagraph); $refID = PHPWord_Footnote::addFootnoteElement($footnote); $footnote->setReferenceId($refID); @@ -163,4 +165,4 @@ class PHPWord_Section_TextRun { return $this->_styleParagraph; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Shared/Font.php b/Classes/PHPWord/Shared/Font.php index ccb19bc7..9e6dc44f 100755 --- a/Classes/PHPWord/Shared/Font.php +++ b/Classes/PHPWord/Shared/Font.php @@ -88,5 +88,4 @@ class PHPWord_Shared_Font { return ($sizeInPoint * 20); } - } diff --git a/Classes/PHPWord/Shared/String.php b/Classes/PHPWord/Shared/String.php index f570e6b7..2aa68d3f 100755 --- a/Classes/PHPWord/Shared/String.php +++ b/Classes/PHPWord/Shared/String.php @@ -266,5 +266,4 @@ class PHPWord_Shared_String $count = strlen($value); return $count; } - } diff --git a/Classes/PHPWord/Shared/XMLWriter.php b/Classes/PHPWord/Shared/XMLWriter.php index ae4fa160..1563ab46 100755 --- a/Classes/PHPWord/Shared/XMLWriter.php +++ b/Classes/PHPWord/Shared/XMLWriter.php @@ -150,4 +150,4 @@ class PHPWord_Shared_XMLWriter return $this->text($text); } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Shared/ZipStreamWrapper.php b/Classes/PHPWord/Shared/ZipStreamWrapper.php index 0dc42875..ee346921 100755 --- a/Classes/PHPWord/Shared/ZipStreamWrapper.php +++ b/Classes/PHPWord/Shared/ZipStreamWrapper.php @@ -121,7 +121,7 @@ class PHPWord_Shared_ZipStreamWrapper /** * Read stream */ - function stream_read($count) + public function stream_read($count) { $ret = substr($this->_data, $this->_position, $count); $this->_position += strlen($ret); diff --git a/Classes/PHPWord/Style.php b/Classes/PHPWord/Style.php index daabd46b..060ce1be 100755 --- a/Classes/PHPWord/Style.php +++ b/Classes/PHPWord/Style.php @@ -175,4 +175,3 @@ class PHPWord_Style } } } - diff --git a/Classes/PHPWord/Style/Cell.php b/Classes/PHPWord/Style/Cell.php index 8783675e..10d4a9be 100755 --- a/Classes/PHPWord/Style/Cell.php +++ b/Classes/PHPWord/Style/Cell.php @@ -123,7 +123,7 @@ class PHPWord_Style_Cell * * @var integer */ - private $_gridSpan = NULL; + private $_gridSpan = null; /** * rowspan (restart, continue) @@ -133,7 +133,7 @@ class PHPWord_Style_Cell * * @var string */ - private $_vMerge = NULL; + private $_vMerge = null; /** * Create a new Cell Style @@ -342,4 +342,4 @@ class PHPWord_Style_Cell { return $this->_vMerge; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Style/Image.php b/Classes/PHPWord/Style/Image.php index 47a71cba..4453463a 100755 --- a/Classes/PHPWord/Style/Image.php +++ b/Classes/PHPWord/Style/Image.php @@ -173,4 +173,4 @@ class PHPWord_Style_Image { return $this->wrappingStyle; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Style/Row.php b/Classes/PHPWord/Style/Row.php index a0e79b3a..66d5505f 100644 --- a/Classes/PHPWord/Style/Row.php +++ b/Classes/PHPWord/Style/Row.php @@ -81,5 +81,4 @@ class PHPWord_Style_Row { return $this->_cantSplit ? 1 : 0; } - -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Style/Tab.php b/Classes/PHPWord/Style/Tab.php index a280eebb..f8ee4b9b 100755 --- a/Classes/PHPWord/Style/Tab.php +++ b/Classes/PHPWord/Style/Tab.php @@ -92,7 +92,7 @@ class PHPWord_Style_Tab * @param int $position Must be an integer; otherwise defaults to 0. * @param string $leader Defaults to NULL if value is not possible. */ - public function __construct($val = NULL, $position = 0, $leader = NULL) + public function __construct($val = null, $position = 0, $leader = null) { // Default to clear if the stop type is not matched $this->_val = (self::isStopType($val)) ? $val : 'clear'; @@ -101,7 +101,7 @@ class PHPWord_Style_Tab $this->_position = (is_numeric($position)) ? intval($position) : 0; // Default to NULL if no tab leader - $this->_leader = (self::isLeaderType($leader)) ? $leader : NULL; + $this->_leader = (self::isLeaderType($leader)) ? $leader : null; } /** @@ -109,7 +109,7 @@ class PHPWord_Style_Tab * * @param PHPWord_Shared_XMLWriter $objWriter */ - public function toXml(PHPWord_Shared_XMLWriter &$objWriter = NULL) + public function toXml(PHPWord_Shared_XMLWriter &$objWriter = null) { if (isset($objWriter)) { $objWriter->startElement("w:tab"); @@ -143,4 +143,4 @@ class PHPWord_Style_Tab { return in_array($attribute, self::$_possibleLeaders); } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Style/Tabs.php b/Classes/PHPWord/Style/Tabs.php index ebad8fbb..144d2a5d 100755 --- a/Classes/PHPWord/Style/Tabs.php +++ b/Classes/PHPWord/Style/Tabs.php @@ -51,7 +51,7 @@ class PHPWord_Style_Tabs * * @param PHPWord_Shared_XMLWriter $objWriter */ - public function toXml(PHPWord_Shared_XMLWriter &$objWriter = NULL) + public function toXml(PHPWord_Shared_XMLWriter &$objWriter = null) { if (isset($objWriter)) { $objWriter->startElement("w:tabs"); @@ -61,4 +61,4 @@ class PHPWord_Style_Tabs $objWriter->endElement(); } } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/TOC.php b/Classes/PHPWord/TOC.php index 1366f0c3..ae514a54 100755 --- a/Classes/PHPWord/TOC.php +++ b/Classes/PHPWord/TOC.php @@ -152,4 +152,4 @@ class PHPWord_TOC { return self::$_styleFont; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Template.php b/Classes/PHPWord/Template.php index edf0de75..4d356dd3 100755 --- a/Classes/PHPWord/Template.php +++ b/Classes/PHPWord/Template.php @@ -75,7 +75,7 @@ class PHPWord_Template throw new PHPWord_Exception('Could not create temporary file with unique name in the default temporary directory.'); } } - + /** * Applies XSL style sheet to template's parts * @@ -133,10 +133,10 @@ class PHPWord_Template } $replace = htmlspecialchars($replace); } else { - foreach($replace as $key=>$value) { + foreach ($replace as $key => $value) { $replace[$key] = htmlspecialchars($value); } - } + } $regExpDelim = '/'; $escapedSearch = preg_quote($search, $regExpDelim); @@ -154,37 +154,40 @@ class PHPWord_Template /** * Find the start position of the nearest table row before $offset - * + * * @param mixed $offset */ - private function _findRowStart($offset) { - $rowStart = strrpos($this->_documentXML, "_documentXML) - $offset) * -1)); - if (!$rowStart) { - $rowStart = strrpos($this->_documentXML, "", ((strlen($this->_documentXML) - $offset) * -1)); - } - if (!$rowStart) { - trigger_error("Can not find the start position of the row to clone."); - return false; - } + private function _findRowStart($offset) + { + $rowStart = strrpos($this->_documentXML, "_documentXML) - $offset) * -1)); + if (!$rowStart) { + $rowStart = strrpos($this->_documentXML, "", ((strlen($this->_documentXML) - $offset) * -1)); + } + if (!$rowStart) { + trigger_error("Can not find the start position of the row to clone."); + return false; + } return $rowStart; } /** * Find the end position of the nearest table row after $offset - * + * * @param mixed $offset */ - private function _findRowEnd($offset) { - $rowEnd = strpos($this->_documentXML, "", $offset) + 7; + private function _findRowEnd($offset) + { + $rowEnd = strpos($this->_documentXML, "", $offset) + 7; return $rowEnd; } /** * Get a slice of a string - * + * * @param mixed $offset */ - private function _getSlice($startPosition, $endPosition = 0) { + private function _getSlice($startPosition, $endPosition = 0) + { if (!$endPosition) { $endPosition = strlen($this->_documentXML); } @@ -193,38 +196,39 @@ class PHPWord_Template /** * Clone a table row in a template document - * + * * @param mixed $search * @param mixed $numberOfClones */ - public function cloneRow($search, $numberOfClones) { - if(substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') { + public function cloneRow($search, $numberOfClones) + { + if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') { $search = '${'.$search.'}'; } - + $tagPos = strpos($this->_documentXML, $search); - if (!$tagPos) { - trigger_error("Can not clone row, template variable not found or variable contains markup."); - return false; - } - + if (!$tagPos) { + trigger_error("Can not clone row, template variable not found or variable contains markup."); + return false; + } + $rowStart = $this->_findRowStart($tagPos); $rowEnd = $this->_findRowEnd($tagPos); $xmlRow = $this->_getSlice($rowStart, $rowEnd); - + // Check if there's a cell spanning multiple rows. if (preg_match('##', $xmlRow)) { $extraRowStart = $rowEnd; $extraRowEnd = $rowEnd; - while(true) { + while (true) { $extraRowStart = $this->_findRowStart($extraRowEnd + 1); $extraRowEnd = $this->_findRowEnd($extraRowEnd + 1); - + // If extraRowEnd is lower then 7, there was no next row found. if ($extraRowEnd < 7) { break; } - + // 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)) { @@ -232,17 +236,17 @@ class PHPWord_Template } // This row was a spanned row, update $rowEnd and search for the next row. $rowEnd = $extraRowEnd; - } + } $xmlRow = $this->_getSlice($rowStart, $rowEnd); } - + $result = $this->_getSlice(0, $rowStart); - for ($i = 1; $i <= $numberOfClones; $i++) { - $result .= preg_replace('/\$\{(.*?)\}/','\${\\1#'.$i.'}', $xmlRow); - } - $result .= $this->_getSlice($rowEnd); - - $this->_documentXML = $result; + for ($i = 1; $i <= $numberOfClones; $i++) { + $result .= preg_replace('/\$\{(.*?)\}/', '\${\\1#'.$i.'}', $xmlRow); + } + $result .= $this->_getSlice($rowEnd); + + $this->_documentXML = $result; } /** @@ -250,7 +254,8 @@ class PHPWord_Template * * @return string */ - public function save() { + public function save() + { $this->_objZip->addFromString('word/document.xml', $this->_documentXML); // Close zip file @@ -266,7 +271,8 @@ class PHPWord_Template * * @param string $strFilename */ - public function saveAs($strFilename) { + public function saveAs($strFilename) + { $tempFilename = $this->save(); if (file_exists($strFilename)) { diff --git a/Classes/PHPWord/Writer/ODText.php b/Classes/PHPWord/Writer/ODText.php index 3421da8f..16a60304 100755 --- a/Classes/PHPWord/Writer/ODText.php +++ b/Classes/PHPWord/Writer/ODText.php @@ -236,7 +236,7 @@ class PHPWord_Writer_ODText implements PHPWord_Writer_IWriter * @param string $pPartName Writer part name * @return PHPWord_Writer_ODText_WriterPart */ - function getWriterPart($pPartName = '') + public function getWriterPart($pPartName = '') { if ($pPartName != '' && isset($this->_writerParts[strtolower($pPartName)])) { return $this->_writerParts[strtolower($pPartName)]; @@ -287,4 +287,4 @@ class PHPWord_Writer_ODText implements PHPWord_Writer_IWriter { return $this->_diskCachingDirectory; } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Writer/ODText/Content.php b/Classes/PHPWord/Writer/ODText/Content.php index f79eb4b4..7ee571a3 100755 --- a/Classes/PHPWord/Writer/ODText/Content.php +++ b/Classes/PHPWord/Writer/ODText/Content.php @@ -249,27 +249,27 @@ class PHPWord_Writer_ODText_Content extends PHPWord_Writer_ODText_WriterPart foreach ($_elements as $element) { if ($element instanceof PHPWord_Section_Text) { $this->_writeText($objWriter, $element); - } elseif($element instanceof PHPWord_Section_TextRun) { + } elseif ($element instanceof PHPWord_Section_TextRun) { $this->_writeTextRun($objWriter, $element); } elseif ($element instanceof PHPWord_Section_TextBreak) { $this->_writeTextBreak($objWriter); /* - } elseif($element instanceof PHPWord_Section_Link) { + } elseif ($element instanceof PHPWord_Section_Link) { $this->_writeLink($objWriter, $element); - } elseif($element instanceof PHPWord_Section_Title) { + } elseif ($element instanceof PHPWord_Section_Title) { $this->_writeTitle($objWriter, $element); - } elseif($element instanceof PHPWord_Section_PageBreak) { + } elseif ($element instanceof PHPWord_Section_PageBreak) { $this->_writePageBreak($objWriter); - } elseif($element instanceof PHPWord_Section_Table) { + } elseif ($element instanceof PHPWord_Section_Table) { $this->_writeTable($objWriter, $element); - } elseif($element instanceof PHPWord_Section_ListItem) { + } elseif ($element instanceof PHPWord_Section_ListItem) { $this->_writeListItem($objWriter, $element); - } elseif($element instanceof PHPWord_Section_Image || + } elseif ($element instanceof PHPWord_Section_Image || $element instanceof PHPWord_Section_MemoryImage) { $this->_writeImage($objWriter, $element); - } elseif($element instanceof PHPWord_Section_Object) { + } elseif ($element instanceof PHPWord_Section_Object) { $this->_writeObject($objWriter, $element); - } elseif($element instanceof PHPWord_TOC) { + } elseif ($element instanceof PHPWord_TOC) { $this->_writeTOC($objWriter); */ } else { @@ -303,8 +303,8 @@ class PHPWord_Writer_ODText_Content extends PHPWord_Writer_ODText_WriterPart protected function _writeText( PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section_Text $text, - $withoutP = false) - { + $withoutP = false + ) { $styleFont = $text->getFontStyle(); $styleParagraph = $text->getParagraphStyle(); @@ -351,9 +351,7 @@ class PHPWord_Writer_ODText_Content extends PHPWord_Writer_ODText_WriterPart * @param PHPWord_Section_TextRun $textrun * @todo Enable all other section types */ - protected function _writeTextRun( - PHPWord_Shared_XMLWriter $objWriter = null, - PHPWord_Section_TextRun $textrun) + protected function _writeTextRun(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section_TextRun $textrun) { $elements = $textrun->getElements(); $objWriter->startElement('text:p'); @@ -377,7 +375,7 @@ class PHPWord_Writer_ODText_Content extends PHPWord_Writer_ODText_WriterPart $objWriter->endElement(); } - private function _writeEndSection(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section $section) + private function _writeEndSection(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section $section = null) { } @@ -386,9 +384,7 @@ class PHPWord_Writer_ODText_Content extends PHPWord_Writer_ODText_WriterPart * * @todo Create the real function */ - private function _writeSection( - PHPWord_Shared_XMLWriter $objWriter = null, - PHPWord_Section $section) + private function _writeSection(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section $section = null) { } } diff --git a/Classes/PHPWord/Writer/ODText/Mimetype.php b/Classes/PHPWord/Writer/ODText/Mimetype.php index 439ada1a..def40db4 100755 --- a/Classes/PHPWord/Writer/ODText/Mimetype.php +++ b/Classes/PHPWord/Writer/ODText/Mimetype.php @@ -42,5 +42,4 @@ class PHPWord_Writer_ODText_Mimetype extends PHPWord_Writer_ODText_WriterPart return 'application/vnd.oasis.opendocument.text'; } - } diff --git a/Classes/PHPWord/Writer/ODText/Styles.php b/Classes/PHPWord/Writer/ODText/Styles.php index 745da08e..7f388809 100755 --- a/Classes/PHPWord/Writer/ODText/Styles.php +++ b/Classes/PHPWord/Writer/ODText/Styles.php @@ -182,8 +182,8 @@ class PHPWord_Writer_ODText_Styles extends PHPWord_Writer_ODText_WriterPart } $objWriter->endElement(); $objWriter->endElement(); - } // PHPWord_Style_Paragraph - elseif ($style instanceof PHPWord_Style_Paragraph) { + } elseif ($style instanceof PHPWord_Style_Paragraph) { + // PHPWord_Style_Paragraph // style:style $objWriter->startElement('style:style'); $objWriter->writeAttribute('style:name', $styleName); @@ -197,9 +197,8 @@ class PHPWord_Writer_ODText_Styles extends PHPWord_Writer_ODText_WriterPart $objWriter->endElement(); $objWriter->endElement(); - - } // PHPWord_Style_TableFull - elseif ($style instanceof PHPWord_Style_TableFull) { + } elseif ($style instanceof PHPWord_Style_TableFull) { + // PHPWord_Style_TableFull } } } diff --git a/Classes/PHPWord/Writer/RTF.php b/Classes/PHPWord/Writer/RTF.php index e22fe99c..c730c9c3 100755 --- a/Classes/PHPWord/Writer/RTF.php +++ b/Classes/PHPWord/Writer/RTF.php @@ -81,7 +81,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter } $hFile = fopen($pFilename, 'w') or die("can't open file"); - fwrite($hFile, $this->_getData()); + fwrite($hFile, $this->getData()); fclose($hFile); // If a temporary file was used, copy it to the correct file stream @@ -135,11 +135,11 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter return $this->_drawingHashTable; } - private function _getData() + private function getData() { // PHPWord object : $this->_document - $this->_fontTable = $this->_getDataFont(); - $this->_colorTable = $this->_getDataColor(); + $this->_fontTable = $this->getDataFont(); + $this->_colorTable = $this->getDataColor(); $sRTFContent = '{\rtf1'; // Set the default character set @@ -180,7 +180,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter $sRTFContent .= '\fs' . (PHPWord::DEFAULT_FONT_SIZE * 2); $sRTFContent .= PHP_EOL; // Body - $sRTFContent .= $this->_getDataContent(); + $sRTFContent .= $this->getDataContent(); $sRTFContent .= '}'; @@ -188,7 +188,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter return $sRTFContent; } - private function _getDataFont() + private function getDataFont() { $pPHPWord = $this->_document; @@ -204,7 +204,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter foreach ($styles as $styleName => $style) { // PHPWord_Style_Font if ($style instanceof PHPWord_Style_Font) { - if (in_array($style->getName(), $arrFonts) == FALSE) { + if (in_array($style->getName(), $arrFonts) == false) { $arrFonts[] = $style->getName(); } } @@ -226,7 +226,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter $fStyle = $element->getFontStyle(); if ($fStyle instanceof PHPWord_Style_Font) { - if (in_array($fStyle->getName(), $arrFonts) == FALSE) { + if (in_array($fStyle->getName(), $arrFonts) == false) { $arrFonts[] = $fStyle->getName(); } } @@ -238,7 +238,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter return $arrFonts; } - private function _getDataColor() + private function getDataColor() { $pPHPWord = $this->_document; @@ -254,10 +254,10 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter if ($style instanceof PHPWord_Style_Font) { $color = $style->getColor(); $fgcolor = $style->getFgColor(); - if (in_array($color, $arrColors) == FALSE && $color != PHPWord::DEFAULT_FONT_COLOR && !empty($color)) { + if (in_array($color, $arrColors) == false && $color != PHPWord::DEFAULT_FONT_COLOR && !empty($color)) { $arrColors[] = $color; } - if (in_array($fgcolor, $arrColors) == FALSE && $fgcolor != PHPWord::DEFAULT_FONT_COLOR && !empty($fgcolor)) { + if (in_array($fgcolor, $arrColors) == false && $fgcolor != PHPWord::DEFAULT_FONT_COLOR && !empty($fgcolor)) { $arrColors[] = $fgcolor; } } @@ -279,10 +279,10 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter $fStyle = $element->getFontStyle(); if ($fStyle instanceof PHPWord_Style_Font) { - if (in_array($fStyle->getColor(), $arrColors) == FALSE) { + if (in_array($fStyle->getColor(), $arrColors) == false) { $arrColors[] = $fStyle->getColor(); } - if (in_array($fStyle->getFgColor(), $arrColors) == FALSE) { + if (in_array($fStyle->getFgColor(), $arrColors) == false) { $arrColors[] = $fStyle->getFgColor(); } } @@ -294,7 +294,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter return $arrColors; } - private function _getDataContent() + private function getDataContent() { $pPHPWord = $this->_document; $sRTFBody = ''; @@ -309,11 +309,11 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter $_elements = $section->getElements(); foreach ($_elements as $element) { if ($element instanceof PHPWord_Section_Text) { - $sRTFBody .= $this->_getDataContent_writeText($element); + $sRTFBody .= $this->getDataContentText($element); } elseif ($element instanceof PHPWord_Section_TextBreak) { - $sRTFBody .= $this->_getDataContent_writeTextBreak(); + $sRTFBody .= $this->getDataContentTextBreak(); } elseif ($element instanceof PHPWord_Section_TextRun) { - $sRTFBody .= $this->_getDataContent_writeTextRun($element); + $sRTFBody .= $this->getDataContentTextRun($element); /* } elseif($element instanceof PHPWord_Section_Link) { $this->_writeLink($objWriter, $element); @@ -346,7 +346,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter /** * Get text */ - private function _getDataContent_writeText(PHPWord_Section_Text $text, $withoutP = false) + private function getDataContentText(PHPWord_Section_Text $text, $withoutP = false) { $sRTFText = ''; @@ -384,7 +384,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter if ($styleFont) { if ($styleFont->getColor() != null) { $idxColor = array_search($styleFont->getColor(), $this->_colorTable); - if ($idxColor !== FALSE) { + if ($idxColor !== false) { $sRTFText .= '\cf' . ($idxColor + 1); } } else { @@ -392,7 +392,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter } if ($styleFont->getName() != null) { $idxFont = array_search($styleFont->getName(), $this->_fontTable); - if ($idxFont !== FALSE) { + if ($idxFont !== false) { $sRTFText .= '\f' . $idxFont; } } else { @@ -411,7 +411,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter if ($this->_lastParagraphStyle != '' || $styleFont) { $sRTFText .= ' '; } - $sRTFText .= $text->getText(); + $sRTFText .= $text->getDataContentText(); if ($styleFont) { $sRTFText .= '\cf0'; @@ -437,7 +437,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter /** * Get text run content */ - private function _getDataContent_writeTextRun(PHPWord_Section_TextRun $textrun) + private function getDataContentTextRun(PHPWord_Section_TextRun $textrun) { $sRTFText = ''; $elements = $textrun->getElements(); @@ -446,7 +446,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter foreach ($elements as $element) { if ($element instanceof PHPWord_Section_Text) { $sRTFText .= '{'; - $sRTFText .= $this->_getDataContent_writeText($element, true); + $sRTFText .= $this->getDataContentText($element, true); $sRTFText .= '}' . PHP_EOL; } } @@ -455,12 +455,10 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter return $sRTFText; } - private function _getDataContent_writeTextBreak() + private function getDataContentTextBreak() { $this->_lastParagraphStyle = ''; return '\par' . PHP_EOL; } - - -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Writer/Word2007.php b/Classes/PHPWord/Writer/Word2007.php index b55fb556..8375c56a 100755 --- a/Classes/PHPWord/Writer/Word2007.php +++ b/Classes/PHPWord/Writer/Word2007.php @@ -115,7 +115,8 @@ class PHPWord_Writer_Word2007 implements PHPWord_Writer_IWriter $footnoteLinks = array(); $_footnoteElements = PHPWord_Footnote::getFootnoteLinkElements(); - foreach($_footnoteElements as $element) { // loop through footnote link elements + // loop through footnote link elements + foreach ($_footnoteElements as $element) { $footnoteLinks[] = $element; } @@ -204,8 +205,9 @@ class PHPWord_Writer_Word2007 implements PHPWord_Writer_IWriter $imagetype = image_type_to_mime_type($imagedata[2]); $imageext = image_type_to_extension($imagedata[2]); $imageext = str_replace('.', '', $imageext); - if ($imageext == 'jpeg') $imageext = 'jpg'; - + if ($imageext == 'jpeg') { + $imageext = 'jpg'; + } if (!in_array($imagetype, $this->_imageTypes)) { $this->_imageTypes[$imageext] = $imagetype; } @@ -262,4 +264,4 @@ class PHPWord_Writer_Word2007 implements PHPWord_Writer_IWriter $this->_chkContentTypes($element['source']); } } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Writer/Word2007/Base.php b/Classes/PHPWord/Writer/Word2007/Base.php index 3ee0823e..0ab9684d 100755 --- a/Classes/PHPWord/Writer/Word2007/Base.php +++ b/Classes/PHPWord/Writer/Word2007/Base.php @@ -108,7 +108,7 @@ class PHPWord_Writer_Word2007_Base extends PHPWord_Writer_Word2007_WriterPart $this->_writeLink($objWriter, $element, true); } elseif ($element instanceof PHPWord_Section_Image) { $this->_writeImage($objWriter, $element, true); - } elseif($element instanceof PHPWord_Section_Footnote) { + } elseif ($element instanceof PHPWord_Section_Footnote) { $this->_writeFootnoteReference($objWriter, $element, true); } } @@ -875,7 +875,8 @@ class PHPWord_Writer_Word2007_Base extends PHPWord_Writer_Word2007_WriterPart $objWriter->endElement(); } - protected function _writeFootnote(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section_Footnote $footnote) { + protected function _writeFootnote(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section_Footnote $footnote) + { $objWriter->startElement('w:footnote'); $objWriter->writeAttribute('w:id', $footnote->getReferenceId()); @@ -884,22 +885,22 @@ class PHPWord_Writer_Word2007_Base extends PHPWord_Writer_Word2007_WriterPart $objWriter->startElement('w:p'); - if($SpIsObject) { + if ($SpIsObject) { $this->_writeParagraphStyle($objWriter, $styleParagraph); - } elseif(!$SpIsObject && !is_null($styleParagraph)) { + } elseif (!$SpIsObject && !is_null($styleParagraph)) { $objWriter->startElement('w:pPr'); - $objWriter->startElement('w:pStyle'); - $objWriter->writeAttribute('w:val', $styleParagraph); - $objWriter->endElement(); + $objWriter->startElement('w:pStyle'); + $objWriter->writeAttribute('w:val', $styleParagraph); + $objWriter->endElement(); $objWriter->endElement(); } $elements = $footnote->getElements(); - if(count($elements) > 0) { - foreach($elements as $element) { - if($element instanceof PHPWord_Section_Text) { + if (count($elements) > 0) { + foreach ($elements as $element) { + if ($element instanceof PHPWord_Section_Text) { $this->_writeText($objWriter, $element, true); - } elseif($element instanceof PHPWord_Section_Link) { + } elseif ($element instanceof PHPWord_Section_Link) { $this->_writeLink($objWriter, $element, true); } } @@ -909,7 +910,8 @@ class PHPWord_Writer_Word2007_Base extends PHPWord_Writer_Word2007_WriterPart $objWriter->endElement(); // w:footnote } - protected function _writeFootnoteReference(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section_Footnote $footnote, $withoutP = false) { + protected function _writeFootnoteReference(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section_Footnote $footnote, $withoutP = false) + { if (!$withoutP) { $objWriter->startElement('w:p'); } diff --git a/Classes/PHPWord/Writer/Word2007/ContentTypes.php b/Classes/PHPWord/Writer/Word2007/ContentTypes.php index b17bdae3..56a33d69 100755 --- a/Classes/PHPWord/Writer/Word2007/ContentTypes.php +++ b/Classes/PHPWord/Writer/Word2007/ContentTypes.php @@ -50,12 +50,16 @@ class PHPWord_Writer_Word2007_ContentTypes extends PHPWord_Writer_Word2007_Write // Rels $this->_writeDefaultContentType( - $objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml' + $objWriter, + 'rels', + 'application/vnd.openxmlformats-package.relationships+xml' ); // XML $this->_writeDefaultContentType( - $objWriter, 'xml', 'application/xml' + $objWriter, + 'xml', + 'application/xml' ); // Add media content-types @@ -65,62 +69,88 @@ class PHPWord_Writer_Word2007_ContentTypes extends PHPWord_Writer_Word2007_Write // Add embedding content-types if (count($_objectTypes) > 0) { - $this->_writeDefaultContentType($objWriter, 'bin', 'application/vnd.openxmlformats-officedocument.oleObject'); + $this->_writeDefaultContentType( + $objWriter, + 'bin', + 'application/vnd.openxmlformats-officedocument.oleObject' + ); } // DocProps $this->_writeOverrideContentType( - $objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml' + $objWriter, + '/docProps/app.xml', + 'application/vnd.openxmlformats-officedocument.extended-properties+xml' ); $this->_writeOverrideContentType( - $objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml' + $objWriter, + '/docProps/core.xml', + 'application/vnd.openxmlformats-package.core-properties+xml' ); // Document $this->_writeOverrideContentType( - $objWriter, '/word/document.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml' + $objWriter, + '/word/document.xml', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml' ); // Styles $this->_writeOverrideContentType( - $objWriter, '/word/styles.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml' + $objWriter, + '/word/styles.xml', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml' ); // Numbering $this->_writeOverrideContentType( - $objWriter, '/word/numbering.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml' + $objWriter, + '/word/numbering.xml', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml' ); // Settings $this->_writeOverrideContentType( - $objWriter, '/word/settings.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml' + $objWriter, + '/word/settings.xml', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml' ); // Theme1 $this->_writeOverrideContentType( - $objWriter, '/word/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml' + $objWriter, + '/word/theme/theme1.xml', + 'application/vnd.openxmlformats-officedocument.theme+xml' ); // WebSettings $this->_writeOverrideContentType( - $objWriter, '/word/webSettings.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml' + $objWriter, + '/word/webSettings.xml', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml' ); // Font Table $this->_writeOverrideContentType( - $objWriter, '/word/fontTable.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml' + $objWriter, + '/word/fontTable.xml', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml' ); for ($i = 1; $i <= $_cHdrs; $i++) { $this->_writeOverrideContentType( - $objWriter, '/word/header' . $i . '.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml' + $objWriter, + '/word/header' . $i . '.xml', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml' ); } for ($i = 1; $i <= $_cFtrs; $i++) { $this->_writeOverrideContentType( - $objWriter, '/word/footer' . $i . '.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml' + $objWriter, + '/word/footer' . $i . '.xml', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml' ); } diff --git a/Classes/PHPWord/Writer/Word2007/Document.php b/Classes/PHPWord/Writer/Word2007/Document.php index 044dbcec..558fa72f 100755 --- a/Classes/PHPWord/Writer/Word2007/Document.php +++ b/Classes/PHPWord/Writer/Word2007/Document.php @@ -94,7 +94,7 @@ class PHPWord_Writer_Word2007_Document extends PHPWord_Writer_Word2007_Base $this->_writeObject($objWriter, $element); } elseif ($element instanceof PHPWord_TOC) { $this->_writeTOC($objWriter); - } elseif($element instanceof PHPWord_Section_Footnote) { + } elseif ($element instanceof PHPWord_Section_Footnote) { $this->_writeFootnoteReference($objWriter, $element); } } diff --git a/Classes/PHPWord/Writer/Word2007/Footnotes.php b/Classes/PHPWord/Writer/Word2007/Footnotes.php index 1bf27ee4..fe7ced0e 100644 --- a/Classes/PHPWord/Writer/Word2007/Footnotes.php +++ b/Classes/PHPWord/Writer/Word2007/Footnotes.php @@ -26,8 +26,10 @@ */ -class PHPWord_Writer_Word2007_Footnotes extends PHPWord_Writer_Word2007_Base { - public function writeFootnotes($allFootnotesCollection) { +class PHPWord_Writer_Word2007_Footnotes extends PHPWord_Writer_Word2007_Base +{ + public function writeFootnotes($allFootnotesCollection) + { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { @@ -40,8 +42,8 @@ class PHPWord_Writer_Word2007_Footnotes extends PHPWord_Writer_Word2007_Base { $objWriter->startDocument('1.0', 'UTF-8', 'yes'); $objWriter->startElement('w:footnotes'); - $objWriter->writeAttribute('xmlns:r','http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $objWriter->writeAttribute('xmlns:w','http://schemas.openxmlformats.org/wordprocessingml/2006/main'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $objWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); // write separator and continuation separator $objWriter->startElement('w:footnote'); @@ -67,8 +69,8 @@ class PHPWord_Writer_Word2007_Footnotes extends PHPWord_Writer_Word2007_Base { $objWriter->endElement(); // w:footnote - foreach($allFootnotesCollection as $footnote) { - if($footnote instanceof PHPWord_Section_Footnote) { + foreach ($allFootnotesCollection as $footnote) { + if ($footnote instanceof PHPWord_Section_Footnote) { $this->_writeFootnote($objWriter, $footnote); } } @@ -78,4 +80,4 @@ class PHPWord_Writer_Word2007_Footnotes extends PHPWord_Writer_Word2007_Base { // Return return $objWriter->getData(); } -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Writer/Word2007/FootnotesRels.php b/Classes/PHPWord/Writer/Word2007/FootnotesRels.php index 22533815..6c81b3c9 100644 --- a/Classes/PHPWord/Writer/Word2007/FootnotesRels.php +++ b/Classes/PHPWord/Writer/Word2007/FootnotesRels.php @@ -26,64 +26,61 @@ */ -class PHPWord_Writer_Word2007_FootnotesRels extends PHPWord_Writer_Word2007_WriterPart { - public function writeFootnotesRels($_relsCollection) { - // Create XML writer - $objWriter = null; - if ($this->getParentWriter()->getUseDiskCaching()) { - $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); - } else { - $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_MEMORY); +class PHPWord_Writer_Word2007_FootnotesRels extends PHPWord_Writer_Word2007_WriterPart +{ + public function writeFootnotesRels($_relsCollection) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + // Relationships to Links + foreach ($_relsCollection as $relation) { + $relationType = $relation['type']; + $relationName = $relation['target']; + $relationId = $relation['rID']; + $targetMode = ($relationType == 'hyperlink') ? 'External' : ''; + + $this->_writeRelationship($objWriter, $relationId, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/' . $relationType, $relationName, $targetMode); + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); } - // XML header - $objWriter->startDocument('1.0','UTF-8','yes'); + private function _writeRelationship(PHPWord_Shared_XMLWriter $objWriter = null, $pId = 1, $pType = '', $pTarget = '', $pTargetMode = '') + { + if ($pType != '' && $pTarget != '') { + if (strpos($pId, 'rId') === false) { + $pId = 'rId' . $pId; + } - // Relationships - $objWriter->startElement('Relationships'); - $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + // Write relationship + $objWriter->startElement('Relationship'); + $objWriter->writeAttribute('Id', $pId); + $objWriter->writeAttribute('Type', $pType); + $objWriter->writeAttribute('Target', $pTarget); - // Relationships to Links - foreach($_relsCollection as $relation) { - $relationType = $relation['type']; - $relationName = $relation['target']; - $relationId = $relation['rID']; - $targetMode = ($relationType == 'hyperlink') ? 'External' : ''; + if ($pTargetMode != '') { + $objWriter->writeAttribute('TargetMode', $pTargetMode); + } - $this->_writeRelationship( - $objWriter, - $relationId, - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/'.$relationType, - $relationName, - $targetMode - ); + $objWriter->endElement(); + } else { + throw new Exception("Invalid parameters passed."); + } } - - $objWriter->endElement(); - - // Return - return $objWriter->getData(); - } - - private function _writeRelationship(PHPWord_Shared_XMLWriter $objWriter = null, $pId = 1, $pType = '', $pTarget = '', $pTargetMode = '') { - if($pType != '' && $pTarget != '') { - if(strpos($pId, 'rId') === false) { - $pId = 'rId' . $pId; - } - - // Write relationship - $objWriter->startElement('Relationship'); - $objWriter->writeAttribute('Id', $pId); - $objWriter->writeAttribute('Type', $pType); - $objWriter->writeAttribute('Target', $pTarget); - - if($pTargetMode != '') { - $objWriter->writeAttribute('TargetMode', $pTargetMode); - } - - $objWriter->endElement(); - } else { - throw new Exception("Invalid parameters passed."); - } - } -} \ No newline at end of file +} From d2a231799de1cb169666469951e7a2acb385abc1 Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Tue, 11 Mar 2014 21:44:54 +0700 Subject: [PATCH 06/17] Code formatting for PSR1 & PSR2 - Part 2 --- Classes/PHPWord/HashTable.php | 4 +- Classes/PHPWord/Writer/ODText.php | 2 +- Classes/PHPWord/Writer/ODText/Manifest.php | 2 +- Tests/PHPWord/AutoloaderTest.php | 2 +- Tests/PHPWord/IOFactoryTest.php | 2 +- Tests/PHPWord/MediaTest.php | 2 +- .../Section/Footer/PreserveTextTest.php | 2 +- Tests/PHPWord/Section/FooterTest.php | 2 +- Tests/PHPWord/Section/FootnoteTest.php | 2 +- Tests/PHPWord/Section/HeaderTest.php | 2 +- Tests/PHPWord/Section/ImageTest.php | 2 +- Tests/PHPWord/Section/LinkTest.php | 2 +- Tests/PHPWord/Section/ListItemTest.php | 2 +- Tests/PHPWord/Section/MemoryImageTest.php | 2 +- Tests/PHPWord/Section/ObjectTest.php | 2 +- Tests/PHPWord/Section/PageBreakTest.php | 2 +- Tests/PHPWord/Section/SettingsTest.php | 2 +- Tests/PHPWord/Section/Table/CellTest.php | 2 +- Tests/PHPWord/Section/Table/RowTest.php | 2 +- Tests/PHPWord/Section/TableTest.php | 2 +- Tests/PHPWord/Section/TextBreakTest.php | 2 +- Tests/PHPWord/Section/TextRunTest.php | 2 +- Tests/PHPWord/Section/TextTest.php | 2 +- Tests/PHPWord/Section/TitleTest.php | 2 +- Tests/PHPWord/SectionTest.php | 2 +- Tests/PHPWord/Shared/DrawingTest.php | 4 +- Tests/PHPWord/Shared/FileTest.php | 13 ++--- Tests/PHPWord/Shared/FontTest.php | 2 +- Tests/PHPWord/Shared/StringTest.php | 2 - Tests/PHPWord/Style/CellTest.php | 3 +- Tests/PHPWord/Style/FontTest.php | 2 +- Tests/PHPWord/Style/ImageTest.php | 4 +- Tests/PHPWord/Style/ListItemTest.php | 4 +- Tests/PHPWord/Style/ParagraphTest.php | 3 +- Tests/PHPWord/Style/RowTest.php | 2 - Tests/PHPWord/Style/TOCTest.php | 2 - Tests/PHPWord/Style/TableFullTest.php | 2 - Tests/PHPWord/Style/TableTest.php | 2 - Tests/PHPWord/Style/TabsTest.php | 1 - Tests/PHPWord/TemplateTest.php | 2 +- Tests/PHPWord/Writer/Word2007/BaseTest.php | 54 +++++++++---------- .../PHPWord/Writer/Word2007/DocumentTest.php | 4 +- Tests/PHPWord/Writer/Word2007/StylesTest.php | 2 +- Tests/_inc/TestHelperDOCX.php | 20 +++---- 44 files changed, 81 insertions(+), 99 deletions(-) diff --git a/Classes/PHPWord/HashTable.php b/Classes/PHPWord/HashTable.php index 5b6fbd04..f2ef3148 100755 --- a/Classes/PHPWord/HashTable.php +++ b/Classes/PHPWord/HashTable.php @@ -69,7 +69,7 @@ class PHPWord_HashTable // Check if an array was passed if ($pSource == null) { return; - } else if (!is_array($pSource)) { + } elseif (!is_array($pSource)) { throw new Exception('Invalid array parameter passed.'); } @@ -91,7 +91,7 @@ class PHPWord_HashTable $hashIndex = $pSource->getHashIndex(); if (is_null($hashIndex)) { $hashCode = $pSource->getHashCode(); - } else if (isset ($this->_keyMap[$hashIndex])) { + } elseif (isset ($this->_keyMap[$hashIndex])) { $hashCode = $this->_keyMap[$hashIndex]; } else { $hashCode = $pSource->getHashCode(); diff --git a/Classes/PHPWord/Writer/ODText.php b/Classes/PHPWord/Writer/ODText.php index 16a60304..71775630 100755 --- a/Classes/PHPWord/Writer/ODText.php +++ b/Classes/PHPWord/Writer/ODText.php @@ -161,7 +161,7 @@ class PHPWord_Writer_ODText implements PHPWord_Writer_IWriter } $objZip->addFromString('Pictures/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); - } else if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPWord_Shape_MemoryDrawing) { + } elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPWord_Shape_MemoryDrawing) { ob_start(); call_user_func( $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(), diff --git a/Classes/PHPWord/Writer/ODText/Manifest.php b/Classes/PHPWord/Writer/ODText/Manifest.php index f9815941..4b1c6b26 100755 --- a/Classes/PHPWord/Writer/ODText/Manifest.php +++ b/Classes/PHPWord/Writer/ODText/Manifest.php @@ -86,7 +86,7 @@ class PHPWord_Writer_ODText_Manifest extends PHPWord_Writer_ODText_WriterPart $objWriter->writeAttribute('manifest:media-type', $mimeType); $objWriter->writeAttribute('manifest:full-path', 'Pictures/' . str_replace(' ', '_', $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getIndexedFilename())); $objWriter->endElement(); - } else if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPWord_Shape_MemoryDrawing) { + } elseif ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPWord_Shape_MemoryDrawing) { $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType()); $extension = explode('/', $extension); $extension = $extension[1]; diff --git a/Tests/PHPWord/AutoloaderTest.php b/Tests/PHPWord/AutoloaderTest.php index 2ad280f0..45ee6066 100644 --- a/Tests/PHPWord/AutoloaderTest.php +++ b/Tests/PHPWord/AutoloaderTest.php @@ -29,4 +29,4 @@ class AutoloaderTest extends PHPUnit_Framework_TestCase Autoloader::autoload('PhpOffice\\PhpWord\\Exceptions\\InvalidStyleException'); // TODO change this class to the main PHPWord class when it is namespaced $this->assertTrue(in_array('PhpOffice\\PhpWord\\Exceptions\\InvalidStyleException', get_declared_classes()), 'PhpOffice\\PhpWord\\Autoloader::autoload() failed to autoload the PhpOffice\\PhpWord\\Exceptions\\InvalidStyleException class'); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/IOFactoryTest.php b/Tests/PHPWord/IOFactoryTest.php index a7c05bcf..0c2976b6 100644 --- a/Tests/PHPWord/IOFactoryTest.php +++ b/Tests/PHPWord/IOFactoryTest.php @@ -59,4 +59,4 @@ class IOFactoryTest extends \PHPUnit_Framework_TestCase $this->assertEquals(PHPWord_IOFactory::createWriter($oPHPWord, 'Word2007'), new PHPWord_Writer_Word2007($oPHPWord)); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/MediaTest.php b/Tests/PHPWord/MediaTest.php index 25cdab0a..86e9651a 100644 --- a/Tests/PHPWord/MediaTest.php +++ b/Tests/PHPWord/MediaTest.php @@ -25,4 +25,4 @@ class MediaTest extends \PHPUnit_Framework_TestCase { $this->assertAttributeEquals(PHPWord_Media::getFooterMediaElements(), '_footerMedia', 'PHPWord_Media'); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/Footer/PreserveTextTest.php b/Tests/PHPWord/Section/Footer/PreserveTextTest.php index ad6b5c24..c8297738 100644 --- a/Tests/PHPWord/Section/Footer/PreserveTextTest.php +++ b/Tests/PHPWord/Section/Footer/PreserveTextTest.php @@ -30,4 +30,4 @@ class PreserveTextTest extends \PHPUnit_Framework_TestCase $this->assertInstanceOf('PHPWord_Style_Font', $oPreserveText->getFontStyle()); $this->assertInstanceOf('PHPWord_Style_Paragraph', $oPreserveText->getParagraphStyle()); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/FooterTest.php b/Tests/PHPWord/Section/FooterTest.php index 46999b59..de1fa613 100644 --- a/Tests/PHPWord/Section/FooterTest.php +++ b/Tests/PHPWord/Section/FooterTest.php @@ -118,4 +118,4 @@ class FooterTest extends \PHPUnit_Framework_TestCase $this->assertInternalType('array', $oFooter->getElements()); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/FootnoteTest.php b/Tests/PHPWord/Section/FootnoteTest.php index a1f26494..1c798f4a 100644 --- a/Tests/PHPWord/Section/FootnoteTest.php +++ b/Tests/PHPWord/Section/FootnoteTest.php @@ -61,4 +61,4 @@ class FootnoteTest extends \PHPUnit_Framework_TestCase $oFootnote = new PHPWord_Section_Footnote(); $this->assertInternalType('array', $oFootnote->getElements()); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/HeaderTest.php b/Tests/PHPWord/Section/HeaderTest.php index d7dc3ace..f9b05318 100644 --- a/Tests/PHPWord/Section/HeaderTest.php +++ b/Tests/PHPWord/Section/HeaderTest.php @@ -161,4 +161,4 @@ class HeaderTest extends \PHPUnit_Framework_TestCase $this->assertEquals($oHeader->getType(), PHPWord_Section_Header::EVEN); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/ImageTest.php b/Tests/PHPWord/Section/ImageTest.php index 4e265db7..5bffbc0c 100644 --- a/Tests/PHPWord/Section/ImageTest.php +++ b/Tests/PHPWord/Section/ImageTest.php @@ -65,4 +65,4 @@ class ImageTest extends \PHPUnit_Framework_TestCase $oImage->setIsWatermark(true); $this->assertEquals($oImage->getIsWatermark(), true); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/LinkTest.php b/Tests/PHPWord/Section/LinkTest.php index c9f1bdca..81c5788e 100644 --- a/Tests/PHPWord/Section/LinkTest.php +++ b/Tests/PHPWord/Section/LinkTest.php @@ -45,4 +45,4 @@ class LinkTest extends \PHPUnit_Framework_TestCase $oLink->setRelationId($iVal); $this->assertEquals($oLink->getRelationId(), $iVal); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/ListItemTest.php b/Tests/PHPWord/Section/ListItemTest.php index 0b656eed..56973822 100644 --- a/Tests/PHPWord/Section/ListItemTest.php +++ b/Tests/PHPWord/Section/ListItemTest.php @@ -29,4 +29,4 @@ class ListItemTest extends \PHPUnit_Framework_TestCase $this->assertEquals($oListItem->getDepth(), $iVal); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/MemoryImageTest.php b/Tests/PHPWord/Section/MemoryImageTest.php index 9b9694d9..be53f119 100644 --- a/Tests/PHPWord/Section/MemoryImageTest.php +++ b/Tests/PHPWord/Section/MemoryImageTest.php @@ -92,4 +92,4 @@ class MemoryImageTest extends \PHPUnit_Framework_TestCase $oMemoryImage->setRelationId($iVal); $this->assertEquals($oMemoryImage->getRelationId(), $iVal); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/ObjectTest.php b/Tests/PHPWord/Section/ObjectTest.php index fa5fa24b..53d26314 100644 --- a/Tests/PHPWord/Section/ObjectTest.php +++ b/Tests/PHPWord/Section/ObjectTest.php @@ -83,4 +83,4 @@ class ObjectTest extends \PHPUnit_Framework_TestCase $oObject->setObjectId($iVal); $this->assertEquals($oObject->getObjectId(), $iVal); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/PageBreakTest.php b/Tests/PHPWord/Section/PageBreakTest.php index 01944d06..497a7c1a 100644 --- a/Tests/PHPWord/Section/PageBreakTest.php +++ b/Tests/PHPWord/Section/PageBreakTest.php @@ -16,4 +16,4 @@ class PageBreakTest extends \PHPUnit_Framework_TestCase $this->assertInstanceOf('PHPWord_Section_PageBreak', $oPageBreak); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/SettingsTest.php b/Tests/PHPWord/Section/SettingsTest.php index 505347e6..69d7fe2c 100644 --- a/Tests/PHPWord/Section/SettingsTest.php +++ b/Tests/PHPWord/Section/SettingsTest.php @@ -233,4 +233,4 @@ class SettingsTest extends \PHPUnit_Framework_TestCase $oSettings->setBreakType(); $this->assertNull($oSettings->getBreakType()); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/Table/CellTest.php b/Tests/PHPWord/Section/Table/CellTest.php index bfd7e0d0..261c9ee0 100644 --- a/Tests/PHPWord/Section/Table/CellTest.php +++ b/Tests/PHPWord/Section/Table/CellTest.php @@ -201,4 +201,4 @@ class CellTest extends \PHPUnit_Framework_TestCase $this->assertInternalType('array', $oCell->getElements()); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/Table/RowTest.php b/Tests/PHPWord/Section/Table/RowTest.php index 849abbac..c6dd762a 100644 --- a/Tests/PHPWord/Section/Table/RowTest.php +++ b/Tests/PHPWord/Section/Table/RowTest.php @@ -36,4 +36,4 @@ class RowTest extends \PHPUnit_Framework_TestCase $this->assertInstanceOf('PHPWord_Section_Table_Cell', $element); $this->assertCount(1, $oRow->getCells()); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/TableTest.php b/Tests/PHPWord/Section/TableTest.php index f207d426..6c479e36 100644 --- a/Tests/PHPWord/Section/TableTest.php +++ b/Tests/PHPWord/Section/TableTest.php @@ -54,4 +54,4 @@ class TableTest extends \PHPUnit_Framework_TestCase $element = $oTable->addCell(); $this->assertInstanceOf('PHPWord_Section_Table_Cell', $element); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/TextBreakTest.php b/Tests/PHPWord/Section/TextBreakTest.php index 86e9ac48..a75b97c4 100644 --- a/Tests/PHPWord/Section/TextBreakTest.php +++ b/Tests/PHPWord/Section/TextBreakTest.php @@ -16,4 +16,4 @@ class TextBreakTest extends \PHPUnit_Framework_TestCase $this->assertInstanceOf('PHPWord_Section_TextBreak', $oTextBreak); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/TextRunTest.php b/Tests/PHPWord/Section/TextRunTest.php index 0ea9d701..aa352fa5 100644 --- a/Tests/PHPWord/Section/TextRunTest.php +++ b/Tests/PHPWord/Section/TextRunTest.php @@ -95,4 +95,4 @@ class TextRunTest extends \PHPUnit_Framework_TestCase $this->assertInstanceOf('PHPWord_Section_Footnote', $element); $this->assertCount(1, $oTextRun->getElements()); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/TextTest.php b/Tests/PHPWord/Section/TextTest.php index 8a2bf321..b85b2028 100644 --- a/Tests/PHPWord/Section/TextTest.php +++ b/Tests/PHPWord/Section/TextTest.php @@ -40,4 +40,4 @@ class TextTest extends \PHPUnit_Framework_TestCase $oText->setParagraphStyle(array('align' => 'center', 'spaceAfter' => 100)); $this->assertInstanceOf('PHPWord_Style_Paragraph', $oText->getParagraphStyle()); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Section/TitleTest.php b/Tests/PHPWord/Section/TitleTest.php index c595ab97..c0a6185d 100644 --- a/Tests/PHPWord/Section/TitleTest.php +++ b/Tests/PHPWord/Section/TitleTest.php @@ -45,4 +45,4 @@ class TitleTest extends \PHPUnit_Framework_TestCase $oTitle->setBookmarkId($iVal); $this->assertEquals($oTitle->getBookmarkId(), $iVal); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/SectionTest.php b/Tests/PHPWord/SectionTest.php index 378fd642..3af02eca 100644 --- a/Tests/PHPWord/SectionTest.php +++ b/Tests/PHPWord/SectionTest.php @@ -35,4 +35,4 @@ class SectionTest extends \PHPUnit_Framework_TestCase $oSection = new PHPWord_Section(0); $this->assertAttributeEquals($oSection->getElements(), '_elementCollection', new PHPWord_Section(0)); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Shared/DrawingTest.php b/Tests/PHPWord/Shared/DrawingTest.php index cfebad34..c939b9c0 100644 --- a/Tests/PHPWord/Shared/DrawingTest.php +++ b/Tests/PHPWord/Shared/DrawingTest.php @@ -12,7 +12,6 @@ use PHPWord_Shared_Drawing; */ class DrawingTest extends \PHPUnit_Framework_TestCase { - /** * Test unit conversion functions with various numbers */ @@ -65,5 +64,4 @@ class DrawingTest extends \PHPUnit_Framework_TestCase $this->assertEquals($value[1], $result); } } - -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Shared/FileTest.php b/Tests/PHPWord/Shared/FileTest.php index fb7a8bd6..618d5801 100644 --- a/Tests/PHPWord/Shared/FileTest.php +++ b/Tests/PHPWord/Shared/FileTest.php @@ -12,13 +12,13 @@ use PHPWord_Shared_File; */ class FileTest extends \PHPUnit_Framework_TestCase { - /** * Test file_exists() */ - public function testFile_exists() + public function testFileExists() { - $dir = join(DIRECTORY_SEPARATOR, + $dir = join( + DIRECTORY_SEPARATOR, array(PHPWORD_TESTS_DIR_ROOT, '_files', 'templates') ); chdir($dir); @@ -30,12 +30,13 @@ class FileTest extends \PHPUnit_Framework_TestCase */ public function testRealpath() { - $dir = join(DIRECTORY_SEPARATOR, - array(PHPWORD_TESTS_DIR_ROOT, '_files', 'templates')); + $dir = join( + DIRECTORY_SEPARATOR, + array(PHPWORD_TESTS_DIR_ROOT, '_files', 'templates') + ); chdir($dir); $file = 'blank.docx'; $expected = $dir . DIRECTORY_SEPARATOR . $file; $this->assertEquals($expected, PHPWord_Shared_File::realpath($file)); } - } diff --git a/Tests/PHPWord/Shared/FontTest.php b/Tests/PHPWord/Shared/FontTest.php index f2950abb..74ece26a 100644 --- a/Tests/PHPWord/Shared/FontTest.php +++ b/Tests/PHPWord/Shared/FontTest.php @@ -43,4 +43,4 @@ class FontTest extends \PHPUnit_Framework_TestCase $result = PHPWord_Shared_Font::pointSizeToTwips($original); $this->assertEquals($original * 20, $result); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Shared/StringTest.php b/Tests/PHPWord/Shared/StringTest.php index 9bb0d63b..a0ab7ad0 100644 --- a/Tests/PHPWord/Shared/StringTest.php +++ b/Tests/PHPWord/Shared/StringTest.php @@ -12,7 +12,6 @@ use PHPWord_Shared_String; */ class StringTest extends \PHPUnit_Framework_TestCase { - /** * Test getIsMbstringEnabled() and getIsIconvEnabled() */ @@ -41,5 +40,4 @@ class StringTest extends \PHPUnit_Framework_TestCase $returned = PHPWord_Shared_String::FormatNumber('1022.1234'); $this->assertEquals($expected, $returned); } - } diff --git a/Tests/PHPWord/Style/CellTest.php b/Tests/PHPWord/Style/CellTest.php index 759f6e0e..61ef93f4 100644 --- a/Tests/PHPWord/Style/CellTest.php +++ b/Tests/PHPWord/Style/CellTest.php @@ -12,7 +12,6 @@ use PHPWord_Style_Cell; */ class CellTest extends \PHPUnit_Framework_TestCase { - /** * Test setting style with normal value */ @@ -75,4 +74,4 @@ class CellTest extends \PHPUnit_Framework_TestCase $object->setStyleValue('_borderSize', $value); $this->assertEquals($expected, $object->getBorderSize()); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Style/FontTest.php b/Tests/PHPWord/Style/FontTest.php index eb29cd5c..375ebe5b 100644 --- a/Tests/PHPWord/Style/FontTest.php +++ b/Tests/PHPWord/Style/FontTest.php @@ -114,4 +114,4 @@ class FontTest extends \PHPUnit_Framework_TestCase $this->assertEquals(720, $lineHeight); $this->assertEquals('auto', $lineRule); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Style/ImageTest.php b/Tests/PHPWord/Style/ImageTest.php index 52d0b4c2..60af0b6e 100644 --- a/Tests/PHPWord/Style/ImageTest.php +++ b/Tests/PHPWord/Style/ImageTest.php @@ -12,7 +12,6 @@ use PHPWord_Style_Image; */ class ImageTest extends \PHPUnit_Framework_TestCase { - /** * Test setting style with normal value */ @@ -67,5 +66,4 @@ class ImageTest extends \PHPUnit_Framework_TestCase $object = new PHPWord_Style_Image(); $object->setWrappingStyle('foo'); } - -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Style/ListItemTest.php b/Tests/PHPWord/Style/ListItemTest.php index 9b9f6ec9..7185e25e 100644 --- a/Tests/PHPWord/Style/ListItemTest.php +++ b/Tests/PHPWord/Style/ListItemTest.php @@ -12,7 +12,6 @@ use PHPWord_Style_ListItem; */ class ListItemTest extends \PHPUnit_Framework_TestCase { - /** * Test construct */ @@ -47,5 +46,4 @@ class ListItemTest extends \PHPUnit_Framework_TestCase $object->setListType($value); $this->assertEquals($value, $object->getListType()); } - -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Style/ParagraphTest.php b/Tests/PHPWord/Style/ParagraphTest.php index e61ff8fd..94550da1 100644 --- a/Tests/PHPWord/Style/ParagraphTest.php +++ b/Tests/PHPWord/Style/ParagraphTest.php @@ -133,5 +133,4 @@ class ParagraphTest extends \PHPUnit_Framework_TestCase $object->setLineHeight('12.5pt'); $this->assertEquals(12.5, $object->getLineHeight()); } - -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Style/RowTest.php b/Tests/PHPWord/Style/RowTest.php index 63c05d61..3d2f9b2f 100644 --- a/Tests/PHPWord/Style/RowTest.php +++ b/Tests/PHPWord/Style/RowTest.php @@ -12,7 +12,6 @@ use PHPWord_Style_Row; */ class RowTest extends \PHPUnit_Framework_TestCase { - /** * Test properties with normal value */ @@ -39,5 +38,4 @@ class RowTest extends \PHPUnit_Framework_TestCase $this->assertEquals($expected, $object->$get()); } } - } diff --git a/Tests/PHPWord/Style/TOCTest.php b/Tests/PHPWord/Style/TOCTest.php index 78ac6506..80e34d74 100644 --- a/Tests/PHPWord/Style/TOCTest.php +++ b/Tests/PHPWord/Style/TOCTest.php @@ -12,7 +12,6 @@ use PHPWord_Style_TOC; */ class TOCTest extends \PHPUnit_Framework_TestCase { - /** * Test properties with normal value */ @@ -37,5 +36,4 @@ class TOCTest extends \PHPUnit_Framework_TestCase $this->assertEquals(null, $object->$get()); } } - } diff --git a/Tests/PHPWord/Style/TableFullTest.php b/Tests/PHPWord/Style/TableFullTest.php index 10855d55..6261404d 100644 --- a/Tests/PHPWord/Style/TableFullTest.php +++ b/Tests/PHPWord/Style/TableFullTest.php @@ -12,7 +12,6 @@ use PHPWord_Style_TableFull; */ class TableFullTest extends \PHPUnit_Framework_TestCase { - /** * Test class construction * @@ -132,5 +131,4 @@ class TableFullTest extends \PHPUnit_Framework_TestCase } $this->assertEquals($values, $object->getCellMargin()); } - } diff --git a/Tests/PHPWord/Style/TableTest.php b/Tests/PHPWord/Style/TableTest.php index 93f4ebfc..61459aad 100644 --- a/Tests/PHPWord/Style/TableTest.php +++ b/Tests/PHPWord/Style/TableTest.php @@ -12,7 +12,6 @@ use PHPWord_Style_Table; */ class TableTest extends \PHPUnit_Framework_TestCase { - /** * Test set style value */ @@ -50,5 +49,4 @@ class TableTest extends \PHPUnit_Framework_TestCase } $this->assertEquals($values, $object->getCellMargin()); } - } diff --git a/Tests/PHPWord/Style/TabsTest.php b/Tests/PHPWord/Style/TabsTest.php index 5d318610..1be0c350 100644 --- a/Tests/PHPWord/Style/TabsTest.php +++ b/Tests/PHPWord/Style/TabsTest.php @@ -42,5 +42,4 @@ class TabsTest extends \PHPUnit_Framework_TestCase $this->assertEquals(1440, $element->getAttribute('w:pos')); $this->assertEquals('dot', $element->getAttribute('w:leader')); } - } diff --git a/Tests/PHPWord/TemplateTest.php b/Tests/PHPWord/TemplateTest.php index 8c17d2e3..65db9850 100644 --- a/Tests/PHPWord/TemplateTest.php +++ b/Tests/PHPWord/TemplateTest.php @@ -115,4 +115,4 @@ class TemplateTest extends \PHPUnit_Framework_TestCase */ @$template->applyXslStyleSheet($xslDOMDocument); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Writer/Word2007/BaseTest.php b/Tests/PHPWord/Writer/Word2007/BaseTest.php index 534dd2a6..e477eee8 100644 --- a/Tests/PHPWord/Writer/Word2007/BaseTest.php +++ b/Tests/PHPWord/Writer/Word2007/BaseTest.php @@ -20,7 +20,7 @@ class BaseTest extends \PHPUnit_Framework_TestCase TestHelperDOCX::clear(); } - public function testWriteImage_Position() + public function testWriteImagePosition() { $PHPWord = new PHPWord(); $section = $PHPWord->createSection(); @@ -42,7 +42,7 @@ class BaseTest extends \PHPUnit_Framework_TestCase $this->assertRegExp('/position:absolute;/', $style); } - public function testWriteParagraphStyle_Align() + public function testWriteParagraphStyleAlign() { $PHPWord = new PHPWord(); $section = $PHPWord->createSection(); @@ -55,34 +55,10 @@ class BaseTest extends \PHPUnit_Framework_TestCase $this->assertEquals('right', $element->getAttribute('w:val')); } - public function testWriteCellStyle_CellGridSpan() - { - $PHPWord = new PHPWord(); - $section = $PHPWord->createSection(); - - $table = $section->addTable(); - - $table->addRow(); - $cell = $table->addCell(200); - $cell->getStyle()->setGridSpan(5); - - $table->addRow(); - $table->addCell(40); - $table->addCell(40); - $table->addCell(40); - $table->addCell(40); - $table->addCell(40); - - $doc = TestHelperDOCX::getDocument($PHPWord); - $element = $doc->getElement('/w:document/w:body/w:tbl/w:tr/w:tc/w:tcPr/w:gridSpan'); - - $this->assertEquals(5, $element->getAttribute('w:val')); - } - /** * Test write paragraph pagination */ - public function testWriteParagraphStyle_Pagination() + public function testWriteParagraphStylePagination() { // Create the doc $PHPWord = new PHPWord(); @@ -108,4 +84,28 @@ class BaseTest extends \PHPUnit_Framework_TestCase $this->assertEquals($expected, $element->getAttribute('w:val')); } } + + public function testWriteCellStyleCellGridSpan() + { + $PHPWord = new PHPWord(); + $section = $PHPWord->createSection(); + + $table = $section->addTable(); + + $table->addRow(); + $cell = $table->addCell(200); + $cell->getStyle()->setGridSpan(5); + + $table->addRow(); + $table->addCell(40); + $table->addCell(40); + $table->addCell(40); + $table->addCell(40); + $table->addCell(40); + + $doc = TestHelperDOCX::getDocument($PHPWord); + $element = $doc->getElement('/w:document/w:body/w:tbl/w:tr/w:tc/w:tcPr/w:gridSpan'); + + $this->assertEquals(5, $element->getAttribute('w:val')); + } } diff --git a/Tests/PHPWord/Writer/Word2007/DocumentTest.php b/Tests/PHPWord/Writer/Word2007/DocumentTest.php index 5d91ebab..22efe7d0 100644 --- a/Tests/PHPWord/Writer/Word2007/DocumentTest.php +++ b/Tests/PHPWord/Writer/Word2007/DocumentTest.php @@ -22,7 +22,7 @@ class DocumentTest extends \PHPUnit_Framework_TestCase TestHelperDOCX::clear(); } - public function testWriteEndSection_PageNumbering() + public function testWriteEndSectionPageNumbering() { $PHPWord = new PHPWord(); $section = $PHPWord->createSection(); @@ -33,4 +33,4 @@ class DocumentTest extends \PHPUnit_Framework_TestCase $this->assertEquals(2, $element->getAttribute('w:start')); } -} \ No newline at end of file +} diff --git a/Tests/PHPWord/Writer/Word2007/StylesTest.php b/Tests/PHPWord/Writer/Word2007/StylesTest.php index 9fd19335..39162eae 100644 --- a/Tests/PHPWord/Writer/Word2007/StylesTest.php +++ b/Tests/PHPWord/Writer/Word2007/StylesTest.php @@ -51,4 +51,4 @@ class StylesTest extends \PHPUnit_Framework_TestCase $element = $doc->getElement($path, $file); $this->assertEquals('Normal', $element->getAttribute('w:val')); } -} \ No newline at end of file +} diff --git a/Tests/_inc/TestHelperDOCX.php b/Tests/_inc/TestHelperDOCX.php index 5c603b0b..c9dd88f8 100644 --- a/Tests/_inc/TestHelperDOCX.php +++ b/Tests/_inc/TestHelperDOCX.php @@ -15,8 +15,8 @@ class TestHelperDOCX public static function getDocument(PHPWord $PHPWord) { self::$file = tempnam(sys_get_temp_dir(), 'PHPWord'); - if(!is_dir(sys_get_temp_dir().'/PHPWord_Unit_Test/')){ - mkdir(sys_get_temp_dir().'/PHPWord_Unit_Test/'); + if (!is_dir(sys_get_temp_dir() . '/PHPWord_Unit_Test/')) { + mkdir(sys_get_temp_dir() . '/PHPWord_Unit_Test/'); } $objWriter = \PHPWord_IOFactory::createWriter($PHPWord, 'Word2007'); @@ -29,16 +29,16 @@ class TestHelperDOCX $zip->close(); } - return new Xml_Document(sys_get_temp_dir().'/PHPWord_Unit_Test/'); + return new Xml_Document(sys_get_temp_dir() . '/PHPWord_Unit_Test/'); } public static function clear() { - if(file_exists(self::$file)){ - unlink(self::$file); + if (file_exists(self::$file)) { + unlink(self::$file); } - if(is_dir(sys_get_temp_dir().'/PHPWord_Unit_Test/')){ - self::deleteDir(sys_get_temp_dir().'/PHPWord_Unit_Test/'); + if (is_dir(sys_get_temp_dir() . '/PHPWord_Unit_Test/')) { + self::deleteDir(sys_get_temp_dir() . '/PHPWord_Unit_Test/'); } } @@ -94,9 +94,9 @@ class Xml_Document } $this->xpath = null; - $this->file = $file; + $this->file = $file; - $file = $this->path . '/' . $file; + $file = $this->path . '/' . $file; $this->dom = new DOMDocument(); $this->dom->load($file); return $this->dom; @@ -121,4 +121,4 @@ class Xml_Document $elements = $this->xpath->query($path); return $elements->item(0); } -} \ No newline at end of file +} From 589e603277e01793742888349f9bba9445d147c6 Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Wed, 12 Mar 2014 00:12:55 +0700 Subject: [PATCH 07/17] Unit test for Reader and additional methods for DocumentProperties, adapted from PHPExcel --- Classes/PHPWord/DocumentProperties.php | 279 ++++++++++++++++++++++++- Classes/PHPWord/Reader/Word2007.php | 21 +- Classes/PHPWord/Writer/RTF.php | 2 +- Tests/PHPWord/Reader/Word2007.php | 69 ++++++ Tests/_files/documents/reader.docx | Bin 0 -> 14208 bytes Tests/_inc/TestHelperDOCX.php | 67 +----- Tests/_inc/XmlDocument.php | 66 ++++++ Tests/bootstrap.php | 1 + 8 files changed, 417 insertions(+), 88 deletions(-) create mode 100644 Tests/PHPWord/Reader/Word2007.php create mode 100644 Tests/_files/documents/reader.docx create mode 100644 Tests/_inc/XmlDocument.php diff --git a/Classes/PHPWord/DocumentProperties.php b/Classes/PHPWord/DocumentProperties.php index 7c2aec24..3fc097b4 100755 --- a/Classes/PHPWord/DocumentProperties.php +++ b/Classes/PHPWord/DocumentProperties.php @@ -30,6 +30,13 @@ */ class PHPWord_DocumentProperties { + /** Constants */ + const PROPERTY_TYPE_BOOLEAN = 'b'; + const PROPERTY_TYPE_INTEGER = 'i'; + const PROPERTY_TYPE_FLOAT = 'f'; + const PROPERTY_TYPE_DATE = 'd'; + const PROPERTY_TYPE_STRING = 's'; + const PROPERTY_TYPE_UNKNOWN = 'u'; /** * Creator @@ -101,21 +108,36 @@ class PHPWord_DocumentProperties */ private $_company; + /** + * Manager + * + * @var string + */ + private $_manager; + + /** + * Custom Properties + * + * @var string + */ + private $_customProperties = array(); + /** * Create new PHPWord_DocumentProperties */ public function __construct() { - $this->_creator = ''; + $this->_creator = ''; $this->_lastModifiedBy = $this->_creator; - $this->_created = time(); - $this->_modified = time(); - $this->_title = ''; - $this->_subject = ''; - $this->_description = ''; - $this->_keywords = ''; - $this->_category = ''; - $this->_company = ''; + $this->_created = time(); + $this->_modified = time(); + $this->_title = ''; + $this->_subject = ''; + $this->_description = ''; + $this->_keywords = ''; + $this->_category = ''; + $this->_company = ''; + $this->_manager = ''; } /** @@ -343,4 +365,243 @@ class PHPWord_DocumentProperties $this->_company = $pValue; return $this; } + + /** + * Get Manager + * + * @return string + */ + public function getManager() + { + return $this->_manager; + } + + /** + * Set Manager + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setManager($pValue = '') + { + $this->_manager = $pValue; + return $this; + } + + /** + * Get a List of Custom Property Names + * + * @return array of string + */ + public function getCustomProperties() + { + return array_keys($this->_customProperties); + } + + /** + * Check if a Custom Property is defined + * + * @param string $propertyName + * @return boolean + */ + public function isCustomPropertySet($propertyName) + { + return isset($this->_customProperties[$propertyName]); + } + + /** + * Get a Custom Property Value + * + * @param string $propertyName + * @return string + */ + public function getCustomPropertyValue($propertyName) + { + if (isset($this->_customProperties[$propertyName])) { + return $this->_customProperties[$propertyName]['value']; + } + + } + + /** + * Get a Custom Property Type + * + * @param string $propertyName + * @return string + */ + public function getCustomPropertyType($propertyName) + { + if (isset($this->_customProperties[$propertyName])) { + return $this->_customProperties[$propertyName]['type']; + } + + } + + /** + * Set a Custom Property + * + * @param string $propertyName + * @param mixed $propertyValue + * @param string $propertyType + * 'i': Integer + * 'f': Floating Point + * 's': String + * 'd': Date/Time + * 'b': Boolean + * @return PHPExcel_DocumentProperties + */ + public function setCustomProperty($propertyName, $propertyValue = '', $propertyType = null) + { + if (($propertyType === null) || (!in_array($propertyType, array( + self::PROPERTY_TYPE_INTEGER, + self::PROPERTY_TYPE_FLOAT, + self::PROPERTY_TYPE_STRING, + self::PROPERTY_TYPE_DATE, + self::PROPERTY_TYPE_BOOLEAN + )))) { + if ($propertyValue === null) { + $propertyType = self::PROPERTY_TYPE_STRING; + } elseif (is_float($propertyValue)) { + $propertyType = self::PROPERTY_TYPE_FLOAT; + } elseif (is_int($propertyValue)) { + $propertyType = self::PROPERTY_TYPE_INTEGER; + } elseif (is_bool($propertyValue)) { + $propertyType = self::PROPERTY_TYPE_BOOLEAN; + } else { + $propertyType = self::PROPERTY_TYPE_STRING; + } + } + + $this->_customProperties[$propertyName] = array( + 'value' => $propertyValue, + 'type' => $propertyType + ); + return $this; + } + + /** + * Convert document propery based on type + * + * @param mixed $propertyValue + * @param string $propertyType + * @return mixed + */ + public static function convertProperty($propertyValue, $propertyType) + { + switch ($propertyType) { + case 'empty': // Empty + return ''; + break; + case 'null': // Null + return null; + break; + case 'i1': // 1-Byte Signed Integer + case 'i2': // 2-Byte Signed Integer + case 'i4': // 4-Byte Signed Integer + case 'i8': // 8-Byte Signed Integer + case 'int': // Integer + return (int) $propertyValue; + break; + case 'ui1': // 1-Byte Unsigned Integer + case 'ui2': // 2-Byte Unsigned Integer + case 'ui4': // 4-Byte Unsigned Integer + case 'ui8': // 8-Byte Unsigned Integer + case 'uint': // Unsigned Integer + return abs((int) $propertyValue); + break; + case 'r4': // 4-Byte Real Number + case 'r8': // 8-Byte Real Number + case 'decimal': // Decimal + return (float) $propertyValue; + break; + case 'lpstr': // LPSTR + case 'lpwstr': // LPWSTR + case 'bstr': // Basic String + return $propertyValue; + break; + case 'date': // Date and Time + case 'filetime': // File Time + return strtotime($propertyValue); + break; + case 'bool': // Boolean + return ($propertyValue == 'true') ? true : false; + break; + case 'cy': // Currency + case 'error': // Error Status Code + case 'vector': // Vector + case 'array': // Array + case 'blob': // Binary Blob + case 'oblob': // Binary Blob Object + case 'stream': // Binary Stream + case 'ostream': // Binary Stream Object + case 'storage': // Binary Storage + case 'ostorage': // Binary Storage Object + case 'vstream': // Binary Versioned Stream + case 'clsid': // Class ID + case 'cf': // Clipboard Data + return $propertyValue; + break; + } + + return $propertyValue; + } + + /** + * Convert document property type + * + * @param string $propertyType + * @return mixed + */ + public static function convertPropertyType($propertyType) + { + switch ($propertyType) { + case 'i1': // 1-Byte Signed Integer + case 'i2': // 2-Byte Signed Integer + case 'i4': // 4-Byte Signed Integer + case 'i8': // 8-Byte Signed Integer + case 'int': // Integer + case 'ui1': // 1-Byte Unsigned Integer + case 'ui2': // 2-Byte Unsigned Integer + case 'ui4': // 4-Byte Unsigned Integer + case 'ui8': // 8-Byte Unsigned Integer + case 'uint': // Unsigned Integer + return self::PROPERTY_TYPE_INTEGER; + break; + case 'r4': // 4-Byte Real Number + case 'r8': // 8-Byte Real Number + case 'decimal': // Decimal + return self::PROPERTY_TYPE_FLOAT; + break; + case 'empty': // Empty + case 'null': // Null + case 'lpstr': // LPSTR + case 'lpwstr': // LPWSTR + case 'bstr': // Basic String + return self::PROPERTY_TYPE_STRING; + break; + case 'date': // Date and Time + case 'filetime': // File Time + return self::PROPERTY_TYPE_DATE; + break; + case 'bool': // Boolean + return self::PROPERTY_TYPE_BOOLEAN; + break; + case 'cy': // Currency + case 'error': // Error Status Code + case 'vector': // Vector + case 'array': // Array + case 'blob': // Binary Blob + case 'oblob': // Binary Blob Object + case 'stream': // Binary Stream + case 'ostream': // Binary Stream Object + case 'storage': // Binary Storage + case 'ostorage': // Binary Storage Object + case 'vstream': // Binary Versioned Stream + case 'clsid': // Class ID + case 'cf': // Clipboard Data + return self::PROPERTY_TYPE_UNKNOWN; + break; + } + return self::PROPERTY_TYPE_UNKNOWN; + } } diff --git a/Classes/PHPWord/Reader/Word2007.php b/Classes/PHPWord/Reader/Word2007.php index ebe5ef9c..c1886e42 100644 --- a/Classes/PHPWord/Reader/Word2007.php +++ b/Classes/PHPWord/Reader/Word2007.php @@ -38,7 +38,6 @@ if (!defined('PHPWORD_BASE_PATH')) { class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements PHPWord_Reader_IReader { - /** * Create a new PHPWord_Reader_Word2007 instance */ @@ -57,8 +56,7 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements // Check if file exists if (!file_exists($pFilename)) { throw new PHPWord_Exception( - "Could not open " . $pFilename . - " for reading! File does not exist." + "Could not open {$pFilename} for reading! File does not exist." ); } @@ -123,16 +121,13 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements * Loads PHPWord from file * * @param string $pFilename - * @return PHPWord + * @return PHPWord|null */ public function load($pFilename) { - // Check if file exists - if (!file_exists($pFilename)) { - throw new PHPWord_Exception( - "Could not open " . $pFilename . - " for reading! File does not exist." - ); + // Check if file exists and can be read + if (!$this->canRead($pFilename)) { + return; } // Initialisations @@ -211,7 +206,7 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements foreach ($xmlDoc->body->children() as $elm) { $elmName = $elm->getName(); if ($elmName == 'p') { // Paragraph/section - // Create new section if section section found + // Create new section if section setting found if ($elm->pPr->sectPr) { $section->setSettings($this->loadSectionSettings($elm->pPr)); $section = $word->createSection(); @@ -262,8 +257,8 @@ class PHPWord_Reader_Word2007 extends PHPWord_Reader_Abstract implements } unset($pStyle); unset($fStyle); - $hasParagraphStyle = $elm->pPr && ($elm->pPr != ''); - $hasFontStyle = $elm->rPr && ($elm->rPr != ''); + $hasParagraphStyle = isset($elm->pPr); + $hasFontStyle = isset($elm->rPr); $styleName = (string)$elm->name['val']; if ($hasParagraphStyle) { $pStyle = $this->loadParagraphStyle($elm); diff --git a/Classes/PHPWord/Writer/RTF.php b/Classes/PHPWord/Writer/RTF.php index c730c9c3..66ec7383 100755 --- a/Classes/PHPWord/Writer/RTF.php +++ b/Classes/PHPWord/Writer/RTF.php @@ -411,7 +411,7 @@ class PHPWord_Writer_RTF implements PHPWord_Writer_IWriter if ($this->_lastParagraphStyle != '' || $styleFont) { $sRTFText .= ' '; } - $sRTFText .= $text->getDataContentText(); + $sRTFText .= $text->getText(); if ($styleFont) { $sRTFText .= '\cf0'; diff --git a/Tests/PHPWord/Reader/Word2007.php b/Tests/PHPWord/Reader/Word2007.php new file mode 100644 index 00000000..cbd500ff --- /dev/null +++ b/Tests/PHPWord/Reader/Word2007.php @@ -0,0 +1,69 @@ +assertTrue($object->canRead($file)); + } + + /** + * Test canRead() failure + * + * @expectedException Exception + */ + public function testCanReadFailed() + { + $dir = join( + DIRECTORY_SEPARATOR, + array(PHPWORD_TESTS_DIR_ROOT, '_files', 'documents') + ); + $object = new PHPWord_Reader_Word2007; + $file = $dir . DIRECTORY_SEPARATOR . 'foo.docx'; + $this->assertFalse($object->canRead($file)); + $object = PHPWord_IOFactory::load($file); + } + + /** + * Test load document + */ + public function testLoad() + { + $dir = join( + DIRECTORY_SEPARATOR, + array(PHPWORD_TESTS_DIR_ROOT, '_files', 'documents') + ); + $file = $dir . DIRECTORY_SEPARATOR . 'reader.docx'; + $object = PHPWord_IOFactory::load($file); + $this->assertInstanceOf('PHPWord', $object); + } +} diff --git a/Tests/_files/documents/reader.docx b/Tests/_files/documents/reader.docx new file mode 100644 index 0000000000000000000000000000000000000000..e2ceeb646e699713e15fb13b7f0da74be49688ee G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+6MmF!^G(Lk;t`RDA0=Tlv5n1$@?qb40jS0a?f4ESE!K22KX6LWP@+hkn#9M=|JaKnd16g45^FPPuk76A#vT#435sR zNLTDbTXOMr+Fs5(sIevtn)ZNAXq^p3NDPJBU7oCv2Z0zRo;BS5kJ)Qw$%6jj}MRAaL7;Y5;embs~Z;&(k> zl?|o*W-d^^K^ifs&kv>Umil3!neZt06{hqC;z{zTFTiDkmGc7ufH*3)XuIhd6HN&w zr{u@Sg4YPIzs-l;g4$fa1pNz^AXNqJ`}ouUW9a1IXlwmn7trrI`uizuoJ$sz1`Alj z4|&yFK3Nb)H~U7aoLXZrETgr}T6*v4U?(jBNi&&k=0G z4Y|vQG(HCV8#A<8)puSkR$Z^L>Bx!4Peb~3oz$1Q9%QXu z+0<**GQ~|YE&`j{8WX{ynkjUXqJyeweTxkX1*yxJNbat95EEr@brE+`(Xd)zt0&sr z9gQ!iT5x8!k5mTdR~wL4%9Z}q6)|BvlK(E?-*+$kRX`C) zJ^!+o;aA|l=WYKLxChG7`@gcdf0guWF7KbR2w?vvv-el{uW5mQ!ch?Zmn6YoMf{or z@}~$h)c-9b`YZg`NX?&cVZ49B|1ECwEB;rf`k(j(f`8(F zak2j@;olw4f8qgvJ5ZqaS2y&p=wID&f8vSW|MB_%a?bq<{&&;-ClmmXr~k{V|1i|Q l!vB59{44y9@vrcI4WM$8Z$LT<03d*VA|N#close(); } - return new Xml_Document(sys_get_temp_dir() . '/PHPWord_Unit_Test/'); + return new XmlDocument(sys_get_temp_dir() . '/PHPWord_Unit_Test/'); } public static function clear() @@ -60,65 +59,3 @@ class TestHelperDOCX rmdir($dir); } } - -class Xml_Document -{ - /** @var string $path */ - private $path; - - /** @var \DOMDocument $dom */ - private $dom; - - /** @var \DOMXpath $xpath */ - private $xpath; - - /** @var string $file */ - private $file; - - /** - * @param string $path - */ - public function __construct($path) - { - $this->path = realpath($path); - } - - /** - * @param string $file - * @return \DOMDocument - */ - public function getFileDom($file = 'word/document.xml') - { - if (null !== $this->dom && $file === $this->file) { - return $this->dom; - } - - $this->xpath = null; - $this->file = $file; - - $file = $this->path . '/' . $file; - $this->dom = new DOMDocument(); - $this->dom->load($file); - return $this->dom; - } - - /** - * @param string $path - * @param string $file - * @return \DOMElement - */ - public function getElement($path, $file = 'word/document.xml') - { - if ($this->dom === null || $file !== $this->file) { - $this->getFileDom($file); - } - - if (null === $this->xpath) { - $this->xpath = new \DOMXpath($this->dom); - - } - - $elements = $this->xpath->query($path); - return $elements->item(0); - } -} diff --git a/Tests/_inc/XmlDocument.php b/Tests/_inc/XmlDocument.php new file mode 100644 index 00000000..2ec27a3b --- /dev/null +++ b/Tests/_inc/XmlDocument.php @@ -0,0 +1,66 @@ +path = realpath($path); + } + + /** + * @param string $file + * @return \DOMDocument + */ + public function getFileDom($file = 'word/document.xml') + { + if (null !== $this->dom && $file === $this->file) { + return $this->dom; + } + + $this->xpath = null; + $this->file = $file; + + $file = $this->path . '/' . $file; + $this->dom = new DOMDocument(); + $this->dom->load($file); + return $this->dom; + } + + /** + * @param string $path + * @param string $file + * @return \DOMElement + */ + public function getElement($path, $file = 'word/document.xml') + { + if ($this->dom === null || $file !== $this->file) { + $this->getFileDom($file); + } + + if (null === $this->xpath) { + $this->xpath = new \DOMXpath($this->dom); + + } + + $elements = $this->xpath->query($path); + return $elements->item(0); + } +} diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php index 916d3503..1066a0d4 100755 --- a/Tests/bootstrap.php +++ b/Tests/bootstrap.php @@ -12,3 +12,4 @@ require_once __DIR__ . '/../Classes/PHPWord/Autoloader.php'; PHPWord_Autoloader::Register(); require_once __DIR__ . '/_inc/TestHelperDOCX.php'; +require_once __DIR__ . '/_inc/XmlDocument.php'; From 07b84302c13613a09d804b2b03b7d0b93cd8db1b Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Wed, 12 Mar 2014 00:46:03 +0700 Subject: [PATCH 08/17] Add php_zip requirement --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index fc9a59d0..1003a29a 100755 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ __Want to contribute?__ Fork us! ## Requirements * PHP version 5.3.0 or higher +* PHP extension [php_zip](http://php.net/manual/en/book.zip.php) enabled ## Installation From 762f812b6b0e993e20c68ef26d8577742cb789bb Mon Sep 17 00:00:00 2001 From: Brandon Skrtich Date: Tue, 11 Mar 2014 16:44:22 -0600 Subject: [PATCH 09/17] Add Text Break to Text Run --- Classes/PHPWord/Section/TextRun.php | 11 +++++++++++ Classes/PHPWord/Writer/Word2007/Base.php | 4 +++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/Classes/PHPWord/Section/TextRun.php b/Classes/PHPWord/Section/TextRun.php index 7c03138b..1ee22032 100755 --- a/Classes/PHPWord/Section/TextRun.php +++ b/Classes/PHPWord/Section/TextRun.php @@ -130,6 +130,17 @@ class PHPWord_Section_TextRun } } + /** + * Add a Text Break + * + * @param int $count + */ + public function addTextBreak($count = 1) { + for ($i=1; $i<=$count; $i++) { + $this->_elementCollection[] = new PHPWord_Section_TextBreak(); + } + } + /** * Create a new Footnote Element * diff --git a/Classes/PHPWord/Writer/Word2007/Base.php b/Classes/PHPWord/Writer/Word2007/Base.php index fcbf71d8..13c0d65d 100755 --- a/Classes/PHPWord/Writer/Word2007/Base.php +++ b/Classes/PHPWord/Writer/Word2007/Base.php @@ -108,8 +108,10 @@ class PHPWord_Writer_Word2007_Base extends PHPWord_Writer_Word2007_WriterPart $this->_writeLink($objWriter, $element, true); } elseif ($element instanceof PHPWord_Section_Image) { $this->_writeImage($objWriter, $element, true); - } elseif($element instanceof PHPWord_Section_Footnote) { + } elseif ($element instanceof PHPWord_Section_Footnote) { $this->_writeFootnoteReference($objWriter, $element, true); + } elseif ($element instanceof PHPWord_Section_TextBreak) { + $objWriter->writeElement('w:br'); } } } From 92cfa12d71696538d09f4a2684c82a530646a28e Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Wed, 12 Mar 2014 13:30:02 +0700 Subject: [PATCH 10/17] Code formatting for PSR1 & PSR2 - Part 3 --- .../Exceptions/InvalidImageException.php | 2 +- .../UnsupportedImageTypeException.php | 2 +- Tests/PHPWord/AutoloaderTest.php | 28 +++++- Tests/PHPWord/IOFactoryTest.php | 17 +++- .../Section/Footer/PreserveTextTest.php | 6 +- Tests/PHPWord/Section/FooterTest.php | 4 +- Tests/PHPWord/Section/HeaderTest.php | 4 +- Tests/PHPWord/Section/ImageTest.php | 6 +- Tests/PHPWord/Section/LinkTest.php | 7 +- Tests/PHPWord/Section/ListItemTest.php | 7 +- Tests/PHPWord/Section/Table/CellTest.php | 12 ++- Tests/PHPWord/Section/Table/RowTest.php | 7 +- Tests/PHPWord/Section/TableTest.php | 6 +- Tests/PHPWord/Writer/Word2007/BaseTest.php | 98 +++++++++---------- Tests/_inc/TestHelperDOCX.php | 72 +------------- Tests/_inc/XmlDocument.php | 4 +- 16 files changed, 143 insertions(+), 139 deletions(-) diff --git a/Classes/PHPWord/Exceptions/InvalidImageException.php b/Classes/PHPWord/Exceptions/InvalidImageException.php index 2d5337b4..eda84a8d 100644 --- a/Classes/PHPWord/Exceptions/InvalidImageException.php +++ b/Classes/PHPWord/Exceptions/InvalidImageException.php @@ -12,4 +12,4 @@ use Exception; */ class InvalidImageException extends Exception { -} \ No newline at end of file +} diff --git a/Classes/PHPWord/Exceptions/UnsupportedImageTypeException.php b/Classes/PHPWord/Exceptions/UnsupportedImageTypeException.php index 56bb310e..3a4975fe 100644 --- a/Classes/PHPWord/Exceptions/UnsupportedImageTypeException.php +++ b/Classes/PHPWord/Exceptions/UnsupportedImageTypeException.php @@ -12,4 +12,4 @@ use Exception; */ class UnsupportedImageTypeException extends Exception { -} \ No newline at end of file +} diff --git a/Tests/PHPWord/AutoloaderTest.php b/Tests/PHPWord/AutoloaderTest.php index 45ee6066..d8882f9f 100644 --- a/Tests/PHPWord/AutoloaderTest.php +++ b/Tests/PHPWord/AutoloaderTest.php @@ -16,8 +16,14 @@ class AutoloaderTest extends PHPUnit_Framework_TestCase public function testAutoloadLegacy() { - $this->assertNull(PHPWord_Autoloader::load('Foo'), 'PHPWord_Autoloader::load() is trying to load classes outside of the PHPWord namespace'); - $this->assertTrue(PHPWord_Autoloader::load('PHPWord'), 'PHPWord_Autoloader::load() failed to autoload the PHPWord class'); + $this->assertNull( + PHPWord_Autoloader::load('Foo'), + 'PHPWord_Autoloader::load() is trying to load classes outside of the PHPWord namespace' + ); + $this->assertTrue( + PHPWord_Autoloader::load('PHPWord'), + 'PHPWord_Autoloader::load() failed to autoload the PHPWord class' + ); } public function testAutoload() @@ -25,8 +31,20 @@ class AutoloaderTest extends PHPUnit_Framework_TestCase $declared = get_declared_classes(); $declaredCount = count($declared); Autoloader::autoload('Foo'); - $this->assertEquals($declaredCount, count(get_declared_classes()), 'PhpOffice\\PhpWord\\Autoloader::autoload() is trying to load classes outside of the PhpOffice\\PhpWord namespace'); - Autoloader::autoload('PhpOffice\\PhpWord\\Exceptions\\InvalidStyleException'); // TODO change this class to the main PHPWord class when it is namespaced - $this->assertTrue(in_array('PhpOffice\\PhpWord\\Exceptions\\InvalidStyleException', get_declared_classes()), 'PhpOffice\\PhpWord\\Autoloader::autoload() failed to autoload the PhpOffice\\PhpWord\\Exceptions\\InvalidStyleException class'); + $this->assertEquals( + $declaredCount, + count(get_declared_classes()), + 'PhpOffice\\PhpWord\\Autoloader::autoload() is trying to load classes ' . + 'outside of the PhpOffice\\PhpWord namespace' + ); + // TODO change this class to the main PHPWord class when it is namespaced + Autoloader::autoload( + 'PhpOffice\\PhpWord\\Exceptions\\InvalidStyleException' + ); + $this->assertTrue( + in_array('PhpOffice\\PhpWord\\Exceptions\\InvalidStyleException', get_declared_classes()), + 'PhpOffice\\PhpWord\\Autoloader::autoload() failed to autoload the ' . + 'PhpOffice\\PhpWord\\Exceptions\\InvalidStyleException class' + ); } } diff --git a/Tests/PHPWord/IOFactoryTest.php b/Tests/PHPWord/IOFactoryTest.php index 0c2976b6..c0dfab30 100644 --- a/Tests/PHPWord/IOFactoryTest.php +++ b/Tests/PHPWord/IOFactoryTest.php @@ -16,7 +16,11 @@ class IOFactoryTest extends \PHPUnit_Framework_TestCase { public function testGetSearchLocations() { - $this->assertAttributeEquals(PHPWord_IOFactory::getSearchLocations(), '_searchLocations', 'PHPWord_IOFactory'); + $this->assertAttributeEquals( + PHPWord_IOFactory::getSearchLocations(), + '_searchLocations', + 'PHPWord_IOFactory' + ); } public function testSetSearchLocationsWithArray() @@ -38,7 +42,11 @@ class IOFactoryTest extends \PHPUnit_Framework_TestCase { PHPWord_IOFactory::setSearchLocations(array()); PHPWord_IOFactory::addSearchLocation('type', 'location', 'classname'); - $this->assertAttributeEquals(array(array('type' => 'type', 'path' => 'location', 'class' => 'classname')), '_searchLocations', 'PHPWord_IOFactory'); + $this->assertAttributeEquals( + array(array('type' => 'type', 'path' => 'location', 'class' => 'classname')), + '_searchLocations', + 'PHPWord_IOFactory' + ); } /** @@ -57,6 +65,9 @@ class IOFactoryTest extends \PHPUnit_Framework_TestCase { $oPHPWord = new PHPWord(); - $this->assertEquals(PHPWord_IOFactory::createWriter($oPHPWord, 'Word2007'), new PHPWord_Writer_Word2007($oPHPWord)); + $this->assertEquals( + PHPWord_IOFactory::createWriter($oPHPWord, 'Word2007'), + new PHPWord_Writer_Word2007($oPHPWord) + ); } } diff --git a/Tests/PHPWord/Section/Footer/PreserveTextTest.php b/Tests/PHPWord/Section/Footer/PreserveTextTest.php index c8297738..02e82fa1 100644 --- a/Tests/PHPWord/Section/Footer/PreserveTextTest.php +++ b/Tests/PHPWord/Section/Footer/PreserveTextTest.php @@ -26,7 +26,11 @@ class PreserveTextTest extends \PHPUnit_Framework_TestCase public function testConstructWithArray() { - $oPreserveText = new PHPWord_Section_Footer_PreserveText('text', array('align' => 'center'), array('marginLeft' => 600, 'marginRight' => 600, 'marginTop' => 600, 'marginBottom' => 600)); + $oPreserveText = new PHPWord_Section_Footer_PreserveText( + 'text', + array('align' => 'center'), + array('marginLeft' => 600, 'marginRight' => 600, 'marginTop' => 600, 'marginBottom' => 600) + ); $this->assertInstanceOf('PHPWord_Style_Font', $oPreserveText->getFontStyle()); $this->assertInstanceOf('PHPWord_Style_Paragraph', $oPreserveText->getParagraphStyle()); } diff --git a/Tests/PHPWord/Section/FooterTest.php b/Tests/PHPWord/Section/FooterTest.php index de1fa613..2942f2fb 100644 --- a/Tests/PHPWord/Section/FooterTest.php +++ b/Tests/PHPWord/Section/FooterTest.php @@ -87,7 +87,9 @@ class FooterTest extends \PHPUnit_Framework_TestCase public function testAddMemoryImage() { $oFooter = new PHPWord_Section_Footer(1); - $element = $oFooter->addMemoryImage('https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png'); + $element = $oFooter->addMemoryImage( + 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' + ); $this->assertCount(1, $oFooter->getElements()); $this->assertInstanceOf('PHPWord_Section_MemoryImage', $element); diff --git a/Tests/PHPWord/Section/HeaderTest.php b/Tests/PHPWord/Section/HeaderTest.php index f9b05318..f71f9d81 100644 --- a/Tests/PHPWord/Section/HeaderTest.php +++ b/Tests/PHPWord/Section/HeaderTest.php @@ -83,7 +83,9 @@ class HeaderTest extends \PHPUnit_Framework_TestCase public function testAddMemoryImage() { $oHeader = new PHPWord_Section_Header(1); - $element = $oHeader->addMemoryImage('https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png'); + $element = $oHeader->addMemoryImage( + 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' + ); $this->assertCount(1, $oHeader->getElements()); $this->assertInstanceOf('PHPWord_Section_MemoryImage', $element); diff --git a/Tests/PHPWord/Section/ImageTest.php b/Tests/PHPWord/Section/ImageTest.php index 8083673a..5832b8c3 100644 --- a/Tests/PHPWord/Section/ImageTest.php +++ b/Tests/PHPWord/Section/ImageTest.php @@ -28,7 +28,11 @@ class ImageTest extends \PHPUnit_Framework_TestCase \DIRECTORY_SEPARATOR, array(\PHPWORD_TESTS_DIR_ROOT, '_files', 'images', 'firefox.png') ); - $oImage = new PHPWord_Section_Image($src, array('width' => 210, 'height' => 210, 'align' => 'center', 'wrappingStyle' => \PHPWord_Style_Image::WRAPPING_STYLE_BEHIND)); + $oImage = new PHPWord_Section_Image( + $src, + array('width' => 210, 'height' => 210, 'align' => 'center', + 'wrappingStyle' => \PHPWord_Style_Image::WRAPPING_STYLE_BEHIND) + ); $this->assertInstanceOf('PHPWord_Style_Image', $oImage->getStyle()); } diff --git a/Tests/PHPWord/Section/LinkTest.php b/Tests/PHPWord/Section/LinkTest.php index 81c5788e..340ddc41 100644 --- a/Tests/PHPWord/Section/LinkTest.php +++ b/Tests/PHPWord/Section/LinkTest.php @@ -20,7 +20,12 @@ class LinkTest extends \PHPUnit_Framework_TestCase public function testConstructWithParamsArray() { - $oLink = new PHPWord_Section_Link('http://www.google.com', 'Search Engine', array('color' => '0000FF', 'underline' => PHPWord_Style_Font::UNDERLINE_SINGLE), array('marginLeft' => 600, 'marginRight' => 600, 'marginTop' => 600, 'marginBottom' => 600)); + $oLink = new PHPWord_Section_Link( + 'http://www.google.com', + 'Search Engine', + array('color' => '0000FF', 'underline' => PHPWord_Style_Font::UNDERLINE_SINGLE), + array('marginLeft' => 600, 'marginRight' => 600, 'marginTop' => 600, 'marginBottom' => 600) + ); $this->assertInstanceOf('PHPWord_Section_Link', $oLink); $this->assertEquals($oLink->getLinkSrc(), 'http://www.google.com'); diff --git a/Tests/PHPWord/Section/ListItemTest.php b/Tests/PHPWord/Section/ListItemTest.php index 56973822..28323695 100644 --- a/Tests/PHPWord/Section/ListItemTest.php +++ b/Tests/PHPWord/Section/ListItemTest.php @@ -16,7 +16,12 @@ class ListItemTest extends \PHPUnit_Framework_TestCase public function testStyle() { - $oListItem = new PHPWord_Section_ListItem('text', 1, null, array('listType' => PHPWord_Style_ListItem::TYPE_NUMBER)); + $oListItem = new PHPWord_Section_ListItem( + 'text', + 1, + null, + array('listType' => PHPWord_Style_ListItem::TYPE_NUMBER) + ); $this->assertInstanceOf('PHPWord_Style_ListItem', $oListItem->getStyle()); $this->assertEquals($oListItem->getStyle()->getListType(), PHPWord_Style_ListItem::TYPE_NUMBER); diff --git a/Tests/PHPWord/Section/Table/CellTest.php b/Tests/PHPWord/Section/Table/CellTest.php index 261c9ee0..8d5b99bd 100644 --- a/Tests/PHPWord/Section/Table/CellTest.php +++ b/Tests/PHPWord/Section/Table/CellTest.php @@ -130,7 +130,9 @@ class CellTest extends \PHPUnit_Framework_TestCase public function testAddMemoryImageSection() { $oCell = new PHPWord_Section_Table_Cell('section', 1); - $element = $oCell->addMemoryImage('https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png'); + $element = $oCell->addMemoryImage( + 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' + ); $this->assertCount(1, $oCell->getElements()); $this->assertInstanceOf('PHPWord_Section_MemoryImage', $element); @@ -139,7 +141,9 @@ class CellTest extends \PHPUnit_Framework_TestCase public function testAddMemoryImageHeader() { $oCell = new PHPWord_Section_Table_Cell('header', 1); - $element = $oCell->addMemoryImage('https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png'); + $element = $oCell->addMemoryImage( + 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' + ); $this->assertCount(1, $oCell->getElements()); $this->assertInstanceOf('PHPWord_Section_MemoryImage', $element); @@ -148,7 +152,9 @@ class CellTest extends \PHPUnit_Framework_TestCase public function testAddMemoryImageFooter() { $oCell = new PHPWord_Section_Table_Cell('footer', 1); - $element = $oCell->addMemoryImage('https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png'); + $element = $oCell->addMemoryImage( + 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' + ); $this->assertCount(1, $oCell->getElements()); $this->assertInstanceOf('PHPWord_Section_MemoryImage', $element); diff --git a/Tests/PHPWord/Section/Table/RowTest.php b/Tests/PHPWord/Section/Table/RowTest.php index c6dd762a..115eb1c7 100644 --- a/Tests/PHPWord/Section/Table/RowTest.php +++ b/Tests/PHPWord/Section/Table/RowTest.php @@ -22,7 +22,12 @@ class RowTest extends \PHPUnit_Framework_TestCase { $iVal = rand(1, 1000); $iVal2 = rand(1, 1000); - $oRow = new PHPWord_Section_Table_Row('section', $iVal, $iVal2, array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF')); + $oRow = new PHPWord_Section_Table_Row( + 'section', + $iVal, + $iVal2, + array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF') + ); $this->assertEquals($oRow->getHeight(), $iVal2); $this->assertInstanceOf('PHPWord_Style_Row', $oRow->getStyle()); diff --git a/Tests/PHPWord/Section/TableTest.php b/Tests/PHPWord/Section/TableTest.php index 6c479e36..80cd4296 100644 --- a/Tests/PHPWord/Section/TableTest.php +++ b/Tests/PHPWord/Section/TableTest.php @@ -26,7 +26,11 @@ class TableTest extends \PHPUnit_Framework_TestCase public function testStyleArray() { - $oTable = new PHPWord_Section_Table('section', 1, array('borderSize' => 6, 'borderColor' => '006699', 'cellMargin' => 80)); + $oTable = new PHPWord_Section_Table( + 'section', + 1, + array('borderSize' => 6, 'borderColor' => '006699', 'cellMargin' => 80) + ); $this->assertInstanceOf('PHPWord_Style_Table', $oTable->getStyle()); } diff --git a/Tests/PHPWord/Writer/Word2007/BaseTest.php b/Tests/PHPWord/Writer/Word2007/BaseTest.php index cb8fa578..cd1f6dbd 100644 --- a/Tests/PHPWord/Writer/Word2007/BaseTest.php +++ b/Tests/PHPWord/Writer/Word2007/BaseTest.php @@ -20,29 +20,7 @@ class BaseTest extends \PHPUnit_Framework_TestCase TestHelperDOCX::clear(); } - public function testWriteImage_Position() - { - $PHPWord = new PHPWord(); - $section = $PHPWord->createSection(); - $section->addImage( - PHPWORD_TESTS_DIR_ROOT . '/_files/images/earth.jpg', - array( - 'marginTop' => -1, - 'marginLeft' => -1, - 'wrappingStyle' => 'behind' - ) - ); - - $doc = TestHelperDOCX::getDocument($PHPWord); - $element = $doc->getElement('/w:document/w:body/w:p/w:r/w:pict/v:shape'); - - $style = $element->getAttribute('style'); - - $this->assertRegExp('/z\-index:\-[0-9]*/', $style); - $this->assertRegExp('/position:absolute;/', $style); - } - - public function testWriteParagraphStyle_Align() + public function testWriteParagraphStyleAlign() { $PHPWord = new PHPWord(); $section = $PHPWord->createSection(); @@ -55,34 +33,10 @@ class BaseTest extends \PHPUnit_Framework_TestCase $this->assertEquals('right', $element->getAttribute('w:val')); } - public function testWriteCellStyle_CellGridSpan() - { - $PHPWord = new PHPWord(); - $section = $PHPWord->createSection(); - - $table = $section->addTable(); - - $table->addRow(); - $cell = $table->addCell(200); - $cell->getStyle()->setGridSpan(5); - - $table->addRow(); - $table->addCell(40); - $table->addCell(40); - $table->addCell(40); - $table->addCell(40); - $table->addCell(40); - - $doc = TestHelperDOCX::getDocument($PHPWord); - $element = $doc->getElement('/w:document/w:body/w:tbl/w:tr/w:tc/w:tcPr/w:gridSpan'); - - $this->assertEquals(5, $element->getAttribute('w:val')); - } - /** * Test write paragraph pagination */ - public function testWriteParagraphStyle_Pagination() + public function testWriteParagraphStylePagination() { // Create the doc $PHPWord = new PHPWord(); @@ -109,6 +63,52 @@ class BaseTest extends \PHPUnit_Framework_TestCase } } + public function testWriteCellStyleCellGridSpan() + { + $PHPWord = new PHPWord(); + $section = $PHPWord->createSection(); + + $table = $section->addTable(); + + $table->addRow(); + $cell = $table->addCell(200); + $cell->getStyle()->setGridSpan(5); + + $table->addRow(); + $table->addCell(40); + $table->addCell(40); + $table->addCell(40); + $table->addCell(40); + $table->addCell(40); + + $doc = TestHelperDOCX::getDocument($PHPWord); + $element = $doc->getElement('/w:document/w:body/w:tbl/w:tr/w:tc/w:tcPr/w:gridSpan'); + + $this->assertEquals(5, $element->getAttribute('w:val')); + } + + public function testWriteImagePosition() + { + $PHPWord = new PHPWord(); + $section = $PHPWord->createSection(); + $section->addImage( + PHPWORD_TESTS_DIR_ROOT . '/_files/images/earth.jpg', + array( + 'marginTop' => -1, + 'marginLeft' => -1, + 'wrappingStyle' => 'behind' + ) + ); + + $doc = TestHelperDOCX::getDocument($PHPWord); + $element = $doc->getElement('/w:document/w:body/w:p/w:r/w:pict/v:shape'); + + $style = $element->getAttribute('style'); + + $this->assertRegExp('/z\-index:\-[0-9]*/', $style); + $this->assertRegExp('/position:absolute;/', $style); + } + public function testWritePreserveText() { $PHPWord = new PHPWord(); @@ -123,4 +123,4 @@ class BaseTest extends \PHPUnit_Framework_TestCase $this->assertEquals('PAGE', $preserve->nodeValue); $this->assertEquals('preserve', $preserve->getAttribute('xml:space')); } -} \ No newline at end of file +} diff --git a/Tests/_inc/TestHelperDOCX.php b/Tests/_inc/TestHelperDOCX.php index 965835d0..643cc00a 100644 --- a/Tests/_inc/TestHelperDOCX.php +++ b/Tests/_inc/TestHelperDOCX.php @@ -2,15 +2,15 @@ namespace PHPWord\Tests; use PHPWord; -use DOMDocument; class TestHelperDOCX { + /** @var string $file */ static protected $file; /** * @param \PHPWord $PHPWord - * @return \PHPWord\Tests\Xml_Document + * @return \PHPWord\Tests\XmlDocument */ public static function getDocument(PHPWord $PHPWord) { @@ -29,7 +29,7 @@ class TestHelperDOCX $zip->close(); } - return new Xml_Document(sys_get_temp_dir() . '/PHPWord_Unit_Test/'); + return new XmlDocument(sys_get_temp_dir() . '/PHPWord_Unit_Test/'); } public static function clear() @@ -50,9 +50,9 @@ class TestHelperDOCX foreach (scandir($dir) as $file) { if ($file === '.' || $file === '..') { continue; - } else if (is_file($dir . "/" . $file)) { + } elseif (is_file($dir . "/" . $file)) { unlink($dir . "/" . $file); - } else if (is_dir($dir . "/" . $file)) { + } elseif (is_dir($dir . "/" . $file)) { self::deleteDir($dir . "/" . $file); } } @@ -60,65 +60,3 @@ class TestHelperDOCX rmdir($dir); } } - -class Xml_Document -{ - /** @var string $path */ - private $path; - - /** @var \DOMDocument $dom */ - private $dom; - - /** @var \DOMXpath $xpath */ - private $xpath; - - /** @var string $file */ - private $file; - - /** - * @param string $path - */ - public function __construct($path) - { - $this->path = realpath($path); - } - - /** - * @param string $file - * @return \DOMDocument - */ - public function getFileDom($file = 'word/document.xml') - { - if (null !== $this->dom && $file === $this->file) { - return $this->dom; - } - - $this->xpath = null; - $this->file = $file; - - $file = $this->path . '/' . $file; - $this->dom = new DOMDocument(); - $this->dom->load($file); - return $this->dom; - } - - /** - * @param string $path - * @param string $file - * @return \DOMElement - */ - public function getElement($path, $file = 'word/document.xml') - { - if ($this->dom === null || $file !== $this->file) { - $this->getFileDom($file); - } - - if (null === $this->xpath) { - $this->xpath = new \DOMXpath($this->dom); - - } - - $elements = $this->xpath->query($path); - return $elements->item(0); - } -} \ No newline at end of file diff --git a/Tests/_inc/XmlDocument.php b/Tests/_inc/XmlDocument.php index 2ec27a3b..69569aa6 100644 --- a/Tests/_inc/XmlDocument.php +++ b/Tests/_inc/XmlDocument.php @@ -36,9 +36,9 @@ class XmlDocument } $this->xpath = null; - $this->file = $file; + $this->file = $file; - $file = $this->path . '/' . $file; + $file = $this->path . '/' . $file; $this->dom = new DOMDocument(); $this->dom->load($file); return $this->dom; From 8f54fa4cc2cc06e04d3300eefecede7825d93af2 Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Wed, 12 Mar 2014 13:32:49 +0700 Subject: [PATCH 11/17] Simple unit tests for ODText, RTF, and Word2007 Writer --- Tests/PHPWord/Writer/ODTextTest.php | 88 +++++++++++++++++++++++++++ Tests/PHPWord/Writer/RTFTest.php | 63 +++++++++++++++++++ Tests/PHPWord/Writer/Word2007Test.php | 63 +++++++++++++++++++ 3 files changed, 214 insertions(+) create mode 100644 Tests/PHPWord/Writer/ODTextTest.php create mode 100644 Tests/PHPWord/Writer/RTFTest.php create mode 100644 Tests/PHPWord/Writer/Word2007Test.php diff --git a/Tests/PHPWord/Writer/ODTextTest.php b/Tests/PHPWord/Writer/ODTextTest.php new file mode 100644 index 00000000..d2ac2fc2 --- /dev/null +++ b/Tests/PHPWord/Writer/ODTextTest.php @@ -0,0 +1,88 @@ +assertInstanceOf('PHPWord', $object->getPHPWord()); + $this->assertInstanceOf("PHPWord_HashTable", $object->getDrawingHashTable()); + + $this->assertEquals('./', $object->getDiskCachingDirectory()); + $writerParts = array('Content', 'Manifest', 'Meta', 'Mimetype', 'Styles'); + foreach ($writerParts as $part) { + $this->assertInstanceOf( + "PHPWord_Writer_ODText_{$part}", + $object->getWriterPart($part) + ); + $this->assertInstanceOf( + "PHPWord_Writer_ODText", + $object->getWriterPart($part)->getParentWriter() + ); + } + } + + /** + * Test construct with null value/without PHPWord + * + * @expectedException Exception + * @expectedExceptionMessage No PHPWord assigned. + */ + public function testConstructWithNull() + { + $object = new PHPWord_Writer_ODText(); + $object->getPHPWord(); + } + + /** + * Test save() + */ + public function testSave() + { + $phpWord = new PHPWord(); + $phpWord->addFontStyle('Font', array('size' => 11)); + $phpWord->addParagraphStyle('Paragraph', array('align' => 'center')); + $section = $phpWord->createSection(); + $section->addText('Test 1', 'Font', 'Paragraph'); + $section->addTextBreak(); + $section->addText('Test 2'); + $section = $phpWord->createSection(); + $textrun = $section->createTextRun(); + $textrun->addText('Test 3'); + + $writer = new PHPWord_Writer_ODText($phpWord); + $file = join( + DIRECTORY_SEPARATOR, + array(PHPWORD_TESTS_DIR_ROOT, '_files', 'temp.odt') + ); + $writer->save($file); + $this->assertTrue(file_exists($file)); + unlink($file); + } + + /** + * Test disk caching parameters + */ + public function testSetDiskCaching() + { + $object = new PHPWord_Writer_ODText(); + $object->setUseDiskCaching(true, PHPWORD_TESTS_DIR_ROOT); + $this->assertTrue($object->getUseDiskCaching()); + $this->assertEquals(PHPWORD_TESTS_DIR_ROOT, $object->getDiskCachingDirectory()); + } +} diff --git a/Tests/PHPWord/Writer/RTFTest.php b/Tests/PHPWord/Writer/RTFTest.php new file mode 100644 index 00000000..fc713786 --- /dev/null +++ b/Tests/PHPWord/Writer/RTFTest.php @@ -0,0 +1,63 @@ +assertInstanceOf('PHPWord', $object->getPHPWord()); + $this->assertInstanceOf("PHPWord_HashTable", $object->getDrawingHashTable()); + } + + /** + * Test construct with null value/without PHPWord + * + * @expectedException Exception + * @expectedExceptionMessage No PHPWord assigned. + */ + public function testConstructWithNull() + { + $object = new PHPWord_Writer_RTF(); + $object->getPHPWord(); + } + + /** + * Test save() + */ + public function testSave() + { + $phpWord = new PHPWord(); + $phpWord->addFontStyle('Font', array('size' => 11)); + $phpWord->addParagraphStyle('Paragraph', array('align' => 'center')); + $section = $phpWord->createSection(); + $section->addText('Test 1', 'Font', 'Paragraph'); + $section->addTextBreak(); + $section->addText('Test 2'); + $section = $phpWord->createSection(); + $textrun = $section->createTextRun(); + $textrun->addText('Test 3'); + + $writer = new PHPWord_Writer_RTF($phpWord); + $file = join( + DIRECTORY_SEPARATOR, + array(PHPWORD_TESTS_DIR_ROOT, '_files', 'temp.rtf') + ); + $writer->save($file); + $this->assertTrue(file_exists($file)); + unlink($file); + } +} diff --git a/Tests/PHPWord/Writer/Word2007Test.php b/Tests/PHPWord/Writer/Word2007Test.php new file mode 100644 index 00000000..28b0d581 --- /dev/null +++ b/Tests/PHPWord/Writer/Word2007Test.php @@ -0,0 +1,63 @@ +assertInstanceOf( + "PHPWord_Writer_Word2007_{$part}", + $object->getWriterPart($part) + ); + $this->assertInstanceOf( + "PHPWord_Writer_Word2007", + $object->getWriterPart($part)->getParentWriter() + ); + } + } + + /** + * Test save() + */ + public function testSave() + { + $phpWord = new PHPWord(); + $phpWord->addFontStyle('Font', array('size' => 11)); + $phpWord->addParagraphStyle('Paragraph', array('align' => 'center')); + $section = $phpWord->createSection(); + $section->addText('Test 1', 'Font', 'Paragraph'); + $section->addTextBreak(); + $section->addText('Test 2'); + $section = $phpWord->createSection(); + $textrun = $section->createTextRun(); + $textrun->addText('Test 3'); + + $writer = new PHPWord_Writer_Word2007($phpWord); + $file = join( + DIRECTORY_SEPARATOR, + array(PHPWORD_TESTS_DIR_ROOT, '_files', 'temp.docx') + ); + $writer->save($file); + $this->assertTrue(file_exists($file)); + unlink($file); + } +} From e5bd649b2cb38394299173c90577f54ef5738772 Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Wed, 12 Mar 2014 13:52:24 +0700 Subject: [PATCH 12/17] Code formatting for PSR1 & PSR2 - Part 4 --- Classes/PHPWord/Footnote.php | 10 +++------- Classes/PHPWord/Reader/Abstract.php | 1 - Classes/PHPWord/Reader/IReader.php | 1 - Classes/PHPWord/Reader/Word2007.php | 1 - Classes/PHPWord/Section/Footnote.php | 21 ++++++++------------- 5 files changed, 11 insertions(+), 23 deletions(-) diff --git a/Classes/PHPWord/Footnote.php b/Classes/PHPWord/Footnote.php index ac39de3a..81b64049 100644 --- a/Classes/PHPWord/Footnote.php +++ b/Classes/PHPWord/Footnote.php @@ -2,7 +2,7 @@ /** * PHPWord * - * Copyright (c) 2011 PHPWord + * Copyright (c) 2014 PHPWord * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -20,18 +20,14 @@ * * @category PHPWord * @package PHPWord - * @copyright Copyright (c) 010 PHPWord + * @copyright Copyright (c) 2014 PHPWord * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL - * @version Beta 0.6.3, 08.07.2011 + * @version 0.7.0 */ /** * PHPWord_Footnote - * - * @category PHPWord - * @package PHPWord - * @copyright Copyright (c) 2011 PHPWord */ class PHPWord_Footnote { diff --git a/Classes/PHPWord/Reader/Abstract.php b/Classes/PHPWord/Reader/Abstract.php index 0d273ea8..1e7acb51 100644 --- a/Classes/PHPWord/Reader/Abstract.php +++ b/Classes/PHPWord/Reader/Abstract.php @@ -25,7 +25,6 @@ * @version 0.7.0 */ - /** * PHPWord_Reader_Abstract */ diff --git a/Classes/PHPWord/Reader/IReader.php b/Classes/PHPWord/Reader/IReader.php index e2ecc4b3..f51eed77 100644 --- a/Classes/PHPWord/Reader/IReader.php +++ b/Classes/PHPWord/Reader/IReader.php @@ -25,7 +25,6 @@ * @version 0.7.0 */ - /** * PHPWord_Reader_IReader */ diff --git a/Classes/PHPWord/Reader/Word2007.php b/Classes/PHPWord/Reader/Word2007.php index c1886e42..48a13e59 100644 --- a/Classes/PHPWord/Reader/Word2007.php +++ b/Classes/PHPWord/Reader/Word2007.php @@ -25,7 +25,6 @@ * @version 0.7.0 */ - /** PHPWord root directory */ if (!defined('PHPWORD_BASE_PATH')) { define('PHPWORD_BASE_PATH', dirname(__FILE__) . '/../../'); diff --git a/Classes/PHPWord/Section/Footnote.php b/Classes/PHPWord/Section/Footnote.php index be9fb678..7b2159e4 100644 --- a/Classes/PHPWord/Section/Footnote.php +++ b/Classes/PHPWord/Section/Footnote.php @@ -2,7 +2,7 @@ /** * PHPWord * - * Copyright (c) 2011 PHPWord + * Copyright (c) 2014 PHPWord * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -11,27 +11,22 @@ * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * - * @category PHPWord - * @package PHPWord - * @copyright Copyright (c) 010 PHPWord - * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL - * @version Beta 0.6.3, 08.07.2011 + * @category PHPWord + * @package PHPWord + * @copyright Copyright (c) 2014 PHPWord + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 0.7.0 */ - /** * PHPWord_Section_Footnote - * - * @category PHPWord - * @package PHPWord_Section - * @copyright Copyright (c) 2011 PHPWord */ class PHPWord_Section_Footnote { From 530a71c2bfd0411aaceab2d629adb1da6883eb06 Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Wed, 12 Mar 2014 16:24:36 +0700 Subject: [PATCH 13/17] Unit test for TOC --- Classes/PHPWord/Section/TextRun.php | 3 +- .../Reader/{Word2007.php => Word2007Test.php} | 0 Tests/PHPWord/TOCTest.php | 72 +++++++++++++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) rename Tests/PHPWord/Reader/{Word2007.php => Word2007Test.php} (100%) create mode 100644 Tests/PHPWord/TOCTest.php diff --git a/Classes/PHPWord/Section/TextRun.php b/Classes/PHPWord/Section/TextRun.php index d6ec7321..c26b2ef6 100755 --- a/Classes/PHPWord/Section/TextRun.php +++ b/Classes/PHPWord/Section/TextRun.php @@ -136,7 +136,8 @@ class PHPWord_Section_TextRun * * @param int $count */ - public function addTextBreak($count = 1) { + public function addTextBreak($count = 1) + { for ($i=1; $i<=$count; $i++) { $this->_elementCollection[] = new PHPWord_Section_TextBreak(); } diff --git a/Tests/PHPWord/Reader/Word2007.php b/Tests/PHPWord/Reader/Word2007Test.php similarity index 100% rename from Tests/PHPWord/Reader/Word2007.php rename to Tests/PHPWord/Reader/Word2007Test.php diff --git a/Tests/PHPWord/TOCTest.php b/Tests/PHPWord/TOCTest.php new file mode 100644 index 00000000..74038ee3 --- /dev/null +++ b/Tests/PHPWord/TOCTest.php @@ -0,0 +1,72 @@ + 9062, + 'tabLeader' => PHPWord_Style_TOC::TABLEADER_DOT, + 'indent' => 200, + ); + $object = new PHPWord_TOC( + array('size' => 11), + array('tabPos' => $expected['tabPos']) + ); + $tocStyle = $object->getStyleTOC(); + + $this->assertInstanceOf('PHPWord_Style_TOC', $tocStyle); + $this->assertInstanceOf('PHPWord_Style_Font', $object->getStyleFont()); + + foreach ($expected as $key => $value) { + $method = "get{$key}"; + $this->assertEquals($value, $tocStyle->$method()); + } + } + + /** + * @covers PHPWord_TOC::addTitle + * @covers PHPWord_TOC::getTitles + */ + public function testAddAndGetTitle() + { + // Prepare variables + $titleCount = 3; + $anchor = '_Toc' . (252634154 + $titleCount); + $bookmark = $titleCount - 1; // zero based + $titles = array( + 'Heading 1' => 1, + 'Heading 2' => 2, + 'Heading 3' => 3, + ); + + // @covers PHPWord_TOC::addTitle + foreach ($titles as $text => $depth) { + $response = PHPWord_TOC::addTitle($text, $depth); + } + $this->assertEquals($anchor, $response[0]); + $this->assertEquals($bookmark, $response[1]); + + // @covers PHPWord_TOC::getTitles + $i = 0; + $savedTitles = PHPWord_TOC::getTitles(); + foreach ($titles as $text => $depth) { + $this->assertEquals($text, $savedTitles[$i]['text']); + $this->assertEquals($depth, $savedTitles[$i]['depth']); + $i++; + } + } +} From b1ee8a3de64dbaeb1499f956be720ea7271de5c6 Mon Sep 17 00:00:00 2001 From: Ivan Lanin Date: Wed, 12 Mar 2014 19:26:30 +0700 Subject: [PATCH 14/17] Unit test for PHPWord main class --- Classes/PHPWord.php | 50 ++++++------ Tests/PHPWordTest.php | 183 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 209 insertions(+), 24 deletions(-) create mode 100644 Tests/PHPWordTest.php diff --git a/Classes/PHPWord.php b/Classes/PHPWord.php index 009af98a..553b1f92 100755 --- a/Classes/PHPWord.php +++ b/Classes/PHPWord.php @@ -26,12 +26,13 @@ */ /** PHPWORD_BASE_PATH */ +// @codeCoverageIgnoreStart if (!defined('PHPWORD_BASE_PATH')) { define('PHPWORD_BASE_PATH', dirname(__FILE__) . '/'); require PHPWORD_BASE_PATH . 'PHPWord/Autoloader.php'; PHPWord_Autoloader::Register(); } - +// @codeCoverageIgnoreEnd /** * PHPWord @@ -151,7 +152,7 @@ class PHPWord } /** - * Get default Font size + * Get default Font size (in points) * @return string */ public function getDefaultFontSize() @@ -160,15 +161,24 @@ class PHPWord } /** - * Set default Font size + * Set default Font size (in points) * @param int $pValue */ public function setDefaultFontSize($pValue) { - $pValue = $pValue * 2; $this->_defaultFontSize = $pValue; } + /** + * Set default paragraph style definition to styles.xml + * + * @param array $styles Paragraph style definition + */ + public function setDefaultParagraphStyle($styles) + { + PHPWord_Style::setDefaultParagraphStyle($styles); + } + /** * Adds a paragraph style definition to styles.xml * @@ -213,16 +223,6 @@ class PHPWord PHPWord_Style::addTitleStyle($titleCount, $styleFont, $styleParagraph); } - /** - * Set default paragraph style definition to styles.xml - * - * @param array $styles Paragraph style definition - */ - public function setDefaultParagraphStyle($styles) - { - PHPWord_Style::setDefaultParagraphStyle($styles); - } - /** * Adds a hyperlink style to styles.xml * @@ -243,15 +243,6 @@ class PHPWord return $this->_sectionCollection; } - /** - * Get section count - * @return int - */ - private function _countSections() - { - return count($this->_sectionCollection); - } - /** * Load a Template File * @@ -264,7 +255,18 @@ class PHPWord $template = new PHPWord_Template($strFilename); return $template; } else { - trigger_error('Template file ' . $strFilename . ' not found.', E_USER_ERROR); + throw new PHPWord_Exception( + "Template file {$strFilename} not found." + ); } } + + /** + * Get section count + * @return int + */ + private function _countSections() + { + return count($this->_sectionCollection); + } } diff --git a/Tests/PHPWordTest.php b/Tests/PHPWordTest.php new file mode 100644 index 00000000..54ab4ae0 --- /dev/null +++ b/Tests/PHPWordTest.php @@ -0,0 +1,183 @@ +assertEquals( + new PHPWord_DocumentProperties(), + $object->getProperties() + ); + $this->assertEquals( + PHPWord::DEFAULT_FONT_NAME, + $object->getDefaultFontName() + ); + $this->assertEquals( + PHPWord::DEFAULT_FONT_SIZE, + $object->getDefaultFontSize() + ); + } + + /** + * @covers PHPWord::setProperties + * @covers PHPWord::getProperties + */ + public function testSetGetProperties() + { + $object = new PHPWord(); + $creator = 'PHPWord'; + $properties = $object->getProperties(); + $properties->setCreator($creator); + $object->setProperties($properties); + $this->assertEquals($creator, $object->getProperties()->getCreator()); + } + + /** + * @covers PHPWord::createSection + * @covers PHPWord::getSections + */ + public function testCreateGetSections() + { + $object = new PHPWord(); + $this->assertEquals(new PHPWord_Section(1), $object->createSection()); + $object->createSection(); + $this->assertEquals(2, count($object->getSections())); + } + + /** + * @covers PHPWord::setDefaultFontName + * @covers PHPWord::getDefaultFontName + */ + public function testSetGetDefaultFontName() + { + $object = new PHPWord(); + $fontName = 'Times New Roman'; + $this->assertEquals( + PHPWord::DEFAULT_FONT_NAME, + $object->getDefaultFontName() + ); + $object->setDefaultFontName($fontName); + $this->assertEquals($fontName, $object->getDefaultFontName()); + } + + /** + * @covers PHPWord::setDefaultFontSize + * @covers PHPWord::getDefaultFontSize + */ + public function testSetGetDefaultFontSize() + { + $object = new PHPWord(); + $fontSize = 16; + $this->assertEquals( + PHPWord::DEFAULT_FONT_SIZE, + $object->getDefaultFontSize() + ); + $object->setDefaultFontSize($fontSize); + $this->assertEquals($fontSize, $object->getDefaultFontSize()); + } + + /** + * @covers PHPWord::setDefaultParagraphStyle + * @covers PHPWord::loadTemplate + */ + public function testSetDefaultParagraphStyle() + { + $object = new PHPWord(); + $object->setDefaultParagraphStyle(array()); + $this->assertInstanceOf( + 'PHPWord_Style_Paragraph', + PHPWord_Style::getStyle('Normal') + ); + } + + /** + * @covers PHPWord::addParagraphStyle + * @covers PHPWord::addFontStyle + * @covers PHPWord::addTableStyle + * @covers PHPWord::addLinkStyle + */ + public function testAddStyles() + { + $object = new PHPWord(); + $styles = array('Paragraph' => 'Paragraph', 'Font' => 'Font', + 'Table' => 'TableFull', 'Link' => 'Font'); + foreach ($styles as $key => $value) { + $method = "add{$key}Style"; + $styleId = "{$key} Style"; + $styleType = "PHPWord_Style_{$value}"; + $object->$method($styleId, array()); + $this->assertInstanceOf( + $styleType, + PHPWord_Style::getStyle($styleId) + ); + } + + } + + /** + * @covers PHPWord::addTitleStyle + */ + public function testAddTitleStyle() + { + $object = new PHPWord(); + $titleLevel = 1; + $titleName = "Heading_{$titleLevel}"; + $object->addTitleStyle($titleLevel, array()); + $this->assertInstanceOf( + 'PHPWord_Style_Font', + PHPWord_Style::getStyle($titleName) + ); + } + + /** + * @covers PHPWord::loadTemplate + */ + public function testLoadTemplate() + { + $file = join( + DIRECTORY_SEPARATOR, + array(PHPWORD_TESTS_DIR_ROOT, '_files', 'templates', 'blank.docx') + ); + $object = new PHPWord(); + $this->assertInstanceOf( + 'PHPWord_Template', + $object->loadTemplate($file) + ); + } + + /** + * @covers PHPWord::loadTemplate + * @expectedException PHPWord_Exception + */ + public function testLoadTemplateException() + { + $file = join( + DIRECTORY_SEPARATOR, + array(PHPWORD_TESTS_DIR_ROOT, '_files', 'templates', 'blanks.docx') + ); + $object = new PHPWord(); + $object->loadTemplate($file); + } +} From 492f88d1e814eff1fe02521c479aa5abb2428183 Mon Sep 17 00:00:00 2001 From: Gabriel Bull Date: Wed, 12 Mar 2014 09:25:21 -0400 Subject: [PATCH 15/17] Use exif_imagetype to check image format instead of extension name --- Classes/PHPWord/Media.php | 91 ++++++++++++++----------- Classes/PHPWord/Section/MemoryImage.php | 10 +-- Tests/PHPWord/MediaTest.php | 25 ++++++- Tests/PHPWord/Section/ImageTest.php | 5 ++ Tests/PHPWord/Style/TabsTest.php | 4 +- 5 files changed, 84 insertions(+), 51 deletions(-) diff --git a/Classes/PHPWord/Media.php b/Classes/PHPWord/Media.php index 413b73de..28d3d033 100755 --- a/Classes/PHPWord/Media.php +++ b/Classes/PHPWord/Media.php @@ -30,15 +30,16 @@ */ class PHPWord_Media { - /** * Section Media Elements * * @var array */ - private static $_sectionMedia = array('images' => array(), + private static $_sectionMedia = array( + 'images' => array(), 'embeddings' => array(), - 'links' => array()); + 'links' => array() + ); /** * Header Media Elements @@ -61,18 +62,18 @@ class PHPWord_Media */ private static $_objectId = 1325353440; - /** * Add new Section Media Element * * @param string $src * @param string $type + * @param PHPWord_Section_MemoryImage|null $memoryImage * @return mixed */ public static function addSectionMediaElement($src, $type, PHPWord_Section_MemoryImage $memoryImage = null) { $mediaId = md5($src); - $key = ($type == 'image') ? 'images' : 'embeddings'; + $key = ($type === 'image') ? 'images' : 'embeddings'; if (!array_key_exists($mediaId, self::$_sectionMedia[$key])) { $cImg = self::countSectionMediaElements('images'); @@ -81,26 +82,39 @@ class PHPWord_Media $media = array(); - if ($type == 'image') { + $folder = null; + $file = null; + if ($type === 'image') { $cImg++; - $inf = pathinfo($src); - $isMemImage = (substr(strtolower($inf['extension']), 0, 3) == 'php' && $type == 'image') ? true : false; + $isMemImage = false; + if (stripos(strrev($src), strrev('.php')) === 0) { + $isMemImage = true; + } + $extension = ''; if ($isMemImage) { - $ext = $memoryImage->getImageExtension(); + $extension = $memoryImage->getImageExtension(); $media['isMemImage'] = true; $media['createfunction'] = $memoryImage->getImageCreateFunction(); $media['imagefunction'] = $memoryImage->getImageFunction(); } else { - $ext = $inf['extension']; - if ($ext == 'jpeg') { // Office crashes when adding a jpEg Image, so rename to jpg - $ext = 'jpg'; + $imageType = exif_imagetype($src); + if ($imageType === IMAGETYPE_JPEG) { + $extension = 'jpg'; + } elseif ($imageType === IMAGETYPE_GIF) { + $extension = 'gif'; + } elseif ($imageType === IMAGETYPE_PNG) { + $extension = 'png'; + } elseif ($imageType === IMAGETYPE_BMP) { + $extension = 'bmp'; + } elseif ($imageType === IMAGETYPE_TIFF_II || $imageType === IMAGETYPE_TIFF_MM) { + $extension = 'tif'; } } $folder = 'media'; - $file = $type . $cImg . '.' . strtolower($ext); - } elseif ($type == 'oleObject') { + $file = $type . $cImg . '.' . strtolower($extension); + } elseif ($type === 'oleObject') { $cObj++; $folder = 'embedding'; $file = $type . $cObj . '.bin'; @@ -113,27 +127,24 @@ class PHPWord_Media self::$_sectionMedia[$key][$mediaId] = $media; - if ($type == 'oleObject') { + if ($type === 'oleObject') { return array($rID, ++self::$_objectId); - } else { - return $rID; - } - } else { - if ($type == 'oleObject') { - $rID = self::$_sectionMedia[$key][$mediaId]['rID']; - return array($rID, ++self::$_objectId); - } else { - return self::$_sectionMedia[$key][$mediaId]['rID']; } + + return $rID; } + + if ($type === 'oleObject') { + $rID = self::$_sectionMedia[$key][$mediaId]['rID']; + return array($rID, ++self::$_objectId); + } + return self::$_sectionMedia[$key][$mediaId]['rID']; } /** * Add new Section Link Element * * @param string $linkSrc - * @param string $linkName - * * @return mixed */ public static function addSectionLinkElement($linkSrc) @@ -160,12 +171,12 @@ class PHPWord_Media { if (!is_null($key)) { return self::$_sectionMedia[$key]; - } else { - $arrImages = self::$_sectionMedia['images']; - $arrObjects = self::$_sectionMedia['embeddings']; - $arrLinks = self::$_sectionMedia['links']; - return array_merge($arrImages, $arrObjects, $arrLinks); } + + $arrImages = self::$_sectionMedia['images']; + $arrObjects = self::$_sectionMedia['embeddings']; + $arrLinks = self::$_sectionMedia['links']; + return array_merge($arrImages, $arrObjects, $arrLinks); } /** @@ -178,12 +189,12 @@ class PHPWord_Media { if (!is_null($key)) { return count(self::$_sectionMedia[$key]); - } else { - $cImages = count(self::$_sectionMedia['images']); - $cObjects = count(self::$_sectionMedia['embeddings']); - $cLinks = count(self::$_sectionMedia['links']); - return ($cImages + $cObjects + $cLinks); } + + $cImages = count(self::$_sectionMedia['images']); + $cObjects = count(self::$_sectionMedia['embeddings']); + $cLinks = count(self::$_sectionMedia['links']); + return ($cImages + $cObjects + $cLinks); } /** @@ -191,6 +202,7 @@ class PHPWord_Media * * @param int $headerCount * @param string $src + * @param PHPWord_Section_MemoryImage|null $memoryImage * @return int */ public static function addHeaderMediaElement($headerCount, $src, PHPWord_Section_MemoryImage $memoryImage = null) @@ -232,9 +244,8 @@ class PHPWord_Media self::$_headerMedia[$key][$mediaId] = $media; return $rID; - } else { - return self::$_headerMedia[$key][$mediaId]['rID']; } + return self::$_headerMedia[$key][$mediaId]['rID']; } /** @@ -263,6 +274,7 @@ class PHPWord_Media * * @param int $footerCount * @param string $src + * @param PHPWord_Section_MemoryImage|null $memoryImage * @return int */ public static function addFooterMediaElement($footerCount, $src, PHPWord_Section_MemoryImage $memoryImage = null) @@ -304,9 +316,8 @@ class PHPWord_Media self::$_footerMedia[$key][$mediaId] = $media; return $rID; - } else { - return self::$_footerMedia[$key][$mediaId]['rID']; } + return self::$_footerMedia[$key][$mediaId]['rID']; } /** diff --git a/Classes/PHPWord/Section/MemoryImage.php b/Classes/PHPWord/Section/MemoryImage.php index 9652955c..8486a2a3 100755 --- a/Classes/PHPWord/Section/MemoryImage.php +++ b/Classes/PHPWord/Section/MemoryImage.php @@ -30,7 +30,6 @@ */ class PHPWord_Section_MemoryImage { - /** * Image Src * @@ -85,7 +84,7 @@ class PHPWord_Section_MemoryImage * Create a new Image * * @param string $src - * @param mixed style + * @param mixed $style */ public function __construct($src, $style = null) { @@ -113,10 +112,6 @@ class PHPWord_Section_MemoryImage } $this->_setFunctions(); - - return $this; - } else { - return false; } } @@ -145,7 +140,6 @@ class PHPWord_Section_MemoryImage } } - /** * Get Image style * @@ -235,4 +229,4 @@ class PHPWord_Section_MemoryImage { return $this->_imageExtension; } -} +} \ No newline at end of file diff --git a/Tests/PHPWord/MediaTest.php b/Tests/PHPWord/MediaTest.php index 86e9651a..e5722724 100644 --- a/Tests/PHPWord/MediaTest.php +++ b/Tests/PHPWord/MediaTest.php @@ -3,6 +3,7 @@ namespace PHPWord\Tests; use PHPUnit_Framework_TestCase; use PHPWord_Media; +use PHPWord_Section; class MediaTest extends \PHPUnit_Framework_TestCase { @@ -25,4 +26,26 @@ class MediaTest extends \PHPUnit_Framework_TestCase { $this->assertAttributeEquals(PHPWord_Media::getFooterMediaElements(), '_footerMedia', 'PHPWord_Media'); } -} + + /** + * Todo: add memory image to this test + * + * @covers PHPWord_Media::addSectionMediaElement + */ + public function testAddSectionMediaElement() + { + $section = new PHPWord_Section(0); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/mars_noext_jpg"); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/mars.jpg"); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/mario.gif"); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/firefox.png"); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/duke_nukem.bmp"); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/angela_merkel.tif"); + + $elements = $section->getElements(); + $this->assertEquals(6, count($elements)); + foreach ($elements as $element) { + $this->assertInstanceOf('PHPWord_Section_Image', $element); + } + } +} \ No newline at end of file diff --git a/Tests/PHPWord/Section/ImageTest.php b/Tests/PHPWord/Section/ImageTest.php index 5832b8c3..9362be19 100644 --- a/Tests/PHPWord/Section/ImageTest.php +++ b/Tests/PHPWord/Section/ImageTest.php @@ -37,6 +37,9 @@ class ImageTest extends \PHPUnit_Framework_TestCase $this->assertInstanceOf('PHPWord_Style_Image', $oImage->getStyle()); } + /** + * @covers PHPWord_Section_Image::__construct + */ public function testValidImageTypes() { new PHPWord_Section_Image(PHPWORD_TESTS_DIR_ROOT . "/_files/images/mars_noext_jpg"); @@ -49,6 +52,7 @@ class ImageTest extends \PHPUnit_Framework_TestCase /** * @expectedException \PhpOffice\PhpWord\Exceptions\InvalidImageException + * @covers PHPWord_Section_Image::__construct */ public function testImageNotFound() { @@ -57,6 +61,7 @@ class ImageTest extends \PHPUnit_Framework_TestCase /** * @expectedException \PhpOffice\PhpWord\Exceptions\UnsupportedImageTypeException + * @covers PHPWord_Section_Image::__construct */ public function testInvalidImageTypes() { diff --git a/Tests/PHPWord/Style/TabsTest.php b/Tests/PHPWord/Style/TabsTest.php index 1be0c350..3a3d69df 100644 --- a/Tests/PHPWord/Style/TabsTest.php +++ b/Tests/PHPWord/Style/TabsTest.php @@ -16,8 +16,8 @@ use PHPWord\Tests\TestHelperDOCX; class TabsTest extends \PHPUnit_Framework_TestCase { /** - * Executed before each method of the class - */ + * Executed before each method of the class + */ public function tearDown() { TestHelperDOCX::clear(); From d991fdc6d1beb3363ebc43ff4d91571aa76ead4e Mon Sep 17 00:00:00 2001 From: Gabriel Bull Date: Wed, 12 Mar 2014 10:09:42 -0400 Subject: [PATCH 16/17] Added image writer tests --- Classes/PHPWord/Writer/Word2007.php | 54 ++++++++++++++++++--------- Tests/PHPWord/Writer/Word2007Test.php | 39 +++++++++++++++---- Tests/_inc/TestHelperDOCX.php | 2 +- Tests/_inc/XmlDocument.php | 16 ++++++++ 4 files changed, 85 insertions(+), 26 deletions(-) diff --git a/Classes/PHPWord/Writer/Word2007.php b/Classes/PHPWord/Writer/Word2007.php index 8375c56a..f58f2c43 100755 --- a/Classes/PHPWord/Writer/Word2007.php +++ b/Classes/PHPWord/Writer/Word2007.php @@ -25,6 +25,9 @@ * @version 0.7.0 */ +use PhpOffice\PhpWord\Exceptions\InvalidImageException; +use PhpOffice\PhpWord\Exceptions\UnsupportedImageTypeException; + /** * Class PHPWord_Writer_Word2007 */ @@ -191,25 +194,40 @@ class PHPWord_Writer_Word2007 implements PHPWord_Writer_IWriter } } - private function _chkContentTypes($src) + /** + * @param string $src + */ + private function checkContentTypes($src) { - $srcInfo = pathinfo($src); - $extension = strtolower($srcInfo['extension']); - if (substr($extension, 0, 3) == 'php') { - $extension = 'php'; - } - $_supportedImageTypes = array('jpg', 'jpeg', 'gif', 'png', 'bmp', 'tif', 'tiff', 'php'); + $supportedImageTypes = array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM); - if (in_array($extension, $_supportedImageTypes)) { - $imagedata = getimagesize($src); - $imagetype = image_type_to_mime_type($imagedata[2]); - $imageext = image_type_to_extension($imagedata[2]); - $imageext = str_replace('.', '', $imageext); - if ($imageext == 'jpeg') { - $imageext = 'jpg'; + $extension = null; + if (stripos(strrev($src), strrev('.php')) === 0) { + $extension = 'php'; + } else { + $imageType = exif_imagetype($src); + if ($imageType === IMAGETYPE_JPEG) { + $extension = 'jpg'; + } elseif ($imageType === IMAGETYPE_GIF) { + $extension = 'gif'; + } elseif ($imageType === IMAGETYPE_PNG) { + $extension = 'png'; + } elseif ($imageType === IMAGETYPE_BMP) { + $extension = 'bmp'; + } elseif ($imageType === IMAGETYPE_TIFF_II || $imageType === IMAGETYPE_TIFF_MM) { + $extension = 'tif'; } - if (!in_array($imagetype, $this->_imageTypes)) { - $this->_imageTypes[$imageext] = $imagetype; + } + + if (in_array($extension, $supportedImageTypes)) { + $imageData = getimagesize($src); + $imageType = image_type_to_mime_type($imageData[2]); + $imageExtension = str_replace('.', '', image_type_to_extension($imageData[2])); + if ($imageExtension === 'jpeg') { + $imageExtension = 'jpg'; + } + if (!in_array($imageType, $this->_imageTypes)) { + $this->_imageTypes[$imageExtension] = $imageType; } } else { if (!in_array($extension, $this->_objectTypes)) { @@ -258,10 +276,10 @@ class PHPWord_Writer_Word2007 implements PHPWord_Writer_IWriter $objZip->addFromString('word/' . $element['target'], $imageContents); imagedestroy($image); - $this->_chkContentTypes($element['source']); + $this->checkContentTypes($element['source']); } else { $objZip->addFile($element['source'], 'word/' . $element['target']); - $this->_chkContentTypes($element['source']); + $this->checkContentTypes($element['source']); } } } diff --git a/Tests/PHPWord/Writer/Word2007Test.php b/Tests/PHPWord/Writer/Word2007Test.php index 28b0d581..59bc6387 100644 --- a/Tests/PHPWord/Writer/Word2007Test.php +++ b/Tests/PHPWord/Writer/Word2007Test.php @@ -4,6 +4,7 @@ namespace PHPWord\Tests\Writer; use PHPUnit_Framework_TestCase; use PHPWord_Writer_Word2007; use PHPWord; +use PHPWord\Tests\TestHelperDOCX; /** * Class Word2007Test @@ -13,9 +14,11 @@ use PHPWord; */ class Word2007Test extends \PHPUnit_Framework_TestCase { - /** - * Test construct - */ + public function tearDown() + { + TestHelperDOCX::clear(); + } + public function testConstruct() { $object = new PHPWord_Writer_Word2007(new PHPWord()); @@ -35,9 +38,6 @@ class Word2007Test extends \PHPUnit_Framework_TestCase } } - /** - * Test save() - */ public function testSave() { $phpWord = new PHPWord(); @@ -60,4 +60,29 @@ class Word2007Test extends \PHPUnit_Framework_TestCase $this->assertTrue(file_exists($file)); unlink($file); } -} + + /** + * @covers PHPWord_Writer_Word2007::checkContentTypes + */ + public function testCheckContentTypes() + { + $phpWord = new PHPWord(); + $section = $phpWord->createSection(); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/mars_noext_jpg"); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/mars.jpg"); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/mario.gif"); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/firefox.png"); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/duke_nukem.bmp"); + $section->addImage(PHPWORD_TESTS_DIR_ROOT . "/_files/images/angela_merkel.tif"); + + $doc = TestHelperDOCX::getDocument($phpWord); + $mediaPath = $doc->getPath() . "/word/media"; + + $this->assertFileEquals(PHPWORD_TESTS_DIR_ROOT . "/_files/images/mars_noext_jpg", $mediaPath . "/section_image1.jpg"); + $this->assertFileEquals(PHPWORD_TESTS_DIR_ROOT . "/_files/images/mars.jpg", $mediaPath . "/section_image2.jpg"); + $this->assertFileEquals(PHPWORD_TESTS_DIR_ROOT . "/_files/images/mario.gif", $mediaPath . "/section_image3.gif"); + $this->assertFileEquals(PHPWORD_TESTS_DIR_ROOT . "/_files/images/firefox.png", $mediaPath . "/section_image4.png"); + $this->assertFileEquals(PHPWORD_TESTS_DIR_ROOT . "/_files/images/duke_nukem.bmp", $mediaPath . "/section_image5.bmp"); + $this->assertFileEquals(PHPWORD_TESTS_DIR_ROOT . "/_files/images/angela_merkel.tif", $mediaPath . "/section_image6.tif"); + } +} \ No newline at end of file diff --git a/Tests/_inc/TestHelperDOCX.php b/Tests/_inc/TestHelperDOCX.php index 643cc00a..a368b8e4 100644 --- a/Tests/_inc/TestHelperDOCX.php +++ b/Tests/_inc/TestHelperDOCX.php @@ -59,4 +59,4 @@ class TestHelperDOCX rmdir($dir); } -} +} \ No newline at end of file diff --git a/Tests/_inc/XmlDocument.php b/Tests/_inc/XmlDocument.php index 69569aa6..f16bd6d8 100644 --- a/Tests/_inc/XmlDocument.php +++ b/Tests/_inc/XmlDocument.php @@ -63,4 +63,20 @@ class XmlDocument $elements = $this->xpath->query($path); return $elements->item(0); } + + /** + * @return string + */ + public function getFile() + { + return $this->file; + } + + /** + * @return string + */ + public function getPath() + { + return $this->path; + } } From 5e0fc7a2d815c96de6f6cdd081404df61e8ed886 Mon Sep 17 00:00:00 2001 From: Gabriel Bull Date: Wed, 12 Mar 2014 11:22:41 -0400 Subject: [PATCH 17/17] Fixed bug with new extension verification --- Classes/PHPWord/Writer/Word2007.php | 4 +--- Tests/_inc/TestHelperDOCX.php | 8 ++++++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/Classes/PHPWord/Writer/Word2007.php b/Classes/PHPWord/Writer/Word2007.php index f58f2c43..8d112d47 100755 --- a/Classes/PHPWord/Writer/Word2007.php +++ b/Classes/PHPWord/Writer/Word2007.php @@ -199,8 +199,6 @@ class PHPWord_Writer_Word2007 implements PHPWord_Writer_IWriter */ private function checkContentTypes($src) { - $supportedImageTypes = array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM); - $extension = null; if (stripos(strrev($src), strrev('.php')) === 0) { $extension = 'php'; @@ -219,7 +217,7 @@ class PHPWord_Writer_Word2007 implements PHPWord_Writer_IWriter } } - if (in_array($extension, $supportedImageTypes)) { + if (isset($extension)) { $imageData = getimagesize($src); $imageType = image_type_to_mime_type($imageData[2]); $imageExtension = str_replace('.', '', image_type_to_extension($imageData[2])); diff --git a/Tests/_inc/TestHelperDOCX.php b/Tests/_inc/TestHelperDOCX.php index a368b8e4..2d59dcb6 100644 --- a/Tests/_inc/TestHelperDOCX.php +++ b/Tests/_inc/TestHelperDOCX.php @@ -59,4 +59,12 @@ class TestHelperDOCX rmdir($dir); } + + /** + * @return string + */ + public static function getFile() + { + return self::$file; + } } \ No newline at end of file