Content.php 16.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
<?php
/**
 * This file is part of PHPWord - A pure PHP library for reading and writing
 * word processing documents.
 *
 * PHPWord is free software distributed under the terms of the GNU Lesser
 * General Public License version 3 as published by the Free Software Foundation.
 *
 * For the full copyright and license information, please read the LICENSE
 * file that was distributed with this source code. For the full list of
 * contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
 *
 * @see         https://github.com/PHPOffice/PHPWord
 * @copyright   2010-2018 PHPWord contributors
 * @license     http://www.gnu.org/licenses/lgpl.txt LGPL version 3
 */

namespace PhpOffice\PhpWord\Writer\ODText\Part;

use PhpOffice\PhpWord\Element\AbstractContainer;
use PhpOffice\PhpWord\Element\Field;
use PhpOffice\PhpWord\Element\Image;
use PhpOffice\PhpWord\Element\Table;
use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\Element\TextRun;
use PhpOffice\PhpWord\Element\TrackChange;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLWriter;
use PhpOffice\PhpWord\Style;
use PhpOffice\PhpWord\Style\Font;
use PhpOffice\PhpWord\Style\Paragraph;
use PhpOffice\PhpWord\Style\Table as TableStyle;
use PhpOffice\PhpWord\Writer\ODText\Element\Container;
use PhpOffice\PhpWord\Writer\ODText\Style\Paragraph as ParagraphStyleWriter;

/**
 * ODText content part writer: content.xml
 */
class Content extends AbstractPart
{
    /**
     * Auto style collection
     *
     * Collect inline style information from section, image, and table elements
     *
     * @todo Merge font and paragraph styles
     * @var array
     */
    private $autoStyles = array('Section' => array(), 'Image' => array(), 'Table' => array());
    private $imageParagraphStyles = array();

    /**
     * Write part
     *
     * @return string
     */
    public function write()
    {
        $xmlWriter = $this->getXmlWriter();
        $phpWord = $this->getParentWriter()->getPhpWord();

        $this->getAutoStyles($phpWord);

        $xmlWriter->startDocument('1.0', 'UTF-8');
        $xmlWriter->startElement('office:document-content');
        $this->writeCommonRootAttributes($xmlWriter);
        $xmlWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms');
        $xmlWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema');
        $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
        $xmlWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0');
        $xmlWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0');

        // Font declarations and automatic styles
        $this->writeFontFaces($xmlWriter); // office:font-face-decls
        $this->writeAutoStyles($xmlWriter); // office:automatic-styles

        // Body
        $xmlWriter->startElement('office:body');
        $xmlWriter->startElement('office:text');

        // Tracked changes declarations
        $trackedChanges = array();
        $sections = $phpWord->getSections();
        foreach ($sections as $section) {
            $this->collectTrackedChanges($section, $trackedChanges);
        }
        $xmlWriter->startElement('text:tracked-changes');
        foreach ($trackedChanges as $trackedElement) {
            $trackedChange = $trackedElement->getTrackChange();
            $xmlWriter->startElement('text:changed-region');
            $trackedChange->setElementId();
            $xmlWriter->writeAttribute('text:id', $trackedChange->getElementId());

            if (($trackedChange->getChangeType() == TrackChange::INSERTED)) {
                $xmlWriter->startElement('text:insertion');
            } elseif ($trackedChange->getChangeType() == TrackChange::DELETED) {
                $xmlWriter->startElement('text:deletion');
            }

            $xmlWriter->startElement('office:change-info');
            $xmlWriter->writeElement('dc:creator', $trackedChange->getAuthor());
            if ($trackedChange->getDate() != null) {
                $xmlWriter->writeElement('dc:date', $trackedChange->getDate()->format('Y-m-d\TH:i:s\Z'));
            }
            $xmlWriter->endElement(); // office:change-info
            if ($trackedChange->getChangeType() == TrackChange::DELETED) {
                $xmlWriter->writeElement('text:p', $trackedElement->getText());
            }

            $xmlWriter->endElement(); // text:insertion|text:deletion
            $xmlWriter->endElement(); // text:changed-region
        }
        $xmlWriter->endElement(); // text:tracked-changes

        // Sequence declarations
        $sequences = array('Illustration', 'Table', 'Text', 'Drawing');
        $xmlWriter->startElement('text:sequence-decls');
        foreach ($sequences as $sequence) {
            $xmlWriter->startElement('text:sequence-decl');
            $xmlWriter->writeAttribute('text:display-outline-level', 0);
            $xmlWriter->writeAttribute('text:name', $sequence);
            $xmlWriter->endElement();
        }
        $xmlWriter->endElement(); // text:sequence-decl

        // Sections
        $sections = $phpWord->getSections();
        foreach ($sections as $section) {
            $name = 'Section' . $section->getSectionId();
            $xmlWriter->startElement('text:section');
            $xmlWriter->writeAttribute('text:name', $name);
            $xmlWriter->writeAttribute('text:style-name', $name);
            $xmlWriter->startElement('text:p');
            $xmlWriter->writeAttribute('text:style-name', 'SB' . $section->getSectionId());
            $xmlWriter->endElement();
            $containerWriter = new Container($xmlWriter, $section);
            $containerWriter->write();
            $xmlWriter->endElement(); // text:section
        }

        $xmlWriter->endElement(); // office:text
        $xmlWriter->endElement(); // office:body

        $xmlWriter->endElement(); // office:document-content

        return $xmlWriter->getData();
    }

