diff --git a/src/PhpSpreadsheet/Writer/IWriter.php b/src/PhpSpreadsheet/Writer/IWriter.php index 448b532f..97b14bef 100644 --- a/src/PhpSpreadsheet/Writer/IWriter.php +++ b/src/PhpSpreadsheet/Writer/IWriter.php @@ -59,7 +59,7 @@ interface IWriter /** * Save PhpSpreadsheet to file. * - * @param string $pFilename Name of the file to save + * @param resource|string $pFilename Name of the file to save * * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception */ diff --git a/src/PhpSpreadsheet/Writer/Ods.php b/src/PhpSpreadsheet/Writer/Ods.php index 43659fa0..2a1dba02 100644 --- a/src/PhpSpreadsheet/Writer/Ods.php +++ b/src/PhpSpreadsheet/Writer/Ods.php @@ -12,7 +12,9 @@ use PhpOffice\PhpSpreadsheet\Writer\Ods\Mimetype; use PhpOffice\PhpSpreadsheet\Writer\Ods\Settings; use PhpOffice\PhpSpreadsheet\Writer\Ods\Styles; use PhpOffice\PhpSpreadsheet\Writer\Ods\Thumbnails; -use ZipArchive; +use ZipStream\Exception\OverflowException; +use ZipStream\Option\Archive; +use ZipStream\ZipStream; class Ods extends BaseWriter { @@ -30,6 +32,11 @@ class Ods extends BaseWriter */ private $spreadSheet; + /** + * @var bool|resource + */ + private $fileHandle; + /** * Create a new Ods. * @@ -73,7 +80,7 @@ class Ods extends BaseWriter /** * Save PhpSpreadsheet to file. * - * @param string $pFilename + * @param resource|string $pFilename * * @throws WriterException */ @@ -88,31 +95,41 @@ class Ods extends BaseWriter // If $pFilename is php://output or php://stdout, make it a temporary file... $originalFilename = $pFilename; - if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') { + if (is_resource($pFilename)) { + $this->fileHandle = $pFilename; + } elseif (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') { + // If $pFilename is php://output or php://stdout, make it a temporary file... $pFilename = @tempnam(File::sysGetTempDir(), 'phpxltmp'); if ($pFilename == '') { $pFilename = $originalFilename; } + $this->fileHandle = fopen($pFilename, 'wb+'); + } else { + $this->fileHandle = fopen($pFilename, 'wb+'); } - $zip = $this->createZip($pFilename); + $zip = $this->createZip(); - $zip->addFromString('META-INF/manifest.xml', $this->getWriterPart('meta_inf')->writeManifest()); - $zip->addFromString('Thumbnails/thumbnail.png', $this->getWriterPart('thumbnails')->writeThumbnail()); - $zip->addFromString('content.xml', $this->getWriterPart('content')->write()); - $zip->addFromString('meta.xml', $this->getWriterPart('meta')->write()); - $zip->addFromString('mimetype', $this->getWriterPart('mimetype')->write()); - $zip->addFromString('settings.xml', $this->getWriterPart('settings')->write()); - $zip->addFromString('styles.xml', $this->getWriterPart('styles')->write()); + $zip->addFile('META-INF/manifest.xml', $this->getWriterPart('meta_inf')->writeManifest()); + $zip->addFile('Thumbnails/thumbnail.png', $this->getWriterPart('thumbnails')->writeThumbnail()); + $zip->addFile('content.xml', $this->getWriterPart('content')->write()); + $zip->addFile('meta.xml', $this->getWriterPart('meta')->write()); + $zip->addFile('mimetype', $this->getWriterPart('mimetype')->write()); + $zip->addFile('settings.xml', $this->getWriterPart('settings')->write()); + $zip->addFile('styles.xml', $this->getWriterPart('styles')->write()); // Close file - if ($zip->close() === false) { - throw new WriterException("Could not close zip file $pFilename."); + try { + $zip->finish(); + } catch (OverflowException $e) { + throw new WriterException('Could not close resource.'); } + rewind($this->fileHandle); + // If a temporary file was used, copy it to the correct file stream if ($originalFilename != $pFilename) { - if (copy($pFilename, $originalFilename) === false) { + if (stream_copy_to_stream($this->fileHandle, fopen($originalFilename, 'wb+')) === false) { throw new WriterException("Could not copy temporary zip file $pFilename to $originalFilename."); } @unlink($pFilename); @@ -122,28 +139,23 @@ class Ods extends BaseWriter /** * Create zip object. * - * @param string $pFilename - * * @throws WriterException * - * @return ZipArchive + * @return ZipStream */ - private function createZip($pFilename) + private function createZip() { - // Create new ZIP file and open it for writing - $zip = new ZipArchive(); - - if (file_exists($pFilename)) { - unlink($pFilename); - } // Try opening the ZIP file - if ($zip->open($pFilename, ZipArchive::OVERWRITE) !== true) { - if ($zip->open($pFilename, ZipArchive::CREATE) !== true) { - throw new WriterException("Could not open $pFilename for writing."); - } + if ($this->fileHandle === false) { + throw new WriterException('Could not open resource for writing.'); } - return $zip; + // Create new ZIP stream + $options = new Archive(); + $options->setEnableZip64(false); + $options->setOutputStream($this->fileHandle); + + return new ZipStream(null, $options); } /** diff --git a/src/PhpSpreadsheet/Writer/Xlsx.php b/src/PhpSpreadsheet/Writer/Xlsx.php index 1fa59e51..2297002b 100644 --- a/src/PhpSpreadsheet/Writer/Xlsx.php +++ b/src/PhpSpreadsheet/Writer/Xlsx.php @@ -24,6 +24,9 @@ use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Theme; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Workbook; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet; use ZipArchive; +use ZipStream\Exception\OverflowException; +use ZipStream\Option\Archive; +use ZipStream\ZipStream; class Xlsx extends BaseWriter { @@ -104,6 +107,11 @@ class Xlsx extends BaseWriter */ private $drawingHashTable; + /** + * @var bool|resource + */ + private $fileHandle; + /** * Create a new Xlsx Writer. * @@ -166,7 +174,7 @@ class Xlsx extends BaseWriter /** * Save PhpSpreadsheet to file. * - * @param string $pFilename + * @param resource|string $pFilename * * @throws WriterException */ @@ -176,13 +184,24 @@ class Xlsx extends BaseWriter // garbage collect $this->spreadSheet->garbageCollect(); - // If $pFilename is php://output or php://stdout, make it a temporary file... $originalFilename = $pFilename; - if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') { + + if (is_resource($pFilename)) { + $this->fileHandle = $pFilename; + } elseif (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') { + // If $pFilename is php://output or php://stdout, make it a temporary file... $pFilename = @tempnam(File::sysGetTempDir(), 'phpxltmp'); if ($pFilename == '') { $pFilename = $originalFilename; } + $this->fileHandle = fopen($pFilename, 'wb+'); + } else { + $this->fileHandle = fopen($pFilename, 'wb+'); + } + + // Try opening the ZIP file + if ($this->fileHandle === false) { + throw new WriterException('Could not open resource for writing.'); } $saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog(); @@ -207,83 +226,77 @@ class Xlsx extends BaseWriter // Create drawing dictionary $this->drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->spreadSheet)); - $zip = new ZipArchive(); + $options = new Archive(); + $options->setEnableZip64(false); + $options->setOutputStream($this->fileHandle); - if (file_exists($pFilename)) { - unlink($pFilename); - } - // Try opening the ZIP file - if ($zip->open($pFilename, ZipArchive::OVERWRITE) !== true) { - if ($zip->open($pFilename, ZipArchive::CREATE) !== true) { - throw new WriterException('Could not open ' . $pFilename . ' for writing.'); - } - } + $zip = new ZipStream(null, $options); // Add [Content_Types].xml to ZIP file - $zip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->spreadSheet, $this->includeCharts)); + $zip->addFile('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->spreadSheet, $this->includeCharts)); //if hasMacros, add the vbaProject.bin file, Certificate file(if exists) if ($this->spreadSheet->hasMacros()) { $macrosCode = $this->spreadSheet->getMacrosCode(); if ($macrosCode !== null) { // we have the code ? - $zip->addFromString('xl/vbaProject.bin', $macrosCode); //allways in 'xl', allways named vbaProject.bin + $zip->addFile('xl/vbaProject.bin', $macrosCode); //allways in 'xl', allways named vbaProject.bin if ($this->spreadSheet->hasMacrosCertificate()) { //signed macros ? // Yes : add the certificate file and the related rels file - $zip->addFromString('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate()); - $zip->addFromString('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet)); + $zip->addFile('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate()); + $zip->addFile('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet)); } } } //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels) if ($this->spreadSheet->hasRibbon()) { $tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target'); - $zip->addFromString($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data')); + $zip->addFile($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data')); if ($this->spreadSheet->hasRibbonBinObjects()) { $tmpRootPath = dirname($tmpRibbonTarget) . '/'; $ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write foreach ($ribbonBinObjects as $aPath => $aContent) { - $zip->addFromString($tmpRootPath . $aPath, $aContent); + $zip->addFile($tmpRootPath . $aPath, $aContent); } //the rels for files - $zip->addFromString($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet)); + $zip->addFile($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet)); } } // Add relationships to ZIP file - $zip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->spreadSheet)); - $zip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->spreadSheet)); + $zip->addFile('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->spreadSheet)); + $zip->addFile('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->spreadSheet)); // Add document properties to ZIP file - $zip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->spreadSheet)); - $zip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->spreadSheet)); + $zip->addFile('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->spreadSheet)); + $zip->addFile('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->spreadSheet)); $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->spreadSheet); if ($customPropertiesPart !== null) { - $zip->addFromString('docProps/custom.xml', $customPropertiesPart); + $zip->addFile('docProps/custom.xml', $customPropertiesPart); } // Add theme to ZIP file - $zip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->spreadSheet)); + $zip->addFile('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->spreadSheet)); // Add string table to ZIP file - $zip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->stringTable)); + $zip->addFile('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->stringTable)); // Add styles to ZIP file - $zip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->spreadSheet)); + $zip->addFile('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->spreadSheet)); // Add workbook to ZIP file - $zip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas)); + $zip->addFile('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas)); $chartCount = 0; // Add worksheets for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { - $zip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts)); + $zip->addFile('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts)); if ($this->includeCharts) { $charts = $this->spreadSheet->getSheet($i)->getChartCollection(); if (count($charts) > 0) { foreach ($charts as $chart) { - $zip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas)); + $zip->addFile('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas)); ++$chartCount; } } @@ -294,19 +307,19 @@ class Xlsx extends BaseWriter // Add worksheet relationships (drawings, ...) for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { // Add relationships - $zip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts)); + $zip->addFile('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts)); // Add unparsedLoadedData $sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName(); $unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData(); if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) { - $zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']); + $zip->addFile($ctrlProp['filePath'], $ctrlProp['content']); } } if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) { - $zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']); + $zip->addFile($ctrlProp['filePath'], $ctrlProp['content']); } } @@ -319,13 +332,13 @@ class Xlsx extends BaseWriter // Add drawing and image relationship parts if (($drawingCount > 0) || ($chartCount > 0)) { // Drawing relationships - $zip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts)); + $zip->addFile('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts)); // Drawings - $zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts)); + $zip->addFile('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts)); } elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) { // Drawings - $zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts)); + $zip->addFile('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts)); } // Add unparsed drawings @@ -334,7 +347,7 @@ class Xlsx extends BaseWriter $drawingFile = array_search($relId, $unparsedLoadedData['sheets'][$sheetCodeName]['drawingOriginalIds']); if ($drawingFile !== false) { $drawingFile = ltrim($drawingFile, '.'); - $zip->addFromString('xl' . $drawingFile, $drawingXml); + $zip->addFile('xl' . $drawingFile, $drawingXml); } } } @@ -342,30 +355,30 @@ class Xlsx extends BaseWriter // Add comment relationship parts if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) { // VML Comments - $zip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i))); + $zip->addFile('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i))); // Comments - $zip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i))); + $zip->addFile('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i))); } // Add unparsed relationship parts if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'] as $vmlDrawing) { - $zip->addFromString($vmlDrawing['filePath'], $vmlDrawing['content']); + $zip->addFile($vmlDrawing['filePath'], $vmlDrawing['content']); } } // Add header/footer relationship parts if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { // VML Drawings - $zip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i))); + $zip->addFile('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i))); // VML Drawing relationships - $zip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i))); + $zip->addFile('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i))); // Media foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { - $zip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath())); + $zip->addFile('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath())); } } } @@ -388,7 +401,7 @@ class Xlsx extends BaseWriter $imageContents = file_get_contents($imagePath); } - $zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); + $zip->addFile('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); } elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) { ob_start(); call_user_func( @@ -398,7 +411,7 @@ class Xlsx extends BaseWriter $imageContents = ob_get_contents(); ob_end_clean(); - $zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); + $zip->addFile('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); } } @@ -406,13 +419,17 @@ class Xlsx extends BaseWriter Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); // Close file - if ($zip->close() === false) { - throw new WriterException("Could not close zip file $pFilename."); + try { + $zip->finish(); + } catch (OverflowException $e) { + throw new WriterException('Could not close resource.'); } + rewind($this->fileHandle); + // If a temporary file was used, copy it to the correct file stream if ($originalFilename != $pFilename) { - if (copy($pFilename, $originalFilename) === false) { + if (stream_copy_to_stream($this->fileHandle, fopen($originalFilename, 'wb+')) === false) { throw new WriterException("Could not copy temporary zip file $pFilename to $originalFilename."); } @unlink($pFilename);