    /**
     * Write automatic styles other than fonts and paragraphs.
     *
     * @since 0.11.0
     *
     * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter
     */
    private function writeAutoStyles(XMLWriter $xmlWriter)
    {
        $xmlWriter->startElement('office:automatic-styles');

        $this->writeTextStyles($xmlWriter);
        foreach ($this->autoStyles as $element => $styles) {
            $writerClass = 'PhpOffice\\PhpWord\\Writer\\ODText\\Style\\' . $element;
            foreach ($styles as $style) {
                /** @var \PhpOffice\PhpWord\Writer\ODText\Style\AbstractStyle $styleWriter Type hint */
                $styleWriter = new $writerClass($xmlWriter, $style);
                $styleWriter->write();
            }
        }

        $xmlWriter->endElement(); // office:automatic-styles
    }

    /**
     * Write automatic styles.
     *
     * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter
     */
    private function writeTextStyles(XMLWriter $xmlWriter)
    {
        $styles = Style::getStyles();
        $paragraphStyleCount = 0;

        $style = new Paragraph();
        $style->setStyleName('PB');
        $style->setAuto();
        $styleWriter = new ParagraphStyleWriter($xmlWriter, $style);
        $styleWriter->write();

        $sects = $this->getParentWriter()->getPhpWord()->getSections();
        $countsects = count($sects);
        for ($i = 0; $i < $countsects; ++$i) {
            $iplus1 = $i + 1;
            $style = new Paragraph();
            $style->setStyleName("SB$iplus1");
            $style->setAuto();
            $pnstart = $sects[$i]->getStyle()->getPageNumberingStart();
            $style->setNumLevel($pnstart);
            $styleWriter = new ParagraphStyleWriter($xmlWriter, $style);
            $styleWriter->write();
        }

        foreach ($styles as $style) {
            $sty = $style->getStyleName();
            if (substr($sty, 0, 8) === 'Heading_') {
                $style = new Paragraph();
                $style->setStyleName('HD' . substr($sty, 8));
                $style->setAuto();
                $styleWriter = new ParagraphStyleWriter($xmlWriter, $style);
                $styleWriter->write();
                $style = new Paragraph();
                $style->setStyleName('HE' . substr($sty, 8));
                $style->setAuto();
                $styleWriter = new ParagraphStyleWriter($xmlWriter, $style);
                $styleWriter->write();
            }
        }

        foreach ($styles as $style) {
            if ($style->isAuto() === true) {
                $styleClass = str_replace('\\Style\\', '\\Writer\\ODText\\Style\\', get_class($style));
                if (class_exists($styleClass)) {
                    /** @var \PhpOffice\PhpWord\Writer\ODText\Style\AbstractStyle $styleWriter Type hint */
                    $styleWriter = new $styleClass($xmlWriter, $style);
                    $styleWriter->write();
                }
                if ($style instanceof Paragraph) {
                    $paragraphStyleCount++;
                }
            }
        }
        foreach ($this->imageParagraphStyles as $style) {
            $styleWriter = new \PhpOffice\PhpWord\Writer\ODText\Style\Paragraph($xmlWriter, $style);
            $styleWriter->write();
        }
    }

    /**
     * Get automatic styles.
     *
     * @param \PhpOffice\PhpWord\PhpWord $phpWord
     */
    private function getAutoStyles(PhpWord $phpWord)
    {
        $sections = $phpWord->getSections();
        $paragraphStyleCount = 0;
        $fontStyleCount = 0;
        foreach ($sections as $section) {
            $style = $section->getStyle();
            $style->setStyleName("Section{$section->getSectionId()}");
            $this->autoStyles['Section'][] = $style;
            $this->getContainerStyle($section, $paragraphStyleCount, $fontStyleCount);
        }
    }

    /**
     * Get all styles of each elements in container recursively
     *
     * Table style can be null or string of the style name
     *
     * @param \PhpOffice\PhpWord\Element\AbstractContainer $container
     * @param int $paragraphStyleCount
     * @param int $fontStyleCount
     * @todo Simplify the logic
     */
    private function getContainerStyle($container, &$paragraphStyleCount, &$fontStyleCount)
    {
        $elements = $container->getElements();
        foreach ($elements as $element) {
            if ($element instanceof TextRun) {
                $this->getElementStyleTextRun($element, $paragraphStyleCount);
                $this->getContainerStyle($element, $paragraphStyleCount, $fontStyleCount);
            } elseif ($element instanceof Text) {
                $this->getElementStyle($element, $paragraphStyleCount, $fontStyleCount);
            } elseif ($element instanceof Field) {
                $this->getElementStyleField($element, $fontStyleCount);
            } elseif ($element instanceof Image) {
                $style = $element->getStyle();
                $style->setStyleName('fr' . $element->getMediaIndex());
                $this->autoStyles['Image'][] = $style;
                $sty = new \PhpOffice\PhpWord\Style\Paragraph();
                $sty->setStyleName('IM' . $element->getMediaIndex());
                $sty->setAuto();
                $sty->setAlignment($style->getAlignment());
                $this->imageParagraphStyles[] = $sty;
            } elseif ($element instanceof Table) {
                /** @var \PhpOffice\PhpWord\Style\Table $style */
                $style = $element->getStyle();
                if (is_string($style)) {
                    $style = Style::getStyle($style);
                }
                if ($style === null) {
                    $style = new TableStyle();
                }
                $style->setStyleName($element->getElementId());
                $style->setColumnWidths($element->findFirstDefinedCellWidths());
                $this->autoStyles['Table'][] = $style;
            }
        }
    }

    /**
     * Get style of individual element
     *
     * @param \PhpOffice\PhpWord\Element\Text $element
     * @param int $paragraphStyleCount
     * @param int $fontStyleCount
     */
    private function getElementStyle($element, &$paragraphStyleCount, &$fontStyleCount)
    {
        $fontStyle = $element->getFontStyle();
        $paragraphStyle = $element->getParagraphStyle();
        $phpWord = $this->getParentWriter()->getPhpWord();

        if ($fontStyle instanceof Font) {
            // Font
            $name = $fontStyle->getStyleName();
            if (!$name) {
                $fontStyleCount++;
                $style = $phpWord->addFontStyle("T{$fontStyleCount}", $fontStyle, null);
                $style->setAuto();
                $style->setParagraph(null);
                $element->setFontStyle("T{$fontStyleCount}");
            } else {
                $element->setFontStyle($name);
            }
        }
        if ($paragraphStyle instanceof Paragraph) {
            // Paragraph
            $name = $paragraphStyle->getStyleName();
            if (!$name) {
                $paragraphStyleCount++;
                $style = $phpWord->addParagraphStyle("P{$paragraphStyleCount}", $paragraphStyle);
                $style->setAuto();
                $element->setParagraphStyle("P{$paragraphStyleCount}");
            } else {
                $element->setParagraphStyle($name);
            }
        } elseif ($paragraphStyle) {
            $paragraphStyleCount++;
            $parstylename = "P$paragraphStyleCount" . "_$paragraphStyle";
            $style = $phpWord->addParagraphStyle($parstylename, $paragraphStyle);
            $style->setAuto();
            $element->setParagraphStyle($parstylename);
        }
    }

    /**
     * Get font style of individual field element
     *
     * @param \PhpOffice\PhpWord\Element\Field $element
     * @param int $paragraphStyleCount
     * @param int $fontStyleCount
     */
    private function getElementStyleField($element, &$fontStyleCount)
    {
        $fontStyle = $element->getFontStyle();
        $phpWord = $this->getParentWriter()->getPhpWord();

        if ($fontStyle instanceof Font) {
            $name = $fontStyle->getStyleName();
            if (!$name) {
                $fontStyleCount++;
                $style = $phpWord->addFontStyle("T{$fontStyleCount}", $fontStyle, null);
                $style->setAuto();
                $style->setParagraph(null);
                $element->setFontStyle("T{$fontStyleCount}");
            } else {
                $element->setFontStyle($name);
            }
        }
    }

    /**
     * Get style of individual element
     *
     * @param \PhpOffice\PhpWord\Element\TextRun $element
     * @param int $paragraphStyleCount
     */
    private function getElementStyleTextRun($element, &$paragraphStyleCount)
    {
        $paragraphStyle = $element->getParagraphStyle();
        $phpWord = $this->getParentWriter()->getPhpWord();

        if ($paragraphStyle instanceof Paragraph) {
            // Paragraph
            $name = $paragraphStyle->getStyleName();
            if (!$name) {
                $paragraphStyleCount++;
                $style = $phpWord->addParagraphStyle("P{$paragraphStyleCount}", $paragraphStyle);
                $style->setAuto();
                $element->setParagraphStyle("P{$paragraphStyleCount}");
            } else {
                $element->setParagraphStyle($name);
            }
        } elseif ($paragraphStyle) {
            $paragraphStyleCount++;
            $parstylename = "P$paragraphStyleCount" . "_$paragraphStyle";
            $style = $phpWord->addParagraphStyle($parstylename, $paragraphStyle);
            $style->setAuto();
            $element->setParagraphStyle($parstylename);
        }
    }

    /**
     * Finds all tracked changes
     *
     * @param AbstractContainer $container
     * @param \PhpOffice\PhpWord\Element\AbstractElement[] $trackedChanges
     */
    private function collectTrackedChanges(AbstractContainer $container, &$trackedChanges = array())
    {
        $elements = $container->getElements();
        foreach ($elements as $element) {
            if ($element->getTrackChange() != null) {
                $trackedChanges[] = $element;
            }
            if (is_callable(array($element, 'getElements'))) {
                $this->collectTrackedChanges($element, $trackedChanges);
            }
        }
    }
}