diff --git a/CHANGELOG.md b/CHANGELOG.md index 562c8fa8..fb999854 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - Import JSON bundles containing shared datasets, reports, folders, and Panoramas; first-start setup now installs the six-tile Business performance demo. ### Changed +- Update the bundled spreadsheet import library to PhpSpreadsheet 5.11.0 for reader and formula fixes. - Show data source previews and load simulations as readable tables, with expandable raw data for troubleshooting. - Cache datasource metadata in browser memory for 60 seconds to speed up repeated editing; reloading the app clears the cache. - Use compact, collapsible Tables data source groups so views appear only when their table is expanded. diff --git a/REUSE.toml b/REUSE.toml index aa8f82d1..6daa977b 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -144,7 +144,7 @@ SPDX-FileCopyrightText = "2017 Mark Baker (https://github.com/MarkBaker/PHPCompl SPDX-License-Identifier = "MIT" [[annotations]] -path = "vendor/phpoffice/phpspreadsheet/**" +path = ["vendor/phpoffice/phpspreadsheet/**", "vendor/phpoffice/wmf/**"] precedence = "aggregate" SPDX-FileCopyrightText = "2019 PhpSpreadsheet Authors" SPDX-License-Identifier = "MIT" diff --git a/composer.lock b/composer.lock index 44c17afa..d70767d9 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "bae58d66b0357c26ca5c29c77e2a2a8a", + "content-hash": "600f1ed82258633a0729ab6f13a2c5ae", "packages": [ { "name": "composer/pcre", @@ -269,16 +269,16 @@ }, { "name": "phpoffice/phpspreadsheet", - "version": "5.10.0", + "version": "5.11.0", "source": { "type": "git", "url": "https://github.com/PHPOffice/PhpSpreadsheet.git", - "reference": "eb18727acf6b1f4cc67145a52ab04f9fd4c28d53" + "reference": "3aa1f0d0f3c658b803c18050ac49244d07d96907" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/eb18727acf6b1f4cc67145a52ab04f9fd4c28d53", - "reference": "eb18727acf6b1f4cc67145a52ab04f9fd4c28d53", + "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/3aa1f0d0f3c658b803c18050ac49244d07d96907", + "reference": "3aa1f0d0f3c658b803c18050ac49244d07d96907", "shasum": "" }, "require": { @@ -301,9 +301,11 @@ "markbaker/complex": "^3.0", "markbaker/matrix": "^3.0", "php": "^8.2", + "phpoffice/wmf": "^0.2.1", "psr/simple-cache": "^1.0 || ^2.0 || ^3.0" }, "require-dev": { + "cyclonedx/cyclonedx-php-composer": "^6.2", "dealerdirect/phpcodesniffer-composer-installer": "dev-main", "dompdf/dompdf": "^2.0 || ^3.0", "ext-intl": "*", @@ -374,9 +376,61 @@ ], "support": { "issues": "https://github.com/PHPOffice/PhpSpreadsheet/issues", - "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/5.10.0" + "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/5.11.0" }, - "time": "2026-09-17T03:54:50+00:00" + "time": "2026-11-08T06:29:49+00:00" + }, + { + "name": "phpoffice/wmf", + "version": "0.2.1", + "source": { + "type": "git", + "url": "https://github.com/PHPOffice/WMF.git", + "reference": "d1eafbab74509ee2adfcdda3888737cd8d349820" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPOffice/WMF/zipball/d1eafbab74509ee2adfcdda3888737cd8d349820", + "reference": "d1eafbab74509ee2adfcdda3888737cd8d349820", + "shasum": "" + }, + "require": { + "ext-gd": "*", + "php": "^7.1|^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.88 || ^1.0.0", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "PhpOffice\\WMF\\": "src/WMF/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Progi1984", + "homepage": "https://lefevre.dev" + } + ], + "description": "WMF - Manipulate WMF Images", + "homepage": "https://phpoffice.github.io/WMF/", + "keywords": [ + "emf", + "image", + "php", + "wmf" + ], + "support": { + "issues": "https://github.com/PHPOffice/WMF/issues", + "source": "https://github.com/PHPOffice/WMF/tree/0.2.1" + }, + "time": "2026-10-08T19:34:28+00:00" }, { "name": "psr/simple-cache", diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php index 28ee599b..869c932f 100644 --- a/vendor/composer/autoload_classmap.php +++ b/vendor/composer/autoload_classmap.php @@ -270,8 +270,11 @@ 'PhpOffice\\PhpSpreadsheet\\Cell\\StringValueBinder' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\Axis' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Axis.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\AxisText' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/AxisText.php', + 'PhpOffice\\PhpSpreadsheet\\Chart\\BoxWhisker' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/BoxWhisker.php', + 'PhpOffice\\PhpSpreadsheet\\Chart\\BoxWhiskerSeries' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/BoxWhiskerSeries.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\Chart' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\ChartColor' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/ChartColor.php', + 'PhpOffice\\PhpSpreadsheet\\Chart\\ChartEx' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/ChartEx.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\DataSeries' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeries.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\DataSeriesValues' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeriesValues.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\DataTable' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataTable.php', @@ -405,10 +408,12 @@ 'PhpOffice\\PhpSpreadsheet\\Shared\\File' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\Font' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\IntOrFloat' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/IntOrFloat.php', + 'PhpOffice\\PhpSpreadsheet\\Shared\\Metafile' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Metafile.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLERead' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLERead.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\ChainedBlockStream' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\PPS' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS.php', + 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\PPSTreeNode' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPSTreeNode.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\PPS\\File' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/File.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\PPS\\Root' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\PasswordHasher' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/PasswordHasher.php', @@ -522,6 +527,31 @@ 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Table\\TableStyle' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/TableStyle.php', 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Validations' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Validations.php', 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Worksheet' => $vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php', + 'PhpOffice\\WMF\\Exception\\WMFException' => $vendorDir . '/phpoffice/wmf/src/WMF/Exception/WMFException.php', + 'PhpOffice\\WMF\\Reader\\Detector' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/Detector.php', + 'PhpOffice\\WMF\\Reader\\EMFPlus\\Buffer' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/EMFPlus/Buffer.php', + 'PhpOffice\\WMF\\Reader\\EMFPlus\\ObjectReader' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/EMFPlus/ObjectReader.php', + 'PhpOffice\\WMF\\Reader\\EMFPlus\\Player' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/EMFPlus/Player.php', + 'PhpOffice\\WMF\\Reader\\EMF\\GD' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/EMF/GD.php', + 'PhpOffice\\WMF\\Reader\\EMF\\Imagick' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/EMF/Imagick.php', + 'PhpOffice\\WMF\\Reader\\EMF\\Magic' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/EMF/Magic.php', + 'PhpOffice\\WMF\\Reader\\EMF\\ReaderAbstract' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/EMF/ReaderAbstract.php', + 'PhpOffice\\WMF\\Reader\\EMF\\ReaderInterface' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/EMF/ReaderInterface.php', + 'PhpOffice\\WMF\\Reader\\GDTrait' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/GDTrait.php', + 'PhpOffice\\WMF\\Reader\\ImagickTrait' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/ImagickTrait.php', + 'PhpOffice\\WMF\\Reader\\MagicTrait' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/MagicTrait.php', + 'PhpOffice\\WMF\\Reader\\ReaderAbstract' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/ReaderAbstract.php', + 'PhpOffice\\WMF\\Reader\\ReaderInterface' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/ReaderInterface.php', + 'PhpOffice\\WMF\\Reader\\WMF\\GD' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/WMF/GD.php', + 'PhpOffice\\WMF\\Reader\\WMF\\Imagick' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/WMF/Imagick.php', + 'PhpOffice\\WMF\\Reader\\WMF\\Magic' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/WMF/Magic.php', + 'PhpOffice\\WMF\\Reader\\WMF\\ReaderAbstract' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/WMF/ReaderAbstract.php', + 'PhpOffice\\WMF\\Reader\\WMF\\ReaderInterface' => $vendorDir . '/phpoffice/wmf/src/WMF/Reader/WMF/ReaderInterface.php', + 'PhpOffice\\WMF\\Renderer\\Bitmap' => $vendorDir . '/phpoffice/wmf/src/WMF/Renderer/Bitmap.php', + 'PhpOffice\\WMF\\Renderer\\Encoding' => $vendorDir . '/phpoffice/wmf/src/WMF/Renderer/Encoding.php', + 'PhpOffice\\WMF\\Renderer\\FontResolver' => $vendorDir . '/phpoffice/wmf/src/WMF/Renderer/FontResolver.php', + 'PhpOffice\\WMF\\Renderer\\GD' => $vendorDir . '/phpoffice/wmf/src/WMF/Renderer/GD.php', + 'PhpOffice\\WMF\\Renderer\\Rasterizer' => $vendorDir . '/phpoffice/wmf/src/WMF/Renderer/Rasterizer.php', 'Psr\\SimpleCache\\CacheException' => $vendorDir . '/psr/simple-cache/src/CacheException.php', 'Psr\\SimpleCache\\CacheInterface' => $vendorDir . '/psr/simple-cache/src/CacheInterface.php', 'Psr\\SimpleCache\\InvalidArgumentException' => $vendorDir . '/psr/simple-cache/src/InvalidArgumentException.php', diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php index abfdd053..1d68f39b 100644 --- a/vendor/composer/autoload_psr4.php +++ b/vendor/composer/autoload_psr4.php @@ -8,6 +8,7 @@ return array( 'ZipStream\\' => array($vendorDir . '/maennchen/zipstream-php/src'), 'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'), + 'PhpOffice\\WMF\\' => array($vendorDir . '/phpoffice/wmf/src/WMF'), 'PhpOffice\\PhpSpreadsheet\\' => array($vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet'), 'Matrix\\' => array($vendorDir . '/markbaker/matrix/classes/src'), 'Composer\\Pcre\\' => array($vendorDir . '/composer/pcre/src'), diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php index 321274d1..c78b21d7 100644 --- a/vendor/composer/autoload_static.php +++ b/vendor/composer/autoload_static.php @@ -14,6 +14,7 @@ class ComposerStaticInitbae58d66b0357c26ca5c29c77e2a2a8a 'P' => array ( 'Psr\\SimpleCache\\' => 16, + 'PhpOffice\\WMF\\' => 14, 'PhpOffice\\PhpSpreadsheet\\' => 25, ), 'M' => @@ -36,6 +37,10 @@ class ComposerStaticInitbae58d66b0357c26ca5c29c77e2a2a8a array ( 0 => __DIR__ . '/..' . '/psr/simple-cache/src', ), + 'PhpOffice\\WMF\\' => + array ( + 0 => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF', + ), 'PhpOffice\\PhpSpreadsheet\\' => array ( 0 => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet', @@ -319,8 +324,11 @@ class ComposerStaticInitbae58d66b0357c26ca5c29c77e2a2a8a 'PhpOffice\\PhpSpreadsheet\\Cell\\StringValueBinder' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\Axis' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Axis.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\AxisText' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/AxisText.php', + 'PhpOffice\\PhpSpreadsheet\\Chart\\BoxWhisker' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/BoxWhisker.php', + 'PhpOffice\\PhpSpreadsheet\\Chart\\BoxWhiskerSeries' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/BoxWhiskerSeries.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\Chart' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\ChartColor' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/ChartColor.php', + 'PhpOffice\\PhpSpreadsheet\\Chart\\ChartEx' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/ChartEx.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\DataSeries' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeries.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\DataSeriesValues' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeriesValues.php', 'PhpOffice\\PhpSpreadsheet\\Chart\\DataTable' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataTable.php', @@ -454,10 +462,12 @@ class ComposerStaticInitbae58d66b0357c26ca5c29c77e2a2a8a 'PhpOffice\\PhpSpreadsheet\\Shared\\File' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\Font' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\IntOrFloat' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/IntOrFloat.php', + 'PhpOffice\\PhpSpreadsheet\\Shared\\Metafile' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Metafile.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLERead' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLERead.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\ChainedBlockStream' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\PPS' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS.php', + 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\PPSTreeNode' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPSTreeNode.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\PPS\\File' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/File.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\OLE\\PPS\\Root' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php', 'PhpOffice\\PhpSpreadsheet\\Shared\\PasswordHasher' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/PasswordHasher.php', @@ -571,6 +581,31 @@ class ComposerStaticInitbae58d66b0357c26ca5c29c77e2a2a8a 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Table\\TableStyle' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/TableStyle.php', 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Validations' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Validations.php', 'PhpOffice\\PhpSpreadsheet\\Worksheet\\Worksheet' => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php', + 'PhpOffice\\WMF\\Exception\\WMFException' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Exception/WMFException.php', + 'PhpOffice\\WMF\\Reader\\Detector' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/Detector.php', + 'PhpOffice\\WMF\\Reader\\EMFPlus\\Buffer' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/EMFPlus/Buffer.php', + 'PhpOffice\\WMF\\Reader\\EMFPlus\\ObjectReader' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/EMFPlus/ObjectReader.php', + 'PhpOffice\\WMF\\Reader\\EMFPlus\\Player' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/EMFPlus/Player.php', + 'PhpOffice\\WMF\\Reader\\EMF\\GD' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/EMF/GD.php', + 'PhpOffice\\WMF\\Reader\\EMF\\Imagick' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/EMF/Imagick.php', + 'PhpOffice\\WMF\\Reader\\EMF\\Magic' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/EMF/Magic.php', + 'PhpOffice\\WMF\\Reader\\EMF\\ReaderAbstract' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/EMF/ReaderAbstract.php', + 'PhpOffice\\WMF\\Reader\\EMF\\ReaderInterface' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/EMF/ReaderInterface.php', + 'PhpOffice\\WMF\\Reader\\GDTrait' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/GDTrait.php', + 'PhpOffice\\WMF\\Reader\\ImagickTrait' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/ImagickTrait.php', + 'PhpOffice\\WMF\\Reader\\MagicTrait' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/MagicTrait.php', + 'PhpOffice\\WMF\\Reader\\ReaderAbstract' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/ReaderAbstract.php', + 'PhpOffice\\WMF\\Reader\\ReaderInterface' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/ReaderInterface.php', + 'PhpOffice\\WMF\\Reader\\WMF\\GD' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/WMF/GD.php', + 'PhpOffice\\WMF\\Reader\\WMF\\Imagick' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/WMF/Imagick.php', + 'PhpOffice\\WMF\\Reader\\WMF\\Magic' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/WMF/Magic.php', + 'PhpOffice\\WMF\\Reader\\WMF\\ReaderAbstract' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/WMF/ReaderAbstract.php', + 'PhpOffice\\WMF\\Reader\\WMF\\ReaderInterface' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Reader/WMF/ReaderInterface.php', + 'PhpOffice\\WMF\\Renderer\\Bitmap' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Renderer/Bitmap.php', + 'PhpOffice\\WMF\\Renderer\\Encoding' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Renderer/Encoding.php', + 'PhpOffice\\WMF\\Renderer\\FontResolver' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Renderer/FontResolver.php', + 'PhpOffice\\WMF\\Renderer\\GD' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Renderer/GD.php', + 'PhpOffice\\WMF\\Renderer\\Rasterizer' => __DIR__ . '/..' . '/phpoffice/wmf/src/WMF/Renderer/Rasterizer.php', 'Psr\\SimpleCache\\CacheException' => __DIR__ . '/..' . '/psr/simple-cache/src/CacheException.php', 'Psr\\SimpleCache\\CacheInterface' => __DIR__ . '/..' . '/psr/simple-cache/src/CacheInterface.php', 'Psr\\SimpleCache\\InvalidArgumentException' => __DIR__ . '/..' . '/psr/simple-cache/src/InvalidArgumentException.php', diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json index c4974de5..7dc29781 100644 --- a/vendor/composer/installed.json +++ b/vendor/composer/installed.json @@ -275,17 +275,17 @@ }, { "name": "phpoffice/phpspreadsheet", - "version": "5.10.0", - "version_normalized": "5.10.0.0", + "version": "5.11.0", + "version_normalized": "5.11.0.0", "source": { "type": "git", "url": "https://github.com/PHPOffice/PhpSpreadsheet.git", - "reference": "eb18727acf6b1f4cc67145a52ab04f9fd4c28d53" + "reference": "3aa1f0d0f3c658b803c18050ac49244d07d96907" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/eb18727acf6b1f4cc67145a52ab04f9fd4c28d53", - "reference": "eb18727acf6b1f4cc67145a52ab04f9fd4c28d53", + "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/3aa1f0d0f3c658b803c18050ac49244d07d96907", + "reference": "3aa1f0d0f3c658b803c18050ac49244d07d96907", "shasum": "" }, "require": { @@ -308,9 +308,11 @@ "markbaker/complex": "^3.0", "markbaker/matrix": "^3.0", "php": "^8.2", + "phpoffice/wmf": "^0.2.1", "psr/simple-cache": "^1.0 || ^2.0 || ^3.0" }, "require-dev": { + "cyclonedx/cyclonedx-php-composer": "^6.2", "dealerdirect/phpcodesniffer-composer-installer": "dev-main", "dompdf/dompdf": "^2.0 || ^3.0", "ext-intl": "*", @@ -334,7 +336,7 @@ "mpdf/mpdf": "Option for rendering PDF with PDF Writer", "tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer" }, - "time": "2026-09-17T03:54:50+00:00", + "time": "2026-11-08T06:29:49+00:00", "type": "library", "installation-source": "dist", "autoload": { @@ -383,10 +385,65 @@ ], "support": { "issues": "https://github.com/PHPOffice/PhpSpreadsheet/issues", - "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/5.10.0" + "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/5.11.0" }, "install-path": "../phpoffice/phpspreadsheet" }, + { + "name": "phpoffice/wmf", + "version": "0.2.1", + "version_normalized": "0.2.1.0", + "source": { + "type": "git", + "url": "https://github.com/PHPOffice/WMF.git", + "reference": "d1eafbab74509ee2adfcdda3888737cd8d349820" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPOffice/WMF/zipball/d1eafbab74509ee2adfcdda3888737cd8d349820", + "reference": "d1eafbab74509ee2adfcdda3888737cd8d349820", + "shasum": "" + }, + "require": { + "ext-gd": "*", + "php": "^7.1|^8.0" + }, + "require-dev": { + "phpstan/phpstan": "^0.12.88 || ^1.0.0", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" + }, + "time": "2026-10-08T19:34:28+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "PhpOffice\\WMF\\": "src/WMF/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Progi1984", + "homepage": "https://lefevre.dev" + } + ], + "description": "WMF - Manipulate WMF Images", + "homepage": "https://phpoffice.github.io/WMF/", + "keywords": [ + "emf", + "image", + "php", + "wmf" + ], + "support": { + "issues": "https://github.com/PHPOffice/WMF/issues", + "source": "https://github.com/PHPOffice/WMF/tree/0.2.1" + }, + "install-path": "../phpoffice/wmf" + }, { "name": "psr/simple-cache", "version": "3.0.0", diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php index 084f788b..e01f0207 100644 --- a/vendor/composer/installed.php +++ b/vendor/composer/installed.php @@ -1,8 +1,8 @@ array( 'name' => '__root__', - 'pretty_version' => 'dev-master', - 'version' => 'dev-master', + 'pretty_version' => '1.0.0+no-version-set', + 'version' => '1.0.0.0', 'reference' => null, 'type' => 'library', 'install_path' => __DIR__ . '/../../', @@ -11,8 +11,8 @@ ), 'versions' => array( '__root__' => array( - 'pretty_version' => 'dev-master', - 'version' => 'dev-master', + 'pretty_version' => '1.0.0+no-version-set', + 'version' => '1.0.0.0', 'reference' => null, 'type' => 'library', 'install_path' => __DIR__ . '/../../', @@ -56,14 +56,23 @@ 'dev_requirement' => false, ), 'phpoffice/phpspreadsheet' => array( - 'pretty_version' => '5.10.0', - 'version' => '5.10.0.0', - 'reference' => 'eb18727acf6b1f4cc67145a52ab04f9fd4c28d53', + 'pretty_version' => '5.11.0', + 'version' => '5.11.0.0', + 'reference' => '3aa1f0d0f3c658b803c18050ac49244d07d96907', 'type' => 'library', 'install_path' => __DIR__ . '/../phpoffice/phpspreadsheet', 'aliases' => array(), 'dev_requirement' => false, ), + 'phpoffice/wmf' => array( + 'pretty_version' => '0.2.1', + 'version' => '0.2.1.0', + 'reference' => 'd1eafbab74509ee2adfcdda3888737cd8d349820', + 'type' => 'library', + 'install_path' => __DIR__ . '/../phpoffice/wmf', + 'aliases' => array(), + 'dev_requirement' => false, + ), 'psr/simple-cache' => array( 'pretty_version' => '3.0.0', 'version' => '3.0.0.0', diff --git a/vendor/phpoffice/phpspreadsheet/CHANGELOG.md b/vendor/phpoffice/phpspreadsheet/CHANGELOG.md index 049eefd9..9a543437 100644 --- a/vendor/phpoffice/phpspreadsheet/CHANGELOG.md +++ b/vendor/phpoffice/phpspreadsheet/CHANGELOG.md @@ -9,7 +9,7 @@ a breaking change. Some earlier branches remain supported and security fixes are applied to them; if the security fix represents a breaking change, it may have to be applied as a minor or patch version. -## TBD - 5.11.0 +## TBD - 5.12.0 ### Added @@ -35,6 +35,67 @@ Some earlier branches remain supported and security fixes are applied to them; i - Nothing yet. +## 2026-11-07 - 5.11.0 + +### Added + +- Ods Writer writes each table as a named database range, with its header row, so that LibreOffice tags the header cells of an exported PDF as `/TH`; Ods Reader reads a named database range back as a table (the anonymous range LibreOffice keeps for the filter of a sheet stays that sheet's autofilter), and an autofilter now lands on the sheet its range names. [Issue #5022](https://github.com/PHPOffice/PhpSpreadsheet/issues/5022) [PR #5023](https://github.com/PHPOffice/PhpSpreadsheet/pull/5023) +- Support for Box and Whisker charts in Xlsx reader and writer. [Issue #3493](https://github.com/PHPOffice/PhpSpreadsheet/issues/3493) +- Support for Windows Metafiles images (WMF, EMF and EMF+), using the `phpoffice/wmf` library: Xlsx Writer stores them as is, Ods, Xls, Html and Pdf Writers and comment backgrounds use a PNG rendering; Xlsx and Ods Writers can switch with `setConvertMetafilesToPng()` (new in `BaseWriter`), and `MemoryDrawing::fromString()` / `fromStream()` accept them. New methods `Drawing::isMetafile()` and `Drawing::getMetafileType()`, and new helper `Shared\Metafile`. +- `Document\Properties::setLanguage()`: the language of a spreadsheet as a BCP 47 tag, written and read as `dc:language` in Xlsx and Ods; the Ods writer also gives it to the default cell style, where LibreOffice keeps a spreadsheet's language, as LibreOffice writes it (the Western, Asian or complex slot by script, and `style:rfc-language-tag` for a tag with more than a language and a country), and the Ods reader reads it from there when there is no `dc:language`. Html writes and reads it as the `lang` of the `html` element. [Issue #5040](https://github.com/PHPOffice/PhpSpreadsheet/issues/5040) [PR #5041](https://github.com/PHPOffice/PhpSpreadsheet/pull/5041) +- Xlsx Writer and Reader: `Chart::setDescription()` is the alternative text of a chart, written as `descr` of the chart's frame and read back, and the frame takes the chart's name; LibreOffice exports it as `/Alt` of the chart in a tagged PDF. [Issue #5038](https://github.com/PHPOffice/PhpSpreadsheet/issues/5038) [PR #5039](https://github.com/PHPOffice/PhpSpreadsheet/pull/5039) +- `BaseDrawing::setDecorative()` marks an image as decorative. Xlsx writes and reads it as Excel and LibreOffice do (`adec:decorative` in the image's `cNvPr`), Ods as LibreOffice does (`loext:decorative` in the frame's graphic style, which the writer now defines; the reader also takes ODF 1.4's `draw:decorative`); LibreOffice then leaves the image out of a tagged PDF as an artifact. Html writes and reads it as an empty `alt`. [Issue #5036](https://github.com/PHPOffice/PhpSpreadsheet/issues/5036) [PR #5037](https://github.com/PHPOffice/PhpSpreadsheet/pull/5037) +- Xlsx Writer and Reader: the description of a header/footer image is its alternative text, `alt` on the VML shape as Excel writes it. [Issue #5056](https://github.com/PHPOffice/PhpSpreadsheet/issues/5056) [PR #5057](https://github.com/PHPOffice/PhpSpreadsheet/pull/5057) + +### Changed + +- Update infrastructure for running samples in browser. [PR #5061](https://github.com/PHPOffice/PhpSpreadsheet/pull/5061) [PR #5068](https://github.com/PHPOffice/PhpSpreadsheet/pull/5068) +- `phpoffice/wmf` is a new required dependency, used to render Windows Metafiles images. +- The exception thrown for an unsupported comment background image now lists WMF and EMF among the supported types (`Drawing::UNSUPPORTED_IMAGE_TYPE_MESSAGE`). +- Some Windows environments are added to CI unit tests. [PR #5053](https://github.com/PHPOffice/PhpSpreadsheet/pull/5053) + +### Deprecated + +- Deprecate `_calculateFormulaValue` for `calculateFormulaValue`. [PR #4992](https://github.com/PHPOffice/PhpSpreadsheet/pull/4992) +- Tcpdf V6 is now officially deprecated. We will continue to support it for now, but are considering dropping support with the next major PhpSpreadsheet release. + +### Fixed + +- Xls Writer: a color matching a built-in palette entry above the custom range (e.g. `333333`) no longer makes the palette look full, so later custom colors are no longer written as black. [Issue #5065](https://github.com/PHPOffice/PhpSpreadsheet/issues/5065) [PR #5066](https://github.com/PHPOffice/PhpSpreadsheet/pull/5066) +- Xlsx Reader and AgileEncryption parser reject a DOCTYPE or entity declaration in encrypted workbook metadata before parsing. [PR #5072](https://github.com/PHPOffice/PhpSpreadsheet/pull/5072) +- `RIGHT()` returns all of the text when the number of characters requested is greater than its length. [PR #5044](https://github.com/PHPOffice/PhpSpreadsheet/pull/5044) +- Comparison operators order values of different types as Excel does (numbers < text < FALSE < TRUE), so `=""<75` is FALSE. [PR #5004](https://github.com/PHPOffice/PhpSpreadsheet/pull/5004) +- A "TRUE" or "FALSE" criterion matches logical values in COUNTIF, SUMIF, the database functions and the others sharing their criteria, as Excel does. [PR #5006](https://github.com/PHPOffice/PhpSpreadsheet/pull/5006) +- OLE Writer now validates directory names, orders and colors sibling trees correctly, writes conformant CLSIDs and timestamps, and initializes unused directory-entry pointers to NOSTREAM. [PR #5033](https://github.com/PHPOffice/PhpSpreadsheet/pull/5033) +- MIN and MAX return #VALUE! for non-numeric text typed as an argument, and count logical values and numeric text typed as an argument, as Excel (and SUM) do. [PR #5005](https://github.com/PHPOffice/PhpSpreadsheet/pull/5005) +- `VALUE()` no longer treats product-like text such as `5V 2.1A - EU Wall Adaptor` as a date serial. [Issue #4996](https://github.com/PHPOffice/PhpSpreadsheet/issues/4996) [PR #4997](https://github.com/PHPOffice/PhpSpreadsheet/issues/4997) +- Minor Xml Reader Improvements. [PR #4989](https://github.com/PHPOffice/PhpSpreadsheet/issues/4989) +- Rename and change visibility of 2 Xls Writer properties. [PR #4995](https://github.com/PHPOffice/PhpSpreadsheet/issues/4995) +- Documentation infrastructure tweaks. [PR #4994](https://github.com/PHPOffice/PhpSpreadsheet/issues/4994) [PR #4999](https://github.com/PHPOffice/PhpSpreadsheet/issues/4999) +- Ods Writer writes a right-to-left sheet as `style:writing-mode="rl-tb"`, and Ods Reader reads it back; the direction was lost both ways. [Issue #5015](https://github.com/PHPOffice/PhpSpreadsheet/issues/5015) [PR #5016](https://github.com/PHPOffice/PhpSpreadsheet/pull/5016) +- Ods Writer writes a link to another sheet as `#Sheet.A1`, as ODF and LibreOffice do, and Ods Reader reads that form back as `sheet://Sheet!A1`, so a Xlsx saved from it no longer gets a broken location. [Issue #5011](https://github.com/PHPOffice/PhpSpreadsheet/issues/5011) [PR #5012](https://github.com/PHPOffice/PhpSpreadsheet/pull/5012) +- Ods Writer and Reader: the description of an image is written as `svg:desc` and read back, so that LibreOffice exports it as the alternative text of the figure. [Issue #5009](https://github.com/PHPOffice/PhpSpreadsheet/issues/5009) [PR #5010](https://github.com/PHPOffice/PhpSpreadsheet/pull/5010) +- Ods Writer and Csv Writer (with `preferHyperlinkToLabel`) no longer add an empty hyperlink to every cell they write, which made a later Xlsx save throw "Invalid parameters passed." [Issue #5007](https://github.com/PHPOffice/PhpSpreadsheet/issues/5007) [PR #5008](https://github.com/PHPOffice/PhpSpreadsheet/pull/5008) [PR #5021](https://github.com/PHPOffice/PhpSpreadsheet/pull/5021) +- Ods Writer keeps the hyperlink of a number, boolean or formula cell, and Ods Reader reads it back; only text cells had one. [Issue #5013](https://github.com/PHPOffice/PhpSpreadsheet/issues/5013) [PR #5014](https://github.com/PHPOffice/PhpSpreadsheet/pull/5014) +- Don't iterate cell ranges on non-existent sheets. [Issue #5032](https://github.com/PHPOffice/PhpSpreadsheet/issues/5032) [PR #5035](https://github.com/PHPOffice/PhpSpreadsheet/pull/5035) +- Xls Writer normalizes color strings to upper case and picks the next custom palette index from the highest index in use, so a color can no longer overwrite the palette slot of an earlier color (e.g. a font rendering in a fill color). [Issue #5019](https://github.com/PHPOffice/PhpSpreadsheet/issues/5019) [PR #5020](https://github.com/PHPOffice/PhpSpreadsheet/pull/5020) +- Ods Reader reads the hyperlink LibreOffice keeps in the style of a number, boolean, date or formula cell (`style:hyperlink` in `style:table-cell-properties`), as it writes a link from a Xlsx file. [Issue #5017](https://github.com/PHPOffice/PhpSpreadsheet/issues/5017) [PR #5018](https://github.com/PHPOffice/PhpSpreadsheet/pull/5018) +- `removeColumn()` no longer throws "Invalid column index 0" when it removes column A and every column up to the highest data column, e.g. `removeColumn('A')` on an empty sheet. [Issue #5049](https://github.com/PHPOffice/PhpSpreadsheet/issues/5049) [PR #5050](https://github.com/PHPOffice/PhpSpreadsheet/pull/5050) +- `removeColumn()` and `removeRow()` take the removed columns/rows out of data validation ranges: a validation that lies only on them is deleted, and a range that ends on them shrinks, instead of covering the column/row that slides into their place. [Issue #5047](https://github.com/PHPOffice/PhpSpreadsheet/issues/5047) [PR #5048](https://github.com/PHPOffice/PhpSpreadsheet/pull/5048) +- Minor cleanup in Ods Reader to fix test which was not working in Windows. [PR #5052](https://github.com/PHPOffice/PhpSpreadsheet/pull/5052) +- A fraction number format writes an integer as a fraction when the format has no integer part, so 1 is `1/1` with `0/0`, and when the last numerator placeholder is 0, so 1 is `1 0/1` with `0 0/0`, as Excel does. [Issue #3625](https://github.com/PHPOffice/PhpSpreadsheet/issues/3625) [PR #5060](https://github.com/PHPOffice/PhpSpreadsheet/pull/5060) +- Removing or inserting a column that shifts the header row of a table no longer throws `Worksheet no longer exists`. [Issue #5058](https://github.com/PHPOffice/PhpSpreadsheet/issues/5058) [PR #5059](https://github.com/PHPOffice/PhpSpreadsheet/pull/5059) +- Branch pruning no longer throws "internal error" for an IF nested in the condition of another IF inside a pruned branch. [Issue #3755](https://github.com/PHPOffice/PhpSpreadsheet/issues/3755) [Issue #3790](https://github.com/PHPOffice/PhpSpreadsheet/issues/3790) [PR #5055](https://github.com/PHPOffice/PhpSpreadsheet/pull/5055) +- Xls Writer no longer loses EMF and WMF images (they are written as PNG); the resulting file could not be read back (`Call to a member function getBlipType() on null`). [Issue #274](https://github.com/PHPOffice/PhpSpreadsheet/issues/274) +- Xls Reader reads EMF and WMF pictures (as PNG `MemoryDrawing`); they were ignored. [Issue #274](https://github.com/PHPOffice/PhpSpreadsheet/issues/274) +- Xlsx Writer declares WMF and EMF images as `image/x-wmf` and `image/x-emf` instead of `application/octet-stream`, and Ods Writer does the same in its manifest when it stores them as is. +- Html and Pdf Writers display WMF and EMF images (as PNG) instead of an empty image. +- Ods Writer no longer writes the formula text as the cell value when formulas are not pre-calculated. [Issue #5045](https://github.com/PHPOffice/PhpSpreadsheet/issues/5045) [PR #5046](https://github.com/PHPOffice/PhpSpreadsheet/pull/5046) +- Xlsx Writer and Reader keep the custom formula of a table totals row (`Column::setTotalsRowFormula()`), written as `totalsRowFormula` with `totalsRowFunction="custom"`; before it was dropped. The totals row label, function (as `SUBTOTAL`) or formula of a column also sets its totals row cell when that cell is empty, so it no longer has to be set by hand. [Issue #5063](https://github.com/PHPOffice/PhpSpreadsheet/issues/5063) [PR #5064](https://github.com/PHPOffice/PhpSpreadsheet/pull/5064) +- Avoid some breaks caused by new versions of libxml. [PR #5054](https://github.com/PHPOffice/PhpSpreadsheet/pull/5054) +- `getDataValidation()` and `dataValidationExists()` no longer throw "Cell coordinate string can not be a range of cells" for a range once a validation on a range exists; a range gets the validation set on exactly that range, or a new one. [Issue #5073](https://github.com/PHPOffice/PhpSpreadsheet/issues/5073) [PR #5074](https://github.com/PHPOffice/PhpSpreadsheet/pull/5074) +- Text formats containing `@` treat a backslash as an escape character, as Excel does, so `@\X` displays `Test` as `TestX` instead of `Test\X`; backslashes in the text itself are kept. [Issue #5069](https://github.com/PHPOffice/PhpSpreadsheet/issues/5069) [PR #5071](https://github.com/PHPOffice/PhpSpreadsheet/pull/5071) + ## 2026-09-15 - 5.10.0 ### Added @@ -638,7 +699,7 @@ Some earlier branches remain supported and security fixes are applied to them; i ### Changed - On read, Xlsx Reader had been breaking up union ranges into separate individual ranges. It will now try to preserve range as it was read in. [PR #4042](https://github.com/PHPOffice/PhpSpreadsheet/pull/4042) -- Xlsx/Xls spreadsheet calculation and formatting of dates will use base date of spreadsheet even when spreadsheets with different base dates are simultaneously open. [Issue #1036](https://github.com/PHPOffice/PhpSpreadsheet/issues/1036) [Issue #1635](https://github.com/PHPOffice/PhpSpreadsheet/issues/1635) [PR #4071](https://github.com/PHPOffice/PhpSpreadsheet/pull/4071) +- Xlsx/Xls spreadsheet calculation and formatting of dates will use base date of spreadsheet even when spreadsheets with different base dates are simultaneously open. [Issue #1036](https://github.com/PHPOffice/PhpSpreadsheet/issues/1036) [Issue #1635](https://github.com/PHPOffice/PhpSpreadsheet/issues/1635) [PR #4071](https://github.com/PHPOffice/PhpSpreadsheet/pull/4071) ### Deprecated @@ -707,7 +768,7 @@ Some earlier branches remain supported and security fixes are applied to them; i ### BREAKING CHANGE - Typing was strengthened by leveraging native typing. This should not change any behavior. However, if you implement - any interfaces or inherit from any classes, you will need to adapt your typing accordingly. If you use static analysis + any interfaces or inherit from any classes, you will need to adapt your typing accordingly. If you use static analysis tools such as PHPStan or Psalm, new errors might be found. If you find actual bugs because of the new typing, please open a PR that fixes it with a **detailed** explanation of the reason. We'll try to merge and release typing-related fixes quickly in the coming days. [PR #3718](https://github.com/PHPOffice/PhpSpreadsheet/pull/3718) @@ -858,7 +919,7 @@ Some earlier branches remain supported and security fixes are applied to them; i - Improved handling for @ placeholder in Number Format Masks [PR #3344](https://github.com/PHPOffice/PhpSpreadsheet/pull/3344) - Improved handling for ? placeholder in Number Format Masks [PR #3394](https://github.com/PHPOffice/PhpSpreadsheet/pull/3394) -- Improved support for locale settings and currency codes when matching formatted strings to numerics in the Calculation Engine [PR #3373](https://github.com/PHPOffice/PhpSpreadsheet/pull/3373) and [PR #3374](https://github.com/PHPOffice/PhpSpreadsheet/pull/3374) +- Improved support for locale settings and currency codes when matching formatted strings to numerics in the Calculation Engine [PR #3373](https://github.com/PHPOffice/PhpSpreadsheet/pull/3373) and [PR #3374](https://github.com/PHPOffice/PhpSpreadsheet/pull/3374) - Improved support for locale settings and matching in the Advanced Value Binder [PR #3376](https://github.com/PHPOffice/PhpSpreadsheet/pull/3376) - `toFormattedString` will now always return a string. This can affect the results of `toArray`, `namedRangeToArray`, and `rangeToArray`. [PR #3304](https://github.com/PHPOffice/PhpSpreadsheet/pull/3304) - Value of constants FORMAT_CURRENCY_EUR and FORMAT_CURRENCY_USD is changed. [Issue #3577](https://github.com/PHPOffice/PhpSpreadsheet/issues/3577) [PR #3377](https://github.com/PHPOffice/PhpSpreadsheet/pull/3377) diff --git a/vendor/phpoffice/phpspreadsheet/CONTRIBUTING.md b/vendor/phpoffice/phpspreadsheet/CONTRIBUTING.md index a8d92371..b7dc3f26 100644 --- a/vendor/phpoffice/phpspreadsheet/CONTRIBUTING.md +++ b/vendor/phpoffice/phpspreadsheet/CONTRIBUTING.md @@ -34,16 +34,17 @@ This makes it easier to see exactly what is being tested when reviewing the PR. ## How to release -1. Complete CHANGELOG.md and commit -2. Create an annotated tag +1. On the master branch only, run `composer sbom`, and, if needed, update release numbers on SECURITY.md. +2. Complete CHANGELOG.md and commit +3. Create an annotated tag 1. `git tag -a 1.2.3` 2. Tag subject must be the version number, eg: `1.2.3` 3. Tag body must be a copy-paste of the changelog entries. -3. Push the tag with `git push --tags`, GitHub Actions will create a GitHub release automatically, and the release details will automatically be sent to packagist. -4. By default, Github removes markdown headings in the Release Notes. You can either edit to restore these, or, probably preferably, change the default comment character on your system - `git config core.commentChar ";"`. +4. Push the tag with `git push --tags`, GitHub Actions will create a GitHub release automatically, and the release details will automatically be sent to packagist. +5. By default, Github removes markdown headings in the Release Notes. You can either edit to restore these, or, probably preferably, change the default comment character on your system - `git config core.commentChar ";"`. > **Note:** Tagged releases are made from the `master` branch. Only in an emergency should a tagged release be made from the `release` branch. (i.e. cherry-picked hot-fixes.) However, there are 4 branches which have been updated to apply security patches, and those may be tagged if future security updates are needed. -- 1.30.x (no further updates aside from security patches, including code changes needed for Php 8.5 compatibility) -- 2.1.x (no further updates aside from security patches, including code changes needed for Php 8.5 compatibility) -- 2.4.x (no further updates aside from security patches) -- 3.10.x +- 1.30.x (no further updates including security patches) +- 2.1.x (no further updates including security patches) +- 2.4.x (no further updates including security patches) +- 3.10.x (no further updates except security patches for a very limited time) diff --git a/vendor/phpoffice/phpspreadsheet/SECURITY.md b/vendor/phpoffice/phpspreadsheet/SECURITY.md new file mode 100644 index 00000000..a624a6d5 --- /dev/null +++ b/vendor/phpoffice/phpspreadsheet/SECURITY.md @@ -0,0 +1,32 @@ +# Security Policy + +## Reporting a Vulnerability + +If you discover a security vulnerability within this project, please report it via [Private Vulnerability Reporting](https://github.com/PHPOffice/PhpSpreadsheet/security/advisories/new). + +Please do not report security vulnerabilities through public GitHub issues. + +### What to Include +* Type of issue (e.g., buffer overflow, SQL injection, cross-site scripting). +* Full paths of source file(s) related to the manifestation of the issue. +* The location of the affected source code within those paths. +* Proof of concept (step-by-step instructions to reproduce the issue). +* Suggested remediation. + +## Supported Versions + +| Version | Supported | +| -------------------- | --------- | +| >= 5.10.0 | ✅ | +| >= 4.0.0, < 5.10.0 | ❌ | +| >= 3.10.8, < 4.0.0 | ✅ | +| >= 3.0.0, < 3.10.8 | ❌ | +| >= 2.4.8, < 3.0.0 | ✅ | +| >= 2.2.0, < 2.4.8 | ❌ | +| >= 2.1.19, < 2.2.0 | ✅ | +| >= 2.0.0, < 2.1.19 | ❌ | +| >= 1.30.6, < 2.0.0 | ✅ | +| < 1.30.6 | ❌ | + +## Disclosure Policy +We follow a coordinated vulnerability disclosure approach. We ask that you give us reasonable time to address the issue before making any public disclosures. diff --git a/vendor/phpoffice/phpspreadsheet/composer.json b/vendor/phpoffice/phpspreadsheet/composer.json index 19cbcc0b..f2db38ff 100644 --- a/vendor/phpoffice/phpspreadsheet/composer.json +++ b/vendor/phpoffice/phpspreadsheet/composer.json @@ -18,6 +18,7 @@ "process-timeout": 600, "sort-packages": true, "allow-plugins": { + "cyclonedx/cyclonedx-php-composer": true, "dealerdirect/phpcodesniffer-composer-installer": true } }, @@ -64,6 +65,10 @@ "phpcbf samples/ src/ tests/ --report=checkstyle", "php-cs-fixer fix" ], + "sbom": [ + "git diff --exit-code composer.lock", + "composer CycloneDX:make-sbom --omit=dev --output-file=./sbom.xml" + ], "versions": [ "phpcs samples/ src/ tests/ --standard=PHPCompatibility --runtime-set testVersion 8.0- --exclude=PHPCompatibility.Variables.ForbiddenThisUseContexts -n" ] @@ -88,11 +93,13 @@ "maennchen/zipstream-php": "^2.1 || ^3.0", "markbaker/complex": "^3.0", "markbaker/matrix": "^3.0", + "phpoffice/wmf": "^0.2.1", "psr/simple-cache": "^1.0 || ^2.0 || ^3.0" }, "require-dev": { "ext-intl": "*", "ext-openssl": "*", + "cyclonedx/cyclonedx-php-composer": "^6.2", "dealerdirect/phpcodesniffer-composer-installer": "dev-main", "dompdf/dompdf": "^2.0 || ^3.0", "friendsofphp/php-cs-fixer": "^3.2", diff --git a/vendor/phpoffice/phpspreadsheet/sbom.xml b/vendor/phpoffice/phpspreadsheet/sbom.xml new file mode 100644 index 00000000..dfc0acc0 --- /dev/null +++ b/vendor/phpoffice/phpspreadsheet/sbom.xml @@ -0,0 +1,336 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/BinaryComparison.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/BinaryComparison.php index 38c298f2..493326e5 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/BinaryComparison.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/BinaryComparison.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; +use Composer\Pcre\Preg; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; @@ -60,6 +61,15 @@ public static function compare(mixed $operand1, mixed $operand2, string $operato return $operand2; } + if (is_string($operand1) && is_string($operand2) && is_numeric($operand1) && is_numeric($operand2)) { + return self::numericStrings($operand1, $operand2, $operator); + } + $rank1 = self::typeRank($operand1); + $rank2 = self::typeRank($operand2); + if ($rank1 !== null && $rank2 !== null && $rank1 !== $rank2) { + return self::compareTypeRanks($rank1, $rank2, $operator); + } + // Use case-insensitive comparison if not OpenOffice mode if (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) { if (is_string($operand1)) { @@ -77,6 +87,39 @@ public static function compare(mixed $operand1, mixed $operand2, string $operato return self::evaluateComparison($operand1, $operand2, $operator, $useLowercaseFirstComparison); } + /** + * Excel orders values of different types by type alone: + * every number is less than every text, and every text is less than FALSE and TRUE. + * So ="">0, ="a">1E+100 and =FALSE>"zzz" are all TRUE. + * LibreOffice treats booleans as numbers, so only numbers and text are ranked there. + * Null (an empty cell) and numeric strings keep their existing handling. + */ + private static function typeRank(mixed $operand): ?int + { + if (is_bool($operand)) { + return Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE ? 0 : 2; + } + if (is_int($operand) || is_float($operand)) { + return 0; + } + if (is_string($operand) && !is_numeric($operand)) { + return 1; + } + + return null; + } + + private static function compareTypeRanks(int $rank1, int $rank2, string $operator): bool + { + return match ($operator) { + '=' => false, + '<>' => true, + '>', '>=' => $rank1 > $rank2, + '<', '<=' => $rank1 < $rank2, + default => throw new Exception('Unsupported binary comparison operator'), + }; + } + private static function evaluateComparison(mixed $operand1, mixed $operand2, string $operator, bool $useLowercaseFirstComparison): bool { return match ($operator) { @@ -147,4 +190,57 @@ private static function notEqual(mixed $operand1, mixed $operand2): bool { return self::equal($operand1, $operand2) !== true; } + + private const EQUAL_COMPARES = ['=', '>=', '<=']; + private const LESS_COMPARES = ['<', '<=', '<>']; + private const GREATER_COMPARES = ['>', '>=', '<>']; + + private static function numericStrings(string $a, string $b, string $operator): bool + { + if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { + return self::numericStringsLibre($a, $b, $operator); + } + // special handling for numeric strings starting with - + $a = Preg::replace('/^-/', '', $a); + $b = Preg::replace('/^-/', '', $b); + $comp = strcmp($a, $b); + if ($comp === 0) { + return in_array($operator, self::EQUAL_COMPARES, true); + } + if ($comp > 0) { + return in_array($operator, self::GREATER_COMPARES, true); + } + + return in_array($operator, self::LESS_COMPARES, true); + } + + private static function numericStringsLibre(string $a2, string $b2, string $operator): bool + { + if (str_starts_with($a2, '+')) { + if (str_starts_with($b2, '+')) { + $comp = strcmp($a2, $b2); + } elseif (str_starts_with($b2, '-')) { + $comp = 1; // "+number1" is always > "-$number2" + } else { + $comp = -1; // "+number1" is always < "$number2" unsigned + } + } elseif (str_starts_with($b2, '+')) { + // $a2 can't start with + here + if (str_starts_with($a2, '-')) { + $comp = -1; // "-$number1" is always < "+$number2" + } else { + $comp = 1; // unsigned "$number1" is always > "+$number2" + } + } else { + $comp = strcmp($a2, $b2); + } + if ($comp === 0) { + return in_array($operator, self::EQUAL_COMPARES, true); + } + if ($comp > 0) { + return in_array($operator, self::GREATER_COMPARES, true); + } + + return in_array($operator, self::LESS_COMPARES, true); + } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php index faaf4407..ef292f92 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php @@ -554,7 +554,7 @@ public function calculateCellValue(?Cell $cell = null, bool $resetLog = true): m $value ); } - $result = self::unwrapResult($this->_calculateFormulaValue($value, $cell->getCoordinate(), $cell)); //* @phpstan-ignore argument.type ($value can be mixed not string) + $result = self::unwrapResult($this->calculateFormulaValue($value, $cell->getCoordinate(), $cell)); //* @phpstan-ignore argument.type ($value can be mixed not string) if ($this->spreadsheet === null) { throw new Exception('null spreadsheet in calculateCellValue'); } @@ -677,7 +677,7 @@ public function calculateFormula(string $formula, ?string $cellID = null, ?Cell // Execute the calculation try { - $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell)); + $result = self::unwrapResult($this->calculateFormulaValue($formula, $cellID, $cell)); } catch (\Exception $e) { throw new Exception($e->getMessage()); } @@ -720,9 +720,9 @@ public function saveValueToCache(string $cellReference, mixed $cellValue): void * @param string $formula The formula to parse and calculate * @param ?string $cellID The ID (e.g. A3) of the cell that we are calculating * @param ?Cell $cell Cell to calculate - * @param bool $ignoreQuotePrefix If set to true, evaluate the formyla even if the referenced cell is quote prefixed + * @param bool $ignoreQuotePrefix If set to true, evaluate the formula even if the referenced cell is quote prefixed */ - public function _calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed + public function calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed { $cellValue = null; @@ -792,6 +792,14 @@ public function _calculateFormulaValue(string $formula, ?string $cellID = null, return $cellValue; } + /** + * @deprecated 5.11.0 use calculateFormulaValue + */ + public function _calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed // phpcs:ignore + { + return $this->calculateFormulaValue($formula, $cellID, $cell, $ignoreQuotePrefix); + } + /** * Ensure that paired matrix operands are both matrices and of the same size. * @@ -1412,7 +1420,7 @@ private function internalParseFormula(string $formula, ?Cell $cell = null): bool $ax = preg_match('/^\s*\)/u', substr($formula, $index + $length)); if ($ax) { $stack->push('Operand Count for Function ' . $valToUpper . ')', 0); - $expectingOperator = true; + $expectingOperator = true; //* @phpstan-ignore assign.redundant (code clarity) } else { $stack->push('Operand Count for Function ' . $valToUpper . ')', 1); $expectingOperator = false; @@ -1475,7 +1483,7 @@ private function internalParseFormula(string $formula, ?Cell $cell = null): bool $outputItem = $stack->getStackItem(Operands\StructuredReference::NAME, $structuredReference, null); $output[] = $outputItem; - $expectingOperator = true; + $expectingOperator = true; //* @phpstan-ignore assign.redundant (code clarity) } else { // it's a variable, constant, string, number or boolean $localeConstant = false; @@ -1515,7 +1523,7 @@ private function internalParseFormula(string $formula, ?Cell $cell = null): bool } else { /** @var non-empty-string $startRowColRef */ $startRowColRef = $output[count($output) - 1]['value'] ?? ''; - [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true); + [$rangeWS1] = Worksheet::extractSheetTitle($startRowColRef, true); $rangeSheetRef = $rangeWS1; if ($rangeWS1 !== '') { $rangeWS1 .= '!'; @@ -1531,8 +1539,10 @@ private function internalParseFormula(string $formula, ?Cell $cell = null): bool } $refSheet = $pCellParent; + $returnRef = false; if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) { $refSheet = $pCellParent->getParentOrThrow()->getSheetByName($rangeSheetRef); + $returnRef = $refSheet === null; } if (ctype_digit($val) && $val <= AddressRange::MAX_ROW) { @@ -1547,6 +1557,9 @@ private function internalParseFormula(string $formula, ?Cell $cell = null): bool $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow() : AddressRange::MAX_ROW; // Max 1,048,576 rows for Excel2007 $val = "{$rangeWS2}{$val}{$endRowColRef}"; } + if ($returnRef) { + $val = ExcelError::REF(); + } $stackItemReference = $val; } } elseif ($opCharacter === self::FORMULA_STRING_QUOTE) { @@ -1820,7 +1833,7 @@ private function processTokenStack(false|array $tokens, ?string $cellID = null, $cellRange = $token->parse($cell); if (str_contains($cellRange, ':')) { $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell Range %s', $token->value(), $cellRange); - $rangeValue = self::getInstance($cell->getWorksheet()->getParent())->_calculateFormulaValue("={$cellRange}", $cellRange, $cell); + $rangeValue = self::getInstance($cell->getWorksheet()->getParent())->calculateFormulaValue("={$cellRange}", $cellRange, $cell); $stack->push('Value', $rangeValue); $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($rangeValue)); } else { @@ -1957,7 +1970,11 @@ private function processTokenStack(false|array $tokens, ?string $cellID = null, } $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); if ($pCellParent !== null && $this->spreadsheet !== null) { - $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($sheet1), false); + if ($operand1Data['value'] === ExcelError::REF()) { + $cellValue = ExcelError::REF(); + } else { + $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($sheet1), false); + } } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } @@ -2075,13 +2092,13 @@ private function processTokenStack(false|array $tokens, ?string $cellID = null, break; } - } elseif (($token === '~') || ($token === '%')) { // @phpstan-ignore booleanOr.alwaysFalse (phpstan says token can't be plain string), identical.alwaysFalse (ditto), identical.alwaysFalse (ditto) + } elseif (($token === '~') || ($token === '%')) { // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on if (($arg = $stack->pop()) === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); } $arg = $arg['value']; - if ($token === '~') { // @phpstan-ignore identical.alwaysFalse (phpstan says token can't be plain string) + if ($token === '~') { $this->debugLog->writeDebugLog('Evaluating Negation of %s', $this->showValue($arg)); $multiplier = -1; } else { @@ -2367,7 +2384,7 @@ private function processTokenStack(false|array $tokens, ?string $cellID = null, $branchStore[$storeKey] = self::EXCEL_CONSTANTS[$excelConstant]; } $this->debugLog->writeDebugLog('Evaluating Constant %s as %s', $excelConstant, $this->showTypeDetails(self::EXCEL_CONSTANTS[$excelConstant])); - } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) { //* @phpstan-ignore function.alreadyNarrowedType (phpstan says is_bool has argument of *NEVER*?), equal.alwaysFalse (ditto) + } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) { /** @var array{type: string, reference: ?string} $tokenData */ $stack->push($tokenData['type'], $token, $tokenData['reference']); if (isset($storeKey)) { @@ -2995,7 +3012,7 @@ private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksh $recursiveCalculator = new self($this->spreadsheet); $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog()); $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog()); - $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true); + $result = $recursiveCalculator->calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true); $cellWorksheet->getCell($originalCoordinate); if ($this->getDebugLog()->getWriteDebugLog()) { diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php index 389464c4..a26d328e 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php @@ -189,7 +189,7 @@ private static function executeQuery(array $database, string $query, array $crit } // evaluate the criteria against the row data - $result = Calculation::getInstance()->_calculateFormulaValue('=' . $conditions); + $result = Calculation::getInstance()->calculateFormulaValue('=' . $conditions); // If the row failed to meet the criteria, remove it from the database if ($result !== true) { diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php index 43a96b08..193a6bdb 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php @@ -5,7 +5,6 @@ use DateTimeInterface; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; -use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Days @@ -48,7 +47,6 @@ public static function between(array|DateTimeInterface|float|int|string $endDate $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); - $days = ExcelError::VALUE(); $diff = $PHPStartDateObject->diff($PHPEndDateObject); $days = $diff->days; if ($diff->invert) { diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/BranchPruner.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/BranchPruner.php index 97e4c951..4ba678e5 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/BranchPruner.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/BranchPruner.php @@ -80,10 +80,15 @@ private function initialiseCondition(): void { if (isset($this->pendingStoreKey, $this->conditionMap[$this->pendingStoreKey]) && $this->conditionMap[$this->pendingStoreKey]) { $this->currentCondition = $this->pendingStoreKey; - $stackDepth = count($this->storeKeysStack); - if ($stackDepth > 1) { - // nested if - $this->previousStoreKey = $this->storeKeysStack[$stackDepth - 2]; + // nested if: find the closest enclosing IF whose then/else branch we are in, + // skipping any enclosing IF where we are only part of its condition + for ($index = count($this->storeKeysStack) - 2; $index >= 0; --$index) { + $storeKey = $this->storeKeysStack[$index]; + if (!empty($this->thenMap[$storeKey]) || !empty($this->elseMap[$storeKey])) { + $this->previousStoreKey = $storeKey; + + break; + } } } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/FormattedNumber.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/FormattedNumber.php index c64c8d27..09474a64 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/FormattedNumber.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/FormattedNumber.php @@ -65,7 +65,7 @@ public static function convertToNumberIfFraction(float|string &$operand): bool $wholePart = ($match[3] === '') ? '' : ($sign . $match[3]); $fractionFormula = '=' . $wholePart . $sign . $match[4]; /** @var string */ - $operandx = Calculation::getInstance()->_calculateFormulaValue($fractionFormula); + $operandx = Calculation::getInstance()->calculateFormulaValue($fractionFormula); $operand = $operandx; return true; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php index 5004f52e..298fb91f 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php @@ -163,6 +163,10 @@ public static function ifCondition(mixed $condition): string if (is_bool($condition)) { return '=' . ($condition ? 'TRUE' : 'FALSE'); } + // A "TRUE" or "FALSE" criterion matches logical values, as the criterion TRUE or FALSE does + if ($condition === Calculation::getTRUE() || $condition === Calculation::getFALSE()) { + return '=' . ($condition === Calculation::getTRUE() ? 'TRUE' : 'FALSE'); + } if (!is_numeric($condition)) { if ($condition !== '""') { // Not an empty string // Escape any quotes in the string value diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/Value.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/Value.php index 56620852..ddcf17f0 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/Value.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/Value.php @@ -54,7 +54,7 @@ public static function isRef(mixed $value, ?Cell $cell = null): bool } try { - [$column, $row] = Coordinate::indexesFromString($cellValue ?? ''); //* @phpstan-ignore nullCoalesce.variable (Not sure whether Phpstan is correct) + Coordinate::indexesFromString($cellValue ?? ''); } catch (SpreadsheetException) { return false; } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php index 59d5875b..f7b03e7d 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php @@ -164,7 +164,7 @@ public static function ROW($cellAddress = null, ?Cell $cell = null): int|string| if (is_array($cellAddress)) { foreach ($cellAddress as $rowKey => $rowValue) { - foreach ($rowValue as $columnKey => $cellValue) { + foreach ($rowValue as $cellValue) { //* @phpstan-ignore foreach.unusedValue (Php syntax requires 'as') return (int) preg_replace('/\D/', '', $rowKey); } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php index 7ac5ec10..a83b1d94 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php @@ -89,9 +89,9 @@ public static function AVERAGEIFS(mixed ...$args): null|int|float|string * COUNTIF(range,condition) * * @param mixed $range Data values, expect array - * @param null|mixed[]|string $condition the criteria that defines which cells will be counted + * @param null|bool|float|int|mixed[]|string $condition the criteria that defines which cells will be counted */ - public static function COUNTIF(mixed $range, null|array|string $condition): string|int + public static function COUNTIF(mixed $range, null|array|bool|float|int|string $condition): string|int { if ( !is_array($range) diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php index a722fbd9..e32e4221 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php @@ -2,6 +2,10 @@ namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; +use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; +use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; + abstract class MaxMinBase { protected static function datatypeAdjustmentAllowStrings(int|float|string|bool $value): int|float @@ -14,4 +18,36 @@ protected static function datatypeAdjustmentAllowStrings(int|float|string|bool $ return $value; } + + /** + * As in Excel (and SUM), a logical value or a text representation of a number + * typed directly into the argument list counts, and any other text typed there is #VALUE!. + * References and arrays are left unchanged, so that their non-numeric values are ignored. + * + * @param mixed[] $args + * + * @return mixed[] + */ + protected static function datatypeAdjustmentLiteralArguments(array $args): array + { + foreach ($args as $index => $arg) { + if (!is_array($arg) && !Functions::isCellValue($index)) { + $args[$index] = self::datatypeAdjustmentLiteral($arg); + } + } + + return $args; + } + + private static function datatypeAdjustmentLiteral(mixed $value): mixed + { + if (is_bool($value)) { + return (int) $value; + } + if (is_string($value) && !ErrorValue::isError($value, true)) { + return is_numeric($value) ? 0 + $value : ExcelError::VALUE(); + } + + return $value; + } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Maximum.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Maximum.php index 3a4f9ebb..b684f53d 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Maximum.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Maximum.php @@ -23,7 +23,7 @@ public static function max(mixed ...$args): float|int|string $returnValue = null; // Loop through arguments - $aArgs = Functions::flattenArray($args); + $aArgs = Functions::flattenArray(self::datatypeAdjustmentLiteralArguments($args)); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg, true)) { $returnValue = $arg; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php index 0a1a0c00..07a77ba5 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php @@ -23,7 +23,7 @@ public static function min(mixed ...$args): float|int|string $returnValue = null; // Loop through arguments - $aArgs = Functions::flattenArray($args); + $aArgs = Functions::flattenArray(self::datatypeAdjustmentLiteralArguments($args)); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg, true)) { $returnValue = $arg; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php index 6a05fa01..d96a96a2 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php @@ -96,7 +96,8 @@ public static function right(mixed $value, mixed $chars = 1): array|string return $e->getMessage(); } - return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8'); + // When more characters are requested than the text contains, return all of the text + return mb_substr($value, max(0, mb_strlen($value, 'UTF-8') - $chars), $chars, 'UTF-8'); } /** diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php index c6e37f40..7b38b9ac 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php @@ -202,6 +202,11 @@ public static function VALUE(mixed $value = '') return (float) $numberValue; } + // Reject text that is not a date/time before DateValue's permissive parser. + if (!self::isDateTimeString($value)) { + return ExcelError::VALUE(); + } + $dateSetting = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); @@ -216,19 +221,41 @@ public static function VALUE(mixed $value = '') } /** @var DateTimeInterface|float|int|string */ $dateValue = Functions::scalar(DateTimeExcel\DateValue::fromString($value)); - if ($dateValue !== ExcelError::VALUE()) { - Functions::setReturnDateType($dateSetting); - - return $dateValue; - } Functions::setReturnDateType($dateSetting); - return ExcelError::VALUE(); + return $dateValue; } return (float) $value; } + /** + * True when $value only contains date/time tokens (digits, separators, English month/weekday, am/pm). + * Product descriptions such as "5V 2.1A - EU Wall Adaptor" leave leftover letters and are rejected. + */ + private static function isDateTimeString(string $value): bool + { + $text = strtolower(trim($value, "\" \t\n\r\0\x0B")); + if ($text === '' || strpbrk($text, '0123456789') === false) { + return false; + } + + // Full month names, then full day names, then leftover abbreviations (longer first). + $text = str_replace([ + 'january', 'february', 'march', 'april', 'may', 'june', + 'july', 'august', 'september', 'october', 'november', 'december', + 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', + 'jan', 'feb', 'mar', 'apr', 'jun', 'jul', 'aug', 'sept', 'sep', + 'oct', 'nov', 'dec', + 'sun', 'mon', 'tues', 'tue', 'wed', 'thurs', 'thur', 'thu', 'fri', 'sat', + 'utc', 'gmt', 'am', 'pm', + ], '', $text); + + $text = Preg::replace('/\d(?:st|nd|rd|th)?|[\/.,:+\-tz\s]/', '', $text); + + return $text === ''; + } + /** * VALUETOTEXT. * diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php index dd9b5331..c9ee2aa1 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php @@ -366,16 +366,20 @@ public function setValueExplicit(mixed $value, string $dataType = DataType::TYPE $this->updateInCollection(); $cellCoordinate = $this->getCoordinate(); - self::updateIfCellIsTableHeader($this->getParent()?->getParent(), $this, $oldValue, $value); - $worksheet = $this->getWorksheet(); + $cellCollection = $this->getParent(); + self::updateIfCellIsTableHeader($cellCollection?->getParent(), $this, $oldValue, $value); + // Updating structured references may access other cells, which detaches this one + // from the collection, so retrieve it again to ensure that it is still attached. + $cell = $cellCollection?->get($cellCoordinate) ?? $this; + $worksheet = $cell->getWorksheet(); $spreadsheet = $worksheet->getParent(); if (isset($spreadsheet) && $spreadsheet->getIndex($worksheet, true) >= 0) { // Avoid Worksheet::getStyle() (selection + validation) unless quotePrefix must change. - $oldQuotePrefix = $spreadsheet->getCellXfByIndex($this->getXfIndex())->getQuotePrefix(); + $oldQuotePrefix = $spreadsheet->getCellXfByIndex($cell->getXfIndex())->getQuotePrefix(); if ($oldQuotePrefix !== $quotePrefix) { $originalSelected = $worksheet->getSelectedCells(); $activeSheetIndex = $spreadsheet->getActiveSheetIndex(); - $this->getStyle()->setQuotePrefix($quotePrefix); + $cell->getStyle()->setQuotePrefix($quotePrefix); $worksheet->setSelectedCells($originalSelected); if ($activeSheetIndex >= 0) { $spreadsheet->setActiveSheetIndex($activeSheetIndex); @@ -383,7 +387,7 @@ public function setValueExplicit(mixed $value, string $dataType = DataType::TYPE } } - return $this->getParent()?->get($cellCoordinate) ?? $this; + return $cellCollection?->get($cellCoordinate) ?? $cell; } public const CALCULATE_DATE_TIME_ASIS = 0; @@ -506,7 +510,7 @@ public function getCalculatedValue(bool $resetLog = true): mixed foreach ($result as $resultRow) { if (is_array($resultRow)) { $newColumn = $column; - foreach ($resultRow as $resultValue) { + foreach ($resultRow as $resultValue) { //* @phpstan-ignore foreach.valueOverwritten (Php syntax demands 'as') if ($row !== $newRow || $column !== $newColumn) { $maxCoordinate = $newColumn . $newRow; if ($thisworksheet->getCell($newColumn . $newRow)->getValue() !== null) { @@ -517,7 +521,6 @@ public function getCalculatedValue(bool $resetLog = true): mixed } } } - /** @var string $newColumn */ StringHelper::stringIncrement($newColumn); } ++$newRow; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php index 02e1d9eb..bf70e80b 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php @@ -646,8 +646,8 @@ private static function getReferencesForCellBlock(string $cellBlock): array // Range... [$rangeStart, $rangeEnd] = $range; - [$startColumnIndex, $startRow, $startColumn] = self::indexesFromString($rangeStart); - [$endColumnIndex, $endRow, $endColumn] = self::indexesFromString($rangeEnd); + [$startColumnIndex, $startRow] = self::indexesFromString($rangeStart); + [$endColumnIndex, $endRow] = self::indexesFromString($rangeEnd); ++$endColumnIndex; // Current data diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidator.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidator.php index 5a4c7744..c6762150 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidator.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidator.php @@ -30,7 +30,7 @@ public function isValid(Cell $cell): bool return false; } - $returnValue = false; + $returnValue = null; $type = $dataValidation->getType(); if ($type === DataValidation::TYPE_LIST) { $returnValue = $this->isValueInList($cell); @@ -50,7 +50,7 @@ public function isValid(Cell $cell): bool $returnValue = $this->numericOperator($dataValidation, mb_strlen($cell->getValueString()), $cell); } - return $returnValue; + return $returnValue ?? false; } private const TWO_FORMULAS = [DataValidation::OPERATOR_BETWEEN, DataValidation::OPERATOR_NOTBETWEEN]; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/BoxWhisker.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/BoxWhisker.php new file mode 100644 index 00000000..ff68dc4e --- /dev/null +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/BoxWhisker.php @@ -0,0 +1,133 @@ +series = $series; + } + + public function getChartType(): string + { + return self::TYPE; + } + + /** + * @return BoxWhiskerSeries[] + */ + public function getSeries(): array + { + return $this->series; + } + + public function setShowMeanLine(bool $showMeanLine): static + { + $this->showMeanLine = $showMeanLine; + + return $this; + } + + public function getShowMeanLine(): bool + { + return $this->showMeanLine; + } + + public function setShowMeanMarker(bool $showMeanMarker): static + { + $this->showMeanMarker = $showMeanMarker; + + return $this; + } + + public function getShowMeanMarker(): bool + { + return $this->showMeanMarker; + } + + public function setShowInnerPoints(bool $showInnerPoints): static + { + $this->showInnerPoints = $showInnerPoints; + + return $this; + } + + public function getShowInnerPoints(): bool + { + return $this->showInnerPoints; + } + + public function setShowOutliers(bool $showOutliers): static + { + $this->showOutliers = $showOutliers; + + return $this; + } + + public function getShowOutliers(): bool + { + return $this->showOutliers; + } + + public function setQuartileMethod(string $quartileMethod): static + { + if ( + !in_array($quartileMethod, [ + self::QUARTILE_METHOD_EXCLUSIVE, + self::QUARTILE_METHOD_INCLUSIVE, + ], true) + ) { + throw new Exception('Invalid quartile method.'); + } + + $this->quartileMethod = $quartileMethod; + + return $this; + } + + public function getQuartileMethod(): string + { + return $this->quartileMethod; + } + + public function refresh(Worksheet $worksheet): void + { + foreach ($this->series as $series) { + $series->refresh($worksheet); + } + } +} diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/BoxWhiskerSeries.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/BoxWhiskerSeries.php new file mode 100644 index 00000000..8d2dc40f --- /dev/null +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/BoxWhiskerSeries.php @@ -0,0 +1,46 @@ +categories = $categories; + $this->values = $values; + $this->label = $label; + } + + public function getCategories(): DataSeriesValues + { + return $this->categories; + } + + public function getValues(): DataSeriesValues + { + return $this->values; + } + + public function getLabel(): ?DataSeriesValues + { + return $this->label; + } + + public function refresh(Worksheet $worksheet): void + { + $this->categories->refresh($worksheet); + $this->values->refresh($worksheet); + + if ($this->label !== null) { + $this->label->refresh($worksheet); + } + } +} diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php index 6288ea1d..e0aefa94 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php @@ -12,6 +12,11 @@ class Chart */ private string $name; + /** + * Alternative text, the description of the chart's frame. + */ + private string $description = ''; + /** * Worksheet. */ @@ -37,6 +42,11 @@ class Chart */ private ?Title $yAxisLabel; + /** + * Chart Ex Area. + */ + private ?ChartEx $chartEx = null; + /** * Chart Plot Area. */ @@ -201,6 +211,18 @@ public function setName(string $name): self return $this; } + public function getDescription(): string + { + return $this->description; + } + + public function setDescription(string $description): self + { + $this->description = $description; + + return $this; + } + /** * Get Worksheet. */ @@ -304,11 +326,34 @@ public function getPlotAreaOrThrow(): PlotArea throw new Exception('Chart has no PlotArea'); } + public function getChartEx(): ?ChartEx + { + return $this->chartEx; + } + + /** + * Set ChartEx. + */ + public function setChartEx(ChartEx $chartEx): static + { + if ($this->plotArea !== null) { + throw new Exception('A chart cannot contain both a PlotArea and ChartEx data.'); + } + + $this->chartEx = $chartEx; + + return $this; + } + /** * Set Plot Area. */ public function setPlotArea(PlotArea $plotArea): self { + if ($this->chartEx !== null) { + throw new Exception('A chart cannot contain both ChartEx and a PlotArea.'); + } + $this->plotArea = $plotArea; return $this; @@ -615,8 +660,12 @@ public function getBottomRightYOffset(): int public function refresh(): void { - if ($this->worksheet !== null && $this->plotArea !== null) { - $this->plotArea->refresh($this->worksheet); + if ($this->worksheet !== null) { + if ($this->plotArea !== null) { + $this->plotArea->refresh($this->worksheet); + } elseif ($this->chartEx !== null) { + $this->chartEx->refresh($this->worksheet); + } } } @@ -842,6 +891,7 @@ public function __clone() $this->yAxis = clone $this->yAxis; $this->borderLines = clone $this->borderLines; $this->fillColor = clone $this->fillColor; + $this->chartEx = $this->chartEx === null ? null : clone $this->chartEx; } /** @return array{ diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/ChartEx.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/ChartEx.php new file mode 100644 index 00000000..a192e617 --- /dev/null +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/ChartEx.php @@ -0,0 +1,18 @@ +dataSource !== null) { $calcEngine = Calculation::getInstance($worksheet->getParent()); $newDataValues = Calculation::unwrapResult( - $calcEngine->_calculateFormulaValue( + $calcEngine->calculateFormulaValue( '=' . $this->dataSource, null, $worksheet->getCell('A1') diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php index 2e18270c..599cdb9f 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php @@ -319,7 +319,7 @@ public function hasBackgroundImage(): bool return false; } - return getimagesize($path) !== false; + return $this->backgroundImage->isMetafile() || getimagesize($path) !== false; } /** @@ -335,8 +335,8 @@ public function getBackgroundImage(): Drawing */ public function setBackgroundImage(Drawing $objDrawing): self { - if (!array_key_exists($objDrawing->getType(), Drawing::IMAGE_TYPES_CONVERTION_MAP)) { - throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); + if (!$objDrawing->isSupportedForSave()) { + throw new PhpSpreadsheetException(Drawing::UNSUPPORTED_IMAGE_TYPE_MESSAGE); } $this->backgroundImage = $objDrawing; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php index 6cad8a9f..abee8d17 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php @@ -68,6 +68,11 @@ class Properties */ private string $category = ''; + /** + * Language, as a BCP 47 tag such as "en-US". + */ + private string $language = ''; + /** * Manager. */ @@ -278,6 +283,23 @@ public function setKeywords(string $keywords): self return $this; } + public function getLanguage(): string + { + return $this->language; + } + + /** + * Set Language, as a BCP 47 tag such as "en-US". + * + * @return $this + */ + public function setLanguage(string $language): self + { + $this->language = $language; + + return $this; + } + /** * Get Category. */ diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Downloader.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Downloader.php index 7aa1494f..63cdb278 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Downloader.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Downloader.php @@ -5,6 +5,7 @@ use DateTimeImmutable; use DateTimeZone; use PhpOffice\PhpSpreadsheet\Exception; +use PhpOffice\PhpSpreadsheet\Writer; /** * Assist downloading files when samples are run in browser. @@ -20,6 +21,10 @@ class Downloader protected string $filetype; + protected ?Writer\IWriter $writer; + + protected bool $oldIE; + protected const CONTENT_TYPES = [ 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xls' => 'application/vnd.ms-excel', @@ -29,28 +34,53 @@ class Downloader 'pdf' => 'application/pdf', ]; - public function __construct(string $folder, string $filename, ?string $filetype = null) + public function __construct(string|Writer\IWriter $folder, string $filename, ?string $filetype = null, bool $oldIE = false) { - clearstatcache(); - $filepath = realpath("{$folder}/{$filename}"); - if ($filepath === false || !is_file($filepath) || !is_readable($filepath)) { - throw new Exception('File not found, or cannot be read'); + if (is_string($folder)) { + $this->writer = null; + clearstatcache(); + $filepath = realpath("{$folder}/{$filename}"); + if ($filepath === false || !is_file($filepath) || !is_readable($filepath)) { + throw new Exception('File not found, or cannot be read'); + } + $this->filepath = $filepath; + $this->filename = basename($this->filepath); + } else { + $this->writer = $folder; + $filetype = match (true) { + // Pdf must come before html; order is otherwise unimportant + $folder instanceof Writer\Pdf => 'pdf', + $folder instanceof Writer\Csv => 'csv', + $folder instanceof Writer\Html => 'html', + $folder instanceof Writer\Ods => 'ods', + $folder instanceof Writer\Xls => 'xls', + $folder instanceof Writer\Xlsx => 'xlsx', + default => '', + }; + $this->filepath = $this->filename = $filename; } - $this->filepath = $filepath; - $this->filename = basename($this->filepath); $filetype ??= pathinfo($this->filename, PATHINFO_EXTENSION); if (!array_key_exists(strtolower($filetype), self::CONTENT_TYPES)) { throw new Exception('Invalid filetype: file cannot be downloaded'); } $this->filetype = strtolower($filetype); + $dotfiletype = '.' . $this->filetype; + if (!str_ends_with($this->filename, $dotfiletype)) { + $this->filename .= $dotfiletype; + } + $this->oldIE = $oldIE; } public function download(): void { $this->headers(); - readfile($this->filepath); + if ($this->writer === null) { + readfile($this->filepath); + } else { + $this->writer->save('php://output'); + } } public function headers(): void @@ -74,6 +104,7 @@ public function headers(): void protected function contentType(): void { header('Content-Type: ' . self::CONTENT_TYPES[$this->filetype]); + header('X-Content-Type-Options: nosniff'); } protected function contentDisposition(): void @@ -83,20 +114,24 @@ protected function contentDisposition(): void protected function cacheHeaders(): void { - header('Cache-Control: max-age=0'); - // If you're serving to IE 9, then the following may be needed - header('Cache-Control: max-age=1'); + $maxAge = 0; + if ($this->oldIE) { + // If you're serving to IE 9, then the following may be needed + $maxAge = 1; - // If you're serving to IE over SSL, then the following may be needed - header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past + // If you're serving to IE over SSL, then the following may be needed + header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past + } $dt = new DateTimeImmutable(timezone: new DateTimeZone('UTC')); header('Last-Modified: ' . $dt->format('D, d M Y H:i:s') . ' GMT'); // always modified - header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 + header("Cache-Control: cache, must-revalidate, max-age=$maxAge"); // HTTP/1.1 header('Pragma: public'); // HTTP/1.0 } protected function fileSize(): void { - header('Content-Length: ' . filesize($this->filepath)); + if ($this->writer === null) { + header('Content-Length: ' . filesize($this->filepath)); + } } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php index 7def6861..40207d05 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php @@ -7,6 +7,8 @@ use DOMElement; use DOMNode; use DOMText; +use PhpOffice\PhpSpreadsheet\Reader\Csv; +use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Font; @@ -581,6 +583,8 @@ public function __construct() 's' => $this->startStrikethruTag(...), 'sup' => $this->startSuperscriptTag(...), 'sub' => $this->startSubscriptTag(...), + 'ul' => $this->ulOlTag(...), + 'ol' => $this->ulOlTag(...), ]; } if (!isset($this->endTagCallbacks)) { @@ -624,13 +628,18 @@ private function initialise(): void public function toRichTextObject(string $html, bool $preserveWhiteSpace = false): RichText { $this->initialise(); + $scanner = new XmlScanner(XmlScanner::HTML_PATTERN); + $html = $scanner->scan($html); // Create a new DOM object $dom = new DOMDocument(); + + // Start with UTF-8 BOM so that loadHTML below will use correct charset + $loadString = Csv::UTF8_BOM . $html; + // Load the HTML file into the DOM object // Note the use of error suppression, because typically this will be an html fragment, so not fully valid markup - $prefix = ''; - @$dom->loadHTML($prefix . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); + @$dom->loadHTML($loadString, LIBXML_HTML_NODEFDTD); // Discard excess white space $dom->preserveWhiteSpace = false; @@ -806,6 +815,13 @@ protected function endStrikethruTag(): void $this->strikethrough = false; } + protected function ulOlTag(): void + { + if (substr($this->stringData, -1) !== "\n") { + $this->breakTag(); + } + } + public function breakTag(): void { $this->stringData .= "\n"; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php index 8cdfe41c..1d2df213 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php @@ -146,6 +146,20 @@ public function addDownloadLink(string $path): void } } + /** + * Add end tags to page. The page will render correctly + * without them, so this is optional, but the page will + * not validate unless it is called. + */ + public function endWebPage(): void + { + if ($this->isCli() === false) { + // @codeCoverageIgnoreStart + echo ''; + // @codeCoverageIgnoreEnd + } + } + protected function isDirOrMkdir(string $folder): bool { return \is_dir($folder) || \mkdir($folder); diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php index da18657d..60c4d9a6 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php @@ -83,9 +83,31 @@ abstract class BaseReader implements IReader2 /** @var null|callable(string):bool function to return whether image path is okay */ protected $isWhitelisted; + protected int $maxLength; + + private const LENGTH_MULTIPLIER = [ + 'G' => 1024 * 1024 * 1024, + 'M' => 1024 * 1024, + 'K' => 1024, + ]; + public function __construct() { $this->readFilter = new DefaultReadFilter(); + $limit = ini_get('memory_limit') ?: '128M'; + $limit = trim(str_replace('-1', '128M', $limit)); + $unit = strtoupper(substr($limit, -1)); + $limit = (int) $limit; + $multiplier = self::LENGTH_MULTIPLIER[$unit] ?? 1; + $limit *= $multiplier; + $this->maxLength = intdiv($limit, 4); + } + + public function setMaxLength(int $maxLength): self + { + $this->maxLength = $maxLength; + + return $this; } public function getReadDataOnly(): bool diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php index 67cbba99..d4616803 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Reader; +use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\DefinedName; @@ -70,14 +71,6 @@ class Gnumeric extends BaseReader ], ]; - protected int $maxLength; - - private const LENGTH_MULTIPLIER = [ - 'G' => 1024 * 1024 * 1024, - 'M' => 1024 * 1024, - 'K' => 1024, - ]; - /** * Create a new Gnumeric. */ @@ -86,20 +79,6 @@ public function __construct() parent::__construct(); $this->referenceHelper = ReferenceHelper::getInstance(); $this->securityScanner = XmlScanner::getInstance($this); - $limit = ini_get('memory_limit') ?: '128M'; - $limit = trim(str_replace('-1', '128M', $limit)); - $unit = strtoupper(substr($limit, -1)); - $limit = (int) $limit; - $multiplier = self::LENGTH_MULTIPLIER[$unit] ?? 1; - $limit *= $multiplier; - $this->maxLength = intdiv($limit, 4); - } - - public function setMaxLength(int $maxLength): self - { - $this->maxLength = $maxLength; - - return $this; } /** @@ -178,7 +157,7 @@ public function listWorksheetInfo(string $filename): array if (self::matchXml($xml, 'Sheet')) { $tmpInfo = [ 'worksheetName' => '', - 'lastColumnLetter' => 'A', + 'lastColumnLetter' => 'A', //* @phpstan-ignore array.offsetOverwritten (preserve array order) 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, @@ -249,7 +228,7 @@ public static function gnumericMappings(): array private function processComments(SimpleXMLElement $sheet): void { if ((!$this->readDataOnly) && (isset($sheet->Objects))) { - foreach ($sheet->Objects->children(self::NAMESPACE_GNM) as $key => $comment) { + foreach ($sheet->Objects->children(self::NAMESPACE_GNM) as $comment) { $commentAttributes = $comment->attributes(); // Only comment objects are handled at the moment if ($commentAttributes && $commentAttributes->Text) { @@ -514,11 +493,13 @@ private function processRowLoop(int $whichRow, int $maxRow, ?SimpleXMLElement $r $rowHeight = (float) $rowAttributes['Unit']; $hidden = (isset($rowAttributes['Hidden'])) && ((string) $rowAttributes['Hidden'] == '1'); $rowCount = (int) ($rowAttributes['Count'] ?? 1); - while ($whichRow < $row) { + $limit = min($row, AddressRange::MAX_ROW); + while ($whichRow < $limit) { ++$whichRow; $this->setRowHeight($whichRow, $defaultHeight); } - while (($whichRow < ($row + $rowCount)) && ($whichRow < $maxRow)) { + $limit = min($maxRow, AddressRange::MAX_ROW); + while (($whichRow < ($row + $rowCount)) && ($whichRow < $limit)) { ++$whichRow; $this->setRowHeight($whichRow, $rowHeight); if ($hidden) { @@ -617,7 +598,7 @@ private function loadCell( $worksheetName ); } - $type = DataType::TYPE_FORMULA; + $type = DataType::TYPE_FORMULA; //* @phpstan-ignore assign.redundant (code clarity) } elseif ($isArrayFormula === false) { $vtype = (string) $ValueType; if (array_key_exists($vtype, self::MAPPINGS['dataType'])) { diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php index 5135ba7f..9124d8c4 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php @@ -448,6 +448,12 @@ private function processDomElementTitle(Worksheet $sheet, int &$row, string &$co /** @param string[] $attributeArray */ private function processDomElementSpanEtc(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void { + if ((string) $child->nodeName === 'span') { + $parent = $child->parentNode; + if ($parent instanceof DOMElement && $parent->childElementCount === 1 && ($parent->nodeName === 'td' || $parent->nodeName === 'th')) { + $this->applyInlineStyle($sheet, $row, $column, $attributeArray); + } + } if (in_array((string) $child->nodeName, self::SPAN_ETC, true)) { if (isset($attributeArray['class']) && $attributeArray['class'] === 'comment') { $sheet->getComment($column . $row) @@ -900,6 +906,10 @@ private static function loadProperties(DOMDocument $dom, Spreadsheet $spreadshee if (!empty($dom->baseURI)) { $properties->setHyperlinkBase($dom->baseURI); } + $language = trim((string) $dom->documentElement?->getAttribute('lang')); + if ($language !== '') { + $properties->setLanguage($language); + } } /** @param string[] $matches */ @@ -1051,7 +1061,7 @@ private function applyInlineStyle(Worksheet &$sheet, int $row, string $column, a $value = explode(':', $st); $styleName = trim($value[0]); $styleValue = isset($value[1]) ? trim($value[1]) : null; - $styleValueString = (string) $styleValue; + $styleValueString = self::cssUnescape((string) $styleValue); if (!$styleName) { continue; @@ -1138,7 +1148,8 @@ private function applyInlineStyle(Worksheet &$sheet, int $row, string $column, a break; case 'font-family': - $cellStyle->getFont()->setName(str_replace('\'', '', $styleValueString)); + $cellStyle->getFont() + ->setName(trim($styleValueString, "'")); break; @@ -1204,6 +1215,17 @@ private function applyInlineStyle(Worksheet &$sheet, int $row, string $column, a } } + /** @param string[] $matches */ + private static function replaceCssEscaped(array $matches): string + { + return mb_chr((int) hexdec($matches[1])); + } + + private static function cssUnescape(string $convert): string + { + return preg_replace_callback('/\\\([0-9a-fA-F]+) ?/', self::replaceCssEscaped(...), $convert) ?? 'unparseable'; + } + /** * Check if has #, so we can get clean hex. */ @@ -1247,6 +1269,8 @@ private function insertImage(Worksheet $sheet, string $column, int $row, array $ if ($name) { $drawing->setName($name); } + // An empty alt is how HTML marks a decorative image + $drawing->setDecorative(($attributes['alt'] ?? null) === ''); /** @var null|scalar $width */ /** @var null|scalar $height */ diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php index bb4b7b1e..00624eb6 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php @@ -33,6 +33,7 @@ use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use SimpleXMLElement; use Throwable; use XMLReader; use ZipArchive; @@ -41,10 +42,26 @@ class Ods extends BaseReader { const INITIAL_FILE = 'content.xml'; + private const MAX_INTEGER_DIGITS = 100; + + private const DRAW_NS = 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'; + + private const LOEXT_NS = 'urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0'; + private ZipArchive $zip; private string $filename; + /** + * Resource budget for spaces generated by text:s in one cell or annotation. + * ODF does not impose this limit. It bounds expansion across runs, nested + * spans, and paragraphs. Literal text and line breaks do not consume it. + */ + private int $remainingSpaceCount = DataType::MAX_STRING_LENGTH; + + /** Characters remaining in one cell or annotation, including paragraph separators. */ + private int $remainingTextCount = DataType::MAX_STRING_LENGTH; + /** * Create a new Ods Reader instance. */ @@ -70,15 +87,8 @@ public function canRead(string $filename): bool $stat = $zip->statName('mimetype'); if (!empty($stat) && ($stat['size'] <= 255)) { $mimeType = $zip->getFromName($stat['name']); - } elseif ($zip->statName('META-INF/manifest.xml')) { - $xml = simplexml_load_string( - $this->getSecurityScannerOrThrow() - ->scan( - $zip->getFromName( - 'META-INF/manifest.xml' - ) - ) - ); + } else { + $xml = $this->loadZipSimple($zip, 'META-INF/manifest.xml'); if ($xml !== false) { $namespacesContent = $xml->getNamespaces(true); if (isset($namespacesContent['manifest'])) { @@ -114,12 +124,10 @@ public function listWorksheetNames(string $filename): array $worksheetNames = []; $xml = new XMLReader(); - $xml->xml( - $this->getSecurityScannerOrThrow() - ->scanFile( - 'zip://' . realpath($filename) . '#' . self::INITIAL_FILE - ) - ); + $zip = new ZipArchive(); + $zip->open($filename); + $this->loadZipXml($xml, $zip, self::INITIAL_FILE); + $zip->close(); $xml->setParserProperty(2, true); // Step into the first level of content of the XML @@ -171,12 +179,10 @@ public function listWorksheetInfo(string $filename): array $worksheetInfo = []; $xml = new XMLReader(); - $xml->xml( - $this->getSecurityScannerOrThrow() - ->scanFile( - 'zip://' . realpath($filename) . '#' . self::INITIAL_FILE - ) - ); + $zip = new ZipArchive(); + $zip->open($filename); + $this->loadZipXml($xml, $zip, self::INITIAL_FILE); + $zip->close(); $xml->setParserProperty(2, true); // Step into the first level of content of the XML @@ -194,14 +200,12 @@ public function listWorksheetInfo(string $filename): array $visibility = $xml->getAttribute('table:display'); $tableVisibility[$lastTableStyle] = ($visibility === 'false') ? Worksheet::SHEETSTATE_HIDDEN : Worksheet::SHEETSTATE_VISIBLE; } elseif ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { - $worksheetNames[] = $xml->getAttribute('table:name'); - $styleName = $xml->getAttribute('table:style-name') ?? ''; $visibility = $tableVisibility[$styleName] ?? ''; $tmpInfo = [ 'worksheetName' => (string) $xml->getAttribute('table:name'), - 'lastColumnLetter' => 'A', - 'lastColumnIndex' => 0, + 'lastColumnLetter' => 'A', //* @phpstan-ignore array.offsetOverwritten (preserve array order) + 'lastColumnIndex' => 0, //* @phpstan-ignore array.offsetOverwritten (preserve array order) 'totalRows' => 0, 'totalColumns' => 0, 'sheetState' => $visibility, @@ -318,8 +322,17 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet /** @var string[] */ private array $numberFormats; + /** @var array The graphic styles that make a frame decorative */ + private array $decorativeStyles = []; + private int $highestDataIndex; + /** @var array links LibreOffice keeps in a cell style, by style name */ + private array $styleHyperlinks = []; + + /** @var array default cell style of a column of the current sheet, only where it has a link */ + private array $columnHyperlinkStyles = []; + /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. */ @@ -327,18 +340,28 @@ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Sp { File::assertFile($filename, self::INITIAL_FILE); - $this->zip = $zip = new ZipArchive(); + $this->zip = new ZipArchive(); $this->filename = $filename; - $zip->open($filename); + + try { + $this->zip->open($filename); + + return $this->load2($spreadsheet); + } finally { + $this->zip->close(); + unset($this->zip); + } + } + + protected function load2(Spreadsheet $spreadsheet): Spreadsheet + { + $zip = $this->zip; // Meta - $xml = @simplexml_load_string( - $this->getSecurityScannerOrThrow() - ->scan($zip->getFromName('meta.xml')) - ); + $xml = @$this->loadZipSimple($zip, 'meta.xml'); if ($xml === false) { - throw new Exception("Unable to read data from {$filename}"); + throw new Exception("Unable to read data from {$this->filename}"); } /** @var array{meta?: string, office?: string, dc?: string} */ @@ -358,6 +381,15 @@ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Sp $textNs = (string) $dom->lookupNamespaceUri('text'); $xlinkNs = (string) $dom->lookupNamespaceUri('xlink'); + // LibreOffice keeps the language of a spreadsheet there, not in dc:language; read even with readDataOnly + foreach ($dom->getElementsByTagNameNS($styleNs, 'default-style') as $defaultStyle) { + if ($spreadsheet->getProperties()->getLanguage() === '' && $defaultStyle->getAttributeNS($styleNs, 'family') === 'table-cell') { + foreach ($defaultStyle->getElementsByTagNameNS($styleNs, 'text-properties') as $textProperty) { + $spreadsheet->getProperties()->setLanguage(self::languageTag($textProperty, $styleNs, $fontNs)); + } + } + } + $automaticStyle0 = $this->readDataOnly ? null : $dom->getElementsByTagNameNS($officeNs, 'styles')->item(0); $this->processSomeNumberFormats($automaticStyle0, $numberNs, $styleNs); $automaticStyles = ($automaticStyle0 === null) ? [] : $automaticStyle0->getElementsByTagNameNS($styleNs, 'default-style'); @@ -419,12 +451,37 @@ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Sp $pageSettings->readStyleCrossReferences($dom); + // LibreOffice writes the link of a non-text cell into its style, as + // , and loext:hyperlink next to it + $this->styleHyperlinks = []; + foreach ($dom->getElementsByTagNameNS($styleNs, 'table-cell-properties') as $cellProperties) { + foreach ($cellProperties->childNodes as $child) { + if ($child instanceof DOMElement && $child->localName === 'hyperlink' && $child->getAttributeNS($xlinkNs, 'href') !== '' && $cellProperties->parentNode instanceof DOMElement) { + $this->styleHyperlinks[$cellProperties->parentNode->getAttributeNS($styleNs, 'name')] = $child->getAttributeNS($xlinkNs, 'href'); + } + } + } + $autoFilterReader = new AutoFilter($spreadsheet, $tableNs); $definedNameReader = new DefinedNames($spreadsheet, $tableNs); $columnWidths = []; $automaticStyle0 = $this->readDataOnly ? null : $dom->getElementsByTagNameNS($officeNs, 'automatic-styles')->item(0); $this->processSomeNumberFormats($automaticStyle0, $numberNs, $styleNs); $automaticStyles = ($automaticStyle0 === null) ? [] : $automaticStyle0->getElementsByTagNameNS($styleNs, 'style'); + // Even with readDataOnly, which still reads the drawings + $this->decorativeStyles = []; + $graphicProperties = $dom->getElementsByTagNameNS($officeNs, 'automatic-styles')->item(0)?->getElementsByTagNameNS($styleNs, 'graphic-properties') ?? []; + foreach ($graphicProperties as $graphicProperty) { + $style = $graphicProperty->parentNode; + // loext as LibreOffice writes it, draw as ODF 1.4 does + if ( + $style instanceof DOMElement + && $style->getAttributeNS($styleNs, 'family') === 'graphic' + && ($graphicProperty->getAttributeNS(self::LOEXT_NS, 'decorative') === 'true' || $graphicProperty->getAttributeNS(self::DRAW_NS, 'decorative') === 'true') + ) { + $this->decorativeStyles[$style->getAttributeNS($styleNs, 'name')] = true; + } + } foreach ($automaticStyles as $automaticStyle) { $styleName = $automaticStyle->getAttributeNS($styleNs, 'name'); $styleFamily = $automaticStyle->getAttributeNS($styleNs, 'family'); @@ -520,6 +577,7 @@ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Sp $rowID = 1; $tableColumnIndex = 1; $this->highestDataIndex = AddressRange::MAX_COLUMN_INT; + $this->columnHyperlinkStyles = []; foreach ($worksheetDataSet->childNodes as $childNode) { /** @var DOMElement $childNode */ @@ -614,6 +672,10 @@ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Sp $spreadsheet->getActiveSheet(), $worksheetStyleName ); + $pageSettings->setRightToLeftForWorksheet( + $spreadsheet->getActiveSheet(), + $worksheetStyleName + ); $pageSettings->setPrintSettingsForWorksheet( $spreadsheet->getActiveSheet(), $worksheetStyleName @@ -894,7 +956,7 @@ private function processTableRow( } $tempSpannedRange = "$columnID$rowID"; $spannedRange = ''; - if ($worksheet !== null && ($cellData->hasChildNodes() || ($cellData->nextSibling !== null)) && isset($this->allStyles[$styleName])) { + if ($worksheet !== null && ($cellData->hasChildNodes() || ($cellData->nextSibling !== null) || $cellData->hasAttributeNS($tableNs, 'formula')) && isset($this->allStyles[$styleName])) { $spannedRange = "$columnID$rowID"; // the following is sufficient for ods, // and does no harm for xlsx/xls. @@ -938,14 +1000,20 @@ private function processTableRow( if ($cellData->hasAttributeNS($tableNs, 'number-matrix-columns-spanned')) { if ($cellData->hasAttributeNS($tableNs, 'number-matrix-rows-spanned')) { $cellDataType = 'array'; - $arrayRow = (int) $cellData->getAttributeNS($tableNs, 'number-matrix-rows-spanned'); - $arrayCol = (int) $cellData->getAttributeNS($tableNs, 'number-matrix-columns-spanned'); + $arrayRow = self::boundedInteger( + $cellData->getAttributeNS($tableNs, 'number-matrix-rows-spanned'), + 1, + AddressRange::MAX_ROW - $rowID + 1, + 'number-matrix-rows-spanned' + ); + $arrayCol = self::boundedInteger( + $cellData->getAttributeNS($tableNs, 'number-matrix-columns-spanned'), + 1, + AddressRange::MAX_COLUMN_INT - $columnIndex + 1, + 'number-matrix-columns-spanned' + ); $lastRow = $rowID + $arrayRow - 1; - $lastCol = $columnID; - while ($arrayCol > 1) { - StringHelper::stringIncrement($lastCol); - --$arrayCol; - } + $lastCol = Coordinate::stringFromColumnIndex($columnIndex + $arrayCol - 1); $cellDataRef = "$columnID$rowID:$lastCol$lastRow"; } } @@ -957,17 +1025,19 @@ private function processTableRow( $textNode = $annotation->item(0)->getElementsByTagNameNS($textNs, 'p'); $textNodeLength = $textNode->length; $newLineOwed = false; + $this->remainingSpaceCount = DataType::MAX_STRING_LENGTH; + $this->remainingTextCount = DataType::MAX_STRING_LENGTH; for ($textNodeIndex = 0; $textNodeIndex < $textNodeLength; ++$textNodeIndex) { $textNodeItem = $textNode->item($textNodeIndex); if ($textNodeItem !== null) { - $text = $this->scanElementForText($textNodeItem); if ($newLineOwed) { $spreadsheet->getActiveSheet() ->getComment($columnID . $rowID) ->getText() - ->createText("\n"); + ->createText($this->truncateText("\n")); } $newLineOwed = true; + $text = $this->scanElementForText($textNodeItem); $spreadsheet->getActiveSheet() ->getComment($columnID . $rowID) @@ -1005,10 +1075,17 @@ private function processTableRow( // Also, here we assume there is no text data is span fields are specified, since // we have no way of knowing proper positioning anyway. + $this->remainingSpaceCount = DataType::MAX_STRING_LENGTH; + $this->remainingTextCount = DataType::MAX_STRING_LENGTH; + $newLineOwed = false; foreach ($paragraphs as $pData) { + if ($newLineOwed) { + $dataArray[] = $this->truncateText("\n"); + } + $newLineOwed = true; $dataArray[] = $this->scanElementForText($pData); } - $allCellDataText = implode("\n", $dataArray); + $allCellDataText = implode('', $dataArray); $type = $cellData->getAttributeNS($officeNs, 'value-type'); $symbol = ''; @@ -1025,18 +1102,20 @@ private function processTableRow( } } + foreach ($paragraphs as $paragraph) { + $link = $paragraph->getElementsByTagNameNS($textNs, 'a'); + if ($link->length > 0 && $link->item(0) !== null) { + $hyperlink = $link->item(0)->getAttributeNS($xlinkNs, 'href'); + } + } + // A cell without a style takes the default cell style of its column + $hyperlink ??= $this->styleHyperlinks[$styleName === '' ? ($this->columnHyperlinkStyles[$columnIndex] ?? '') : $styleName] ?? null; + switch ($type) { case 'string': $type = DataType::TYPE_STRING; $dataValue = $allCellDataText; - foreach ($paragraphs as $paragraph) { - $link = $paragraph->getElementsByTagNameNS($textNs, 'a'); - if ($link->length > 0 && $link->item(0) !== null) { - $hyperlink = $link->item(0)->getAttributeNS($xlinkNs, 'href'); - } - } - break; case 'boolean': $type = DataType::TYPE_BOOL; @@ -1059,15 +1138,12 @@ private function processTableRow( $type = DataType::TYPE_NUMERIC; $dataValue = (float) $cellData->getAttributeNS($officeNs, 'value'); - $currency = $cellData->getAttributeNS($officeNs, 'currency'); if ($leftHandCurrency) { - $typeValue = 'currency'; $formatting = str_contains($allCellDataText, '.') ? NumberFormat::FORMAT_CURRENCY_USD : NumberFormat::FORMAT_CURRENCY_USD_INTEGER; if ($symbol !== '$') { $formatting = str_replace('$', $symbol, $formatting); } } elseif (str_contains($allCellDataText, '€')) { - $typeValue = 'currency'; $formatting = str_contains($allCellDataText, '.') ? NumberFormat::FORMAT_CURRENCY_EUR : NumberFormat::FORMAT_CURRENCY_EUR_INTEGER; } @@ -1140,7 +1216,7 @@ private function processTableRow( break; default: - $dataValue = null; + $dataValue = null; //* @phpstan-ignore assign.redundant (phpstan probably correct but it's hard to see why) } if ($customFormatting !== '') { $formatting = $customFormatting; @@ -1201,7 +1277,8 @@ private function processTableRow( if ($hyperlink !== null) { if ($hyperlink[0] === '#') { - $hyperlink = 'sheet://' . substr($hyperlink, 1); + // #Sheet.A1 as ODF writes it, #Sheet!A1 as older releases wrote it; a named range has no sheet + $hyperlink = 'sheet://' . Preg::replace("/^('(?:[^']|'')*'|[^'.!]+)\\.(?=\\$?[A-Z]{1,3}\\$?\\d)/i", '$1!', substr($hyperlink, 1)); } $cell->getHyperlink() ->setUrl($hyperlink); @@ -1225,13 +1302,14 @@ private function processDrawFrame(string $spannedRange, DOMElement $item, Worksh $svgHeight = $item->getAttribute('svg:height'); $styleName = $item->getAttribute('draw:style-name'); $drawImage = null; + $description = ''; foreach ($item->childNodes as $node) { // Check if the node is a standard element tag - if ($node->nodeType === XML_ELEMENT_NODE && $node->nodeName === 'draw:image') { + if ($node->nodeType === XML_ELEMENT_NODE && $node->nodeName === 'draw:image' && $drawImage === null) { /** @var DOMElement */ $drawImage = $node; - - break; + } elseif ($node->nodeType === XML_ELEMENT_NODE && $node->nodeName === 'svg:desc') { + $description = $node->textContent; } } @@ -1268,11 +1346,33 @@ private function processDrawFrame(string $spannedRange, DOMElement $item, Worksh ->setWidth((int) $width) ->setHeight((int) $height) ->setName($drawName) + ->setDescription($description) + ->setDecorative(isset($this->decorativeStyles[$styleName])) ->setWorksheet($worksheet); } } } + /** + * The language of text properties as a BCP 47 tag, or '' for none. + */ + private static function languageTag(DOMElement $textProperties, string $styleNs, string $fontNs): string + { + $tag = $textProperties->getAttributeNS($styleNs, 'rfc-language-tag'); + $language = strtolower($textProperties->getAttributeNS($fontNs, 'language')); + // zxx: no linguistic content + if ($tag !== '' || !Preg::isMatch('/^[a-z]{2,3}$/', $language) || $language === 'zxx') { + return $tag; + } + $script = $textProperties->getAttributeNS($fontNs, 'script'); + $country = $textProperties->getAttributeNS($fontNs, 'country'); + + // ponytail: the Western slot only, where LibreOffice always writes one; an Asian or complex document language needs dc:language + return $language + . (Preg::isMatch('/^[a-z]{4}$/i', $script) ? '-' . ucfirst(strtolower($script)) : '') + . (Preg::isMatch('/^([a-z]{2}|\d{3})$/i', $country) ? '-' . strtoupper($country) : ''); + } + private static function extractNodeName(string $key): string { // Remove ns from node name @@ -1414,6 +1514,11 @@ private function processTableColumn( } if ($processStyles) { $defaultStyleName = $childNode->getAttributeNS($tableNs, 'default-cell-style-name'); + if (isset($this->styleHyperlinks[$defaultStyleName])) { + for ($column = $tableColumnIndex; $column < $tableColumnIndex + $colRepeats && $column <= AddressRange::MAX_COLUMN_INT; ++$column) { + $this->columnHyperlinkStyles[$column] = $defaultStyleName; + } + } if ($defaultStyleName !== 'Default' && isset($this->allStyles[$defaultStyleName])) { $tableColumnIndex2 = $tableColumnIndex; $tableColumnString = Coordinate::stringFromColumnIndex($tableColumnIndex2); @@ -1506,9 +1611,9 @@ protected function scanElementForText(DOMNode $element): string foreach ($element->childNodes as $child) { /** @var DOMNode $child */ if ($child->nodeType == XML_TEXT_NODE) { - $str .= $child->nodeValue; + $str .= $this->truncateText((string) $child->nodeValue); } elseif ($child->nodeType == XML_ELEMENT_NODE && $child->nodeName == 'text:line-break') { - $str .= "\n"; + $str .= $this->truncateText("\n"); } elseif ($child->nodeType == XML_ELEMENT_NODE && $child->nodeName == 'text:s') { // It's a space @@ -1517,7 +1622,13 @@ protected function scanElementForText(DOMNode $element): string /** @var ?DOMAttr $cAttr */ $cAttr = ($attributes === null) ? null : $attributes->getNamedItem('c'); $multiplier = self::getMultiplier($cAttr); - $str .= str_repeat(' ', $multiplier); + if ($multiplier > $this->remainingSpaceCount) { + throw new Exception('ODS text space expansion exceeds the supported limit.'); + } + $this->remainingSpaceCount -= $multiplier; + $spaceCount = min($multiplier, $this->remainingTextCount); + $this->remainingTextCount -= $spaceCount; + $str .= str_repeat(' ', $spaceCount); } if ($child->hasChildNodes()) { @@ -1528,10 +1639,28 @@ protected function scanElementForText(DOMNode $element): string return $str; } + private function truncateText(string $text): string + { + if ($this->remainingTextCount === 0) { + return ''; + } + $text = StringHelper::substring($text, 0, $this->remainingTextCount); + $this->remainingTextCount -= StringHelper::countCharacters($text); + + return $text; + } + private static function getMultiplier(?DOMAttr $cAttr): int { if ($cAttr) { - $multiplier = (int) $cAttr->nodeValue; + $count = trim($cAttr->value); + if (!Preg::isMatch('/^\+?[0-9]+$/D', $count)) { + throw new Exception('Invalid text:c space count.'); + } + $multiplier = (int) $count; + if ($multiplier < 1) { + throw new Exception('Invalid text:c space count.'); + } } else { $multiplier = 1; } @@ -1819,7 +1948,6 @@ protected function getProtectionStyles(DOMElement $tableCellProperties, string $ protected function getBorderStyles(DOMElement $tableCellProperties, string $fontNs, string $styleNs): array { $borders = []; - $temp = $tableCellProperties->getAttributeNs($fontNs, 'border'); $diagonalIndex = Borders::DIAGONAL_NONE; foreach (['bottom', 'left', 'right', 'top', 'diagonal-tl-br', 'diagonal-bl-tr'] as $direction) { if ($direction === 'diagonal-tl-br' || $direction === 'diagonal-bl-tr') { @@ -1837,7 +1965,6 @@ protected function getBorderStyles(DOMElement $tableCellProperties, string $font } elseif ($width >= 1.75) { $style = self::MAP_BORDER_MEDIUM[$style] ?? $style; } - $color = $matches[3]; $borders[$directionIndex] = ['borderStyle' => $style, 'color' => ['rgb' => $matches[3]]]; if ($direction === 'diagonal-tl-br') { $diagonalIndex = Borders::DIAGONAL_DOWN; @@ -1866,13 +1993,43 @@ protected function processNumberNumber(DOMElement $automaticStyle, string $numbe $styleName = $automaticStyle->getAttributeNS($styleNs, 'name'); foreach ($automaticStyle->getElementsByTagNameNS($numberNs, 'number') as $numberNumber) { $decimalPlaces = $numberNumber->getAttributeNs($numberNs, 'decimal-places'); - $minIntegerDigits = (int) $numberNumber->getAttributeNs($numberNs, 'min-integer-digits'); - if ($decimalPlaces === '0' && $minIntegerDigits > 1) { - $this->numberFormats[$styleName] = str_repeat('0', $minIntegerDigits); + if ($decimalPlaces === '0' && $numberNumber->hasAttributeNS($numberNs, 'min-integer-digits')) { + $minIntegerDigits = self::boundedInteger( + $numberNumber->getAttributeNS($numberNs, 'min-integer-digits'), + 0, + self::MAX_INTEGER_DIGITS, + 'min-integer-digits' + ); + if ($minIntegerDigits > 1) { + $this->numberFormats[$styleName] = str_repeat('0', $minIntegerDigits); + } } } } + /** Validate the lexical value and its bound before converting to an integer. */ + private static function boundedInteger(string $value, int $minimum, int $maximum, string $attribute): int + { + $value = trim($value); + if (!Preg::isMatch('/^\+?[0-9]+$/D', $value)) { + throw new Exception("Invalid ODS $attribute value."); + } + $digits = ltrim($value, '+0'); + $maximumDigits = (string) $maximum; + if ( + strlen($digits) > strlen($maximumDigits) + || (strlen($digits) === strlen($maximumDigits) && strcmp($digits, $maximumDigits) > 0) + ) { + throw new Exception("Invalid ODS $attribute value."); + } + $integer = (int) $value; + if ($integer < $minimum) { + throw new Exception("Invalid ODS $attribute value."); + } + + return $integer; + } + private static function checkRowsRepeated(int $rowID, int $rowRepeats): void { if ($rowRepeats < 1 || $rowID + $rowRepeats - 1 > AddressRange::MAX_ROW) { @@ -1904,12 +2061,8 @@ private function loadDom(string $file, ZipArchive $zip): DOMDocument try { $orig = libxml_use_internal_errors(true); - $result = $dom->loadXML( - $this->getSecurityScannerOrThrow() - ->scan($zip->getFromName($file)) - ); + $result = $this->loadZipDom($dom, $zip, $file); if ($result === false) { - $fatal = false; foreach (libxml_get_errors() as $err) { if ($err->level === LIBXML_ERR_FATAL) { throw new Exception($err->message); @@ -1923,4 +2076,61 @@ private function loadDom(string $file, ZipArchive $zip): DOMDocument return $dom; } + + private function loadZipSimple(ZipArchive $zip, string $fileName): false|SimpleXMLElement + { + $retVal = false; + $stat = $zip->statName($fileName); + if ($stat !== false) { + if ($stat['size'] > $this->maxLength) { + throw new Exception( + "Zip member $fileName expands to {$stat['size']} bytes, over the limit" + ); + } + $retVal = simplexml_load_string( + $this->getSecurityScannerOrThrow() + ->scan($zip->getFromName($fileName)) + ); + } + + return $retVal; + } + + private function loadZipDom(DOMDocument $dom, ZipArchive $zip, string $fileName): bool + { + $retVal = false; + $stat = $zip->statName($fileName); + if ($stat !== false) { + if ($stat['size'] > $this->maxLength) { + throw new Exception( + "Zip member $fileName expands to {$stat['size']} bytes, over the limit" + ); + } + $retVal = $dom->loadXML( + $this->getSecurityScannerOrThrow() + ->scan($zip->getFromName($fileName)) + ); + } + + return $retVal; + } + + private function loadZipXml(XMLReader $xml, ZipArchive $zip, string $fileName): bool + { + $retVal = false; + $stat = $zip->statName($fileName); + if ($stat !== false) { + if ($stat['size'] > $this->maxLength) { + throw new Exception( + "Zip member $fileName expands to {$stat['size']} bytes, over the limit" + ); + } + $retVal = $xml->xml( + $this->getSecurityScannerOrThrow() + ->scan($zip->getFromName($fileName)) + ); + } + + return (bool) $retVal; + } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php index 1f5f975d..404d1d84 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php @@ -4,6 +4,9 @@ use DOMElement; use DOMNode; +use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; +use PhpOffice\PhpSpreadsheet\Worksheet\Table; +use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class AutoFilter extends BaseLoader { @@ -21,12 +24,47 @@ protected function readAutoFilters(DOMElement $workbookData): void $autofilterRange = $this->getAttributeValue($autofilter, 'target-range-address'); if ($autofilterRange !== null) { $baseAddress = FormulaTranslator::convertToExcelAddressValue($autofilterRange); - $this->spreadsheet->getActiveSheet()->setAutoFilter($baseAddress); + if ($baseAddress === '') { + continue; + } + [$title, $range] = Worksheet::extractSheetTitle($baseAddress, true, true); + $range = str_replace('$', '', $range); + // A sheet that does not exist, or that was not loaded, takes nothing of it + $worksheet = $title === '' ? $this->spreadsheet->getActiveSheet() : $this->spreadsheet->getSheetByName($title); + if ($worksheet === null) { + continue; + } + if (!$this->readTable($autofilter, $worksheet, $range)) { + $worksheet->setAutoFilter($range); + } } } } } + /** + * A named database range is a table, as LibreOffice writes one; a range with no name + * or an anonymous one of LibreOffice (the filter of a sheet) is not. As in LibreOffice, + * a range whose name cannot be a table, or is taken already, is dropped. + */ + private function readTable(DOMNode $databaseRange, Worksheet $worksheet, string $range): bool + { + $name = (string) $this->getAttributeValue($databaseRange, 'name'); + if ($name === '' || str_starts_with($name, '__Anonymous_Sheet_DB__') || str_starts_with($name, '__Anonymous_DB__')) { + return false; + } + + try { + $table = new Table($range, $name); + $table->setShowHeaderRow($this->getAttributeValue($databaseRange, 'contains-header') !== 'false'); + $table->setAllowFilter($this->getAttributeValue($databaseRange, 'display-filter-buttons') === 'true'); + $worksheet->addTable($table, false); + } catch (PhpSpreadsheetException) { + } + + return true; + } + protected function getAttributeValue(?DOMNode $node, string $attributeName): ?string { if ($node !== null && $node->attributes !== null) { diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/PageSettings.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/PageSettings.php index 6686141d..afeed686 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/PageSettings.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/PageSettings.php @@ -22,6 +22,11 @@ class PageSettings */ private array $tableStylesCrossReference = []; + /** + * @var bool[] whether a table style lays its sheet out right to left + */ + private array $tableStylesRightToLeft = []; + /** @var mixed[] */ private array $pageLayoutStyles = []; @@ -116,6 +121,8 @@ public function readStyleCrossReferences(DOMDocument $contentDom): void $styleVisibility = 'true'; foreach ($styleXreferenceSet->getElementsByTagNameNS($this->stylesNs, 'table-properties') as $tableProperties) { $styleVisibility = $tableProperties->getAttributeNS($this->tableNs, 'display'); + // rl-tb, or rl, which ODF also allows + $this->tableStylesRightToLeft[$styleXRefName] = str_starts_with($tableProperties->getAttributeNS($this->stylesNs, 'writing-mode'), 'rl'); } $this->tableStylesCrossReference[$styleXRefName] = $styleVisibility; } @@ -138,6 +145,13 @@ public function setVisibilityForWorksheet(Worksheet $worksheet, string $styleNam ); } + public function setRightToLeftForWorksheet(Worksheet $worksheet, string $styleName): void + { + if (array_key_exists($styleName, $this->tableStylesRightToLeft)) { + $worksheet->setRightToLeft($this->tableStylesRightToLeft[$styleName]); + } + } + public function setPrintSettingsForWorksheet(Worksheet $worksheet, string $styleName): void { if (!array_key_exists($styleName, $this->masterStylesCrossReference)) { diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php index 4dada28f..815a5680 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php @@ -62,6 +62,10 @@ private function setCoreProperties(DocumentProperties $docProps, SimpleXMLElemen case 'description': $docProps->setDescription($propertyValue); + break; + case 'language': + $docProps->setLanguage($propertyValue); + break; } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php index 5d238a80..d8722688 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php @@ -14,14 +14,17 @@ class XmlScanner /** @var ?callable */ private $callback; - public function __construct(string $pattern = 'pattern = $pattern; } public static function getInstance(Reader\IReader $reader): self { - $pattern = ($reader instanceof Reader\Html) ? 'version === self::XLS_BIFF8) { // offset: 8; size: 2; not used // offset: 10; size: 2; cached magnification factor in page break preview (in percent); 0 = Default (60%) @@ -4042,7 +4037,7 @@ protected function readRangeProtection(): void // offset: var; size: 4; the encrypted password (only 16-bit although field is 32-bit) $wPassword = self::getInt4d($recordData, $offset); - $offset += 4; + //$offset += 4; // Apply range protection to sheet if ($cellRanges) { @@ -4382,7 +4377,6 @@ private function getNextToken(string $formulaData, string $baseCell = 'A1'): arr { // offset: 0; size: 1; token id $id = ord($formulaData[0]); // token id - $name = false; // initialize token name switch ($id) { case 0x03: diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ConditionalFormatting.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ConditionalFormatting.php index 9f89d162..98d909d0 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ConditionalFormatting.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ConditionalFormatting.php @@ -178,7 +178,7 @@ protected function readCFRule2(array $cellRangeAddresses, Xls $xls): void return; } - $offset += $size2; + $offset += $size2; //* @phpstan-ignore assign.unused (code clarity) } $this->setCFRules($cellRangeAddresses, $type, $operator, $formula1, $formula2, $style, $noFormatSet, $xls); diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Escher.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Escher.php index 018c1718..735a35c9 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Escher.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Escher.php @@ -31,6 +31,8 @@ class Escher const CLIENTTEXTBOX = 0xF00D; const CLIENTANCHOR = 0xF010; const CLIENTDATA = 0xF011; + const BLIPEMF = 0xF01A; + const BLIPWMF = 0xF01B; const BLIPJPEG = 0xF01D; const BLIPPNG = 0xF01E; const SPLITMENUCOLORS = 0xF11E; @@ -73,6 +75,8 @@ public function __construct(BSE|BstoreContainer|DgContainer|DggContainer|\PhpOff self::DGG => 'readDgg', self::BSTORECONTAINER => 'readBstoreContainer', self::BSE => 'readBSE', + self::BLIPEMF => 'readBlipMetafile', + self::BLIPWMF => 'readBlipMetafile', self::BLIPJPEG => 'readBlipJPEG', self::BLIPPNG => 'readBlipPNG', self::OPT => 'readOPT', @@ -333,6 +337,58 @@ private function readBlipPNG(): void $this->applyAttribute('setBlip', $blip); } + /** + * Read BlipEMF or BlipWMF record. Holds a (possibly compressed) Windows Metafile. + */ + private function readBlipMetafile(): void + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; + + $length = Xls::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + + $pos = 0; + + // offset: 0; size: 16; rgbUid1 (MD4 digest of) + $pos += 16; + + // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x3D5 (EMF) or 0x217 (WMF) + if (in_array($recInstance, [0x03D5, 0x0217], true)) { + $pos += 16; + } + + // offset: var; size: 34; metafileHeader + // size: 4; cbSize, uncompressed size of the metafile + // size: 16; rcBounds + // size: 8; ptSize + // size: 4; cbSave, size of the metafile data + $cbSave = Xls::getInt4d($recordData, $pos + 28); + // size: 1; compression (0x00: DEFLATE, 0xFE: none) + $compression = ord($recordData[$pos + 32] ?? "\xFE"); + // size: 1; filter + $pos += 34; + + // offset: var; size: var; the metafile data + $data = substr($recordData, $pos, $cbSave); + if ($compression === 0x00) { + $data = @gzuncompress($data); + if ($data === false) { + return; + } + } + + $blip = new Blip(); + $blip->setData($data); + + $this->applyAttribute('setBlip', $blip); + } + /** * Read OPT record. This record may occur within DggContainer record or SpContainer. */ diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ListFunctions.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ListFunctions.php index 2bc472fd..eeda3273 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ListFunctions.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ListFunctions.php @@ -106,10 +106,10 @@ protected function listWorksheetInfo2(string $filename, Xls $xls): array $tmpInfo = []; $tmpInfo['worksheetName'] = StringHelper::convertToString($sheet['name']); - $tmpInfo['lastColumnLetter'] = 'A'; + $tmpInfo['lastColumnLetter'] = 'A'; //* @phpstan-ignore assign.overwritten (preserve array order) $tmpInfo['lastColumnIndex'] = 0; $tmpInfo['totalRows'] = 0; - $tmpInfo['totalColumns'] = 0; + $tmpInfo['totalColumns'] = 0; //* @phpstan-ignore assign.overwritten (preserve array order) $tmpInfo['sheetState'] = StringHelper::convertToString($sheet['sheetState']); $xls->pos = $sheet['offset']; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/LoadSpreadsheet.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/LoadSpreadsheet.php index 10a2e5e6..8e6d1d17 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/LoadSpreadsheet.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/LoadSpreadsheet.php @@ -11,6 +11,7 @@ use PhpOffice\PhpSpreadsheet\Shared\Escher as SharedEscher; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; +use PhpOffice\PhpSpreadsheet\Shared\Metafile; use PhpOffice\PhpSpreadsheet\Shared\Xls as SharedXls; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; @@ -501,9 +502,16 @@ protected function loadSpreadsheetFromFile2(string $filename, Xls $xls): Spreads $BSE = $BSECollection[$BSEindex - 1]; $blipType = $BSE->getBlipType(); - // need check because some blip types are not supported by Escher reader such as EMF + // need check because some blip types are not supported by Escher reader such as PICT if ($blip = $BSE->getBlip()) { - $ih = imagecreatefromstring($blip->getData()); + $blipData = $blip->getData(); + if (Metafile::detect($blipData) !== null) { + // Windows Metafiles (WMF, EMF, EMF+) are rendered as PNG + $blipType = BSE::BLIPTYPE_PNG; + $ih = Metafile::tryToGdImage($blipData) ?? false; + } else { + $ih = imagecreatefromstring($blipData); + } if ($ih !== false) { $drawing = new MemoryDrawing(); $drawing->setImageResource($ih); @@ -566,7 +574,7 @@ protected function loadSpreadsheetFromFile2(string $filename, Xls $xls): Spreads $textObject = $xls->textObjects[$note]; $noteDetails['objTextData'] = $textObject; } else { - $noteDetails['objTextData']['text'] = ''; + $noteDetails['objTextData']['text'] = ''; //* @phpstan-ignore offsetAccess.nonOffsetAccessible (I don't know) } } $cellAddress = str_replace('$', '', $noteDetails['cellRef']); diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php index b1de05a5..05c3a2cb 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php @@ -173,6 +173,9 @@ private function decryptToTemporaryFile(string $filename): ?string return null; } + $encryptionInfo = substr($encryptionInfo, 0, 8) + . $this->getSecurityScannerOrThrow()->scan(substr($encryptionInfo, 8)); + $temporaryFilename = File::temporaryFilename(); $encryptedPackageFilename = File::temporaryFilename(); $encryptedPackage = fopen($encryptedPackageFilename, 'wb'); @@ -381,8 +384,8 @@ private function listWorksheetInfoFromFile(string $filename): array foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { $tmpInfo = [ 'worksheetName' => (string) self::getAttributes($eleSheet)['name'], - 'lastColumnLetter' => 'A', - 'lastColumnIndex' => 0, + 'lastColumnLetter' => 'A', //* @phpstan-ignore array.offsetOverwritten (preserve array order) + 'lastColumnIndex' => 0, //* @phpstan-ignore array.offsetOverwritten (preserve array order) 'totalRows' => 0, 'totalColumns' => 0, ]; @@ -496,7 +499,6 @@ protected function castToFormula(?SimpleXMLElement $c, string $r, string &$cellD $master = Coordinate::indexesFromString($this->sharedFormulae[$instance]->master()); $current = Coordinate::indexesFromString($r); - $difference = [0, 0]; $difference[0] = $current[0] - $master[0]; $difference[1] = $current[1] - $master[1]; @@ -507,19 +509,16 @@ protected function castToFormula(?SimpleXMLElement $c, string $r, string &$cellD private function fileExistsInArchive(ZipArchive $archive, string $fileName = ''): bool { - // Root-relative paths - if (str_contains($fileName, '//')) { - $fileName = substr($fileName, strpos($fileName, '//') + 1); - } - $fileName = File::realpath($fileName); + $fileName = File::realpath($fileName, true); // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming // so we need to load case-insensitively from the zip file - - // Apache POI fixes $contents = $archive->locateName($fileName, ZipArchive::FL_NOCASE); + + // Has the file been saved with Windoze directory separators rather than unix? if ($contents === false) { - $contents = $archive->locateName(substr($fileName, 1), ZipArchive::FL_NOCASE); + $fileName1 = str_replace('/', '\\', $fileName); + $contents = $archive->locateName($fileName1, ZipArchive::FL_NOCASE); } return $contents !== false; @@ -527,31 +526,34 @@ private function fileExistsInArchive(ZipArchive $archive, string $fileName = '') protected function getFromZipArchive(ZipArchive $archive, string $fileName = ''): string { - // Root-relative paths - if (str_contains($fileName, '//')) { - $fileName = substr($fileName, strpos($fileName, '//') + 1); - } // Relative paths generated by dirname($filename) when $filename // has no path (i.e.files in root of the zip archive) $fileName = Preg::replace('/^\.\//', '', $fileName); - $fileName = File::realpath($fileName); + $fileName = File::realpath($fileName, true); // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming // so we need to load case-insensitively from the zip file + $stat = $archive->statName($fileName, ZipArchive::FL_NOCASE); - $contents = $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE); - - // Apache POI fixes - if ($contents === false) { - $contents = $archive->getFromName(substr($fileName, 1), 0, ZipArchive::FL_NOCASE); + // Has the file been saved with Windoze directory separators rather than unix? + if ($stat === false) { + $fileName1 = str_replace('/', '\\', $fileName); + $stat = $archive->statName($fileName1, ZipArchive::FL_NOCASE); + if ($stat !== false) { + $fileName = $fileName1; + } } - // Has the file been saved with Windoze directory separators rather than unix? - if ($contents === false) { - $contents = $archive->getFromName(str_replace('/', '\\', $fileName), 0, ZipArchive::FL_NOCASE); + if ($stat === false) { + return ''; + } + if ($stat['size'] > $this->maxLength) { + throw new Exception( + "Zip member $fileName expands to {$stat['size']} bytes, over the limit" + ); } - return ($contents === false) ? '' : $contents; + return (string) $archive->getFromName($fileName, 0, ZipArchive::FL_NOCASE); } /** @@ -707,7 +709,7 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet $worksheets = []; $pivotCacheRels = []; - $macros = $customUI = null; + $macros = null; foreach ($relsWorkbook->Relationship as $elex) { $ele = self::getAttributes($elex); switch ($ele['Type']) { @@ -931,7 +933,6 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet // Set protection $this->readProtection($excel, $xmlWorkbook); - $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 = []; // mapping of sheet ids from old to new @@ -993,9 +994,14 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet // It might be better just to drop the test. if ($fileWorksheet[0] == '/' && $dir !== '.') { $fileWorksheet = substr($fileWorksheet, strlen($dir) + 2); + $targetWorksheet = "$dir/$fileWorksheet"; + } elseif ($fileWorksheet[0] === '/') { + $targetWorksheet = substr($fileWorksheet, 1); + } else { + $targetWorksheet = "$dir/$fileWorksheet"; } - $xmlSheet = $this->loadZipNoNamespace("$dir/$fileWorksheet", $mainNS); - $xmlSheetNS = $this->loadZip("$dir/$fileWorksheet", $mainNS); + $xmlSheet = $this->loadZipNoNamespace($targetWorksheet, $mainNS); + $xmlSheetNS = $this->loadZip($targetWorksheet, $mainNS); // Shared Formula table is unique to each Worksheet, so we need to reset it here $this->sharedFormulae = []; @@ -1173,9 +1179,13 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet } // Loop through comments - foreach ($comments as $relName => $relPath) { + foreach ($comments as $relPath) { // Load comments file - $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); + if (substr($relPath, 0, 1) === '/') { + $relPath = File::realpath(substr($relPath, 1)); + } else { + $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); + } // okay to ignore namespace - using xpath $commentsFile = $this->loadZip($relPath, ''); @@ -1429,6 +1439,7 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet if (isset($imageData['title'])) { $hfImages[$shapeId]->setName((string) $imageData['title']); } + $hfImages[$shapeId]->setDescription((string) $shape['alt']); $hfImages[$shapeId]->setPath('zip://' . File::realpath($filename) . '#' . $drawings[(string) $imageData['relid']], false, $zip); $hfImages[$shapeId]->setResizeProportional(false); @@ -1500,7 +1511,7 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet } else { $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $eleTarget); } - } elseif ($eleType === "$xmlNamespaceBase/chart") { + } elseif ($eleType === "$xmlNamespaceBase/chart" || $eleType === Namespaces::RELATIONSHIPS_CHART_EX) { if ($this->includeCharts) { $eleTarget = (string) $ele['Target']; if (str_starts_with($eleTarget, '/xl/')) { @@ -1560,6 +1571,7 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet $objDrawing->setName(self::getArrayItemString(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'name')); $objDrawing->setDescription(self::getArrayItemString(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'descr')); + $objDrawing->setDecorative(self::isDecorative($oneCellAnchor->pic->nvPicPr->cNvPr)); $embedImageKey = self::getArrayItemString( self::getAttributes($blip, $xmlNamespaceBase), 'embed' @@ -1626,8 +1638,15 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet $height = Drawing::EMUToPixels(self::getArrayItemIntOrSxml(self::getAttributes($oneCellAnchor->ext), 'cy')); $graphic = $oneCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic; + $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; - $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); + $chartRefEx = $graphic->graphicData->children(Namespaces::CHART_EX)->chart; + + if ($chartRef->count() > 0) { + $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); + } else { + $thisChart = (string) self::getAttributes($chartRefEx, $xmlNamespaceBase); + } $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ 'fromCoordinate' => $coordinates, @@ -1637,6 +1656,7 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet 'height' => $height, 'worksheetTitle' => $docSheet->getTitle(), 'oneCellAnchor' => true, + 'description' => self::getArrayItemString(self::getAttributes($oneCellAnchor->graphicFrame->nvGraphicFramePr->cNvPr), 'descr'), ]; } } @@ -1664,6 +1684,7 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet } $objDrawing->setName((string) self::getArrayItemString(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'name')); $objDrawing->setDescription(self::getArrayItemString(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'descr')); + $objDrawing->setDecorative(self::isDecorative($twoCellAnchor->pic->nvPicPr->cNvPr)); $embedImageKey = self::getArrayItemString( self::getAttributes($blip, $xmlNamespaceBase), 'embed' @@ -1736,8 +1757,15 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet $toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff); $toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff); $graphic = $twoCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic; + $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; - $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); + $chartRefEx = $graphic->graphicData->children(Namespaces::CHART_EX)->chart; + + if ($chartRef->count() > 0) { + $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); + } else { + $thisChart = (string) self::getAttributes($chartRefEx, $xmlNamespaceBase); + } $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ 'fromCoordinate' => $fromCoordinate, @@ -1747,6 +1775,7 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet 'toOffsetX' => $toOffsetX, 'toOffsetY' => $toOffsetY, 'worksheetTitle' => $docSheet->getTitle(), + 'description' => self::getArrayItemString(self::getAttributes($twoCellAnchor->graphicFrame->nvGraphicFramePr->cNvPr), 'descr'), ]; } } @@ -1755,8 +1784,16 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet foreach ($xmlDrawingChildren->absoluteAnchor as $absoluteAnchor) { if (($this->includeCharts) && ($absoluteAnchor->graphicFrame)) { $graphic = $absoluteAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic; + $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; - $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); + $chartRefEx = $graphic->graphicData->children(Namespaces::CHART_EX)->chart; + + if ($chartRef->count() > 0) { + $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); + } else { + $thisChart = (string) self::getAttributes($chartRefEx, $xmlNamespaceBase); + } + $width = Drawing::EMUToPixels((int) self::getArrayItemString(self::getAttributes($absoluteAnchor->ext), 'cx')[0]); $height = Drawing::EMUToPixels((int) self::getArrayItemString(self::getAttributes($absoluteAnchor->ext), 'cy')[0]); @@ -1767,6 +1804,7 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet 'width' => $width, 'height' => $height, 'worksheetTitle' => $docSheet->getTitle(), + 'description' => self::getArrayItemString(self::getAttributes($absoluteAnchor->graphicFrame->nvGraphicFramePr->cNvPr), 'descr'), ]; } } @@ -1815,8 +1853,8 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet } /** @var mixed[][][][] $unparsedLoadedData */ - $this->readFormControlProperties($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); - $this->readPrinterSettings($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); + $this->readFormControlProperties($dir, $fileWorksheet, $docSheet, $unparsedLoadedData); + $this->readPrinterSettings($dir, $fileWorksheet, $docSheet, $unparsedLoadedData); // Loop through definedNames if ($xmlWorkbook->definedNames) { @@ -1893,9 +1931,6 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet } } } - - // Next sheet id - ++$sheetId; } // Loop through definedNames @@ -2001,17 +2036,21 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet // Override content types foreach ($contentTypes->Override as $contentType) { switch ($contentType['ContentType']) { + case 'application/vnd.ms-office.chartex+xml': case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml': if ($this->includeCharts) { $chartEntryRef = ltrim((string) $contentType['PartName'], '/'); $chartElements = $this->loadZip($chartEntryRef); $chartReader = new Chart($chartNS, $drawingNS); - $objChart = $chartReader->readChart($chartElements, basename($chartEntryRef, '.xml')); + $objChart = (string) $contentType['ContentType'] === 'application/vnd.ms-office.chartex+xml' + ? $chartReader->readChartEx($chartElements, basename($chartEntryRef, '.xml'), $excel) + : $chartReader->readChart($chartElements, basename($chartEntryRef, '.xml')); if (isset($charts[$chartEntryRef])) { $chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id']; if (isset($chartDetails[$chartPositionRef]) && $excel->getSheetByName($charts[$chartEntryRef]['sheet']) !== null) { $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet'])); + $objChart->setDescription($chartDetails[$chartPositionRef]['description']); // For oneCellAnchor or absoluteAnchor positioned charts, // toCoordinate is not in the data. Does it need to be calculated? if (array_key_exists('toCoordinate', $chartDetails[$chartPositionRef])) { @@ -2385,6 +2424,18 @@ private static function getArrayItem(null|array|bool|SimpleXMLElement $array, in return ($array === null || is_bool($array)) ? null : ($array[$key] ?? null); } + /** + * Excel and LibreOffice mark a decorative drawing in an extension of its cNvPr. + */ + private static function isDecorative(SimpleXMLElement $cNvPr): bool + { + $cNvPr->registerXPathNamespace('a', Namespaces::DRAWINGML); + $cNvPr->registerXPathNamespace('adec', Namespaces::DECORATIVE); + $value = (string) (($cNvPr->xpath('a:extLst/a:ext/adec:decorative/@val') ?: [])[0] ?? ''); + + return $value === '1' || $value === 'true'; + } + /** @param null|bool|mixed[]|SimpleXMLElement $array */ private static function getArrayItemString(null|array|bool|SimpleXMLElement $array, int|string $key = 0): string { @@ -2405,8 +2456,13 @@ private static function dirAdd(null|SimpleXMLElement|string $base, null|SimpleXM { $base = (string) $base; $add = (string) $add; + if (substr($add, 0, 1) === '/') { + $target = substr($add, 1); + } else { + $target = dirname($base) . "/$add"; + } - return Preg::replace('~[^/]+/\.\./~', '', dirname($base) . "/$add"); + return Preg::replace('~[^/]+/\.\./~', '', $target); } /** @return mixed[] */ @@ -2571,7 +2627,7 @@ private static function getLockValue(SimpleXMLElement $protection, string $key): } /** @param mixed[][][][] $unparsedLoadedData */ - private function readFormControlProperties(Spreadsheet $excel, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void + private function readFormControlProperties(string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void { $zip = $this->zip; if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') === false) { @@ -2600,7 +2656,7 @@ private function readFormControlProperties(Spreadsheet $excel, string $dir, stri } /** @param mixed[][][][] $unparsedLoadedData */ - private function readPrinterSettings(Spreadsheet $excel, string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void + private function readPrinterSettings(string $dir, string $fileWorksheet, Worksheet $docSheet, array &$unparsedLoadedData): void { if ($this->readDataOnly) { return; @@ -2766,7 +2822,11 @@ private function readTablesInTablesFile( if ((string) $relationshipAttributes['Id'] === $tablePartRel) { $relationshipFileName = (string) $relationshipAttributes['Target']; - $relationshipFilePath = dirname("$dir/$fileWorksheet") . '/' . $relationshipFileName; + if (substr($relationshipFileName, 0, 1) === '/') { + $relationshipFilePath = substr($relationshipFileName, 1); + } else { + $relationshipFilePath = dirname("$dir/$fileWorksheet") . '/' . $relationshipFileName; + } $relationshipFilePath = File::realpath($relationshipFilePath); if ($this->fileExistsInArchive($this->zip, $relationshipFilePath)) { @@ -2996,6 +3056,11 @@ private function processIgnoredErrors(SimpleXMLElement $xml, Worksheet $sheet): $lastCol = $firstCol; $lastRow = $firstRow; } + $firstColInt = Coordinate::columnIndexFromString($firstCol); + $lastColInt = Coordinate::columnIndexFromString($lastCol); + if ($firstRow > $lastRow || $firstColInt > $lastColInt) { + throw new Exception('bad sqref in ignoredErrors'); + } StringHelper::stringIncrement($lastCol); for ($row = $firstRow; $row <= $lastRow; ++$row) { for ($col = $firstCol; $col !== $lastCol; StringHelper::stringIncrement($col)) { diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php index d00a7aed..69bc24e2 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php @@ -5,6 +5,8 @@ use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Chart\Axis; use PhpOffice\PhpSpreadsheet\Chart\AxisText; +use PhpOffice\PhpSpreadsheet\Chart\BoxWhisker; +use PhpOffice\PhpSpreadsheet\Chart\BoxWhiskerSeries; use PhpOffice\PhpSpreadsheet\Chart\ChartColor; use PhpOffice\PhpSpreadsheet\Chart\DataSeries; use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues; @@ -18,6 +20,7 @@ use PhpOffice\PhpSpreadsheet\Chart\TrendLine; use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\RichText\RichText; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Font; use SimpleXMLElement; @@ -517,6 +520,107 @@ public function readChart(SimpleXMLElement $chartElements, string $chartName): \ return $chart; } + /** + * Read a ChartEx chart. + */ + public function readChartEx(SimpleXMLElement $chartElements, string $chartName, Spreadsheet $spreadsheet): \PhpOffice\PhpSpreadsheet\Chart\Chart + { + $chartSpace = $chartElements->children(Namespaces::CHART_EX); + + $dataSources = []; + foreach ($chartSpace->chartData->data as $data) { + $dataId = self::getAttributeInteger($data, 'id'); + if ($dataId !== null && isset($data->numDim->f)) { + $dataSources[$dataId] = (string) $data->numDim->f; + } + } + + $series = []; + + foreach ($chartSpace->chart->plotArea->plotAreaRegion->series as $seriesElement) { + if (self::getAttributeString($seriesElement, 'layoutId') !== BoxWhisker::TYPE) { + continue; + } + + $txData = $seriesElement->tx->txData; + $dataSource = (string) $txData->f; + + $label = null; + if ($dataSource === '') { + $categories = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, pointCount: 1, dataValues: [(string) $txData->v]); + } else { + $definedName = $spreadsheet->getDefinedName($dataSource); + $dataSource = $definedName === null ? $dataSource : $definedName->getValue(); + + $categories = new DataSeriesValues( + DataSeriesValues::DATASERIES_TYPE_STRING, + $dataSource + ); + + $label = new DataSeriesValues( + DataSeriesValues::DATASERIES_TYPE_STRING, + $dataSource + ); + } + + $dataId = self::getAttributeInteger($seriesElement->dataId, 'val'); + $valuesSource = $dataId === null ? null : ($dataSources[$dataId] ?? null); + + if ($valuesSource !== null) { + $definedName = $spreadsheet->getDefinedName($valuesSource); + if ($definedName !== null) { + $valuesSource = $definedName->getValue(); + } + + $values = new DataSeriesValues( + DataSeriesValues::DATASERIES_TYPE_NUMBER, + $valuesSource + ); + + $series[] = new BoxWhiskerSeries($categories, $values, $label); + } + } + + $boxWhisker = new BoxWhisker($series); + + $visibility = null; + $statistics = null; + + foreach ($chartSpace->chart->plotArea->plotAreaRegion->series as $seriesElement) { + if (self::getAttributeString($seriesElement, 'layoutId') === BoxWhisker::TYPE) { + $visibility = $seriesElement->layoutPr->visibility ?? null; + $statistics = $seriesElement->layoutPr->statistics ?? null; + + break; + } + } + + if ($visibility !== null) { + $boxWhisker->setShowMeanLine(self::getAttributeBoolean($visibility, 'meanLine') ?? false) + ->setShowMeanMarker(self::getAttributeBoolean($visibility, 'meanMarker') ?? true) + ->setShowInnerPoints(self::getAttributeBoolean($visibility, 'nonoutliers') ?? false) + ->setShowOutliers(self::getAttributeBoolean($visibility, 'outliers') ?? true); + } + + if ($statistics !== null) { + $quartileMethod = self::getAttributeString($statistics, 'quartileMethod'); + if ($quartileMethod !== null) { + $boxWhisker->setQuartileMethod($quartileMethod); + } + } + + $objChart = new \PhpOffice\PhpSpreadsheet\Chart\Chart($chartName); + $objChart->setChartEx($boxWhisker); + + if (isset($chartSpace->chart->title->tx->txData->v)) { + $objChart->setTitle( + new Title((string) $chartSpace->chart->title->tx->txData->v) + ); + } + + return $objChart; + } + private function chartTitle(SimpleXMLElement $titleDetails): Title { $caption = ''; @@ -987,7 +1091,7 @@ private function chartDataSeriesValuesMultiLevel(SimpleXMLElement $seriesValueSe $formatCode = ''; $pointCount = 0; - foreach ($seriesValueSet->lvl as $seriesLevelIdx => $seriesLevel) { + foreach ($seriesValueSet->lvl as $seriesLevel) { foreach ($seriesLevel as $seriesValueIdx => $seriesValue) { $seriesValue = Xlsx::testSimpleXml($seriesValue); switch ($seriesValueIdx) { diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php index 7af514cc..51f3dd60 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php @@ -5,8 +5,8 @@ use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter; +use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Reader\IReadFilter; -use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; @@ -152,15 +152,14 @@ private function readColumnAttributes(SimpleXMLElement $worksheetCols, bool $rea foreach ($worksheetCols->col as $columnx) { $column = $columnx->attributes(); if ($column !== null) { - $startColumn = Coordinate::stringFromColumnIndex((int) $column['min']); - $endColumn = Coordinate::stringFromColumnIndex((int) $column['max']); - StringHelper::stringIncrement($endColumn); - for ($columnAddress = $startColumn; $columnAddress !== $endColumn; StringHelper::stringIncrement($columnAddress)) { + $minCol = max((int) $column['min'], 1); + $maxCol = min((int) $column['max'], AddressRange::MAX_COLUMN_INT); + if ($minCol > $maxCol) { + throw new ReaderException('min col > max col'); + } + for ($col = $minCol; $col <= $maxCol; ++$col) { + $columnAddress = Coordinate::stringFromColumnIndex($col); $columnAttributes[$columnAddress] = $this->readColumnRangeAttributes($column, $readDataOnly); - - if ((int) ($column['max']) === AddressRange::MAX_COLUMN_INT) { - break; - } } } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php index c414c09f..cc971405 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php @@ -30,10 +30,14 @@ class Namespaces const CHART = 'http://schemas.openxmlformats.org/drawingml/2006/chart'; + const CHART_EX = 'http://schemas.microsoft.com/office/drawing/2014/chartex'; + const CHART_ALTERNATE = 'http://schemas.microsoft.com/office/drawing/2007/8/2/chart'; const RELATIONSHIPS_CHART = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart'; + const RELATIONSHIPS_CHART_EX = 'http://schemas.microsoft.com/office/2014/relationships/chartEx'; + const SPREADSHEET_DRAWING = 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'; const SCHEMA_OFFICE_DOCUMENT = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'; @@ -126,6 +130,8 @@ class Namespaces const DYNAMIC_ARRAY = 'http://schemas.microsoft.com/office/spreadsheetml/2017/dynamicarray'; + const DECORATIVE = 'http://schemas.microsoft.com/office/drawing/2017/decorative'; + const DYNAMIC_ARRAY_RICHDATA = 'http://schemas.microsoft.com/office/spreadsheetml/2017/richdata'; const RELATIONSHIPS_RICH_VALUE_TYPES = 'http://schemas.microsoft.com/office/2017/06/relationships/rdRichValueTypes'; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php index a792235a..52f6d9ae 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php @@ -46,6 +46,7 @@ public function readCoreProperties(string $propertyData): void $this->docProps->setSubject($this->getArrayItem($xmlCore->xpath('dc:subject'))); $this->docProps->setKeywords($this->getArrayItem($xmlCore->xpath('cp:keywords'))); $this->docProps->setCategory($this->getArrayItem($xmlCore->xpath('cp:category'))); + $this->docProps->setLanguage($this->getArrayItem($xmlCore->xpath('dc:language'))); } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php index 1ef14591..5a2fe368 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php @@ -205,7 +205,6 @@ public function readFillStyle(Fill $fillStyle, SimpleXMLElement $fillStyleXml): $bgFound = true; } - $type = ''; if ((string) $fillStyleXml->patternFill['patternType'] !== '') { $type = (string) $fillStyleXml->patternFill['patternType']; } else { diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/TableReader.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/TableReader.php index 5c4556e0..5f49706c 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/TableReader.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/TableReader.php @@ -60,7 +60,8 @@ private function readTable(string $tableRange, array $tableStyles, array $dxfs): $this->readTableStyle($table, $this->tableXml->tableStyleInfo, $tableStyles, $dxfs); (new AutoFilter($table, $this->tableXml))->load(); - $this->worksheet->addTable($table); + // The cells come from the file, and a read filter may have skipped the totals row + $this->worksheet->addTable($table, false); } /** @@ -101,6 +102,10 @@ private function readTableColumns(Table $table, SimpleXMLElement $tableColumnsXm if ($attributes['totalsRowFunction']) { $column->setTotalsRowFunction((string) $attributes['totalsRowFunction']); } + + if ($tableColumn->totalsRowFormula) { + $column->setTotalsRowFormula((string) $tableColumn->totalsRowFormula); + } } if ($tableColumn->calculatedColumnFormula) { diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php index 9e5bd997..8a718ec4 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php @@ -40,6 +40,9 @@ class Xml extends BaseReader */ protected array $styles = []; + /** @var string[] */ + private array $numberFormatMappings = Style\NumberFormat::FORMAT_MAPPINGS; + /** * Create a new Excel2003XML Reader instance. */ @@ -56,6 +59,8 @@ public static function unentity(string $contents): string { // fffe is invalid, replace with replacement char $contents = str_replace("\u{fffe}", "\u{fffd}", $contents); + // Excel allows X; Xml does not; changing to x allows both + $contents = Preg::replace('/&#X(?=[0-9a-fA-F]+;)/', '&#x', $contents); // use positive lookahead to "protect" valid xml entities $contents = Preg::replace('/&(?=(?:amp|lt|gt|quot|apos|#[0-9]+|#x[0-9a-fA-F]+);)/', "\u{fffe}", trim($contents)); // now decode remaining html entities @@ -128,27 +133,23 @@ private function trySimpleXMLLoadStringPrivate(string $filename, string $fileOrS $this->xmlFailMessage = "Cannot load invalid XML $fileOrString: " . $filename; $xml = false; - try { - $data = $this->fileContents; - $continue = true; - if ($data === '' && $fileOrString === 'file') { - if ($filename === '') { - $this->xmlFailMessage = 'Cannot load empty path'; - $continue = false; - } else { - $datax = @file_get_contents($filename); - $data = $datax ?: ''; - $continue = $datax !== false; - } + $data = $this->fileContents; + $continue = true; + if ($data === '' && $fileOrString === 'file') { + if ($filename === '') { + $this->xmlFailMessage = 'Cannot load empty path'; + $continue = false; + } else { + $datax = @file_get_contents($filename); + $data = $datax ?: ''; + $continue = $datax !== false; } - if ($continue) { - $xml = @simplexml_load_string( - $this->getSecurityScannerOrThrow() - ->scan($data) - ); - } - } catch (Throwable $e) { - throw new Exception($this->xmlFailMessage, 0, $e); + } + if ($continue) { + $xml = @simplexml_load_string( + $this->getSecurityScannerOrThrow() + ->scan($data) + ); } $this->fileContents = ''; @@ -208,13 +209,12 @@ public function listWorksheetInfo(string $filename): array $worksheet_ss = self::getAttributes($worksheet, self::NAMESPACES_SS); $tmpInfo = []; - $tmpInfo['worksheetName'] = ''; - $tmpInfo['lastColumnLetter'] = 'A'; + $tmpInfo['worksheetName'] = "Worksheet_{$worksheetID}"; + $tmpInfo['lastColumnLetter'] = 'A'; //* @phpstan-ignore assign.overwritten (preserve array order) $tmpInfo['lastColumnIndex'] = 0; $tmpInfo['totalRows'] = 0; - $tmpInfo['totalColumns'] = 0; + $tmpInfo['totalColumns'] = 0; //* @phpstan-ignore assign.overwritten (preserve array order) - $tmpInfo['worksheetName'] = "Worksheet_{$worksheetID}"; if (isset($worksheet_ss['Name'])) { $tmpInfo['worksheetName'] = (string) $worksheet_ss['Name']; } @@ -307,7 +307,7 @@ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet, boo (new Properties($spreadsheet))->readProperties($xml, $namespaces); - $this->styles = (new Style())->parseStyles($xml, $namespaces); + $this->styles = (new Style())->parseStyles($xml, $namespaces, $this->numberFormatMappings); if (isset($this->styles['Default']) && is_array($this->styles['Default'])) { $spreadsheet->getCellXfCollection()[0]->applyFromArray($this->styles['Default']); } @@ -513,8 +513,13 @@ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet, boo break; case 'DateTime': $type = DataType::TYPE_NUMERIC; - $dateTime = new DateTime($cellValue, new DateTimeZone('UTC')); - $cellValue = Date::PHPToExcel($dateTime); + + try { + $dateTime = new DateTime($cellValue, new DateTimeZone('UTC')); + $cellValue = Date::PHPToExcel($dateTime); + } catch (Throwable) { + $type = DataType::TYPE_STRING; + } break; case 'Error': @@ -609,12 +614,18 @@ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet, boo } $leftTopRow = (string) $xmlX->WorksheetOptions->TopRowBottomPane; $leftTopColumn = (string) $xmlX->WorksheetOptions->LeftColumnRightPane; + $leftTopCoordinateParm = null; if (is_numeric($leftTopRow) && is_numeric($leftTopColumn)) { - $leftTopCoordinate = Coordinate::stringFromColumnIndex((int) $leftTopColumn + 1) . (string) ($leftTopRow + 1); - $spreadsheet->getActiveSheet()->freezePane(Coordinate::stringFromColumnIndex($freezeColumn) . (string) $freezeRow, $leftTopCoordinate, !isset($xmlX->WorksheetOptions->FrozenNoSplit)); - } else { - $spreadsheet->getActiveSheet()->freezePane(Coordinate::stringFromColumnIndex($freezeColumn) . (string) $freezeRow, null, !isset($xmlX->WorksheetOptions->FrozenNoSplit)); + $leftTopCoordinateParm = $leftTopCoordinate = Coordinate::stringFromColumnIndex((int) $leftTopColumn + 1) . (string) ($leftTopRow + 1); //* @phpstan-ignore assign.overwritten (Phpstan is probably right but it's hard to see why) } + $spreadsheet->getActiveSheet()->freezePane( + Coordinate::stringFromColumnIndex( + $freezeColumn + ) + . (string) $freezeRow, + $leftTopCoordinateParm, + !isset($xmlX->WorksheetOptions->FrozenNoSplit) + ); } elseif (isset($xmlX->WorksheetOptions->SplitVertical) || isset($xmlX->WorksheetOptions->SplitHorizontal)) { if (isset($xmlX->WorksheetOptions->SplitHorizontal)) { $ySplit = (int) $xmlX->WorksheetOptions->SplitHorizontal; @@ -757,8 +768,13 @@ protected function parseRichText(string $annotation): RichText private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { - return ($simple === null) - ? new SimpleXMLElement('') - : ($simple->attributes($node) ?? new SimpleXMLElement('')); + return ($simple === null) ? new SimpleXMLElement('') : ($simple->attributes($node) ?? new SimpleXMLElement('')); + } + + public function setNumberFormatMapping(string $key, string $value): self + { + $this->numberFormatMappings[$key] = $value; + + return $this; } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/DataValidations.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/DataValidations.php index 74d7ec46..6d2527dc 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/DataValidations.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/DataValidations.php @@ -61,7 +61,6 @@ public function loadDataValidations(SimpleXMLElement $worksheet, Spreadsheet $sp switch ($tagName) { case 'Range': foreach (explode(',', $tagValue) as $range) { - $cell = ''; if (preg_match('/^R(\d+)C(\d+):R(\d+)C(\d+)$/', (string) $range, $selectionMatches) === 1) { // range $firstCell = Coordinate::stringFromColumnIndex((int) $selectionMatches[2]) diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php index 699d7182..f4ab459b 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php @@ -16,10 +16,11 @@ class Style /** * @param string[] $namespaces + * @param string[] $numberFormatMappings * * @return mixed[] */ - public function parseStyles(SimpleXMLElement $xml, array $namespaces): array + public function parseStyles(SimpleXMLElement $xml, array $namespaces, array $numberFormatMappings = Style\NumberFormat::FORMAT_MAPPINGS): array { $children = $xml->children('urn:schemas-microsoft-com:office:spreadsheet'); $stylesXml = $children->Styles[0]; @@ -70,7 +71,7 @@ public function parseStyles(SimpleXMLElement $xml, array $namespaces): array break; case 'NumberFormat': if ($styleAttributes) { - $numberFormat = $numberFormatStyleParser->parseStyle($styleAttributes); + $numberFormat = $numberFormatStyleParser->parseStyle($styleAttributes, $numberFormatMappings); } break; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php index 1ca825a5..83ce6a4b 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php @@ -2,29 +2,57 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xml\Style; +use PhpOffice\PhpSpreadsheet\Shared\StringHelper; +use PhpOffice\PhpSpreadsheet\Style\NumberFormat as Format; use SimpleXMLElement; class NumberFormat extends StyleBase { - /** @return mixed[] */ - public function parseStyle(SimpleXMLElement $styleAttributes): array + /** @internal */ + public const FORMAT_MAPPINGS = [ + 'Euro Currency' => '€#,##0.00;[Red](€#,##0.00)', + 'Fixed' => Format::FORMAT_NUMBER_00, + 'General' => '', + 'General Number' => '', + 'General Date' => Format::FORMAT_DATE_DATETIME_BETTER, + 'Long Date' => Format::FORMAT_DATE_LONG_DATE, + 'Long Time' => Format::FORMAT_DATE_TIME2, + 'Medium Date' => Format::FORMAT_DATE_XLSX15_YYYY, + 'Medium Time' => Format::FORMAT_DATE_TIME1, + 'Percent' => Format::FORMAT_PERCENTAGE_00, + 'Scientific' => '0.00E+00', + 'Short Date' => Format::FORMAT_DATE_YYYYMMDD, + 'Short Time' => Format::FORMAT_DATE_TIME1, + 'Standard' => Format::FORMAT_NUMBER_COMMA_SEPARATED1, + // N.B. - following formats apply to numbers, not booleans + 'True/False' => '"True";"True";"False"', + 'Yes/No' => '"Yes";"Yes";"No"', + 'On/Off' => '"On";"On";"Off"', + ]; + + /** + * @param string[] $numberFormatMappings expected to be FORMAT_MAPPINGS, but individual entries can be overridden + * + * @return mixed[] + */ + public function parseStyle(SimpleXMLElement $styleAttributes, array $numberFormatMappings = self::FORMAT_MAPPINGS): array { $style = []; $fromFormats = ['\-', '\ ']; $toFormats = ['-', ' ']; - foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { - $styleAttributeValue = str_replace($fromFormats, $toFormats, (string) $styleAttributeValue); - - switch ($styleAttributeValue) { - case 'Short Date': - $styleAttributeValue = 'dd/mm/yyyy'; - - break; + foreach ($styleAttributes as $styleAttributeValue) { + $styleAttributeValue = (string) $styleAttributeValue; + $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue); + if (array_key_exists($styleAttributeValue, $numberFormatMappings)) { + $styleAttributeValue = $numberFormatMappings[$styleAttributeValue]; + } elseif ($styleAttributeValue === 'Currency') { + $currencyCode = StringHelper::getCurrencyCode(); + $styleAttributeValue = "{$currencyCode}#,##0.00;[Red]({$currencyCode}#,##0.00)"; } - if ($styleAttributeValue > '') { + if ($styleAttributeValue !== '') { $style['numberFormat']['formatCode'] = $styleAttributeValue; } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php index 03b76c75..5ac93f50 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php @@ -257,6 +257,7 @@ protected function adjustDataValidations(Worksheet $worksheet, int $numberOfColu ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aDataValidationCollection, [self::class, 'cellReverseSort']) : uksort($aDataValidationCollection, [self::class, 'cellSort']); + $remove = $numberOfColumns < 0 || $numberOfRows < 0; foreach ($aDataValidationCollection as $cellAddress => $dataValidation) { $formula = $dataValidation->getFormula1(); @@ -285,23 +286,67 @@ protected function adjustDataValidations(Worksheet $worksheet, int $numberOfColu ) ); } - $addressParts = explode(' ', $cellAddress); - $newReference = ''; - $separator = ''; - foreach ($addressParts as $addressPart) { - $newReference .= $separator . $this->updateCellReference($addressPart); - $separator = ' '; + $newReferences = []; + foreach (explode(' ', $cellAddress) as $addressPart) { + $newReference = $remove + ? $this->updateDataValidationReferenceForRemove($addressPart) + : $this->updateCellReference($addressPart); + if ($newReference !== '') { + $newReferences[] = $newReference; + } } + $newReference = implode(' ', $newReferences); if ($cellAddress !== $newReference) { - $worksheet->setDataValidation($newReference, $dataValidation); $worksheet->setDataValidation($cellAddress, null); - if ($newReference) { + if ($newReference !== '') { $worksheet->setDataValidation($newReference, $dataValidation); } } } } + /** + * Update a data validation cell or range when removing rows/columns. + * Removed rows/columns are taken out of the range, + * and an empty string is returned when nothing of the range is left. + */ + private function updateDataValidationReferenceForRemove(string $reference): string + { + /** @var CellReferenceHelper */ + $cellReferenceHelper = $this->cellReferenceHelper; + if (!Coordinate::coordinateIsRange($reference)) { + return $cellReferenceHelper->cellAddressInDeleteRange($reference) + ? '' + : $cellReferenceHelper->updateCellReference($reference); + } + + [$rangeStart] = Coordinate::splitRange($reference)[0]; + [[$startColumn, $startRow], [$endColumn, $endRow]] = Coordinate::rangeBoundaries($reference); + $startColumn = $cellReferenceHelper->computeNewColumnIndex($startColumn, true); + $endColumn = $cellReferenceHelper->computeNewColumnIndex($endColumn, false); + $startRow = $cellReferenceHelper->computeNewRowIndex($startRow, true); + $endRow = $cellReferenceHelper->computeNewRowIndex($endRow, false); + + if (ctype_digit($rangeStart)) { + // Whole row(s), e.g. 2:3 + return ($endRow < $startRow) ? '' : "$startRow:$endRow"; + } + if ($endColumn < $startColumn) { + return ''; + } + $startColumnString = Coordinate::stringFromColumnIndex($startColumn); + $endColumnString = Coordinate::stringFromColumnIndex($endColumn); + if (ctype_alpha($rangeStart)) { + // Whole column(s), e.g. B:C + return "$startColumnString:$endColumnString"; + } + if ($endRow < $startRow) { + return ''; + } + + return "$startColumnString$startRow:$endColumnString$endRow"; + } + /** * Update merged cells when inserting/deleting rows/columns. * @@ -336,7 +381,7 @@ protected function adjustProtectedCells(Worksheet $worksheet, int $numberOfColum foreach ($aProtectedCells as $key2 => $value) { $ranges = $value->allRanges(); $newKey = $separator = ''; - foreach ($ranges as $key => $range) { + foreach ($ranges as $range) { $oldKey = $range[0] . (array_key_exists(1, $range) ? (':' . $range[1]) : ''); $newKey .= $separator . $this->updateCellReference($oldKey); $separator = ' '; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php index da5a36b2..fa9a8716 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php @@ -62,7 +62,7 @@ public static function fileExists(string $filename): bool $zip = new ZipArchive(); $res = $zip->open($zipFile); if ($res === true) { - $returnValue = ($zip->getFromName($archiveFile) !== false); + $returnValue = $zip->statName($archiveFile) !== false; $zip->close(); return $returnValue; @@ -78,34 +78,24 @@ public static function fileExists(string $filename): bool /** * Returns canonicalized absolute pathname, also for ZIP archives. */ - public static function realpath(string $filename): string + public static function realpath(string $filename, bool $trimLeadingSlash = false): string { - // Returnvalue - $returnValue = ''; - - // Try using realpath() - if (file_exists($filename)) { - $returnValue = realpath($filename) ?: ''; + if ($trimLeadingSlash && substr($filename, 0, 1) === '/') { // Apache POI + $filename = substr($filename, 1); } - - // Found something? - if ($returnValue === '') { - $pathArray = explode('/', $filename); - while (in_array('..', $pathArray) && $pathArray[0] != '..') { - $iMax = count($pathArray); - for ($i = 1; $i < $iMax; ++$i) { - if ($pathArray[$i] == '..') { - array_splice($pathArray, $i - 1, 2); - - break; - } + $pathArray = Preg::split('~[/\\\]~', $filename); + while (in_array('..', $pathArray, true) && $pathArray[0] !== '..') { + $iMax = count($pathArray); + for ($i = 1; $i < $iMax; ++$i) { + if ($pathArray[$i] === '..') { + array_splice($pathArray, $i - 1, 2); + + break; } } - $returnValue = implode('/', $pathArray); } - // Return - return $returnValue; + return implode('/', $pathArray); } /** diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php index 3b0afbde..f08c2718 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php @@ -375,7 +375,7 @@ public static function calculateColumnWidth( $lineTexts = explode("\n", $cellText); $lineWidths = []; foreach ($lineTexts as $lineText) { - $lineWidths[] = self::calculateColumnWidth($font, $lineText, $rotation = 0, $defaultFont, $filterAdjustment); + $lineWidths[] = self::calculateColumnWidth($font, $lineText, 0, $defaultFont, $filterAdjustment); } return max($lineWidths); // width of longest line in cell diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Metafile.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Metafile.php new file mode 100644 index 00000000..b3cf7fea --- /dev/null +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Metafile.php @@ -0,0 +1,137 @@ +loadFromString($content)) { + $image = $reader->getResource(); + if ($image instanceof GdImage) { + return $image; + } + } + } catch (Throwable $e) { + throw new Exception('Unable to render metafile: ' . $e->getMessage(), 0, $e); + } + + throw new Exception('Unable to render metafile'); + } + + /** + * Render a metafile as PNG data. + * + * @throws Exception + */ + public static function toPng(string $content): string + { + return self::encodePng(self::toGdImage($content)); + } + + /** + * Render a metafile as a GD image, or null if it can not be rendered. + */ + public static function tryToGdImage(?string $content): ?GdImage + { + if ($content === null) { + return null; + } + + try { + return self::toGdImage($content); + } catch (Exception) { + return null; + } + } + + /** + * Render a metafile as PNG data, or null if it can not be rendered. + */ + public static function tryToPng(?string $content): ?string + { + $image = self::tryToGdImage($content); + + return ($image === null) ? null : self::encodePng($image); + } + + private static function encodePng(GdImage $image): string + { + ob_start(); + imagepng($image); + + return (string) ob_get_clean(); + } +} diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS.php index dae381b0..8e992a86 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS.php @@ -20,6 +20,7 @@ // | Based on OLE::Storage_Lite by Kawai, Takanori | // +----------------------------------------------------------------------+ // +use InvalidArgumentException; use PhpOffice\PhpSpreadsheet\Shared\OLE; /** @@ -31,6 +32,10 @@ class PPS { private const ALL_ONE_BITS = (PHP_INT_SIZE > 4) ? 0xFFFFFFFF : -1; + private const COLOR_RED = 0; + + private const COLOR_BLACK = 1; + /** * The PPS index. */ @@ -61,6 +66,11 @@ class PPS */ public int $DirPps; + /** + * The color in the directory entry red-black tree. + */ + public int $Color = self::COLOR_BLACK; + /** * A timestamp. */ @@ -148,21 +158,25 @@ public function getDataLen(): int */ public function getPpsWk(): string { - $ret = str_pad($this->Name, 64, "\x00"); + $name = self::validateName($this->Name); + $creationTime = $this->Type === OLE::OLE_PPS_TYPE_FILE || $this->Type === OLE::OLE_PPS_TYPE_ROOT + ? str_repeat("\x00", 8) + : OLE::localDateToOLE($this->Time1st); + $modifiedTime = $this->Type === OLE::OLE_PPS_TYPE_FILE + ? str_repeat("\x00", 8) + : OLE::localDateToOLE($this->Time2nd); + $ret = str_pad($name . "\x00\x00", 64, "\x00"); - $ret .= pack('v', strlen($this->Name) + 2) // 66 - . pack('c', $this->Type) // 67 - . pack('c', 0x00) //UK // 68 + $ret .= pack('v', strlen($name) + 2) // 66 + . pack('C', $this->Type) // 67 + . pack('C', $this->Color) // 68 . pack('V', $this->PrevPps) //Prev // 72 . pack('V', $this->NextPps) //Next // 76 . pack('V', $this->DirPps) //Dir // 80 - . "\x00\x09\x02\x00" // 84 - . "\x00\x00\x00\x00" // 88 - . "\xc0\x00\x00\x00" // 92 - . "\x00\x00\x00\x46" // 96 // Seems to be ok only for Root - . "\x00\x00\x00\x00" // 100 - . OLE::localDateToOLE($this->Time1st) // 108 - . OLE::localDateToOLE($this->Time2nd) // 116 + . str_repeat("\x00", 16) // 96 CLSID + . pack('V', 0) // 100 State bits + . $creationTime // 108 + . $modifiedTime // 116 . pack('V', $this->startBlock ?? 0) // 120 . pack('V', $this->Size) // 124 . pack('V', 0); // 128 @@ -171,8 +185,8 @@ public function getPpsWk(): string } /** - * Updates index and pointers to previous, next and children PPS's for this - * PPS. I don't think it'll work with Dir PPS's. + * Assigns directory IDs and sibling/child pointers using CFB name order + * and valid red-black trees, recursively including nested storages. * * @param self[] $raList Reference to the array of PPS's for the whole OLE * container @@ -185,27 +199,139 @@ public static function savePpsSetPnt(array &$raList, mixed $to_save, int $depth return self::ALL_ONE_BITS; } /** @var self[] $to_save */ - if (count($to_save) == 1) { - $cnt = count($raList); - // If the first entry, it's the root... Don't clone it! - $raList[$cnt] = ($depth == 0) ? $to_save[0] : clone $to_save[0]; - $raList[$cnt]->No = $cnt; - $raList[$cnt]->PrevPps = self::ALL_ONE_BITS; - $raList[$cnt]->NextPps = self::ALL_ONE_BITS; - $raList[$cnt]->DirPps = self::savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); - } else { - $iPos = (int) floor(count($to_save) / 2); - $aPrev = array_slice($to_save, 0, $iPos); - $aNext = array_slice($to_save, $iPos + 1); - $cnt = count($raList); - // If the first entry, it's the root... Don't clone it! - $raList[$cnt] = ($depth == 0) ? $to_save[$iPos] : clone $to_save[$iPos]; - $raList[$cnt]->No = $cnt; - $raList[$cnt]->PrevPps = self::savePpsSetPnt($raList, $aPrev, $depth++); - $raList[$cnt]->NextPps = self::savePpsSetPnt($raList, $aNext, $depth++); - $raList[$cnt]->DirPps = self::savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); + $tree = self::buildSiblingTree($to_save); + + return self::saveSiblingTree($raList, $tree, $depth); + } + + /** @param self[] $ppsEntries */ + private static function buildSiblingTree(array $ppsEntries): PPSTreeNode + { + foreach ($ppsEntries as $pps) { + self::validateName($pps->Name); + } + usort($ppsEntries, [self::class, 'comparePpsNames']); + for ($index = 1, $count = count($ppsEntries); $index < $count; ++$index) { + if (self::comparePpsNames($ppsEntries[$index - 1], $ppsEntries[$index]) === 0) { + throw new InvalidArgumentException('OLE PPS sibling names must be unique.'); + } + } + + return self::buildTreeFromSortedEntries( + $ppsEntries, + 0, + count($ppsEntries) - 1, + 0, + self::redLevel(count($ppsEntries)) + ); + } + + /** + * @param self[] $ppsEntries + */ + private static function buildTreeFromSortedEntries(array $ppsEntries, int $first, int $last, int $level, int $redLevel): PPSTreeNode + { + $middle = $first + intdiv($last - $first, 2); + $node = new PPSTreeNode($ppsEntries[$middle]); + $node->color = $level === $redLevel ? self::COLOR_RED : self::COLOR_BLACK; + if ($first < $middle) { + $node->left = self::buildTreeFromSortedEntries($ppsEntries, $first, $middle - 1, $level + 1, $redLevel); + } + if ($middle < $last) { + $node->right = self::buildTreeFromSortedEntries($ppsEntries, $middle + 1, $last, $level + 1, $redLevel); + } + + return $node; + } + + private static function redLevel(int $entryCount): int + { + $level = 0; + for ($nodes = $entryCount - 1; $nodes >= 0; $nodes = intdiv($nodes, 2) - 1) { + ++$level; } + return $level; + } + + /** @param self[] $raList */ + private static function saveSiblingTree(array &$raList, PPSTreeNode $node, int $depth): int + { + $cnt = count($raList); + $raList[$cnt] = ($depth === 0) ? $node->pps : clone $node->pps; + $raList[$cnt]->No = $cnt; + $raList[$cnt]->Color = $node->color; + $raList[$cnt]->PrevPps = $node->left === null ? self::ALL_ONE_BITS : self::saveSiblingTree($raList, $node->left, $depth + 1); + $raList[$cnt]->NextPps = $node->right === null ? self::ALL_ONE_BITS : self::saveSiblingTree($raList, $node->right, $depth + 1); + $raList[$cnt]->DirPps = self::savePpsSetPnt($raList, $raList[$cnt]->children, $depth + 1); + return $cnt; } + + private static function comparePpsNames(self $left, self $right): int + { + $leftName = self::uppercaseCodeUnits($left->Name); + $rightName = self::uppercaseCodeUnits($right->Name); + $length = count($leftName) <=> count($rightName); + if ($length !== 0) { + return $length; + } + + foreach ($leftName as $index => $codeUnit) { + $comparison = $codeUnit <=> $rightName[$index]; + if ($comparison !== 0) { + return $comparison; + } + } + + return 0; + } + + /** @return list */ + private static function uppercaseCodeUnits(string $name): array + { + $codeUnits = []; + for ($offset = 0, $length = strlen($name); $offset < $length; $offset += 2) { + $codeUnit = ord($name[$offset]) | (ord($name[$offset + 1]) << 8); + if ($codeUnit >= 0xD800 && $codeUnit <= 0xDFFF) { + // CFB compares surrogate code units without applying case conversion. + $codeUnits[] = $codeUnit; + + continue; + } + $character = mb_convert_encoding(pack('v', $codeUnit), 'UTF-8', 'UTF-16LE'); + $uppercase = mb_convert_case($character, MB_CASE_UPPER_SIMPLE, 'UTF-8'); + $utf16 = mb_convert_encoding($uppercase, 'UTF-16LE', 'UTF-8'); + $codeUnits[] = ord($utf16[0]) | (ord($utf16[1]) << 8); + } + + return $codeUnits; + } + + private static function validateName(string $name): string + { + if ((strlen($name) % 2) !== 0 || strlen($name) > 62) { + throw new InvalidArgumentException('OLE PPS names must contain at most 31 UTF-16LE code units.'); + } + for ($offset = 0, $length = strlen($name); $offset < $length; $offset += 2) { + $codeUnit = ord($name[$offset]) | (ord($name[$offset + 1]) << 8); + if ($codeUnit === 0 || in_array($codeUnit, [0x2F, 0x5C, 0x3A, 0x21], true)) { + throw new InvalidArgumentException('OLE PPS names contain an invalid character.'); + } + if ($codeUnit >= 0xD800 && $codeUnit <= 0xDBFF) { + $offset += 2; + if ($offset >= $length) { + throw new InvalidArgumentException('OLE PPS names must be well-formed UTF-16LE.'); + } + $followingCodeUnit = ord($name[$offset]) | (ord($name[$offset + 1]) << 8); + if ($followingCodeUnit < 0xDC00 || $followingCodeUnit > 0xDFFF) { + throw new InvalidArgumentException('OLE PPS names must be well-formed UTF-16LE.'); + } + } elseif ($codeUnit >= 0xDC00 && $codeUnit <= 0xDFFF) { + throw new InvalidArgumentException('OLE PPS names must be well-formed UTF-16LE.'); + } + } + + return $name; + } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php index 9dca5067..3aaab5c8 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php @@ -109,7 +109,7 @@ public function save($fileHandle): bool private function calcSize(array &$raList): array { // Calculate Basic Setting - [$iSBDcnt, $iBBcnt, $iPPScnt] = [0, 0, 0]; + $iBBcnt = 0; $iSBcnt = 0; $iCount = count($raList); for ($i = 0; $i < $iCount; ++$i) { @@ -326,7 +326,11 @@ private function savePps(array &$raList): void $iCnt = count($raList); $iBCnt = $this->bigBlockSize / OLE::OLE_PPS_SIZE; if ($iCnt % $iBCnt) { - fwrite($this->fileHandle, str_repeat("\x00", ($iBCnt - ($iCnt % $iBCnt)) * OLE::OLE_PPS_SIZE)); + // MS-CFB 2.6.3: unused entries are zero except for NOSTREAM tree pointers. + $unusedEntry = str_repeat("\x00", 68) + . str_repeat("\xFF", 12) + . str_repeat("\x00", 48); + fwrite($this->fileHandle, str_repeat($unusedEntry, (int) ($iBCnt - ($iCnt % $iBCnt)))); } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPSTreeNode.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPSTreeNode.php new file mode 100644 index 00000000..6960b63c --- /dev/null +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPSTreeNode.php @@ -0,0 +1,21 @@ +bigBlockChain = ''; $bbs = self::BIG_BLOCK_SIZE / 4; for ($i = 0; $i < $this->numBigBlockDepotBlocks; ++$i) { $pos = ($bigBlockDepotBlocks[$i] + 1) * self::BIG_BLOCK_SIZE; $this->bigBlockChain .= substr($this->data, $pos, 4 * $bbs); - $pos += 4 * $bbs; + $pos += 4 * $bbs; //* @phpstan-ignore assign.overwritten (code clarity) } $sbdBlock = $this->sbdStartBlock; @@ -146,7 +145,7 @@ public function read(string $filename): void $pos = ($sbdBlock + 1) * self::BIG_BLOCK_SIZE; $this->smallBlockChain .= substr($this->data, $pos, 4 * $bbs); - $pos += 4 * $bbs; + $pos += 4 * $bbs; //* @phpstan-ignore assign.overwritten (code clarity) $sbdBlock = self::getInt4d($this->bigBlockChain, $sbdBlock * 4); } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Xlsx/AgileEncryption.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Xlsx/AgileEncryption.php index f41c4071..54c7198c 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Xlsx/AgileEncryption.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Xlsx/AgileEncryption.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Shared\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Exception; +use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Shared\File as SharedFile; use PhpOffice\PhpSpreadsheet\Shared\OLE; use SimpleXMLElement; @@ -109,7 +110,7 @@ public static function parse(string $encryptionInfo, int $maxSpinCount = self::M throw new Exception('Unsupported XLSX encryption profile.'); } - $xml = @simplexml_load_string(substr($encryptionInfo, 8)); + $xml = @simplexml_load_string((new XmlScanner())->scan(substr($encryptionInfo, 8))); if (!$xml instanceof SimpleXMLElement) { throw new Exception('Malformed XLSX encryption information.'); } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php index b8b95273..8b091c06 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php @@ -390,9 +390,6 @@ public function getWrapText(): bool */ public function setWrapText(bool $wrapped): static { - if ($wrapped == '') { - $wrapped = false; - } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['wrapText' => $wrapped]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); @@ -422,9 +419,6 @@ public function getShrinkToFit(): bool */ public function setShrinkToFit(bool $shrink): static { - if ($shrink == '') { - $shrink = false; - } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['shrinkToFit' => $shrink]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalColorScale.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalColorScale.php index 65beebd8..b77ae7f3 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalColorScale.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalColorScale.php @@ -122,9 +122,9 @@ public function setScaleArray(): self if ($this->sqref !== null && $this->worksheet !== null) { $values = $this->worksheet->rangesToArray($this->sqref, null, true, false, true); $this->valueArray = []; - foreach ($values as $key => $value) { + foreach ($values as $value) { /** @var array $value */ - foreach ($value as $k => $v) { + foreach ($value as $v) { $this->valueArray[] = (float) $v; } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php index 3a715668..fd25c969 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php @@ -63,9 +63,9 @@ private static function splitFormatForSectionSelection(array $sections, mixed $v // Colour could be a named colour, or a numeric index entry in the colour-palette $color_regex = '/\[(' . implode('|', Color::NAMED_COLORS) . '|color\s*(\d+))\]/mui'; $cond_regex = '/\[(>|>=|<|<=|=|<>)([+-]?\d+([.]\d+)?)\]/'; - $colors = ['', '', '', '', '']; - $conditionOperations = ['', '', '', '', '']; - $conditionComparisonValues = [0, 0, 0, 0, 0]; + $colors = ['', '', '', '', '']; //* @phpstan-ignore array.unusedOffset (unreasonably strict), array.unusedOffset (ditto) + $conditionOperations = ['', '', '', '', '']; //* @phpstan-ignore array.unusedOffset (unreasonably strict), array.unusedOffset (ditto), array.unusedOffset (ditto) + $conditionComparisonValues = [0, 0, 0, 0, 0]; //* @phpstan-ignore array.unusedOffset (unreasonably strict), array.unusedOffset (ditto), array.unusedOffset (ditto) for ($idx = 0; $idx < $sectionCount; ++$idx) { if (preg_match($color_regex, $sections[$idx], $matches)) { if (isset($matches[2])) { @@ -135,7 +135,7 @@ public static function toFormattedString($value, string $format, ?callable $call // Process a single block format code containing @ for text substitution $formatx = str_replace('\"', self::QUOTE_REPLACEMENT, $format); if (preg_match(self::SECTION_SPLIT, $format) === 0 && preg_match(self::SYMBOL_AT, $formatx) === 1) { - if (!str_contains($format, '"')) { + if (!str_contains($format, '"') && !str_contains($format, '\\')) { $temp = str_replace('@', StringHelper::convertToString($value, lessFloatPrecision: $lessFloatPrecision), $format); if (is_callable($callBack)) { $temp = $callBack($temp, $format); @@ -143,10 +143,12 @@ public static function toFormattedString($value, string $format, ?callable $call return $temp; } - //escape any dollar signs on the string, so they are not replaced with an empty value + // Convert any escaped characters to quoted strings, e.g. (\X to "X") + $formatx = (string) preg_replace('/\\\(.)(?=(?:[^"]|"[^"]*")*$)/u', '"${1}"', $formatx); + //escape any backslashes and dollar signs on the string, so they are not treated as references $value = str_replace( - ['$', '"'], - ['\$', self::QUOTE_REPLACEMENT], + ['\\', '$', '"'], + ['\\\\', '\$', self::QUOTE_REPLACEMENT], StringHelper::convertToString($value, lessFloatPrecision: $lessFloatPrecision) ); $temp = preg_replace(self::SYMBOL_AT, $value, $formatx) ?? $value; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php index 7affc215..f9aa8b10 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php @@ -9,6 +9,11 @@ class FractionFormatter extends BaseFormatter /** @param null|bool|float|int|string $value value to be formatted */ public static function format(mixed $value, string $format): string { + // A 0 placeholder for the last digit of the numerator shows a numerator of 0 + $showZeroNumerator = str_contains($format, '0/'); + // It's a dirty hack; but replace # and 0 digit placeholders with ? + $format = (string) preg_replace('/[#0]+\//', '?/', $format); + $format = (string) preg_replace('/\/[#0]+/', '/?', $format); $format = self::stripQuotes($format); $value = (float) $value; $absValue = abs($value); @@ -17,25 +22,36 @@ public static function format(mixed $value, string $format): string $integerPart = floor($absValue); - $decimalPart = self::getDecimal((string) $absValue); - if ($decimalPart === '0') { - return "{$sign}{$integerPart}"; - } - $decimalLength = strlen($decimalPart); - $decimalDivisor = 10 ** $decimalLength; - preg_match('/(#?.*\?)\/(\?+|\d+)/', $format, $matches); $formatIntegerPart = $matches[1] ?? '0'; + $fixedDivisor = (isset($matches[2]) && is_numeric($matches[2])) ? (int) $matches[2] : null; + $isVulgar = !str_contains($formatIntegerPart, '0') + && !str_contains($formatIntegerPart, '#') + && !str_starts_with($formatIntegerPart, '? ?'); - if (isset($matches[2]) && is_numeric($matches[2])) { - $fractionDivisor = 100 / (int) $matches[2]; + $decimalPart = self::getDecimal((string) $absValue); + if ($decimalPart === '0') { + // An integer is written as a fraction when the format has no integer part, + // or when the numerator shows 0; otherwise the fraction is left out + if (!$isVulgar && !$showZeroNumerator) { + return "{$sign}{$integerPart}"; + } + $adjustedDecimalPart = 0; + $adjustedDecimalDivisor = $fixedDivisor ?? 1; } else { - /** @var float $fractionDivisor */ - $fractionDivisor = MathTrig\Gcd::evaluate((int) $decimalPart, $decimalDivisor); - } + $decimalLength = strlen($decimalPart); + $decimalDivisor = 10 ** $decimalLength; + + if ($fixedDivisor !== null) { + $fractionDivisor = 100 / $fixedDivisor; + } else { + /** @var float $fractionDivisor */ + $fractionDivisor = MathTrig\Gcd::evaluate((int) $decimalPart, $decimalDivisor); + } - $adjustedDecimalPart = (int) round((int) $decimalPart / $fractionDivisor, 0); - $adjustedDecimalDivisor = $decimalDivisor / $fractionDivisor; + $adjustedDecimalPart = (int) round((int) $decimalPart / $fractionDivisor, 0); + $adjustedDecimalDivisor = $decimalDivisor / $fractionDivisor; + } if ((str_contains($formatIntegerPart, '0'))) { return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/NumberFormatter.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/NumberFormatter.php index 22b02b12..a6240bc1 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/NumberFormatter.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/NumberFormatter.php @@ -208,9 +208,6 @@ public static function format(mixed $value, string $format): string $scale = self::scaleThousandsMillions($format); if (preg_match('/[#\?0]?.*[#\?0]\/(\?+|\d+|#)/', $format)) { - // It's a dirty hack; but replace # and 0 digit placeholders with ? - $format = (string) preg_replace('/[#0]+\//', '?/', $format); - $format = (string) preg_replace('/\/[#0]+/', '/?', $format); $value = FractionFormatter::format($value, $format); } else { // Handle the number itself diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php index 9df62897..969d13e6 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php @@ -443,16 +443,6 @@ public function applyFromArray(array $styleArray, bool $advancedBorders = true): /** @var Style $existingStyle */ $newXfIndexes[$oldXfIndex] = $existingStyle->getIndex(); } else { - if (!isset($newStyle)) { - // Handle bug in PHPStan, see https://github.com/phpstan/phpstan/issues/5805 - // $newStyle should always be defined. - // This block might not be needed in the future - // @codeCoverageIgnoreStart - $newStyle = clone $style; - $newStyle->applyFromArray($styleArray); - // @codeCoverageIgnoreEnd - } - // we don't have such a cell Xf, need to add $workbook->addCellXf($newStyle); $newXfIndexes[$oldXfIndex] = $newStyle->getIndex(); @@ -711,9 +701,6 @@ public function getQuotePrefix(): bool */ public function setQuotePrefix(bool $quotePrefix): static { - if ($quotePrefix == '') { - $quotePrefix = false; - } if ($this->isSupervisor) { $styleArray = ['quotePrefix' => $quotePrefix]; $this->getActiveSheet() diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php index ad733025..f0e4edac 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php @@ -223,7 +223,7 @@ public function getColumn(string $column): AutoFilter\Column */ public function getColumnByOffset(int $columnOffset): AutoFilter\Column { - [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); + [$rangeStart] = Coordinate::rangeBoundaries($this->range); $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset); return $this->getColumn($pColumn); @@ -894,7 +894,7 @@ public function showHideRows(): static // Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards $ruleValue = WildcardMatch::wildcard($ruleValue); if (trim($ruleValue) == '') { - $customRuleForBlanks = true; + $customRuleForBlanks = true; //* @phpstan-ignore assign.redundant (code clarity) $ruleValue = trim($ruleValue); } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php index a14cdf63..be8417d7 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php @@ -44,6 +44,11 @@ class BaseDrawing implements IComparable */ protected string $description = ''; + /** + * A decorative drawing adds nothing to the content: assistive technology skips it. + */ + protected bool $decorative = false; + /** * Worksheet. */ @@ -188,6 +193,18 @@ public function setDescription(string $description): self return $this; } + public function isDecorative(): bool + { + return $this->decorative; + } + + public function setDecorative(bool $decorative): self + { + $this->decorative = $decorative; + + return $this; + } + public function getWorksheet(): ?Worksheet { return $this->worksheet; diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php index bfc38b8e..21072e8e 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php @@ -4,6 +4,7 @@ use Composer\Pcre\Preg; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; +use PhpOffice\PhpSpreadsheet\Shared\Metafile; use ZipArchive; class Drawing extends BaseDrawing @@ -15,6 +16,8 @@ class Drawing extends BaseDrawing IMAGETYPE_BMP => IMAGETYPE_PNG, ]; + const UNSUPPORTED_IMAGE_TYPE_MESSAGE = 'Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF, WMF, EMF.'; + /** * Path. */ @@ -25,6 +28,11 @@ class Drawing extends BaseDrawing */ private bool $isUrl; + /** + * Metafile type (Metafile::TYPE_WMF, Metafile::TYPE_EMF or Metafile::TYPE_EMFPLUS), null if not a metafile. + */ + private ?string $metafileType = null; + /** * Create a new Drawing. */ @@ -62,6 +70,9 @@ public function getExtension(): string if (Preg::isMatch('~^data:image/([^;]+);base64,~', $this->path, $matches)) { return $matches[1]; } + if ($this->metafileType !== null) { + return Metafile::getExtension($this->metafileType); + } $exploded = explode('.', basename($this->path)); return $exploded[count($exploded) - 1]; @@ -72,10 +83,6 @@ public function getExtension(): string */ public function getMediaFilename(): string { - if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { - throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); - } - return sprintf('image%d%s', $this->getImageIndex(), $this->getImageFileExtensionForSave()); } @@ -100,6 +107,7 @@ public function getPath(): string public function setPath(string $path, bool $verifyFile = true, ?ZipArchive $zip = null, bool $allowExternal = true, ?callable $isWhitelisted = null): static { $this->isUrl = false; + $this->metafileType = null; if (Preg::isMatch('~^data:image/[a-z]+;base64,~', $path)) { $this->path = $path; @@ -196,10 +204,68 @@ private function isImage(string $path): bool $extension = pathinfo($path, PATHINFO_EXTENSION); $retVal = in_array($extension, ['bin', 'emf'], true); } + if (!$retVal) { + $retVal = Metafile::detectFile($path) !== null; + } return $retVal; } + /** + * Set Fact Sizes and Type of Image, rendering Windows Metafiles (WMF, EMF, EMF+) to know their sizes. + */ + protected function setSizesAndType(string $path): void + { + $this->metafileType = Metafile::detectFile($path); + if ($this->metafileType !== null && $this->imageWidth === 0 && $this->imageHeight === 0) { + // If the metafile can not be rendered, its sizes stay unknown + $image = Metafile::tryToGdImage((string) file_get_contents($path)); + if ($image !== null) { + $this->imageWidth = imagesx($image); + $this->imageHeight = imagesy($image); + } + } + + parent::setSizesAndType($path); + } + + /** + * Whether the image is a Windows Metafile (WMF, EMF or EMF+). + */ + public function isMetafile(): bool + { + return $this->metafileType !== null; + } + + /** + * Get the Windows Metafile type (Metafile::TYPE_WMF, Metafile::TYPE_EMF or Metafile::TYPE_EMFPLUS), null if not a metafile. + */ + public function getMetafileType(): ?string + { + return $this->metafileType; + } + + /** + * Get the contents of the image file. + */ + public function getContents(): ?string + { + if ($this->path === '') { + return null; + } + $contents = @file_get_contents($this->path); + + return ($contents === false) ? null : $contents; + } + + /** + * Whether the image can be saved as PNG, JPEG (comment background, ...). + */ + public function isSupportedForSave(): bool + { + return $this->metafileType !== null || array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP); + } + /** * Get isURL. */ @@ -227,8 +293,12 @@ public function getHashCode(): string */ public function getImageTypeForSave(): int { + // Windows Metafiles are converted to PNG + if ($this->metafileType !== null) { + return IMAGETYPE_PNG; + } if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { - throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); + throw new PhpSpreadsheetException(self::UNSUPPORTED_IMAGE_TYPE_MESSAGE); } return self::IMAGE_TYPES_CONVERTION_MAP[$this->type]; @@ -239,11 +309,7 @@ public function getImageTypeForSave(): int */ public function getImageFileExtensionForSave(bool $includeDot = true): string { - if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { - throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); - } - - $result = image_type_to_extension(self::IMAGE_TYPES_CONVERTION_MAP[$this->type], $includeDot); + $result = image_type_to_extension($this->getImageTypeForSave(), $includeDot); return "$result"; } @@ -253,10 +319,6 @@ public function getImageFileExtensionForSave(bool $includeDot = true): string */ public function getImageMimeType(): string { - if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { - throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); - } - - return image_type_to_mime_type(self::IMAGE_TYPES_CONVERTION_MAP[$this->type]); + return image_type_to_mime_type($this->getImageTypeForSave()); } } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php index f036f988..1c64b7da 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php @@ -5,6 +5,7 @@ use GdImage; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Shared\File; +use PhpOffice\PhpSpreadsheet\Shared\Metafile; class MemoryDrawing extends BaseDrawing { @@ -138,12 +139,18 @@ public static function fromStream($imageStream): self */ public static function fromString(string $imageString): self { - $gdImage = @imagecreatefromstring($imageString); - if ($gdImage === false) { - throw new Exception('Value cannot be converted to an image'); - } + if (Metafile::detect($imageString) !== null) { + // Windows Metafiles (WMF, EMF, EMF+) are rendered as PNG + $gdImage = Metafile::toGdImage($imageString); + $mimeType = self::MIMETYPE_PNG; + } else { + $gdImage = @imagecreatefromstring($imageString); + if ($gdImage === false) { + throw new Exception('Value cannot be converted to an image'); + } - $mimeType = self::identifyMimeType($imageString); + $mimeType = self::identifyMimeType($imageString); + } if (imageistruecolor($gdImage) || imagecolortransparent($gdImage) >= 0) { imagesavealpha($gdImage, true); } diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PivotTable/PivotTableBuilder.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PivotTable/PivotTableBuilder.php index 701badf6..2590f6e3 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PivotTable/PivotTableBuilder.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PivotTable/PivotTableBuilder.php @@ -247,15 +247,71 @@ private function distinctValues(string $fieldName): array } /** - * Resolve the pivot table's rendered range. The exact extent is recomputed - * by the spreadsheet application on refresh; a single-cell ref is a valid - * starting point that Excel expands. + * Resolve the pivot table's rendered range. + * + * The exact extent is recomputed when the application refreshes the pivot + * table, but the declared range still has to be large enough to hold the + * layout described by the rest of the definition. A single-cell ref is not + * expanded on load: Excel treats a range that cannot contain the header, + * body and grand total as inconsistent and drops the pivot table. */ private function targetLocation(string $targetCell): string { $targetCell = str_replace('$', '', $targetCell); + [$column, $row] = Coordinate::coordinateFromString($targetCell); + $firstColumn = Coordinate::columnIndexFromString($column); + $firstRow = (int) $row; + + // Columns: the row-field header column, then one column per distinct + // value of each column field, then one for the grand total. Without + // column fields the data fields are laid out across instead. + $width = 1; + foreach ($this->placements as $fieldName => $placement) { + if ($placement['axis'] === PivotField::AXIS_COLUMN) { + $width += max(count($this->distinctValues($fieldName)), 1); + } + } + $hasColumnFields = $width > 1; + $dataFieldCount = $this->countPlacements(PivotField::AXIS_VALUES); + if ($hasColumnFields) { + ++$width; // grand total column + } else { + // No column fields: each data field occupies its own column + // alongside the row-label column. + $width += max($dataFieldCount, 1); + } + + // Rows: the header row (plus a second one when column fields add their + // own header), one per distinct value of each row field, and the grand + // total row. + $height = $hasColumnFields ? 2 : 1; + $rowValueCount = 0; + foreach ($this->placements as $fieldName => $placement) { + if ($placement['axis'] === PivotField::AXIS_ROW) { + $rowValueCount += max(count($this->distinctValues($fieldName)), 1); + } + } + $height += $rowValueCount + 1; + + $lastColumn = Coordinate::stringFromColumnIndex($firstColumn + $width - 1); + $lastRow = $firstRow + $height - 1; + + return $targetCell . ':' . $lastColumn . $lastRow; + } + + /** + * Count the fields placed on a given axis. + */ + private function countPlacements(string $axis): int + { + $count = 0; + foreach ($this->placements as $placement) { + if ($placement['axis'] === $axis) { + ++$count; + } + } - return "$targetCell:$targetCell"; + return $count; } private function defaultCaption(?string $subtotal, string $fieldName): string diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table.php index d6378b00..020e90c9 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table.php @@ -233,6 +233,19 @@ public function getShowTotalsRow(): bool public function setShowTotalsRow(bool $showTotalsRow): self { $this->showTotalsRow = $showTotalsRow; + $this->updateTotalsRowCells(); + + return $this; + } + + /** + * Set the empty cells of the totals row from the totals row formula, function or label of each column. + */ + public function updateTotalsRowCells(): self + { + foreach ($this->columns as $column) { + $column->updateTotalsRowCell(); + } return $this; } @@ -426,7 +439,7 @@ public function getColumn(string $column): Table\Column */ public function getColumnByOffset(int $columnOffset): Table\Column { - [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); + [$rangeStart] = Coordinate::rangeBoundaries($this->range); $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset); return $this->getColumn($pColumn); diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/Column.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/Column.php index 257e3e39..89470d5f 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/Column.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/Column.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet\Table; +use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; @@ -10,6 +11,20 @@ class Column { + /** + * SUBTOTAL function numbers used by Excel for the totals row functions. + */ + private const TOTALS_ROW_SUBTOTALS = [ + 'average' => 101, + 'countnums' => 102, + 'count' => 103, + 'max' => 104, + 'min' => 105, + 'stddev' => 107, + 'sum' => 109, + 'var' => 110, + ]; + /** * Table Column Index. */ @@ -115,6 +130,7 @@ public function getTotalsRowLabel(): ?string public function setTotalsRowLabel(string $totalsRowLabel): self { $this->totalsRowLabel = $totalsRowLabel; + $this->updateTotalsRowCell(); return $this; } @@ -133,6 +149,7 @@ public function getTotalsRowFunction(): ?string public function setTotalsRowFunction(string $totalsRowFunction): self { $this->totalsRowFunction = $totalsRowFunction; + $this->updateTotalsRowCell(); return $this; } @@ -151,10 +168,71 @@ public function getTotalsRowFormula(): ?string public function setTotalsRowFormula(string $totalsRowFormula): self { $this->totalsRowFormula = $totalsRowFormula; + $this->updateTotalsRowCell(); return $this; } + /** + * Set the totals row cell of this column from its totals row formula, function or label. + * An existing value in that cell is left alone. + */ + public function updateTotalsRowCell(): void + { + $table = $this->table; + $worksheet = $table?->getWorksheet(); + if ($table === null || $worksheet === null || !$table->getShowTotalsRow()) { + return; + } + + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($table->getRange()); + $coordinate = $this->columnIndex . $rangeEnd[1]; + if ($worksheet->cellExists($coordinate) && $worksheet->getCell($coordinate)->getValueString() !== '') { + return; + } + + $value = $this->getTotalsRowCellValue($table, $worksheet, $rangeStart); + if ($value !== null) { + $worksheet->getCell($coordinate)->setValue($value); + } + } + + /** + * @param array{0: int, 1: int} $rangeStart + */ + private function getTotalsRowCellValue(Table $table, Worksheet $worksheet, array $rangeStart): ?string + { + $function = strtolower($this->totalsRowFunction ?? ''); + if ($this->totalsRowFormula !== null && $this->totalsRowFormula !== '' && ($function === '' || $function === 'custom')) { + return '=' . ltrim($this->totalsRowFormula, '='); + } + + if (isset(self::TOTALS_ROW_SUBTOTALS[$function])) { + $offset = Coordinate::columnIndexFromString($this->columnIndex) - $rangeStart[0]; + $headerCoordinate = $this->columnIndex . $rangeStart[1]; + if (!$table->getShowHeaderRow()) { + $columnName = 'Column' . ($offset + 1); + } elseif ($worksheet->cellExists($headerCoordinate)) { + $columnName = $worksheet->getCell($headerCoordinate)->getValueString(); + } else { + $columnName = ''; + } + if ($columnName === '') { + return null; + } + // Special characters in a column name are escaped with an apostrophe + $columnName = (string) preg_replace("/(['#\\[\\]])/", "'$1", $columnName); + + return '=SUBTOTAL(' . self::TOTALS_ROW_SUBTOTALS[$function] . ',' . $table->getName() . '[' . $columnName . '])'; + } + + if ($function === '' && $this->totalsRowLabel !== null && $this->totalsRowLabel !== '') { + return $this->totalsRowLabel; + } + + return null; + } + /** * Get column Formula. */ diff --git a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php index b8221410..ed0bf2bf 100644 --- a/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php +++ b/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php @@ -638,7 +638,7 @@ public function getChartNames(): array */ public function getChartByName(string $chartName) { - foreach ($this->chartCollection as $index => $chart) { + foreach ($this->chartCollection as $chart) { if ($chart->getName() == $chartName) { return $chart; } @@ -2164,12 +2164,18 @@ public function getTableCollection(): ArrayObject /** * Add Table. * + * @param bool $updateTotalsRowCells Set the empty cells of the table's totals row + * from the totals row formula, function or label of its columns + * * @return $this */ - public function addTable(Table $table): self + public function addTable(Table $table, bool $updateTotalsRowCells = true): self { $table->setWorksheet($this); $this->tableCollection[] = $table; + if ($updateTotalsRowCells) { + $table->updateTotalsRowCells(); + } return $this; } @@ -2824,8 +2830,7 @@ public function removeColumn(string $column, int $numberOfColumns = 1): static $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1; for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) { - $this->cellCollection->removeColumn($highestColumn); - $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1); + $this->cellCollection->removeColumn(Coordinate::stringFromColumnIndex($highestColumnIndex - $c)); } $this->cachedHighestColumn = $newHighestColumn; @@ -3381,7 +3386,6 @@ public function rangeToArrayYieldRows( $hideColumns = !empty($hiddenColumns); $keys = $this->cellCollection->getSortedCoordinatesInt(); - $keyIndex = 0; $keysCount = count($keys); // Loop through rows for ($row = $minRow; $row <= $maxRow; ++$row) { @@ -3786,13 +3790,14 @@ public function getDataValidation(string $cellCoordinate): DataValidation } // or if cell is part of a data validation range + $isRange = Preg::isMatch('/[: ]/', $cellCoordinate); foreach ($this->dataValidationCollection as $key => $dataValidation) { $keyParts = explode(' ', $key); foreach ($keyParts as $keyPart) { if ($keyPart === $cellCoordinate) { return $dataValidation; } - if (str_contains($keyPart, ':')) { + if (!$isRange && str_contains($keyPart, ':')) { if (Coordinate::coordinateIsInsideRange($keyPart, $cellCoordinate)) { return $dataValidation; } @@ -3837,13 +3842,14 @@ public function dataValidationExists(string $coordinate): bool if (isset($this->dataValidationCollection[$coordinate])) { return true; } + $isRange = Preg::isMatch('/[: ]/', $coordinate); foreach ($this->dataValidationCollection as $key => $dataValidation) { $keyParts = explode(' ', $key); foreach ($keyParts as $keyPart) { if ($keyPart === $coordinate) { return true; } - if (str_contains($keyPart, ':')) { + if (!$isRange && str_contains($keyPart, ':')) { if (Coordinate::coordinateIsInsideRange($keyPart, $coordinate)) { return true; } @@ -4042,7 +4048,7 @@ public function __clone() foreach ($currentCollection as $item) { $newTable = clone $item; $newTable->setName($item->getName() . 'clone'); - $this->addTable($newTable); + $this->addTable($newTable, false); } } elseif ($key === 'chartCollection') { $currentCollection = $this->chartCollection; diff --git a/vendor/phpoffice/wmf/.gitattributes b/vendor/phpoffice/wmf/.gitattributes new file mode 100644 index 00000000..0ab9aeb0 --- /dev/null +++ b/vendor/phpoffice/wmf/.gitattributes @@ -0,0 +1,2 @@ +/tests/resources/libemf2svg export-ignore +/tests/resources/phpspreadsheet export-ignore diff --git a/vendor/phpoffice/wmf/.github/workflows/deploy.yml b/vendor/phpoffice/wmf/.github/workflows/deploy.yml new file mode 100644 index 00000000..2fbacc73 --- /dev/null +++ b/vendor/phpoffice/wmf/.github/workflows/deploy.yml @@ -0,0 +1,51 @@ +name: Deploy + +on: + push: + branches: + - master + pull_request: + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + ### ProperDocs + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: 3.x + - name: Install Python Dependencies + run: pip install properdocs mkdocs-material autolink-references-mkdocs-plugin + - name: Build documentation + run: properdocs build --site-dir public + ### PHPUnit + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: 7.1 + extensions: dom, xml + coverage: xdebug + - name: Create directory public/coverage + run: mkdir ./public/coverage + - name: Install PHP Dependencies + run: composer install --ansi --prefer-dist --no-interaction --no-progress + - name: Build Coverage Report + run: XDEBUG_MODE=coverage ./vendor/bin/phpunit -c ./ --coverage-text --coverage-html ./public/coverage + ### PHPDoc + #- name: Create directory public/docs + # run: mkdir ./public/docs + #- name: Install PhpDocumentor + # run: wget https://phpdoc.org/phpDocumentor.phar && chmod +x phpDocumentor.phar + #- name: Build Documentation + # run: ./phpDocumentor.phar run -d ./src -t ./public/docs + + ### Deploy + - name: Deploy + uses: peaceiris/actions-gh-pages@v3 + if: github.ref == 'refs/heads/master' + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./public \ No newline at end of file diff --git a/vendor/phpoffice/wmf/.github/workflows/php.yml b/vendor/phpoffice/wmf/.github/workflows/php.yml new file mode 100644 index 00000000..e871f61f --- /dev/null +++ b/vendor/phpoffice/wmf/.github/workflows/php.yml @@ -0,0 +1,120 @@ +name: PHP +on: + push: + branches: + - master + pull_request: + +jobs: + php-cs-fixer: + name: PHP CS Fixer + runs-on: ubuntu-latest + steps: + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '7.4' + extensions: xml + + - uses: actions/checkout@v4 + + - name: Validate composer config + run: composer validate --strict + + - name: Composer Install + run: composer global require friendsofphp/php-cs-fixer + + - name: Add environment path + run: export PATH="$PATH:$HOME/.composer/vendor/bin" + + - name: Run PHPCSFixer + run: php-cs-fixer fix --dry-run --diff + + phpstan: + name: PHP Static Analysis + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: + - '7.1' + - '7.2' + - '7.3' + - '7.4' + - '8.0' + - '8.1' + - '8.2' + - '8.3' + - '8.4' + - '8.5' + steps: + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: xml + + - uses: actions/checkout@v4 + + - name: Composer Install + run: composer install --ansi --prefer-dist --no-interaction --no-progress + + - name: Run phpstan + run: ./vendor/bin/phpstan analyse -c phpstan.neon.dist + + phpunit: + name: PHPUnit + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + php: + - '7.1' + - '7.2' + - '7.3' + - '7.4' + - '8.0' + - '8.1' + - '8.2' + - '8.3' + - '8.4' + - '8.5' + steps: + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: xml + coverage: ${{ (matrix.php == '8.1') && 'xdebug' || 'none' }} + + - uses: actions/checkout@v4 + + - name: Install dependencies + run: composer install --ansi --prefer-dist --no-interaction --no-progress + + - name: Run PHPUnit + if: matrix.php != '8.1' + run: ./vendor/bin/phpunit -c phpunit.xml.dist + + - name: Run PHPUnit (w CodeCoverage) + if: matrix.php == '8.1' + run: XDEBUG_MODE=coverage ./vendor/bin/phpunit -c phpunit.xml.dist --coverage-clover build/clover.xml + + - name: Upload coverage results to Coveralls + if: matrix.php == '8.1' + env: + COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + wget https://github.com/php-coveralls/php-coveralls/releases/download/v2.4.3/php-coveralls.phar + chmod +x php-coveralls.phar + php php-coveralls.phar --coverage_clover=build/clover.xml --json_path=build/coveralls-upload.json -vvv + + #roave-backwards-compatibility-check: + # name: Roave Backwards Compatibility Check + # runs-on: ubuntu-latest + # steps: + # - uses: actions/checkout@v4 + # with: + # fetch-depth: 0 + # - name: "Check for BC breaks" + # run: docker run -u $(id -u) -v $(pwd):/app nyholm/roave-bc-check-ga \ No newline at end of file diff --git a/vendor/phpoffice/wmf/.gitignore b/vendor/phpoffice/wmf/.gitignore new file mode 100644 index 00000000..5812d06f --- /dev/null +++ b/vendor/phpoffice/wmf/.gitignore @@ -0,0 +1,9 @@ +.phpunit.cache +.phpunit.result.cache +.php-cs-fixer.cache +composer.lock +phpDocumentor.phar + +build/ +public/ +vendor/ \ No newline at end of file diff --git a/vendor/phpoffice/wmf/.php-cs-fixer.dist.php b/vendor/phpoffice/wmf/.php-cs-fixer.dist.php new file mode 100644 index 00000000..aaa50168 --- /dev/null +++ b/vendor/phpoffice/wmf/.php-cs-fixer.dist.php @@ -0,0 +1,45 @@ +setUsingCache(true) + ->setRiskyAllowed(true) + ->setRules([ + '@Symfony' => true, + 'array_indentation' => true, + 'cast_spaces' => [ + 'space' => 'single', + ], + 'combine_consecutive_issets' => true, + 'concat_space' => [ + 'spacing' => 'one', + ], + 'error_suppression' => [ + 'mute_deprecation_error' => false, + 'noise_remaining_usages' => false, + 'noise_remaining_usages_exclude' => [], + ], + 'function_to_constant' => false, + 'global_namespace_import' => true, + 'method_chaining_indentation' => true, + 'no_alias_functions' => false, + 'no_superfluous_phpdoc_tags' => false, + 'non_printable_character' => [ + 'use_escape_sequences_in_strings' => true, + ], + 'phpdoc_align' => [ + 'align' => 'left', + ], + 'phpdoc_summary' => false, + 'protected_to_private' => false, + 'self_accessor' => false, + 'yoda_style' => false, + 'single_line_throw' => false, + 'no_alias_language_construct_call' => false, + ]) + ->getFinder() + ->in(__DIR__) + ->exclude('vendor'); + +return $config; \ No newline at end of file diff --git a/vendor/phpoffice/wmf/LICENSE b/vendor/phpoffice/wmf/LICENSE new file mode 100644 index 00000000..a3380df6 --- /dev/null +++ b/vendor/phpoffice/wmf/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 PhpSpreadsheet Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/vendor/phpoffice/wmf/README.md b/vendor/phpoffice/wmf/README.md new file mode 100644 index 00000000..b38608df --- /dev/null +++ b/vendor/phpoffice/wmf/README.md @@ -0,0 +1,63 @@ +# WMF + +[![Latest Stable Version](https://poser.pugx.org/phpoffice/wmf/v)](https://packagist.org/packages/phpoffice/wmf) +[![Coverage Status](https://coveralls.io/repos/github/PHPOffice/WMF/badge.svg?branch=master)](https://coveralls.io/github/PHPOffice/WMF?branch=master) +[![Total Downloads](https://poser.pugx.org/phpoffice/wmf/downloads)](https://packagist.org/packages/phpoffice/wmf) +[![License](https://poser.pugx.org/phpoffice/wmf/license)](https://packagist.org/packages/phpoffice/wmf) +[![CI](https://github.com/PHPOffice/WMF/actions/workflows/php.yml/badge.svg)](https://github.com/PHPOffice/WMF/actions/workflows/php.yml) + +WMF is a library written in pure PHP that provides a set of classes to read WMF based file (like `.wmf` or `.emf` files). + +WMF is an open source project licensed under the terms of [MIT](https://github.com/PHPOffice/WMF/blob/master/LICENCE). WMF is aimed to be a high quality software product by incorporating [continuous integration and unit testing](https://github.com/PHPOffice/WMF/actions/workflows/php.yml). You can learn more about WMF by reading this Developers'Documentation and the [API Documentation](http://phpoffice.github.io/WMF/docs/develop/) + +If you have any questions, please ask on [StackOverFlow](https://stackoverflow.com/questions/tagged/phpoffice-wmf) + +Read more about WMF: + +- [Features](#features) +- [Requirements](#requirements) +- [Installation](#installation) +- [Contributing](#contributing) +- [Developers' Documentation](https://phpoffice.github.io/WMF/) + +## Features + +- Read files + + * WMF files + * EMF files + * EMF+ files + +## Requirements + +WMF requires the following: + +- PHP 7.1+ + +## Installation + +WMF is installed via [Composer](https://getcomposer.org/). +To [add a dependency](https://getcomposer.org/doc/04-schema.md#package-links) to WMF in your project, either + +Run the following to use the latest stable version +```sh +composer require phpoffice/wmf +``` +or if you want the latest unreleased version +```sh +composer require phpoffice/wmf:dev-master +``` + +## Credits + +The EMF test files of the directory `tests/resources/libemf2svg` come from the [libemf2svg](https://github.com/kakwa/libemf2svg/tree/master/tests/resources) project, licensed under the [GNU General Public License v2.0](https://github.com/kakwa/libemf2svg/blob/master/LICENSE). +The EMF test file `tests/resources/phpspreadsheet/issue274.emf` comes from the issue [PHPOffice/PhpSpreadsheet#274](https://github.com/PHPOffice/PhpSpreadsheet/issues/274). +They are only used by the test suite and are not distributed in the Composer package. + +## Contributing + +We welcome everyone to contribute to PHPWord. Below are some of the things that you can do to contribute. + +- [Fork us](https://github.com/PHPOffice/WMF/fork) and [request a pull](https://github.com/PHPOffice/WMF/pulls) to the [master](https://github.com/PHPOffice/WMF/tree/master) branch. +- Submit [bug reports or feature requests](https://github.com/PHPOffice/WMF/issues) to GitHub. +- Follow [@PHPOffice](https://twitter.com/PHPOffice) on Twitter. diff --git a/vendor/phpoffice/wmf/composer.json b/vendor/phpoffice/wmf/composer.json new file mode 100644 index 00000000..70450fd6 --- /dev/null +++ b/vendor/phpoffice/wmf/composer.json @@ -0,0 +1,32 @@ +{ + "name": "phpoffice/wmf", + "description": "WMF - Manipulate WMF Images", + "keywords": ["PHP", "wmf", "emf", "image"], + "homepage": "https://phpoffice.github.io/WMF/", + "type": "library", + "license": "MIT", + "autoload": { + "psr-4": { + "PhpOffice\\WMF\\": "src/WMF/" + } + }, + "autoload-dev": { + "psr-4": { + "Tests\\PhpOffice\\WMF\\": "tests/WMF/" + } + }, + "authors": [ + { + "name": "Progi1984", + "homepage": "https://lefevre.dev" + } + ], + "require": { + "php": "^7.1|^8.0", + "ext-gd": "*" + }, + "require-dev": { + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0", + "phpstan/phpstan": "^0.12.88 || ^1.0.0" + } +} diff --git a/vendor/phpoffice/wmf/docs/changes/0.1.0.md b/vendor/phpoffice/wmf/docs/changes/0.1.0.md new file mode 100644 index 00000000..9abdf4f7 --- /dev/null +++ b/vendor/phpoffice/wmf/docs/changes/0.1.0.md @@ -0,0 +1,17 @@ +# 0.1.0 + +## Enhancements + +- Initial version by [@Progi1984](https://github/Progi1984) +- Enable/Disable Exceptions in [#3](https://github.com/PHPOffice/WMF/pull/3) by [@Progi1984](https://github/Progi1984) + +## Bug fixes + +- N/A + +## Miscellaneous + +- Github Action : PHP (PHPCSFixer / PHPStan / PHPUnit) in [#1](https://github.com/PHPOffice/WMF/pull/1) by [@Progi1984](https://github/Progi1984) +- Refactored WMF Reader in [#2](https://github.com/PHPOffice/WMF/pull/2) by [@Progi1984](https://github/Progi1984) +- Github Action : Documentation in [#4](https://github.com/PHPOffice/WMF/pull/4) by [@Progi1984](https://github/Progi1984) + \ No newline at end of file diff --git a/vendor/phpoffice/wmf/docs/changes/0.1.1.md b/vendor/phpoffice/wmf/docs/changes/0.1.1.md new file mode 100644 index 00000000..81a59f78 --- /dev/null +++ b/vendor/phpoffice/wmf/docs/changes/0.1.1.md @@ -0,0 +1,14 @@ +# 0.1.1 + +## Enhancements + +- Load a WMF file from a string in [#5](https://github.com/PHPOffice/WMF/pull/5) by [@Progi1984](https://github/Progi1984) + +## Bug fixes + +- N/A + +## Miscellaneous + +- N/A + \ No newline at end of file diff --git a/vendor/phpoffice/wmf/docs/changes/0.1.2.md b/vendor/phpoffice/wmf/docs/changes/0.1.2.md new file mode 100644 index 00000000..6009c4e2 --- /dev/null +++ b/vendor/phpoffice/wmf/docs/changes/0.1.2.md @@ -0,0 +1,14 @@ +# 0.1.2 + +## Enhancements + +- WMF\Reader\WMF\Magic : Backends sorted by priority in [#6](https://github.com/PHPOffice/WMF/pull/6) by [@Progi1984](https://github/Progi1984) + +## Bug fixes + +- N/A + +## Miscellaneous + +- N/A + \ No newline at end of file diff --git a/vendor/phpoffice/wmf/docs/changes/0.1.3.md b/vendor/phpoffice/wmf/docs/changes/0.1.3.md new file mode 100644 index 00000000..599e9312 --- /dev/null +++ b/vendor/phpoffice/wmf/docs/changes/0.1.3.md @@ -0,0 +1,14 @@ +# 0.1.3 + +## Enhancements + +- WMF\Reader : Save as WMF in [#7](https://github.com/PHPOffice/WMF/pull/7) by [@Progi1984](https://github/Progi1984) + +## Bug fixes + +- N/A + +## Miscellaneous + +- N/A + \ No newline at end of file diff --git a/vendor/phpoffice/wmf/docs/changes/0.2.0.md b/vendor/phpoffice/wmf/docs/changes/0.2.0.md new file mode 100644 index 00000000..8f40a91b --- /dev/null +++ b/vendor/phpoffice/wmf/docs/changes/0.2.0.md @@ -0,0 +1,25 @@ +# 0.2.0 + +## Enhancements + +- Added support for EMF files (`PhpOffice\WMF\Reader\EMF`) in [#9](https://github.com/PHPOffice/WMF/pull/9) by [@Progi1984](https://github/Progi1984) +- Added detection of the type of an image (`PhpOffice\WMF\Reader\Detector`) in [#9](https://github.com/PHPOffice/WMF/pull/9) by [@Progi1984](https://github/Progi1984) +- Added method `isSupported` to readers in [#9](https://github.com/PHPOffice/WMF/pull/9) by [@Progi1984](https://github/Progi1984) +- `PhpOffice\WMF\Reader\WMF\GD` : Uses the renderer of EMF files (texts, curves, regions, clipping, bitmaps, antialiasing...) in [#9](https://github.com/PHPOffice/WMF/pull/9) by [@Progi1984](https://github/Progi1984) +- Added support for EMF+ files (`PhpOffice\WMF\Reader\EMF\GD`) in [#10](https://github.com/PHPOffice/WMF/pull/10) by [@Progi1984](https://github/Progi1984) +- GD readers : Added dashed pens, hatched brushes, raster operations & the conversion of the `Symbol` font in [#11](https://github.com/PHPOffice/WMF/pull/11) by [@Progi1984](https://github/Progi1984) +- GD readers : Added the color of the background (`setBackgroundColor`), which may be transparent in [#11](https://github.com/PHPOffice/WMF/pull/11) by [@Progi1984](https://github/Progi1984) +- `PhpOffice\WMF\Reader\EMF\GD` : Texts of EMF+ files are wrapped in [#11](https://github.com/PHPOffice/WMF/pull/11) by [@Progi1984](https://github/Progi1984) +- GD readers : Added pattern brushes & compressed bitmaps (`BI_RLE4` & `BI_RLE8`) in [#11](https://github.com/PHPOffice/WMF/pull/11) by [@Progi1984](https://github/Progi1984) +- `PhpOffice\WMF\Reader\WMF\GD` : Added support for WMF files without placeable header & `META_INVERTREGION` in [#11](https://github.com/PHPOffice/WMF/pull/11) by [@Progi1984](https://github/Progi1984) +- `PhpOffice\WMF\Reader\EMF\GD` : Added the vertical advances of texts (`ETO_PDY`), compound lines & surrounding colors of path gradients of EMF+ files in [#11](https://github.com/PHPOffice/WMF/pull/11) by [@Progi1984](https://github/Progi1984) + +## Bug fixes + +- `PhpOffice\WMF\Reader\WMF\Magic` : Use the next backend if Imagick doesn't support WMF files in [#9](https://github.com/PHPOffice/WMF/pull/9) by [@Progi1984](https://github/Progi1984) + +## Miscellaneous + +- Added support for PHP 8.4 & 8.5 in [#8](https://github.com/PHPOffice/WMF/pull/8) by [@Progi1984](https://github/Progi1984) +- Readers : Added a common abstract class `PhpOffice\WMF\Reader\ReaderAbstract` & common traits (`PhpOffice\WMF\Reader\GDTrait`, `PhpOffice\WMF\Reader\ImagickTrait`, `PhpOffice\WMF\Reader\MagicTrait`) in [#9](https://github.com/PHPOffice/WMF/pull/9) by [@Progi1984](https://github/Progi1984) +- Added a renderer shared by GD readers (`PhpOffice\WMF\Renderer`) in [#9](https://github.com/PHPOffice/WMF/pull/9) by [@Progi1984](https://github/Progi1984) diff --git a/vendor/phpoffice/wmf/docs/changes/0.2.1.md b/vendor/phpoffice/wmf/docs/changes/0.2.1.md new file mode 100644 index 00000000..d7a2337e --- /dev/null +++ b/vendor/phpoffice/wmf/docs/changes/0.2.1.md @@ -0,0 +1,13 @@ +# 0.2.1 + +## Enhancements + +- N/A + +## Bug fixes + +- `PhpOffice\WMF\Reader\EMF\GD` : Added support for `EMR_SETDIBITSTODEVICE` records, including DIBs drawn by bands of scan lines by [@Progi1984](https://github/Progi1984) + +## Miscellaneous + +- Documentation : Migrated from MkDocs to ProperDocs in [#12](https://github.com/PHPOffice/WMF/pull/12) by [@Progi1984](https://github/Progi1984) diff --git a/vendor/phpoffice/wmf/docs/credits.md b/vendor/phpoffice/wmf/docs/credits.md new file mode 100644 index 00000000..3d634f7c --- /dev/null +++ b/vendor/phpoffice/wmf/docs/credits.md @@ -0,0 +1,23 @@ +## References + +### WMF + +### EMF + +### EMF+ + +## Test files + +### EMF + +The EMF files of the directory `tests/resources/libemf2svg` come from the [libemf2svg](https://github.com/kakwa/libemf2svg) project, by Pierre-François Carpentier. + +- Source : https://github.com/kakwa/libemf2svg/tree/master/tests/resources (commit `658a718de180666d342a78fd4046ec1f41e65e17`) +- License : [GNU General Public License v2.0](https://github.com/kakwa/libemf2svg/blob/master/LICENSE) + +These files are only used by the test suite : they are not distributed in the Composer package. + +The EMF file `tests/resources/phpspreadsheet/issue274.emf` comes from the file `imgBook1.xlsx` attached to the issue [PHPOffice/PhpSpreadsheet#274](https://github.com/PHPOffice/PhpSpreadsheet/issues/274) (`xl/media/image1.emf`). +Its reference image `issue274.png` is rendered by `PhpOffice\WMF\Reader\EMF\GD`. + +This file is only used by the test suite : it is not distributed in the Composer package. diff --git a/vendor/phpoffice/wmf/docs/index.md b/vendor/phpoffice/wmf/docs/index.md new file mode 100644 index 00000000..5d95f3a3 --- /dev/null +++ b/vendor/phpoffice/wmf/docs/index.md @@ -0,0 +1,21 @@ +# + +WMF is a library written in pure PHP that provides a set of classes to read WMF based file (like `.wmf` or `.emf` files). + +WMF is an open source project licensed under the terms of [MIT](https://github.com/PHPOffice/WMF/blob/master/LICENCE). WMF is aimed to be a high quality software product by incorporating [continuous integration and unit testing](https://github.com/PHPOffice/WMF/actions/workflows/php.yml). You can learn more about WMF by reading this Developers'Documentation and the [API Documentation](http://phpoffice.github.io/WMF/docs/develop/) + +## Features + +- Read files + + * WMF files + * EMF files + * EMF+ files + +## Contributing + +We welcome everyone to contribute to WMF. Below are some of the things that you can do to contribute: + +- [Fork us](https://github.com/PHPOffice/WMF/fork) and [request a pull](https://github.com/PHPOffice/WMF/pulls) to the [master](https://github.com/PHPOffice/WMF/tree/master) branch +- Submit [bug reports or feature requests](https://github.com/PHPOffice/WMF/issues) to GitHub +- Follow [@PHPOffice](https://twitter.com/PHPOffice) on Twitter \ No newline at end of file diff --git a/vendor/phpoffice/wmf/docs/install.md b/vendor/phpoffice/wmf/docs/install.md new file mode 100644 index 00000000..ca73f249 --- /dev/null +++ b/vendor/phpoffice/wmf/docs/install.md @@ -0,0 +1,21 @@ +# Installation + +## Requirements + +Mandatory: + +- PHP 7.1+ + +## Installation + +### Using Composer + +To install via [Composer](http://getcomposer.org), add the following lines to your `composer.json`: + +``` json +{ + "require": { + "phpoffice/wmf": "dev-master" + } +} +``` \ No newline at end of file diff --git a/vendor/phpoffice/wmf/docs/usage/detector.md b/vendor/phpoffice/wmf/docs/usage/detector.md new file mode 100644 index 00000000..fb0f5904 --- /dev/null +++ b/vendor/phpoffice/wmf/docs/usage/detector.md @@ -0,0 +1,69 @@ +# Detector + +The `Detector` class detects the type of an image from its content : WMF, EMF, EMF+ or unknown. + +| Constant | Value | Description | +|----------------------------|-----------|-------------------------------------------------------------------| +| `Detector::TYPE_WMF` | `wmf` | WMF file (placeable or not) | +| `Detector::TYPE_EMF` | `emf` | EMF file | +| `Detector::TYPE_EMFPLUS` | `emf+` | EMF file containing EMF+ records | +| `Detector::TYPE_UNKNOWN` | `unknown` | Other file | + +!!! note "EMF+ files" + + EMF+ files are EMF files whose first record (after the header) is a EMF+ header. + EMF+ "dual" files contain a EMF fallback : they can be read by the EMF readers. + +## `detect` + +The method returns the type of an image from its content. + +```php +load('sample'); +``` + +## `isWMF`, `isPlaceableWMF`, `isEMF` & `isEMFPlus` + +These methods return if the content is a WMF file (placeable or not), a placeable WMF file, a EMF file (including EMF+ files) or a EMF+ file. + +```php +load('sample.emf'); +``` + +For next samples, I will use the magic one. + +### `getBackends` + +This specific method for `Magic::class` returns backends sorted by priority. + +```php +getBackends()); +``` + +### `setBackends` + +This specific method for `Magic::class` defines backends sorted by priority. + +```php +setBackends([ + GD::class, + Imagick::class, +]); + +var_dump($reader->getBackends()); +``` + +## GD backend + +The `GD` backend is a renderer written in pure PHP, shared with the WMF reader (`PhpOffice\WMF\Renderer\GD`). +The image is generated at 96 DPI, based on the frame of the EMF file (big images are scaled down). + +It supports : + +- paths & shapes (polygons, polylines, Bézier curves, rectangles, rounded rectangles, ellipses, arcs, chords, pies) +- pens (width, end caps, joins, dashes) & brushes (solid, hatched, pattern brushes) +- world & page transforms (map modes, window, viewport) +- clipping (paths, rectangles, regions) +- bitmaps (`EMR_STRETCHDIBITS`, `EMR_BITBLT`, `EMR_STRETCHBLT`, including JPEG & PNG bitmaps) & gradients (`EMR_GRADIENTFILL`) +- texts (`EMR_EXTTEXTOUTW`, `EMR_EXTTEXTOUTA`, `EMR_SMALLTEXTOUT`), with TrueType/OpenType fonts + +If a not supported record is found (like `EMR_ALPHABLEND`, `EMR_MASKBLT`, `EMR_PLGBLT`, `EMR_TRANSPARENTBLT`, `EMR_POLYDRAW` or `EMR_EXTFLOODFILL`), +or a bitmap which is not supported (like CMYK bitmaps, `BI_CMYK`), +an exception is thrown (or `load` returns `false`, if exceptions are disabled). +Corrupted files throw an exception too. + +### Known limitations + +- The background of the image is white by default (see [`setBackgroundColor`](#setbackgroundcolor)). +- The content outside of the frame of the file is clipped. +- For the limitations of EMF+ files, see [EMF+ > Known limitations](#known-limitations-of-emf). +- Pens : + - pens have a minimal width of one pixel, + - the dashes of geometric pens are proportional to their width, and dashes have flat caps. +- Brushes : + - the patterns of pattern brushes are aligned on the origin of the image (the brush origin is ignored). +- Bitmaps : + - CMYK bitmaps (`BI_CMYK`, `BI_CMYKRLE4` & `BI_CMYKRLE8`) are not supported : an exception is thrown, + - the pixels skipped by compressed bitmaps (`BI_RLE4` & `BI_RLE8`) are transparent, + - bitmaps using the palette of the file (`DIB_PAL_COLORS`) are drawn with a gray scale (the palette is not supported), + - raster operations are applied on the image : a transparent background is used as a white background, + - corrupted JPEG & PNG bitmaps are not drawn. +- Texts : + - texts are not drawn if no font is found (see [Fonts](#fonts)), + - the metrics of fonts are approximated (ascent, descent), the width & the orientation of fonts are ignored, + - the characters of the `Symbol` font are converted to Unicode (Greek letters, mathematical symbols...), + other symbol fonts (like `Wingdings`) are drawn with another font. +- `EMR_SETROP2`, `EMR_SETSTRETCHBLTMODE` & palettes are ignored. + +### Fonts + +Texts are drawn with the TrueType/OpenType fonts (`.ttf` & `.otf`) found in the system directories : + +- Windows : `C:\Windows\Fonts` +- MacOS : `/Library/Fonts`, `/System/Library/Fonts` & `~/Library/Fonts` +- Linux : `/usr/share/fonts`, `/usr/local/share/fonts`, `~/.fonts` & `~/.local/share/fonts` + +If a font is not available, a similar font is used (for example, `Liberation Sans` or `DejaVu Sans` for `Arial`). +If no font is found, texts are not drawn. + +You can define the directories where fonts are searched (recursively) with `setFontDirectories`. + +```php +setFontDirectories([ + __DIR__ . '/fonts', +]); +$reader->load('sample.emf'); +``` + +## EMF+ + +EMF+ files are EMF files containing EMF+ records (GDI+), in comments : the `GD` backend draws them. + +- EMF+ "dual" files contain EMF+ records and EMF records (a fallback for applications not supporting EMF+) : + the EMF+ records are drawn, and only the EMF records following `EmfPlusGetDC` records are drawn (like GDI+). +- EMF+ "only" files contain only EMF+ records. +- If the EMF+ records can not be drawn (not supported or corrupted), the file is drawn with its EMF records. + +It supports : + +- shapes (rectangles, polygons, lines, ellipses, arcs, pies, Bézier curves, cardinal curves), paths & regions +- pens (width & unit, start & end caps, joins, dashes, arrows & custom caps) & brushes (solid colors with transparency, + hatches, textures, linear & path gradients) +- world & page transforms (units : pixel, point, inch, document, millimeter), containers & saved states +- clipping (rectangles, paths, regions) +- images : bitmaps (all pixel formats, PNG, JPEG, GIF...) & metafiles (WMF, EMF & EMF+), drawn in parallelograms +- texts (`EmfPlusDrawString` & `EmfPlusDrawDriverString`) + +### Methods for EMF+ + +```php +setEMFPlusEnabled(false); +var_dump($reader->isEMFPlusEnabled()); + +$reader->load('sample.emf'); +// If the file has been drawn with its EMF+ records +var_dump($reader->isEMFPlusRendered()); +``` + +### Known limitations of EMF+ + +- Rendering hints (antialiasing, interpolation, compositing...) are ignored : the drawing is always antialiased. +- Image attributes (color adjustments, wrap modes of images) & image effects (`EmfPlusSerializableObject`) are ignored. +- Pens : + - the transform & the alignment of pens are ignored, the lines of compound pens have mitered joins, + - custom caps are drawn as filled shapes, triangle & diamond caps are drawn as flat caps. +- Brushes : + - hatch styles other than horizontal, vertical, diagonal, cross & percent styles are drawn with a pattern of 50%, + - the focus scales of path gradients are ignored, and their surrounding colors are interpolated along the boundary (without preset colors), + - the vertical blend of linear gradients is ignored. +- Images : the source rectangle of metafiles is ignored (the whole metafile is drawn). +- Texts : + - texts are wrapped at spaces, and the flags of string formats (except `NoWrap` & `NoClip`) are ignored (direction, trimming, tabs...), + - `EmfPlusDrawDriverString` with indexes of glyphs (instead of characters) is not supported. +- `EmfPlusStrokeFillPath`, the multi-format records & the records of terminal services are ignored. + +## Methods + +### `getResource` + +The method returns the resource used in internal by the library. + +The `GD` backend returns a `GDImage` object or resource, depending the PHP version. +The `Imagick` backend returns a `Imagick` object. + +```php +load('sample.emf'); + +var_dump($reader->getResource()); +``` + +### `getMediaType` + +The method returns the media type for a EMF file. + +```php +getMediaType(); + +echo 'The media type for a EMF file is ' . $mediaType; +``` + +### `setBackgroundColor` + +The method defines the color of the background (white by default), or a transparent background (`null`). +The background must be defined before loading the file. +Formats without alpha channel (`gif`, `jpg` & `wbmp`) are saved with a white background. + +```php +setBackgroundColor(null); +// Blue background +$reader->setBackgroundColor([0, 0, 255]); +$reader->load('sample.emf'); +``` + +### `isEMF` + +The method returns if the file is supported by the library. + +```php +load('sample.emf'); + +$isEMF = $reader->isEMF(); + +echo 'The file sample.emf ' . ($isEMF ? 'is a EMF file' : 'is not a EMF file'); +``` + +### `isSupported` + +The method returns if the reader can be used : the extension is loaded (and supports the format, for `Imagick`). +For `Magic::class`, the method returns if one of its backends can be used. + +```php +isSupported() ? 'can' : 'can not') . ' be used'; +``` + +### `load` + +The method loads a EMF file in the object. +The method returns `true` if the file has been correctly loaded, or `false` if it has not. + +```php +load('sample.emf'); +``` + +### `loadFromString` + +The method loads a EMF file in the object from a string. +The method returns `true` if the file has been correctly loaded, or `false` if it has not. + +```php +loadFromString(file_get_contents('sample.emf')); +``` + +### `save` + +The method transforms the loaded EMF file in an another image. + +```php +load('sample.emf'); +$reader->save('sample.png', 'png'); +``` diff --git a/vendor/phpoffice/wmf/docs/usage/wmf.md b/vendor/phpoffice/wmf/docs/usage/wmf.md new file mode 100644 index 00000000..203733b2 --- /dev/null +++ b/vendor/phpoffice/wmf/docs/usage/wmf.md @@ -0,0 +1,256 @@ +# WMF + +You can load `.wmf` files. + +## Backends + +You can one of two current backends : `gd` or `imagick`. +If you don't know which one used, you can use the magic one. + +By default, the order of the backends is Imagick, followed by GD. +Each backend is tested on different criteria: extension loaded, format support. + +```php +load('sample.wmf'); +``` + +For next samples, I will use the magic one. + +### `getBackends` + +This specific method for `Magic::class` returns backends sorted by priority. + +```php +getBackends()); +``` + +### `setBackends` + +This specific method for `Magic::class` defines backends sorted by priority. + +```php +setBackends([ + GD::class, + Imagick::class, +]); + +var_dump($reader->getBackends()); +``` + +## GD backend + +The `GD` backend is a renderer written in pure PHP, shared with the EMF reader (`PhpOffice\WMF\Renderer\GD`). +The image is generated at 72 DPI, based on the bounding box of the placeable header. +For WMF files without placeable header, the bounding box is the first window of the file (`META_SETWINDOWORG` & `META_SETWINDOWEXT`), +and the number of logical units per inch depends on the map mode (`META_SETMAPMODE`) : 1440 for `MM_ANISOTROPIC` & `MM_ISOTROPIC`. +The window of the file is mapped to the image : the map mode and the viewport are ignored. + +It supports : + +- shapes (polygons, polylines, rectangles, rounded rectangles, ellipses, arcs, chords, pies) +- pens (width, end caps, joins, dashes) & brushes (solid, hatched, pattern brushes) +- regions & clipping +- bitmaps (`META_STRETCHDIB`, `META_DIBBITBLT`, `META_DIBSTRETCHBLT`, `META_BITBLT`, `META_STRETCHBLT`, `META_SETDIBTODEV`) & flood fills +- texts (`META_TEXTOUT`, `META_EXTTEXTOUT`), with TrueType/OpenType fonts + +If a not supported record is found (like `META_DRAWTEXT`), or a bitmap which is not supported (like CMYK bitmaps, `BI_CMYK`), +an exception is thrown (or `load` returns `false`, if exceptions are disabled). +Corrupted files throw an exception too. + +### Known limitations + +- WMF files without placeable header must define a window (`META_SETWINDOWEXT`) : else, an exception is thrown. +- The background of the image is white by default (see [`setBackgroundColor`](#setbackgroundcolor)). +- The map mode & the viewport (`META_SETMAPMODE`, `META_SETVIEWPORTORG`, `META_SETVIEWPORTEXT`...) are ignored. +- Pens : + - pens have a minimal width of one pixel, and dashes have flat caps. +- Brushes : + - the patterns of pattern brushes are aligned on the origin of the image (the brush origin is ignored). +- Regions : `META_FRAMEREGION` draws the frame of each rectangle of the region. +- Bitmaps : + - CMYK bitmaps (`BI_CMYK`, `BI_CMYKRLE4` & `BI_CMYKRLE8`) are not supported : an exception is thrown, + - the pixels skipped by compressed bitmaps (`BI_RLE4` & `BI_RLE8`) are transparent, + - bitmaps using the palette of the file (`DIB_PAL_COLORS`) and indexed device dependent bitmaps (`Bitmap16`) are drawn with a gray scale, + and monochrome `Bitmap16` are drawn in black & white, + - raster operations are applied on the image : a transparent background is used as a white background, + - corrupted JPEG & PNG bitmaps are not drawn. +- Flood fills (`META_FLOODFILL` & `META_EXTFLOODFILL`) ignore the clipping region. +- Texts : + - texts are not drawn if no font is found (see [Fonts](#fonts)), + - the metrics of fonts are approximated (ascent, descent), the width & the orientation of fonts are ignored, + - the charset is ignored : texts are decoded as Windows-1252, + - the characters of the `Symbol` font are converted to Unicode (Greek letters, mathematical symbols...), + other symbol fonts (like `Wingdings`) are drawn with another font. +- `META_SETROP2`, `META_SETSTRETCHBLTMODE`, `META_ESCAPE` & palettes are ignored. + +### Fonts + +Texts are drawn with the TrueType/OpenType fonts (`.ttf` & `.otf`) found in the system directories. +You can define the directories where fonts are searched (recursively) with `setFontDirectories`. + +See [EMF > Fonts](emf.md#fonts) for more details. + +```php +setFontDirectories([ + __DIR__ . '/fonts', +]); +$reader->load('sample.wmf'); +``` + +## Methods + +### `getResource` + +The method returns the resource used in internal by the library. + +The `GD` backend returns a `GDImage` object or resource, depending the PHP version. +The `Imagick` backend returns a `Imagick` object. + +```php +load('sample.wmf'); + +var_dump($reader->getResource()); +``` + +### `getMediaType` + +The method returns the media type for a WMF file. + +```php +getMediaType(); + +echo 'The media type for a WMF file is ' . $$mediaType; +``` + +### `setBackgroundColor` + +The method defines the color of the background (white by default), or a transparent background (`null`). +The background must be defined before loading the file. +Formats without alpha channel (`gif`, `jpg` & `wbmp`) are saved with a white background. + +```php +setBackgroundColor(null); +// Blue background +$reader->setBackgroundColor([0, 0, 255]); +$reader->load('sample.wmf'); +``` + +### `isWMF` + +The method returns if the file is supported by the library. + +```php +load('sample.wmf'); + +$isWMF = $reader->isWMF(); + +echo 'The file sample.wmf ' . ($isWMF ? 'is a WMF file' : 'is not a WMF file'); +``` + +### `isSupported` + +The method returns if the reader can be used : the extension is loaded (and supports the format, for `Imagick`). +For `Magic::class`, the method returns if one of its backends can be used. + +```php +isSupported() ? 'can' : 'can not') . ' be used'; +``` + +### `load` + +The method loads a WMF file in the object. +The method returns `true` if the file has been correctly loaded, or `false` if it has not. + +```php +load('sample.wmf'); +``` + +### `loadFromString` + +The method loads a WMF file in the object from a string. +The method returns `true` if the file has been correctly loaded, or `false` if it has not. + +```php +loadFromString(file_get_contents('sample.wmf')); +``` + +### `save` + +The method transforms the loaded WMF file in an another image. + +```php +load('sample.wmf'); +$reader->save('sample.png', 'png'); +``` diff --git a/vendor/phpoffice/wmf/phpstan.neon.dist b/vendor/phpoffice/wmf/phpstan.neon.dist new file mode 100644 index 00000000..cd5eabf1 --- /dev/null +++ b/vendor/phpoffice/wmf/phpstan.neon.dist @@ -0,0 +1,9 @@ +parameters: + level: 6 + bootstrapFiles: + - vendor/autoload.php + paths: + - src + - tests + reportUnmatchedIgnoredErrors: false + ignoreErrors: \ No newline at end of file diff --git a/vendor/phpoffice/wmf/phpunit.xml.dist b/vendor/phpoffice/wmf/phpunit.xml.dist new file mode 100644 index 00000000..94ebc8ab --- /dev/null +++ b/vendor/phpoffice/wmf/phpunit.xml.dist @@ -0,0 +1,29 @@ + + + + ./tests/WMF + + + + + ./src + + + + + + + + + src + + + \ No newline at end of file diff --git a/vendor/phpoffice/wmf/properdocs.yml b/vendor/phpoffice/wmf/properdocs.yml new file mode 100644 index 00000000..e077decb --- /dev/null +++ b/vendor/phpoffice/wmf/properdocs.yml @@ -0,0 +1,57 @@ +site_name: WMF +site_url: https://phpoffice.github.io/WMF +repo_url: https://github.com/PHPOffice/WMF +repo_name: PHPOffice/WMF +edit_uri: edit/master/docs/ + +## Theme +theme: + name: material + palette: + primary: grey + features: + - search.highlight + - search.suggest + +## Plugins +plugins: + - search + +## Config +extra: + generator: false +extra_javascript: + - https://polyfill.io/v3/polyfill.min.js?features=es6 +markdown_extensions: + ## Syntax highlighting + - pymdownx.highlight + - pymdownx.superfences + ## Support for emojis + - pymdownx.emoji: + emoji_index: !!python/name:materialx.emoji.twemoji + emoji_generator: !!python/name:materialx.emoji.to_svg + ## Support for call-outs + - admonition + - pymdownx.details +use_directory_urls: false + +## Navigation +nav: + - Introduction: 'index.md' + - Install: 'install.md' + - Usage: + - WMF: 'usage/wmf.md' + - EMF: 'usage/emf.md' + - Detector: 'usage/detector.md' + - Credits: 'credits.md' + - Releases: + - '0.2.1 (WIP)': 'changes/0.2.1.md' + - '0.2.0': 'changes/0.2.0.md' + - '0.1.3': 'changes/0.1.3.md' + - '0.1.2': 'changes/0.1.2.md' + - '0.1.1': 'changes/0.1.1.md' + - '0.1.0': 'changes/0.1.0.md' + - Developers: + - 'Coveralls': 'https://coveralls.io/github/PHPOffice/WMF' + - 'Code Coverage': 'coverage/index.html' + - 'PHPDoc': 'docs/index.html' \ No newline at end of file diff --git a/vendor/phpoffice/wmf/src/WMF/Exception/WMFException.php b/vendor/phpoffice/wmf/src/WMF/Exception/WMFException.php new file mode 100644 index 00000000..662df2d2 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Exception/WMFException.php @@ -0,0 +1,11 @@ += 88 && $signature == self::EMF_SIGNATURE; + } + + /** + * Returns if the content is a EMF+ file : a EMF file whose first record after the header is a EMF+ header + */ + public static function isEMFPlus(string $content): bool + { + if (!self::isEMF($content)) { + return false; + } + list(, $headerSize) = unpack('V', (string) substr($content, 4, 4)); + $record = (string) substr($content, $headerSize, 28); + if (strlen($record) < 28) { + return false; + } + $comment = unpack('Vtype/Vsize/VdataSize/Videntifier/vplusType', $record); + + return $comment['type'] == EMFReader::EMR_GDICOMMENT + && $comment['identifier'] == self::EMFPLUS_IDENTIFIER + && $comment['plusType'] == self::EMFPLUS_HEADER; + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/EMF/GD.php b/vendor/phpoffice/wmf/src/WMF/Reader/EMF/GD.php new file mode 100644 index 00000000..e775e451 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/EMF/GD.php @@ -0,0 +1,833 @@ +> + */ + protected $objects = []; + + /** + * If the EMF+ records are drawn (else, only the EMF records are drawn) + * + * @var bool + */ + protected $isEMFPlusEnabled = true; + /** + * If the last loaded file has been drawn with its EMF+ records + * + * @var bool + */ + protected $isEMFPlusRendered = false; + + public function __construct() + { + $this->fontResolver = new FontResolver(); + } + + /** + * Enables/disables the drawing of EMF+ records + * + * When enabled (by default), EMF+ files are drawn with their EMF+ records, and only the EMF records following + * EmfPlusGetDC records are drawn. If the EMF+ records can not be drawn, the file is drawn with its EMF records. + */ + public function setEMFPlusEnabled(bool $isEnabled): self + { + $this->isEMFPlusEnabled = $isEnabled; + + return $this; + } + + public function isEMFPlusEnabled(): bool + { + return $this->isEMFPlusEnabled; + } + + /** + * Returns if the last loaded file has been drawn with its EMF+ records + */ + public function isEMFPlusRendered(): bool + { + return $this->isEMFPlusRendered; + } + + /** + * Returns if the file is a EMF file (EMF+ dual files are EMF files too) + */ + public function isEMF(): bool + { + return Detector::isEMF((string) $this->content); + } + + /** + * Defines the directories where TrueType/OpenType fonts are searched (recursively) + * + * By default, the system directories are used + * + * @param array $directories + */ + public function setFontDirectories(array $directories): self + { + $this->fontResolver->setDirectories($directories); + + return $this; + } + + /** + * @return array + */ + public function getFontDirectories(): array + { + return $this->fontResolver->getDirectories(); + } + + protected function loadContent(): bool + { + if (!$this->isEMF()) { + return false; + } + + // Corrupted files must not raise PHP errors + set_error_handler(function (int $errno, string $errstr): bool { + if (!(error_reporting() & $errno)) { + return false; + } + throw new WMFException('Reader : Invalid file : ' . $errstr); + }); + $this->isEMFPlusRendered = false; + try { + if ($this->isEMFPlusEnabled && Detector::isEMFPlus((string) $this->content)) { + try { + $this->readRecords(true); + $this->isEMFPlusRendered = true; + } catch (WMFException $e) { + // The EMF+ records can not be drawn : the EMF records are drawn + $this->readRecords(false); + } + } else { + $this->readRecords(false); + } + } catch (WMFException $e) { + if ($this->hasExceptionsEnabled()) { + throw $e; + } + + return false; + } finally { + restore_error_handler(); + } + + return true; + } + + /** + * @param bool $isEMFPlus If the EMF+ records are drawn (the EMF records are then drawn only after EmfPlusGetDC records) + */ + protected function readRecords(bool $isEMFPlus = false): void + { + $this->readHeader(); + $this->objects = []; + $player = $isEMFPlus ? new Player($this->renderer) : null; + $isEMFPlaying = !$isEMFPlus; + + $contentLen = strlen($this->content); + // The first record is the header + list(, $pos) = unpack('V', (string) substr($this->content, 4, 4)); + $pos = (int) $pos; + + while ($pos + 8 <= $contentLen) { + list(, $recordType, $size) = unpack('V2', (string) substr($this->content, $pos, 8)); + $recordType = (int) $recordType; + $size = (int) $size; + if ($size < 8 || $pos + $size > $contentLen) { + break; + } + $record = (string) substr($this->content, $pos, $size); + $pos += $size; + + if ($recordType == self::EMR_EOF) { + break; + } + // EMF+ records are stored in comments (after the "EMF+" identifier) + if ($player && $recordType == self::EMR_GDICOMMENT && $size >= 16 && (string) substr($record, 12, 4) === 'EMF+') { + list(, $dataSize) = unpack('V', (string) substr($record, 8, 4)); + $isEMFPlaying = $player->play((string) substr($record, 16, max(0, min((int) $dataSize, $size - 12) - 4))); + continue; + } + if (!$isEMFPlaying) { + continue; + } + if (in_array($recordType, self::IGNORED_RECORDS)) { + continue; + } + if (!$this->readRecord($recordType, $record)) { + throw new WMFException('Reader : Function not implemented : 0x' . str_pad(dechex($recordType), 4, '0', STR_PAD_LEFT)); + } + } + + $this->gd = $this->renderer->render(); + } + + /** + * Creates the renderer from the header : the frame defines the size of the image + */ + protected function readHeader(): void + { + $header = unpack( + 'Vtype/Vsize/lboundsLeft/lboundsTop/lboundsRight/lboundsBottom/lframeLeft/lframeTop/lframeRight/lframeBottom/Vsignature/Vversion/Vbytes/Vrecords/vhandles/vreserved/VnDescription/VoffDescription/VnPalEntries/ldeviceX/ldeviceY/lmillimetersX/lmillimetersY', + (string) substr($this->content, 0, 88) + ); + + $pixelsPerMmX = $header['millimetersX'] > 0 ? $header['deviceX'] / $header['millimetersX'] : 96 / 25.4; + $pixelsPerMmY = $header['millimetersY'] > 0 ? $header['deviceY'] / $header['millimetersY'] : 96 / 25.4; + + $frameWidth = $header['frameRight'] - $header['frameLeft']; + $frameHeight = $header['frameBottom'] - $header['frameTop']; + if ($frameWidth > 0 && $frameHeight > 0) { + // The frame (in 0.01mm) defines the physical size of the image + $originX = $header['frameLeft'] * $pixelsPerMmX / 100; + $originY = $header['frameTop'] * $pixelsPerMmY / 100; + $deviceWidth = $frameWidth * $pixelsPerMmX / 100; + $deviceHeight = $frameHeight * $pixelsPerMmY / 100; + $width = (int) max(1, round($frameWidth / 2540 * self::DPI)); + $height = (int) max(1, round($frameHeight / 2540 * self::DPI)); + } else { + // Fallback on the bounds (in device units) + $originX = $header['boundsLeft']; + $originY = $header['boundsTop']; + $deviceWidth = $width = (int) max(1, $header['boundsRight'] - $header['boundsLeft'] + 1); + $deviceHeight = $height = (int) max(1, $header['boundsBottom'] - $header['boundsTop'] + 1); + } + + $this->destroyImage($this->gd); + $this->gd = false; + $this->renderer = new Renderer($width, $height, $deviceWidth, $deviceHeight, $originX, $originY, $this->fontResolver, $this->backgroundColor); + $this->renderer->setPixelsPerMm($pixelsPerMmX, $pixelsPerMmY); + } + + /** + * Returns false if the record is not supported + */ + protected function readRecord(int $recordType, string $record): bool + { + $renderer = $this->renderer; + switch ($recordType) { + case self::EMR_SETMAPMODE: + $renderer->setMapMode($this->readUInt($record, 8)); + break; + case self::EMR_SETWINDOWEXTEX: + $renderer->setWindowExt(...$this->readInts($record, 8, 2)); + break; + case self::EMR_SETWINDOWORGEX: + $renderer->setWindowOrg(...$this->readInts($record, 8, 2)); + break; + case self::EMR_SETVIEWPORTEXTEX: + $renderer->setViewportExt(...$this->readInts($record, 8, 2)); + break; + case self::EMR_SETVIEWPORTORGEX: + $renderer->setViewportOrg(...$this->readInts($record, 8, 2)); + break; + case self::EMR_SCALEVIEWPORTEXTEX: + $renderer->scaleViewportExt(...$this->readInts($record, 8, 4)); + break; + case self::EMR_SCALEWINDOWEXTEX: + $renderer->scaleWindowExt(...$this->readInts($record, 8, 4)); + break; + case self::EMR_SETWORLDTRANSFORM: + $renderer->setWorldTransform(array_values(unpack('g6', (string) substr($record, 8, 24)))); + break; + case self::EMR_MODIFYWORLDTRANSFORM: + $renderer->modifyWorldTransform(array_values(unpack('g6', (string) substr($record, 8, 24))), $this->readUInt($record, 32)); + break; + case self::EMR_SETARCDIRECTION: + $renderer->setArcDirection($this->readUInt($record, 8)); + break; + case self::EMR_SETTEXTCOLOR: + $renderer->setTextColor($this->readColor($record, 8)); + break; + case self::EMR_SETBKCOLOR: + $renderer->setBkColor($this->readColor($record, 8)); + break; + case self::EMR_SETBKMODE: + $renderer->setBkMode($this->readUInt($record, 8)); + break; + case self::EMR_SETTEXTALIGN: + $renderer->setTextAlign($this->readUInt($record, 8)); + break; + case self::EMR_SETMITERLIMIT: + $renderer->setMiterLimit($this->readUInt($record, 8)); + break; + case self::EMR_SETPOLYFILLMODE: + $renderer->setPolyFillMode($this->readUInt($record, 8)); + break; + case self::EMR_SAVEDC: + $renderer->saveDC(); + break; + case self::EMR_RESTOREDC: + $renderer->restoreDC($this->readInts($record, 8, 1)[0]); + break; + + case self::EMR_CREATEPEN: + $pen = unpack('Vih/Vstyle/lwidth/lunused/Cr/Cg/Cb', (string) substr($record, 8, 23)); + $this->objects[$pen['ih']] = [ + 'type' => 'pen', + 'style' => $pen['style'], + 'width' => $pen['width'], + 'geometric' => true, + 'color' => [$pen['r'], $pen['g'], $pen['b']], + // Dashes are drawn only for pens of one pixel + 'dashes' => $pen['width'] <= 1 ? Renderer::getPenDashes($pen['style'], true, $pen['width']) : null, + ]; + break; + case self::EMR_EXTCREATEPEN: + $pen = unpack('Vih/VoffBmi/VcbBmi/VoffBits/VcbBits/Vstyle/Vwidth/VbrushStyle/Cr/Cg/Cb', (string) substr($record, 8, 35)); + $isGeometric = ($pen['style'] & 0x00010000) > 0; + // PS_USERSTYLE : lengths of dashes & spaces + $userStyle = []; + if (($pen['style'] & 0x0F) == 7 && strlen($record) >= 52) { + $count = min($this->readUInt($record, 48), intdiv(strlen($record) - 52, 4)); + $userStyle = $count > 0 ? array_values(unpack('V' . $count, (string) substr($record, 52, 4 * $count))) : []; + } + $this->objects[$pen['ih']] = [ + 'type' => 'pen', + 'style' => $pen['brushStyle'] == 1 ? 5 : $pen['style'], + 'width' => $pen['width'], + 'geometric' => $isGeometric, + 'color' => [$pen['r'], $pen['g'], $pen['b']], + 'dashes' => Renderer::getPenDashes($pen['style'], !$isGeometric, $pen['width'], $userStyle), + ]; + break; + case self::EMR_CREATEBRUSHINDIRECT: + $brush = unpack('Vih/Vstyle/Cr/Cg/Cb/x/Vhatch', (string) substr($record, 8, 16)); + $this->objects[$brush['ih']] = [ + 'type' => 'brush', + 'style' => $brush['style'], + 'color' => [$brush['r'], $brush['g'], $brush['b']], + 'hatch' => $brush['hatch'], + ]; + break; + case self::EMR_CREATEMONOBRUSH: + case self::EMR_CREATEDIBPATTERNBRUSHPT: + // The pattern is tiled (its average color is used when a color is needed) + $brush = unpack('Vih/Vusage/VoffBmi/VcbBmi/VoffBits/VcbBits', (string) substr($record, 8, 24)); + $bitmap = $this->requireBitmap( + Bitmap::readDIB($record, $brush['offBmi'], $brush['offBits'], $brush['cbBmi'], $brush['cbBits'], $brush['usage'] == Bitmap::DIB_PAL_COLORS), + $recordType + ); + $this->objects[$brush['ih']] = [ + 'type' => 'brush', + 'style' => 3, + 'color' => Bitmap::getAverageColor($bitmap), + 'pattern' => $bitmap, + ]; + break; + case self::EMR_EXTCREATEFONTINDIRECTW: + $font = unpack('Vih/lheight/lwidth/lescapement/lorientation/lweight/Citalic/Cunderline/CstrikeOut/Ccharset/CoutPrecision/CclipPrecision/Cquality/CpitchAndFamily', (string) substr($record, 8, 32)); + $this->objects[$font['ih']] = [ + 'type' => 'font', + 'height' => $font['height'], + 'escapement' => $font['escapement'], + 'weight' => $font['weight'], + 'italic' => $font['italic'] > 0, + 'underline' => $font['underline'] > 0, + 'strikeOut' => $font['strikeOut'] > 0, + 'charset' => $font['charset'], + 'pitchAndFamily' => $font['pitchAndFamily'], + 'face' => Encoding::decodeUTF16((string) substr($record, 40, 64)), + ]; + break; + case self::EMR_CREATEPALETTE: + $this->objects[$this->readUInt($record, 8)] = ['type' => 'other']; + break; + case self::EMR_SELECTOBJECT: + $ih = $this->readUInt($record, 8); + $object = ($ih & 0x80000000) ? Renderer::getStockObject($ih & 0x7FFFFFFF) : ($this->objects[$ih] ?? null); + if ($object) { + $renderer->selectObject($object); + } + break; + case self::EMR_DELETEOBJECT: + unset($this->objects[$this->readUInt($record, 8)]); + break; + + case self::EMR_BEGINPATH: + $renderer->beginPath(); + break; + case self::EMR_ENDPATH: + $renderer->endPath(); + break; + case self::EMR_ABORTPATH: + $renderer->abortPath(); + break; + case self::EMR_CLOSEFIGURE: + $renderer->closeFigure(); + break; + case self::EMR_FILLPATH: + $renderer->fillPath(); + break; + case self::EMR_STROKEPATH: + $renderer->strokePath(); + break; + case self::EMR_STROKEANDFILLPATH: + $renderer->strokeAndFillPath(); + break; + case self::EMR_SELECTCLIPPATH: + $renderer->selectClipPath($this->readUInt($record, 8)); + break; + + case self::EMR_INTERSECTCLIPRECT: + $renderer->intersectClipRect(...$this->readInts($record, 8, 4)); + break; + case self::EMR_EXCLUDECLIPRECT: + $renderer->excludeClipRect(...$this->readInts($record, 8, 4)); + break; + case self::EMR_OFFSETCLIPRGN: + $renderer->offsetClipRegion(...$this->readInts($record, 8, 2)); + break; + case self::EMR_EXTSELECTCLIPRGN: + list(, $cbRgnData, $mode) = unpack('V2', (string) substr($record, 8, 8)); + if ($cbRgnData == 0) { + // Only RGN_COPY is allowed : the clipping region is reset + $renderer->resetClipRegion(); + break; + } + // Region rectangles are in device units + $count = $this->readUInt($record, 16 + 8); + $rectangles = []; + for ($i = 0; $i < $count; ++$i) { + $rectangles[] = $this->readInts($record, 16 + 32 + 16 * $i, 4); + } + $renderer->selectClipRegion($rectangles, $mode, true); + break; + + case self::EMR_POLYGON: + case self::EMR_POLYGON16: + $renderer->polygon($this->readPoints($record, 28, $this->readUInt($record, 24), $recordType == self::EMR_POLYGON16)); + break; + case self::EMR_POLYLINE: + case self::EMR_POLYLINE16: + $renderer->polyline($this->readPoints($record, 28, $this->readUInt($record, 24), $recordType == self::EMR_POLYLINE16)); + break; + case self::EMR_POLYBEZIER: + case self::EMR_POLYBEZIER16: + $renderer->polyBezier($this->readPoints($record, 28, $this->readUInt($record, 24), $recordType == self::EMR_POLYBEZIER16)); + break; + case self::EMR_POLYPOLYGON: + case self::EMR_POLYPOLYGON16: + case self::EMR_POLYPOLYLINE: + case self::EMR_POLYPOLYLINE16: + $is16 = in_array($recordType, [self::EMR_POLYPOLYGON16, self::EMR_POLYPOLYLINE16]); + $numPolys = $this->readUInt($record, 24); + $counts = $numPolys > 0 ? array_values(unpack('V' . $numPolys, (string) substr($record, 32, 4 * $numPolys))) : []; + $offset = 32 + 4 * $numPolys; + $polygons = []; + foreach ($counts as $count) { + $polygons[] = $this->readPoints($record, $offset, $count, $is16); + $offset += $count * ($is16 ? 4 : 8); + } + $renderer->polyPolygon($polygons, in_array($recordType, [self::EMR_POLYPOLYGON, self::EMR_POLYPOLYGON16])); + break; + case self::EMR_RECTANGLE: + $renderer->rectangle(...$this->readInts($record, 8, 4)); + break; + case self::EMR_ELLIPSE: + $renderer->ellipse(...$this->readInts($record, 8, 4)); + break; + case self::EMR_ROUNDRECT: + $renderer->roundRect(...$this->readInts($record, 8, 6)); + break; + case self::EMR_ARC: + $renderer->arc(...$this->readInts($record, 8, 8)); + break; + case self::EMR_ARCTO: + $renderer->arcTo(...$this->readInts($record, 8, 8)); + break; + case self::EMR_CHORD: + $renderer->chord(...$this->readInts($record, 8, 8)); + break; + case self::EMR_PIE: + $renderer->pie(...$this->readInts($record, 8, 8)); + break; + case self::EMR_ANGLEARC: + $data = unpack('lx/ly/Vradius/gstart/gsweep', (string) substr($record, 8, 20)); + $renderer->angleArc($data['x'], $data['y'], $data['radius'], $data['start'], $data['sweep']); + break; + case self::EMR_SETPIXELV: + list($x, $y) = $this->readInts($record, 8, 2); + $renderer->setPixel($x, $y, $this->readColor($record, 16)); + break; + case self::EMR_EXTTEXTOUTA: + case self::EMR_EXTTEXTOUTW: + $this->readText($record, $recordType == self::EMR_EXTTEXTOUTW); + break; + case self::EMR_SMALLTEXTOUT: + $data = unpack('lx/ly/Vchars/Voptions', (string) substr($record, 8, 16)); + $offset = 36; + $rectangle = [0, 0, 0, 0]; + // ETO_NO_RECT + if (!($data['options'] & 0x0100)) { + $rectangle = $this->readInts($record, $offset, 4); + $offset += 16; + } + // ETO_SMALL_CHARS : 8-bit characters + $text = ($data['options'] & 0x0200) + ? Encoding::decodeANSI((string) substr($record, $offset, $data['chars'])) + : Encoding::decodeUTF16((string) substr($record, $offset, 2 * $data['chars'])); + $renderer->textOut($data['x'], $data['y'], $text, [], $data['options'], $rectangle); + break; + case self::EMR_MOVETOEX: + $renderer->moveTo(...$this->readInts($record, 8, 2)); + break; + case self::EMR_LINETO: + $renderer->lineTo(...$this->readInts($record, 8, 2)); + break; + case self::EMR_POLYLINETO: + case self::EMR_POLYLINETO16: + $renderer->polylineTo($this->readPoints($record, 28, $this->readUInt($record, 24), $recordType == self::EMR_POLYLINETO16)); + break; + case self::EMR_POLYBEZIERTO: + case self::EMR_POLYBEZIERTO16: + $renderer->polylineTo($this->readPoints($record, 28, $this->readUInt($record, 24), $recordType == self::EMR_POLYBEZIERTO16), true); + break; + + case self::EMR_STRETCHDIBITS: + $data = unpack('l4bounds/lxDest/lyDest/lxSrc/lySrc/lcxSrc/lcySrc/VoffBmi/VcbBmi/VoffBits/VcbBits/Vusage/Vrop/lcxDest/lcyDest', (string) substr($record, 8, 72)); + if ($data['rop'] == Renderer::ROP_NOP) { + break; + } + $bitmap = $this->requireBitmap( + Bitmap::readDIB($record, $data['offBmi'], $data['offBits'], $data['cbBmi'], $data['cbBits'], $data['usage'] == Bitmap::DIB_PAL_COLORS), + $recordType + ); + $renderer->drawBitmap($bitmap, $data['xDest'], $data['yDest'], $data['cxDest'], $data['cyDest'], $data['xSrc'], $data['ySrc'], $data['cxSrc'], $data['cySrc'], $data['rop']); + break; + case self::EMR_SETDIBITSTODEVICE: + $this->readSetDIBitsToDevice($record); + break; + case self::EMR_GRADIENTFILL: + $this->readGradientFill($record); + break; + case self::EMR_BITBLT: + case self::EMR_STRETCHBLT: + $data = unpack('l4bounds/lxDest/lyDest/lcxDest/lcyDest/Vrop/lxSrc/lySrc/g6xform/VbkColor/Vusage/VoffBmi/VcbBmi/VoffBits/VcbBits', (string) substr($record, 8, 92)); + if ($data['rop'] == Renderer::ROP_NOP) { + break; + } + if ($data['cbBmi'] == 0) { + // No source bitmap : the rectangle is filled with the brush (PATCOPY), in black or in white + $renderer->patBlt($data['xDest'], $data['yDest'], $data['xDest'] + $data['cxDest'], $data['yDest'] + $data['cyDest'], $data['rop']); + break; + } + $bitmap = $this->requireBitmap( + Bitmap::readDIB($record, $data['offBmi'], $data['offBits'], $data['cbBmi'], $data['cbBits'], $data['usage'] == Bitmap::DIB_PAL_COLORS), + $recordType + ); + $cxSrc = $data['cxDest']; + $cySrc = $data['cyDest']; + if ($recordType == self::EMR_STRETCHBLT) { + list($cxSrc, $cySrc) = $this->readInts($record, 100, 2); + } + $renderer->drawBitmap($bitmap, $data['xDest'], $data['yDest'], $data['cxDest'], $data['cyDest'], $data['xSrc'], $data['ySrc'], $cxSrc, $cySrc, $data['rop']); + break; + default: + return false; + } + + return true; + } + + /** + * Draws a EMR_SETDIBITSTODEVICE record : a band of scan lines of a DIB, copied without stretching + * + * The bits only contain the scan lines from iStartScan to iStartScan + cScans - 1 (the scan line 0 is the bottom row + * of a bottom-up DIB, the top row of a top-down DIB), while the header of the DIB defines the height of the whole DIB. + * The source rectangle is expressed in the coordinates of the whole DIB, whose origin is its lower-left corner for + * a bottom-up DIB and its upper-left corner for a top-down DIB. + */ + protected function readSetDIBitsToDevice(string $record): void + { + $data = unpack('l4bounds/lxDest/lyDest/lxSrc/lySrc/lcxSrc/lcySrc/VoffBmi/VcbBmi/VoffBits/VcbBits/Vusage/ViStartScan/VcScans', (string) substr($record, 8, 68)); + if ($data['cScans'] <= 0 || $data['cxSrc'] <= 0 || $data['cySrc'] <= 0 || strlen($record) < $data['offBmi'] + 40) { + return; + } + list(, $height) = unpack('l', (string) substr($record, $data['offBmi'] + 8, 4)); + $isBottomUp = $height > 0; + // The DIB is decoded with the height of the band + $band = substr_replace($record, pack('l', $isBottomUp ? $data['cScans'] : -$data['cScans']), $data['offBmi'] + 8, 4); + $bitmap = $this->requireBitmap( + Bitmap::readDIB($band, $data['offBmi'], $data['offBits'], $data['cbBmi'], $data['cbBits'], $data['usage'] == Bitmap::DIB_PAL_COLORS), + self::EMR_SETDIBITSTODEVICE + ); + // Top row of the source rectangle in the band (whose rows are decoded from top to bottom) + $ySrc = $isBottomUp + ? $data['iStartScan'] + $data['cScans'] - $data['ySrc'] - $data['cySrc'] + : $data['ySrc'] - $data['iStartScan']; + // Only the scan lines of the band are drawn + $top = max(0, $ySrc); + $bottom = min($bitmap['height'], $ySrc + $data['cySrc']); + if ($bottom <= $top) { + return; + } + $this->renderer->drawBitmap( + $bitmap, + $data['xDest'], + $data['yDest'] + $top - $ySrc, + $data['cxSrc'], + $bottom - $top, + $data['xSrc'], + $top, + $data['cxSrc'], + $bottom - $top + ); + } + + protected function readUInt(string $record, int $offset): int + { + list(, $value) = unpack('V', (string) substr($record, $offset, 4)); + + return (int) $value; + } + + /** + * @return array + */ + protected function readInts(string $record, int $offset, int $count): array + { + return array_values(unpack('l' . $count, (string) substr($record, $offset, 4 * $count))); + } + + /** + * Reads a COLORREF + * + * @return array + */ + protected function readColor(string $record, int $offset): array + { + return array_values(unpack('C3', (string) substr($record, $offset, 3))); + } + + /** + * @return array> Logical coordinates + */ + protected function readPoints(string $record, int $offset, int $count, bool $is16): array + { + if ($count <= 0) { + return []; + } + $values = array_values(unpack(($is16 ? 's' : 'l') . ($count * 2), (string) substr($record, $offset, $count * ($is16 ? 4 : 8)))); + + $points = []; + for ($i = 0; $i < $count; ++$i) { + $points[] = [$values[2 * $i], $values[2 * $i + 1]]; + } + + return $points; + } + + /** + * Reads EMR_EXTTEXTOUTA & EMR_EXTTEXTOUTW records + */ + protected function readText(string $record, bool $isUnicode): void + { + $data = unpack('lx/ly/Vchars/VoffString/Voptions/lleft/ltop/lright/lbottom/VoffDx', (string) substr($record, 36, 40)); + $count = $data['chars']; + + $text = ''; + if ($count > 0) { + $text = $isUnicode + ? Encoding::decodeUTF16((string) substr($record, $data['offString'], 2 * $count)) + : Encoding::decodeANSI((string) substr($record, $data['offString'], $count)); + } + + // Advances of each character (ETO_PDY : pairs of horizontal & vertical advances) + $dx = $dy = []; + if ($count > 0 && $data['offDx'] > 0) { + $step = ($data['options'] & 0x2000) ? 2 : 1; + $values = array_values(unpack('l' . ($count * $step), (string) substr($record, $data['offDx'], 4 * $count * $step))); + for ($i = 0; $i < $count; ++$i) { + $dx[] = $values[$i * $step]; + if ($step == 2) { + $dy[] = $values[$i * $step + 1]; + } + } + } + + $this->renderer->textOut($data['x'], $data['y'], $text, $dx, $data['options'], [$data['left'], $data['top'], $data['right'], $data['bottom']], $dy); + } + + protected function readGradientFill(string $record): void + { + list(, $countVertices, $countObjects, $mode) = unpack('V3', (string) substr($record, 24, 12)); + + $vertices = []; + for ($i = 0; $i < $countVertices; ++$i) { + $vertex = unpack('lx/ly/vr/vg/vb', (string) substr($record, 36 + 16 * $i, 14)); + $vertices[] = [$vertex['x'], $vertex['y'], [$vertex['r'] >> 8, $vertex['g'] >> 8, $vertex['b'] >> 8]]; + } + + // Triangles (GRADIENT_FILL_TRIANGLE) or rectangles (GRADIENT_FILL_RECT_H & GRADIENT_FILL_RECT_V) + $size = $mode == 2 ? 3 : 2; + $offset = 36 + 16 * $countVertices; + $objects = []; + for ($i = 0; $i < $countObjects; ++$i) { + $objects[] = array_values(unpack('V' . $size, (string) substr($record, $offset + 4 * $size * $i, 4 * $size))); + } + + $this->renderer->gradientFill($vertices, $objects, $mode); + } + + /** + * @phpstan-ignore-next-line + * + * @return GdImage|resource + */ + public function getResource() + { + return $this->gd; + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/EMF/Imagick.php b/vendor/phpoffice/wmf/src/WMF/Reader/EMF/Imagick.php new file mode 100644 index 00000000..fc23e75f --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/EMF/Imagick.php @@ -0,0 +1,17 @@ +isImagickFormat(); + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/EMF/Magic.php b/vendor/phpoffice/wmf/src/WMF/Reader/EMF/Magic.php new file mode 100644 index 00000000..db4eb7c8 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/EMF/Magic.php @@ -0,0 +1,35 @@ + + */ + protected $backends = [ + ImagickReader::class, + GD::class, + ]; + + protected function isBackend(string $backend): bool + { + return is_a($backend, ReaderInterface::class, true); + } + + public function isEMF(): bool + { + $backend = $this->getBackend(); + + return $backend instanceof ReaderInterface && $backend->isEMF(); + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/EMF/ReaderAbstract.php b/vendor/phpoffice/wmf/src/WMF/Reader/EMF/ReaderAbstract.php new file mode 100644 index 00000000..cdc05cc6 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/EMF/ReaderAbstract.php @@ -0,0 +1,15 @@ +data = $data; + } + + public function getPosition(): int + { + return $this->position; + } + + public function getRemaining(): int + { + return strlen($this->data) - $this->position; + } + + public function skip(int $length): self + { + $this->read($length); + + return $this; + } + + /** + * Skips the padding up to a multiple of 4 bytes (from the start of the data) + */ + public function align(): self + { + $this->position = min(strlen($this->data), (int) (ceil($this->position / 4) * 4)); + + return $this; + } + + public function read(int $length): string + { + if ($length < 0 || $this->position + $length > strlen($this->data)) { + throw new WMFException('Reader : Invalid file : truncated EMF+ data'); + } + $value = (string) substr($this->data, $this->position, $length); + $this->position += $length; + + return $value; + } + + public function readUInt8(): int + { + return ord($this->read(1)); + } + + public function readUInt16(): int + { + return (int) unpack('v', $this->read(2))[1]; + } + + public function readInt16(): int + { + $value = $this->readUInt16(); + + return $value >= 0x8000 ? $value - 0x10000 : $value; + } + + public function readUInt32(): int + { + return (int) unpack('V', $this->read(4))[1]; + } + + public function readInt32(): int + { + $value = $this->readUInt32(); + + return $value >= 0x80000000 ? $value - 0x100000000 : $value; + } + + public function readFloat(): float + { + $value = (float) unpack('g', $this->read(4))[1]; + + return is_finite($value) ? $value : 0.0; + } + + /** + * Reads an ARGB color : [r, g, b, a] + * + * @return array + */ + public function readColor(): array + { + return self::toColor($this->readUInt32()); + } + + /** + * Converts an ARGB value to a color [r, g, b, a] + * + * @return array + */ + public static function toColor(int $argb): array + { + return [($argb >> 16) & 0xFF, ($argb >> 8) & 0xFF, $argb & 0xFF, ($argb >> 24) & 0xFF]; + } + + /** + * Reads a matrix [m11, m12, m21, m22, dx, dy] + * + * @return array + */ + public function readMatrix(): array + { + $matrix = []; + for ($i = 0; $i < 6; ++$i) { + $matrix[] = $this->readFloat(); + } + + return $matrix; + } + + /** + * Reads a rectangle [x, y, width, height] : 16-bit integers if compressed, else floats + * + * @return array + */ + public function readRect(bool $isCompressed = false): array + { + if ($isCompressed) { + return [$this->readInt16(), $this->readInt16(), $this->readInt16(), $this->readInt16()]; + } + + return [$this->readFloat(), $this->readFloat(), $this->readFloat(), $this->readFloat()]; + } + + /** + * Reads points : floats, 16-bit integers (compressed) or relative points (EmfPlusPointR) + * + * @return array> + */ + public function readPoints(int $count, bool $isCompressed = false, bool $isRelative = false): array + { + if ($count < 0 || $count > $this->getRemaining()) { + throw new WMFException('Reader : Invalid file : truncated EMF+ data'); + } + $points = []; + $x = $y = 0; + for ($i = 0; $i < $count; ++$i) { + if ($isRelative) { + // Each coordinate is relative to the previous point + $x += $this->readRelativeInteger(); + $y += $this->readRelativeInteger(); + $points[] = [$x, $y]; + } elseif ($isCompressed) { + $points[] = [$this->readInt16(), $this->readInt16()]; + } else { + $points[] = [$this->readFloat(), $this->readFloat()]; + } + } + + return $points; + } + + /** + * Reads an EmfPlusInteger7 (1 byte) or an EmfPlusInteger15 (2 bytes, big-endian) + */ + protected function readRelativeInteger(): int + { + $first = $this->readUInt8(); + if ($first & 0x80) { + $value = (($first & 0x7F) << 8) | $this->readUInt8(); + + return $value >= 0x4000 ? $value - 0x8000 : $value; + } + + return $first >= 0x40 ? $first - 0x80 : $first; + } + + /** + * Reads a UTF-16LE string of $length characters + */ + public function readString(int $length): string + { + return $this->read(2 * max(0, $length)); + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/EMFPlus/ObjectReader.php b/vendor/phpoffice/wmf/src/WMF/Reader/EMFPlus/ObjectReader.php new file mode 100644 index 00000000..5818c798 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/EMFPlus/ObjectReader.php @@ -0,0 +1,909 @@ + + */ + public function read(int $type, string $data): array + { + $buffer = new Buffer($data); + switch ($type) { + case self::OBJECT_BRUSH: + return $this->readBrush($buffer); + case self::OBJECT_PEN: + return $this->readPen($buffer); + case self::OBJECT_PATH: + return $this->readPath($buffer); + case self::OBJECT_REGION: + $buffer->skip(4); + $buffer->skip(4); + + return ['type' => 'region', 'node' => $this->readRegionNode($buffer)]; + case self::OBJECT_IMAGE: + return $this->readImage($buffer); + case self::OBJECT_FONT: + return $this->readFont($buffer); + case self::OBJECT_STRING_FORMAT: + return $this->readStringFormat($buffer); + case self::OBJECT_IMAGE_ATTRIBUTES: + case self::OBJECT_CUSTOM_LINE_CAP: + // Image attributes are ignored, custom line caps are read with pens + return ['type' => 'other']; + default: + throw new WMFException(sprintf('Reader : EMF+ object not implemented : %d', $type)); + } + } + + // --------------------------------------------------------------------- + // Brushes + // --------------------------------------------------------------------- + + /** + * Returns a brush of the renderer : a color, or a shader (a callable returning the color of a point) + * + * @return array + */ + public function readBrush(Buffer $buffer): array + { + $buffer->skip(4); + $type = $buffer->readUInt32(); + switch ($type) { + case self::BRUSH_SOLID: + return self::getSolidBrush($buffer->readColor()); + case self::BRUSH_HATCH: + return $this->readHatchBrush($buffer); + case self::BRUSH_TEXTURE: + return $this->readTextureBrush($buffer); + case self::BRUSH_PATH_GRADIENT: + return $this->readPathGradientBrush($buffer); + case self::BRUSH_LINEAR_GRADIENT: + return $this->readLinearGradientBrush($buffer); + default: + throw new WMFException(sprintf('Reader : EMF+ brush not implemented : %d', $type)); + } + } + + /** + * @param array $color [r, g, b, a] + * + * @return array + */ + public static function getSolidBrush(array $color): array + { + return ['type' => 'brush', 'style' => 0, 'color' => $color]; + } + + /** + * @return array + */ + protected function readHatchBrush(Buffer $buffer): array + { + $style = $buffer->readUInt32(); + $foreColor = $buffer->readColor(); + $backColor = $buffer->readColor(); + + return [ + 'type' => 'brush', + 'style' => 0, + 'color' => self::mixColors($foreColor, $backColor, 0.5), + 'space' => 'device', + 'shader' => function (float $x, float $y) use ($style, $foreColor, $backColor): array { + return Renderer::isHatchForeground($style, (int) floor($x), (int) floor($y)) ? $foreColor : $backColor; + }, + ]; + } + + /** + * @return array + */ + protected function readTextureBrush(Buffer $buffer): array + { + $flags = $buffer->readUInt32(); + $wrapMode = $buffer->readInt32(); + $transform = ($flags & 0x02) ? $buffer->readMatrix() : [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + $image = $this->readImage($buffer); + $bitmap = $image['bitmap']; + if (empty($bitmap['pixels'])) { + return self::getSolidBrush([128, 128, 128, 255]); + } + $inverse = self::invertMatrix($transform); + $width = $bitmap['width']; + $height = $bitmap['height']; + $average = Bitmap::getAverageColor($bitmap); + + return [ + 'type' => 'brush', + 'style' => 0, + 'color' => [$average[0], $average[1], $average[2], 255], + 'shader' => function (float $x, float $y) use ($inverse, $bitmap, $width, $height, $wrapMode): array { + list($u, $v) = self::transformPoint($inverse, $x, $y); + $u = self::wrap($u / $width, $wrapMode, true); + $v = self::wrap($v / $height, $wrapMode, false); + if ($u === null || $v === null) { + return [0, 0, 0, 0]; + } + $pixel = $bitmap['pixels'][min($height - 1, (int) floor($v * $height))][min($width - 1, (int) floor($u * $width))] ?? 0; + + return [($pixel >> 16) & 0xFF, ($pixel >> 8) & 0xFF, $pixel & 0xFF, 255 - (int) round((($pixel >> 24) & 0x7F) * 255 / 127)]; + }, + ]; + } + + /** + * @return array + */ + protected function readLinearGradientBrush(Buffer $buffer): array + { + $flags = $buffer->readUInt32(); + $wrapMode = $buffer->readInt32(); + $rect = $buffer->readRect(); + $startColor = $buffer->readColor(); + $endColor = $buffer->readColor(); + $buffer->skip(8); + $transform = ($flags & 0x02) ? $buffer->readMatrix() : [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + $blend = $this->readBlend($buffer, $flags, $startColor, $endColor); + if ($flags & 0x10) { + // Vertical blend factors are ignored + $count = $buffer->readUInt32(); + $buffer->skip(8 * $count); + } + + $inverse = self::invertMatrix($transform); + $width = $rect[2] ?: 1; + + return [ + 'type' => 'brush', + 'style' => 0, + 'color' => self::mixColors($startColor, $endColor, 0.5), + 'shader' => function (float $x, float $y) use ($inverse, $rect, $width, $wrapMode, $blend): array { + list($u) = self::transformPoint($inverse, $x, $y); + $position = self::wrap(($u - $rect[0]) / $width, $wrapMode, true) ?? 0.0; + + return $blend($position); + }, + ]; + } + + /** + * @return array + */ + protected function readPathGradientBrush(Buffer $buffer): array + { + $flags = $buffer->readUInt32(); + $wrapMode = $buffer->readInt32(); + $centerColor = $buffer->readColor(); + list($centerX, $centerY) = [$buffer->readFloat(), $buffer->readFloat()]; + $countColors = $buffer->readUInt32(); + $surroundingColors = []; + for ($i = 0; $i < $countColors; ++$i) { + $surroundingColors[] = $buffer->readColor(); + } + // Boundary : a path, or points + if ($flags & 0x01) { + $size = $buffer->readUInt32(); + $path = $this->readPath(new Buffer($buffer->read($size))); + $boundary = []; + foreach ($path['figures'] as $figure) { + $boundary = array_merge($boundary, $figure['points']); + } + } else { + $boundary = $buffer->readPoints($buffer->readUInt32()); + } + $transform = ($flags & 0x02) ? $buffer->readMatrix() : [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + $surroundingColor = $surroundingColors[0] ?? $centerColor; + // From the boundary (0) to the center (1) + $blend = $this->readBlend($buffer, $flags, $surroundingColor, $centerColor); + // Several surrounding colors (without preset colors) : the color of the boundary is interpolated between its points + $countColors = count($surroundingColors); + $isMultiColor = !($flags & 0x04) && $countColors > 1; + + $inverse = self::invertMatrix($transform); + $count = count($boundary); + + return [ + 'type' => 'brush', + 'style' => 0, + 'color' => self::mixColors($centerColor, $surroundingColor, 0.5), + 'shader' => function (float $x, float $y) use ($inverse, $centerX, $centerY, $boundary, $count, $blend, $isMultiColor, $surroundingColors, $countColors): array { + list($x, $y) = self::transformPoint($inverse, $x, $y); + $dx = $x - $centerX; + $dy = $y - $centerY; + if ($dx == 0 && $dy == 0) { + return $blend(1.0); + } + // Intersection of the ray from the center through the point with the boundary + $nearest = null; + $nearestEdge = 0; + $nearestRatio = 0.0; + for ($i = 0; $i < $count; ++$i) { + list($ax, $ay) = $boundary[$i]; + list($bx, $by) = $boundary[($i + 1) % $count]; + $ex = $bx - $ax; + $ey = $by - $ay; + $denominator = $dx * $ey - $dy * $ex; + if ($denominator == 0) { + continue; + } + $s = (($ax - $centerX) * $ey - ($ay - $centerY) * $ex) / $denominator; + $r = (($ax - $centerX) * $dy - ($ay - $centerY) * $dx) / $denominator; + if ($s > 0 && $r >= 0 && $r <= 1 && ($nearest === null || $s < $nearest)) { + $nearest = $s; + $nearestEdge = $i; + $nearestRatio = $r; + } + } + $position = $nearest === null ? 0.0 : max(0.0, 1 - 1 / $nearest); + if (!$isMultiColor) { + return $blend($position); + } + // Color of the boundary (the last color is used for the points without color) + $edgeColor = self::mixColors( + $surroundingColors[min($nearestEdge, $countColors - 1)], + $surroundingColors[min(($nearestEdge + 1) % $count, $countColors - 1)], + $nearestRatio + ); + + return $blend($position, $edgeColor); + }, + ]; + } + + /** + * Reads the optional blend of a gradient (preset colors or blend factors), and returns the color for a position (0 to 1) + * + * @param array $startColor + * @param array $endColor + * + * @return callable(float, array|null=): array Color for a position (the start color may be overridden, except for preset colors) + */ + protected function readBlend(Buffer $buffer, int $flags, array $startColor, array $endColor): callable + { + if ($flags & 0x04) { + // Preset colors + $count = $buffer->readUInt32(); + $positions = []; + for ($i = 0; $i < $count; ++$i) { + $positions[] = $buffer->readFloat(); + } + $colors = []; + for ($i = 0; $i < $count; ++$i) { + $colors[] = $buffer->readColor(); + } + + return function (float $position, ?array $start = null) use ($positions, $colors, $count): array { + for ($i = 0; $i + 1 < $count; ++$i) { + if ($position <= $positions[$i + 1]) { + $range = $positions[$i + 1] - $positions[$i]; + + return self::mixColors($colors[$i], $colors[$i + 1], $range > 0 ? ($position - $positions[$i]) / $range : 0); + } + } + + return $colors[$count - 1] ?? [0, 0, 0, 0]; + }; + } + + $positions = [0.0, 1.0]; + $factors = [0.0, 1.0]; + if ($flags & 0x08) { + // Blend factors + $count = $buffer->readUInt32(); + $positions = $factors = []; + for ($i = 0; $i < $count; ++$i) { + $positions[] = $buffer->readFloat(); + } + for ($i = 0; $i < $count; ++$i) { + $factors[] = $buffer->readFloat(); + } + } + $count = count($positions); + + return function (float $position, ?array $start = null) use ($positions, $factors, $count, $startColor, $endColor): array { + $factor = $factors[$count - 1] ?? 1.0; + for ($i = 0; $i + 1 < $count; ++$i) { + if ($position <= $positions[$i + 1]) { + $range = $positions[$i + 1] - $positions[$i]; + $factor = $factors[$i] + ($factors[$i + 1] - $factors[$i]) * ($range > 0 ? ($position - $positions[$i]) / $range : 0); + break; + } + } + + return self::mixColors($start ?? $startColor, $endColor, $factor); + }; + } + + /** + * Applies a wrap mode to a position (0 to 1) : null if the position is outside (WrapModeClamp) + */ + protected static function wrap(float $position, int $wrapMode, bool $isHorizontal): ?float + { + switch ($wrapMode) { + case 1: // WrapModeTileFlipX + case 2: // WrapModeTileFlipY + case 3: // WrapModeTileFlipXY + $isFlipped = $wrapMode == 3 || ($wrapMode == 1) == $isHorizontal; + $period = (int) floor($position); + $position -= $period; + + return $isFlipped && $period % 2 != 0 ? 1 - $position : $position; + case 4: // WrapModeClamp + return $position < 0 || $position > 1 ? null : $position; + default: // WrapModeTile + return $position - floor($position); + } + } + + // --------------------------------------------------------------------- + // Pens + // --------------------------------------------------------------------- + + /** + * Returns a pen of the renderer : its width is in the unit `unit` (converted when the pen is used) + * + * @return array + */ + public function readPen(Buffer $buffer): array + { + $buffer->skip(8); + $flags = $buffer->readUInt32(); + $unit = $buffer->readUInt32(); + $width = $buffer->readFloat(); + + $pen = [ + 'type' => 'pen', + // PS_GEOMETRIC & PS_JOIN_MITER (the default join of EMF+) + 'style' => 0x00012000, + 'width' => $width, + 'unit' => $unit, + 'geometric' => true, + 'startCap' => 0x0200, + 'endCap' => 0x0200, + ]; + if ($flags & 0x0001) { + // Transform + $buffer->readMatrix(); + } + if ($flags & 0x0002) { + $this->setLineCap($pen, 'start', $buffer->readInt32()); + } + if ($flags & 0x0004) { + $this->setLineCap($pen, 'end', $buffer->readInt32()); + } + if ($flags & 0x0008) { + // Miter (0), Bevel (1), Round (2), MiterClipped (3) + $joins = [0 => 0x2000, 1 => 0x1000, 2 => 0x0000, 3 => 0x2000]; + $pen['style'] = 0x00010000 | ($joins[$buffer->readInt32()] ?? 0x2000); + } + if ($flags & 0x0010) { + $pen['miterLimit'] = $buffer->readFloat(); + } + if ($flags & 0x0020) { + // Solid (0), Dash (1), Dot (2), DashDot (3), DashDotDot (4), Custom (5) + $styles = [1 => [3, 1], 2 => [1, 1], 3 => [3, 1, 1, 1], 4 => [3, 1, 1, 1, 1, 1]]; + $lineStyle = $buffer->readInt32(); + if (isset($styles[$lineStyle])) { + $pen['dashes'] = $styles[$lineStyle]; + } + } + if ($flags & 0x0040) { + // Flat (0), Round (2), Triangle (3) + $pen['dashCap'] = $buffer->readInt32() == 2 ? 0x0000 : 0x0200; + } + if ($flags & 0x0080) { + $pen['dashOffset'] = $buffer->readFloat(); + } + if ($flags & 0x0100) { + $count = $buffer->readUInt32(); + $dashes = []; + for ($i = 0; $i < $count; ++$i) { + $dashes[] = $buffer->readFloat(); + } + if (count($dashes) >= 2) { + $pen['dashes'] = $dashes; + } + } + if ($flags & 0x0200) { + // Alignment + $buffer->skip(4); + } + if ($flags & 0x0400) { + // Compound lines : pairs of positions in the width of the pen + $count = $buffer->readUInt32(); + $compound = []; + for ($i = 0; $i < $count; ++$i) { + $compound[] = $buffer->readFloat(); + } + // A single line on the whole width is a simple line + if ($compound != [0.0, 1.0]) { + $pen['compound'] = $compound; + } + } + if ($flags & 0x0800) { + $this->readCustomLineCap($pen, 'start', new Buffer($buffer->read($buffer->readUInt32()))); + } + if ($flags & 0x1000) { + $this->readCustomLineCap($pen, 'end', new Buffer($buffer->read($buffer->readUInt32()))); + } + + $brush = $this->readBrush($buffer); + + return $pen + ['color' => $brush['color']] + (isset($brush['shader']) ? ['shader' => $brush['shader'], 'space' => $brush['space'] ?? 'logical'] : []); + } + + /** + * @param array $pen + */ + protected function setLineCap(array &$pen, string $end, int $cap): void + { + switch ($cap) { + case 1: // Square + case 0x11: // SquareAnchor + $pen[$end . 'Cap'] = 0x0100; + break; + case 2: // Round + case 0x12: // RoundAnchor + $pen[$end . 'Cap'] = 0x0000; + break; + case 0x14: // ArrowAnchor + $pen[$end . 'CapShape'] = [[0, 0], [1, -2], [-1, -2]]; + break; + default: // Flat, Triangle, NoAnchor, DiamondAnchor, Custom + $pen[$end . 'Cap'] = 0x0200; + } + } + + /** + * Reads a custom line cap : an adjustable arrow, or a path (in pen widths) + * + * @param array $pen + */ + protected function readCustomLineCap(array &$pen, string $end, Buffer $buffer): void + { + $buffer->skip(4); + // CustomLineCapDataTypeAdjustableArrow + if ($buffer->readUInt32() == 1) { + $width = $buffer->readFloat(); + $height = $buffer->readFloat(); + $middleInset = $buffer->readFloat(); + $pen[$end . 'CapShape'] = [[0, 0], [$width / 2, -$height], [0, -$height + $middleInset], [-$width / 2, -$height]]; + + return; + } + + // CustomLineCapDataTypeDefault : fill path and/or line path + $flags = $buffer->readUInt32(); + // BaseCap, BaseInset, StrokeStartCap, StrokeEndCap, StrokeJoin, StrokeMiterLimit + $buffer->skip(24); + $widthScale = $buffer->readFloat() ?: 1.0; + // FillHotSpot, StrokeHotSpot + $buffer->skip(16); + if ($flags & 0x03) { + $path = $this->readPath(new Buffer($buffer->read($buffer->readUInt32()))); + $shape = []; + foreach ($path['figures'] as $figure) { + foreach ($figure['points'] as list($x, $y)) { + $shape[] = [$x * $widthScale, $y * $widthScale]; + } + } + $pen[$end . 'CapShape'] = $shape; + } + } + + // --------------------------------------------------------------------- + // Paths & regions + // --------------------------------------------------------------------- + + /** + * Returns the figures of a path (see PhpOffice\WMF\Renderer\GD::drawPathFigures()) + * + * @return array{type: string, figures: array>, types: array, closed: bool}>} + */ + public function readPath(Buffer $buffer): array + { + $buffer->skip(4); + $count = $buffer->readUInt32(); + $flags = $buffer->readUInt16(); + $buffer->skip(2); + $points = $buffer->readPoints($count, ($flags & 0x4000) > 0, ($flags & 0x0800) > 0); + + // Types of points, run-length encoded (R flag) or not + $types = []; + if ($flags & 0x1000) { + while (count($types) < $count) { + $run = $buffer->readUInt8(); + $type = $buffer->readUInt8(); + $length = $run & 0x3F; + for ($i = 0; $i < max(1, $length) && count($types) < $count; ++$i) { + $types[] = $type; + } + } + } else { + for ($i = 0; $i < $count; ++$i) { + $types[] = $buffer->readUInt8(); + } + } + + $figures = []; + $current = null; + foreach ($points as $i => $point) { + $type = $types[$i] & 0x07; + if ($type == 0 || $current === null) { + if ($current !== null) { + $figures[] = $current; + } + $current = ['points' => [], 'types' => [], 'closed' => false]; + $type = 0; + } + $current['points'][] = $point; + $current['types'][] = $type; + // PathPointTypeCloseSubpath + if ($types[$i] & 0x80) { + $current['closed'] = true; + $figures[] = $current; + $current = null; + } + } + if ($current !== null) { + $figures[] = $current; + } + + return ['type' => 'path', 'figures' => $figures]; + } + + /** + * Reads a node of a region : a rectangle, a path, an empty or infinite region, or a combination of two nodes + * + * @return array + */ + protected function readRegionNode(Buffer $buffer): array + { + $type = $buffer->readUInt32(); + switch ($type) { + case self::REGION_AND: + case self::REGION_UNION: + case self::REGION_XOR: + case self::REGION_EXCLUDE: + case self::REGION_COMPLEMENT: + $left = $this->readRegionNode($buffer); + $right = $this->readRegionNode($buffer); + + return ['type' => $type, 'left' => $left, 'right' => $right]; + case self::REGION_RECT: + return ['type' => $type, 'rect' => $buffer->readRect()]; + case self::REGION_PATH: + $size = $buffer->readUInt32(); + + return ['type' => $type, 'path' => $this->readPath(new Buffer($buffer->read($size)))]; + case self::REGION_EMPTY: + case self::REGION_INFINITE: + return ['type' => $type]; + default: + throw new WMFException(sprintf('Reader : EMF+ region node not implemented : 0x%08x', $type)); + } + } + + // --------------------------------------------------------------------- + // Images, fonts & string formats + // --------------------------------------------------------------------- + + /** + * Returns an image : a decoded bitmap (pixels with a GD alpha channel), metafiles are rendered + * + * @return array{type: string, bitmap: array{width: int, height: int, pixels: array>}, isMetafile: bool} + */ + public function readImage(Buffer $buffer): array + { + $buffer->skip(4); + $type = $buffer->readUInt32(); + if ($type == 1) { + return ['type' => 'image', 'bitmap' => $this->readBitmap($buffer), 'isMetafile' => false]; + } + if ($type == 2) { + $metafileType = $buffer->readUInt32(); + $size = $buffer->readUInt32(); + // The size of placeable WMF files doesn't include their placeable header (24 bytes with its padding) + if ($metafileType == 2) { + $size += 24; + } + $data = $buffer->read(min($size, $buffer->getRemaining())); + + return ['type' => 'image', 'bitmap' => $this->renderMetafile($metafileType, $data), 'isMetafile' => true]; + } + + throw new WMFException(sprintf('Reader : EMF+ image not implemented : %d', $type)); + } + + /** + * @return array{width: int, height: int, pixels: array>} + */ + protected function readBitmap(Buffer $buffer): array + { + $width = $buffer->readInt32(); + $height = $buffer->readInt32(); + $stride = $buffer->readInt32(); + $pixelFormat = $buffer->readUInt32(); + $isCompressed = $buffer->readUInt32() == 1; + if ($isCompressed) { + // PNG, JPEG, GIF, BMP... decoded by GD + return Bitmap::readImage($buffer->read($buffer->getRemaining()), true) + ?? ['width' => 0, 'height' => 0, 'pixels' => []]; + } + if ($width <= 0 || $height <= 0 || $width * $height > 16000000) { + throw new WMFException('Reader : Invalid file : EMF+ bitmap'); + } + + $bitCount = ($pixelFormat >> 8) & 0xFF; + // PixelFormatIndexed : the palette precedes the pixels + $palette = []; + if ($pixelFormat & 0x00010000) { + $buffer->skip(4); + $count = $buffer->readUInt32(); + for ($i = 0; $i < $count; ++$i) { + $palette[] = self::toGDPixel($buffer->readColor()); + } + } + + $rowSize = abs($stride) ?: (int) (ceil($width * $bitCount / 32) * 4); + $rows = []; + for ($row = 0; $row < $height; ++$row) { + $rows[] = $buffer->read(min($rowSize, $buffer->getRemaining())); + } + // A negative stride means a bottom-up bitmap + if ($stride < 0) { + $rows = array_reverse($rows); + } + + $pixels = []; + foreach ($rows as $data) { + $bytes = array_values(unpack('C*', $data . str_repeat("\0", (int) ceil($width * $bitCount / 8) + 8))); + $line = []; + for ($x = 0; $x < $width; ++$x) { + $line[] = $this->readPixel($bytes, $x, $pixelFormat, $bitCount, $palette); + } + $pixels[] = $line; + } + + return ['width' => $width, 'height' => $height, 'pixels' => $pixels]; + } + + /** + * @param array $bytes + * @param array $palette + */ + protected function readPixel(array $bytes, int $x, int $pixelFormat, int $bitCount, array $palette): int + { + switch ($pixelFormat) { + case 0x00030101: // 1bpp indexed + return $palette[($bytes[$x >> 3] >> (7 - ($x & 7))) & 0x01] ?? 0; + case 0x00030402: // 4bpp indexed + return $palette[($bytes[$x >> 1] >> (($x & 1) ? 0 : 4)) & 0x0F] ?? 0; + case 0x00030803: // 8bpp indexed + return $palette[$bytes[$x]] ?? 0; + case 0x00101004: // 16bpp gray scale + $gray = $bytes[2 * $x + 1]; + + return ($gray << 16) | ($gray << 8) | $gray; + case 0x00021005: // 16bpp RGB 555 + case 0x00061007: // 16bpp ARGB 1555 + $value = $bytes[2 * $x] | ($bytes[2 * $x + 1] << 8); + $pixel = intdiv((($value >> 10) & 0x1F) * 255, 31) << 16 | intdiv((($value >> 5) & 0x1F) * 255, 31) << 8 | intdiv(($value & 0x1F) * 255, 31); + + return $pixelFormat == 0x00061007 && !($value & 0x8000) ? $pixel | (127 << 24) : $pixel; + case 0x00021006: // 16bpp RGB 565 + $value = $bytes[2 * $x] | ($bytes[2 * $x + 1] << 8); + + return intdiv((($value >> 11) & 0x1F) * 255, 31) << 16 | intdiv((($value >> 5) & 0x3F) * 255, 63) << 8 | intdiv(($value & 0x1F) * 255, 31); + case 0x00021808: // 24bpp RGB + return ($bytes[3 * $x + 2] << 16) | ($bytes[3 * $x + 1] << 8) | $bytes[3 * $x]; + case 0x0026200A: // 32bpp ARGB + case 0x000E200B: // 32bpp premultiplied ARGB + list($blue, $green, $red, $alpha) = [$bytes[4 * $x], $bytes[4 * $x + 1], $bytes[4 * $x + 2], $bytes[4 * $x + 3]]; + if ($pixelFormat == 0x000E200B && $alpha > 0) { + $red = min(255, intdiv($red * 255, $alpha)); + $green = min(255, intdiv($green * 255, $alpha)); + $blue = min(255, intdiv($blue * 255, $alpha)); + } + + return self::toGDPixel([$red, $green, $blue, $alpha]); + case 0x0010300C: // 48bpp RGB + return ($bytes[6 * $x + 5] << 16) | ($bytes[6 * $x + 3] << 8) | $bytes[6 * $x + 1]; + case 0x0034400D: // 64bpp ARGB + case 0x001A400E: // 64bpp premultiplied ARGB + return self::toGDPixel([$bytes[8 * $x + 5], $bytes[8 * $x + 3], $bytes[8 * $x + 1], $bytes[8 * $x + 7]]); + case 0x00022009: // 32bpp RGB + default: + if ($bitCount == 32) { + return ($bytes[4 * $x + 2] << 16) | ($bytes[4 * $x + 1] << 8) | $bytes[4 * $x]; + } + throw new WMFException(sprintf('Reader : EMF+ pixel format not implemented : 0x%08x', $pixelFormat)); + } + } + + /** + * Renders an embedded metafile (WMF, placeable WMF, EMF, EMF+) with the readers of the library + * + * @return array{width: int, height: int, pixels: array>} + */ + protected function renderMetafile(int $type, string $data): array + { + // GDI+ may write the placeable header of WMF files with a padding of 2 bytes (24 bytes instead of 22) + if ($type == 2 && !Detector::isPlaceableWMF($data) && Detector::isPlaceableWMF((string) substr($data, 0, 22) . (string) substr($data, 24))) { + $data = (string) substr($data, 0, 22) . (string) substr($data, 24); + } + $type = Detector::detect($data); + if ($type == Detector::TYPE_EMF || $type == Detector::TYPE_EMFPLUS) { + $reader = new EMFReader(); + } elseif ($type == Detector::TYPE_WMF) { + $reader = new WMFReader(); + } else { + return ['width' => 0, 'height' => 0, 'pixels' => []]; + } + // A metafile which can not be read is not drawn, its background is transparent + $reader->enableExceptions(false); + $reader->setBackgroundColor(null); + if (!$reader->loadFromString($data)) { + return ['width' => 0, 'height' => 0, 'pixels' => []]; + } + $image = $reader->getResource(); + $width = imagesx($image); + $height = imagesy($image); + $pixels = []; + for ($y = 0; $y < $height; ++$y) { + $line = []; + for ($x = 0; $x < $width; ++$x) { + $line[] = imagecolorat($image, $x, $y); + } + $pixels[] = $line; + } + + return ['width' => $width, 'height' => $height, 'pixels' => $pixels]; + } + + /** + * @return array + */ + protected function readFont(Buffer $buffer): array + { + $buffer->skip(4); + $emSize = $buffer->readFloat(); + $unit = $buffer->readUInt32(); + $style = $buffer->readInt32(); + $buffer->skip(4); + $length = $buffer->readUInt32(); + + return [ + 'type' => 'font', + 'emSize' => $emSize, + 'unit' => $unit, + 'weight' => ($style & 0x01) ? 700 : 400, + 'italic' => ($style & 0x02) > 0, + 'underline' => ($style & 0x04) > 0, + 'strikeOut' => ($style & 0x08) > 0, + 'face' => Encoding::decodeUTF16($buffer->readString($length)), + ]; + } + + /** + * @return array + */ + protected function readStringFormat(Buffer $buffer): array + { + $buffer->skip(4); + $flags = $buffer->readUInt32(); + $buffer->skip(4); + $alignment = $buffer->readUInt32(); + $lineAlignment = $buffer->readUInt32(); + + return ['type' => 'stringFormat', 'flags' => $flags, 'alignment' => $alignment, 'lineAlignment' => $lineAlignment]; + } + + // --------------------------------------------------------------------- + // Helpers + // --------------------------------------------------------------------- + + /** + * @param array $first + * @param array $second + * + * @return array + */ + public static function mixColors(array $first, array $second, float $ratio): array + { + $ratio = max(0.0, min(1.0, $ratio)); + $color = []; + for ($i = 0; $i < 4; ++$i) { + $color[] = (int) round(($first[$i] ?? 255) + ((($second[$i] ?? 255) - ($first[$i] ?? 255)) * $ratio)); + } + + return $color; + } + + /** + * Converts a color [r, g, b, a] to a GD pixel (with an alpha channel) + * + * @param array $color + */ + public static function toGDPixel(array $color): int + { + return ((127 - (int) round($color[3] * 127 / 255)) << 24) | ($color[0] << 16) | ($color[1] << 8) | $color[2]; + } + + /** + * @param array $matrix [m11, m12, m21, m22, dx, dy] + * + * @return array + */ + public static function invertMatrix(array $matrix): array + { + list($m11, $m12, $m21, $m22, $dx, $dy) = $matrix; + $determinant = $m11 * $m22 - $m12 * $m21; + if ($determinant == 0) { + return [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + } + + return [ + $m22 / $determinant, + -$m12 / $determinant, + -$m21 / $determinant, + $m11 / $determinant, + ($m21 * $dy - $m22 * $dx) / $determinant, + ($m12 * $dx - $m11 * $dy) / $determinant, + ]; + } + + /** + * @param array $matrix [m11, m12, m21, m22, dx, dy] + * + * @return array + */ + public static function transformPoint(array $matrix, float $x, float $y): array + { + return [$x * $matrix[0] + $y * $matrix[2] + $matrix[4], $x * $matrix[1] + $y * $matrix[3] + $matrix[5]]; + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/EMFPlus/Player.php b/vendor/phpoffice/wmf/src/WMF/Reader/EMFPlus/Player.php new file mode 100644 index 00000000..742c4b0b --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/EMFPlus/Player.php @@ -0,0 +1,1009 @@ +> + */ + protected $objects = []; + /** + * Data of objects split in several records, indexed by their id + * + * @var array + */ + protected $continuedObjects = []; + /** + * Graphics state : world transform, page unit & scale, base transform (containers), clipping region (spans) + * + * @var array + */ + protected $state; + /** + * Saved states, indexed by their stack index + * + * @var array> + */ + protected $stack = []; + + public function __construct(Renderer $renderer) + { + $this->renderer = $renderer; + $this->objectReader = new ObjectReader(); + $this->state = $this->getDefaultState(); + } + + /** + * @return array + */ + protected function getDefaultState(): array + { + return [ + 'world' => self::IDENTITY, + // UnitDisplay + 'pageUnit' => 1, + 'pageScale' => 1.0, + // Transform of the containers (EMF+ pixels are the device units of the EMF file) + 'base' => self::IDENTITY, + 'clip' => null, + ]; + } + + /** + * Plays the EMF+ records of an EMR_COMMENT record (without the "EMF+" identifier) + * + * @return bool If the next EMF records must be played (the last EMF+ record is EmfPlusGetDC) + */ + public function play(string $data): bool + { + $buffer = new Buffer($data); + $lastType = 0; + while ($buffer->getRemaining() >= 12) { + $type = $buffer->readUInt16(); + $flags = $buffer->readUInt16(); + $size = $buffer->readUInt32(); + $dataSize = $buffer->readUInt32(); + if ($size < 12 || $dataSize > $size - 12) { + throw new WMFException('Reader : Invalid file : EMF+ record size'); + } + $recordData = $buffer->read($dataSize); + $buffer->skip(min($size - 12 - $dataSize, $buffer->getRemaining())); + + if (!in_array($type, self::IGNORED_RECORDS)) { + $this->playRecord($type, $flags, new Buffer($recordData)); + } + $lastType = $type; + } + + return $lastType == self::EMFPLUS_GET_DC; + } + + protected function playRecord(int $type, int $flags, Buffer $data): void + { + $isCompressed = ($flags & self::FLAG_COMPRESSED) > 0; + $isRelative = ($flags & self::FLAG_RELATIVE) > 0; + $id = $flags & 0xFF; + + switch ($type) { + case self::EMFPLUS_HEADER: + $data->skip(8); + $this->dpiX = (float) ($data->readUInt32() ?: 96); + $this->dpiY = (float) ($data->readUInt32() ?: 96); + $this->state = $this->getDefaultState(); + break; + case self::EMFPLUS_GET_DC: + break; + case self::EMFPLUS_OBJECT: + $this->readObject($flags, $data); + break; + + // State + case self::EMFPLUS_SAVE: + $this->stack[$data->readUInt32()] = $this->state; + break; + case self::EMFPLUS_RESTORE: + case self::EMFPLUS_END_CONTAINER: + $index = $data->readUInt32(); + if (isset($this->stack[$index])) { + $this->state = $this->stack[$index]; + unset($this->stack[$index]); + } + break; + case self::EMFPLUS_BEGIN_CONTAINER: + // The source rectangle (in the unit of the flags) is mapped to the destination rectangle (world coordinates) + $destination = $data->readRect(); + $source = $data->readRect(); + $this->stack[$data->readUInt32()] = $this->state; + $unitX = $this->getUnitPixels(($flags >> 8) & 0xFF, $this->dpiX); + $unitY = $this->getUnitPixels(($flags >> 8) & 0xFF, $this->dpiY); + $scaleX = $source[2] != 0 ? $destination[2] / ($source[2] * $unitX) : 1; + $scaleY = $source[3] != 0 ? $destination[3] / ($source[3] * $unitY) : 1; + $mapping = [$scaleX, 0.0, 0.0, $scaleY, $destination[0] - $source[0] * $unitX * $scaleX, $destination[1] - $source[1] * $unitY * $scaleY]; + $this->beginContainer($mapping); + break; + case self::EMFPLUS_BEGIN_CONTAINER_NO_PARAMS: + $this->stack[$data->readUInt32()] = $this->state; + $this->beginContainer(self::IDENTITY); + break; + + // Transforms + case self::EMFPLUS_SET_WORLD_TRANSFORM: + $this->state['world'] = $data->readMatrix(); + break; + case self::EMFPLUS_RESET_WORLD_TRANSFORM: + $this->state['world'] = self::IDENTITY; + break; + case self::EMFPLUS_MULTIPLY_WORLD_TRANSFORM: + $this->multiplyWorld($data->readMatrix(), $flags); + break; + case self::EMFPLUS_TRANSLATE_WORLD_TRANSFORM: + $this->multiplyWorld([1.0, 0.0, 0.0, 1.0, $data->readFloat(), $data->readFloat()], $flags); + break; + case self::EMFPLUS_SCALE_WORLD_TRANSFORM: + $this->multiplyWorld([$data->readFloat(), 0.0, 0.0, $data->readFloat(), 0.0, 0.0], $flags); + break; + case self::EMFPLUS_ROTATE_WORLD_TRANSFORM: + $angle = deg2rad($data->readFloat()); + $this->multiplyWorld([cos($angle), sin($angle), -sin($angle), cos($angle), 0.0, 0.0], $flags); + break; + case self::EMFPLUS_SET_PAGE_TRANSFORM: + $this->state['pageUnit'] = $flags & 0xFF; + $this->state['pageScale'] = $data->readFloat(); + break; + + // Clipping + case self::EMFPLUS_RESET_CLIP: + $this->state['clip'] = null; + break; + case self::EMFPLUS_SET_CLIP_RECT: + $rect = $data->readRect(); + $this->combineClip($this->getSpans(function () use ($rect): array { + return $this->renderer->getFiguresSpans([$this->getRectFigure($rect)], false); + }), ($flags >> 8) & 0x0F); + break; + case self::EMFPLUS_SET_CLIP_PATH: + $path = $this->getObject($id, 'path'); + $this->combineClip($this->getSpans(function () use ($path): array { + return $this->renderer->getFiguresSpans($path['figures'], false); + }), ($flags >> 8) & 0x0F); + break; + case self::EMFPLUS_SET_CLIP_REGION: + $region = $this->getObject($id, 'region'); + $this->combineClip($this->getSpans(function () use ($region): array { + return $this->getRegionSpans($region['node']); + }), ($flags >> 8) & 0x0F); + break; + case self::EMFPLUS_OFFSET_CLIP: + $offsetX = $data->readFloat(); + $offsetY = $data->readFloat(); + if ($this->state['clip'] !== null) { + $this->state['clip'] = $this->getSpans(function () use ($offsetX, $offsetY): array { + return (array) $this->renderer->offsetClipRegion($offsetX, $offsetY)->getClipSpans(); + }); + } + break; + + // Drawing + case self::EMFPLUS_CLEAR: + $color = $data->readColor(); + $this->draw(function () use ($color): void { + $this->renderer->clear($color); + }); + break; + case self::EMFPLUS_FILL_RECTS: + case self::EMFPLUS_DRAW_RECTS: + $paint = $type == self::EMFPLUS_FILL_RECTS ? $this->getBrush($flags, $data->readUInt32()) : $this->getPen($id); + $figures = []; + $count = $data->readUInt32(); + for ($i = 0; $i < $count; ++$i) { + $figures[] = $this->getRectFigure($data->readRect($isCompressed)); + } + $this->drawFigures($figures, $paint); + break; + case self::EMFPLUS_FILL_POLYGON: + $brush = $this->getBrush($flags, $data->readUInt32()); + $points = $data->readPoints($data->readUInt32(), $isCompressed, $isRelative); + $this->drawFigures([$this->getPolylineFigure($points, true)], $brush); + break; + case self::EMFPLUS_DRAW_LINES: + $points = $data->readPoints($data->readUInt32(), $isCompressed, $isRelative); + $this->drawFigures([$this->getPolylineFigure($points, ($flags & self::FLAG_CLOSED) > 0)], $this->getPen($id)); + break; + case self::EMFPLUS_FILL_ELLIPSE: + case self::EMFPLUS_DRAW_ELLIPSE: + $paint = $type == self::EMFPLUS_FILL_ELLIPSE ? $this->getBrush($flags, $data->readUInt32()) : $this->getPen($id); + $this->drawFigures([$this->getEllipseFigure($data->readRect($isCompressed))], $paint); + break; + case self::EMFPLUS_FILL_PIE: + case self::EMFPLUS_DRAW_PIE: + case self::EMFPLUS_DRAW_ARC: + $paint = $type == self::EMFPLUS_FILL_PIE ? $this->getBrush($flags, $data->readUInt32()) : $this->getPen($id); + $startAngle = $data->readFloat(); + $sweepAngle = $data->readFloat(); + $rect = $data->readRect($isCompressed); + $points = $this->getArcPoints($rect, $startAngle, $sweepAngle); + if ($type != self::EMFPLUS_DRAW_ARC) { + $points[] = [$rect[0] + $rect[2] / 2, $rect[1] + $rect[3] / 2]; + } + $this->drawFigures([$this->getPolylineFigure($points, $type != self::EMFPLUS_DRAW_ARC)], $paint); + break; + case self::EMFPLUS_FILL_REGION: + $brush = $this->getBrush($flags, $data->readUInt32()); + $region = $this->getObject($id, 'region'); + $this->draw(function () use ($region, $brush): void { + $spans = $this->getRegionSpans($region['node']); + $this->renderer->setClipSpans($this->state['clip'] === null ? $spans : Rasterizer::combineSpans($this->state['clip'], $spans, Rasterizer::RGN_AND)); + if (isset($brush['shader'])) { + $this->renderer->selectObject($brush)->drawPathFigures([$this->getRectFigure([-1e6, -1e6, 2e6, 2e6])], true, false); + } else { + $this->renderer->clear($brush['color']); + } + }); + break; + case self::EMFPLUS_FILL_PATH: + $brush = $this->getBrush($flags, $data->readUInt32()); + $this->drawFigures($this->getObject($id, 'path')['figures'], $brush); + break; + case self::EMFPLUS_DRAW_PATH: + $pen = $this->getPen($data->readUInt32()); + $this->drawFigures($this->getObject($id, 'path')['figures'], $pen); + break; + case self::EMFPLUS_FILL_CLOSED_CURVE: + $brush = $this->getBrush($flags, $data->readUInt32()); + $tension = $data->readFloat(); + $points = $data->readPoints($data->readUInt32(), $isCompressed, $isRelative); + $this->drawFigures([$this->getCurveFigure($points, $tension, true)], $brush, ($flags & self::FLAG_CLOSED) > 0); + break; + case self::EMFPLUS_DRAW_CLOSED_CURVE: + $tension = $data->readFloat(); + $points = $data->readPoints($data->readUInt32(), $isCompressed, $isRelative); + $this->drawFigures([$this->getCurveFigure($points, $tension, true)], $this->getPen($id)); + break; + case self::EMFPLUS_DRAW_CURVE: + $tension = $data->readFloat(); + $offset = $data->readUInt32(); + $segments = $data->readUInt32(); + $points = $data->readPoints($data->readUInt32(), $isCompressed); + $this->drawFigures([$this->getCurveFigure($points, $tension, false, $offset, $segments)], $this->getPen($id)); + break; + case self::EMFPLUS_DRAW_BEZIERS: + $points = $data->readPoints($data->readUInt32(), $isCompressed, $isRelative); + $types = []; + foreach ($points as $i => $point) { + $types[] = $i == 0 ? 0 : 3; + } + $this->drawFigures([['points' => $points, 'types' => $types, 'closed' => false]], $this->getPen($id)); + break; + case self::EMFPLUS_DRAW_IMAGE: + case self::EMFPLUS_DRAW_IMAGE_POINTS: + $this->drawImage($type, $id, $isCompressed, $isRelative, $data); + break; + case self::EMFPLUS_DRAW_STRING: + $this->drawString($flags, $id, $data); + break; + case self::EMFPLUS_DRAW_DRIVER_STRING: + $this->drawDriverString($flags, $id, $data); + break; + default: + throw new WMFException(sprintf('Reader : EMF+ record not implemented : 0x%04x', $type)); + } + } + + // --------------------------------------------------------------------- + // Objects + // --------------------------------------------------------------------- + + /** + * Reads an object, which may be split in several records + */ + protected function readObject(int $flags, Buffer $data): void + { + $id = $flags & 0xFF; + $type = ($flags >> 8) & 0x7F; + if ($flags & 0x8000) { + // Continued object : the total size precedes the data + $size = $data->readUInt32(); + if (!isset($this->continuedObjects[$id])) { + $this->continuedObjects[$id] = ['type' => $type, 'size' => $size, 'data' => '']; + } + $this->continuedObjects[$id]['data'] .= $data->read($data->getRemaining()); + if (strlen($this->continuedObjects[$id]['data']) < $size) { + return; + } + } elseif (isset($this->continuedObjects[$id])) { + // Last part of a continued object + $this->continuedObjects[$id]['data'] .= $data->read($data->getRemaining()); + } + + if (isset($this->continuedObjects[$id])) { + $object = $this->continuedObjects[$id]; + unset($this->continuedObjects[$id]); + $this->objects[$id] = $this->objectReader->read($object['type'], $object['data']); + + return; + } + $this->objects[$id] = $this->objectReader->read($type, $data->read($data->getRemaining())); + } + + /** + * @return array + */ + protected function getObject(int $id, string $type): array + { + if (!isset($this->objects[$id]) || $this->objects[$id]['type'] != $type) { + throw new WMFException(sprintf('Reader : Invalid file : EMF+ object %d is not a %s', $id, $type)); + } + + return $this->objects[$id]; + } + + /** + * Returns the brush of a record : a solid color (flag S) or a brush object + * + * @return array + */ + protected function getBrush(int $flags, int $brushId): array + { + if ($flags & self::FLAG_SOLID_COLOR) { + return ObjectReader::getSolidBrush(Buffer::toColor($brushId)); + } + + return $this->getObject($brushId & 0xFF, 'brush'); + } + + /** + * @return array + */ + protected function getPen(int $penId): array + { + return $this->getObject($penId & 0xFF, 'pen'); + } + + // --------------------------------------------------------------------- + // Transforms + // --------------------------------------------------------------------- + + /** + * Number of EMF+ pixels per unit + */ + protected function getUnitPixels(int $unit, float $dpi): float + { + switch ($unit) { + case 3: // UnitPoint + return $dpi / 72; + case 4: // UnitInch + return $dpi; + case 5: // UnitDocument + return $dpi / 300; + case 6: // UnitMillimeter + return $dpi / 25.4; + default: // UnitWorld, UnitDisplay, UnitPixel + return 1.0; + } + } + + /** + * Multiplies the world transform : the matrix is applied after the world transform (flag A) or before + * + * @param array $matrix + */ + protected function multiplyWorld(array $matrix, int $flags): void + { + $this->state['world'] = ($flags & 0x2000) + ? self::multiply($this->state['world'], $matrix) + : self::multiply($matrix, $this->state['world']); + } + + /** + * Starts a container : its coordinates are mapped (by the matrix) to the world coordinates of the current state + * + * @param array $mapping + */ + protected function beginContainer(array $mapping): void + { + $this->state['base'] = self::multiply($mapping, $this->getMatrix()); + $this->state['world'] = self::IDENTITY; + $this->state['pageUnit'] = 1; + $this->state['pageScale'] = 1.0; + } + + /** + * Returns the matrix converting world coordinates to device units of the EMF file + * + * @return array + */ + protected function getMatrix(): array + { + $pageX = $this->state['pageScale'] * $this->getUnitPixels($this->state['pageUnit'], $this->dpiX); + $pageY = $this->state['pageScale'] * $this->getUnitPixels($this->state['pageUnit'], $this->dpiY); + + return self::multiply(self::multiply($this->state['world'], [$pageX, 0.0, 0.0, $pageY, 0.0, 0.0]), $this->state['base']); + } + + /** + * Number of EMF+ pixels per world unit (to convert sizes in other units) + */ + protected function getWorldPixels(): float + { + $pageX = $this->state['pageScale'] * $this->getUnitPixels($this->state['pageUnit'], $this->dpiX); + list($m11, $m12, $m21, $m22) = $this->state['world']; + + return sqrt(abs($m11 * $m22 - $m12 * $m21)) * abs($pageX) ?: 1.0; + } + + /** + * Product of matrices : the first one is applied first + * + * @param array $first + * @param array $second + * + * @return array + */ + public static function multiply(array $first, array $second): array + { + return [ + $first[0] * $second[0] + $first[1] * $second[2], + $first[0] * $second[1] + $first[1] * $second[3], + $first[2] * $second[0] + $first[3] * $second[2], + $first[2] * $second[1] + $first[3] * $second[3], + $first[4] * $second[0] + $first[5] * $second[2] + $second[4], + $first[4] * $second[1] + $first[5] * $second[3] + $second[5], + ]; + } + + // --------------------------------------------------------------------- + // Drawing + // --------------------------------------------------------------------- + + /** + * Calls the renderer with the state of EMF+ (transform & clipping), then restores the state of EMF + * + * @param callable(): void $callback + * @param array|null $matrix Matrix applied before the world transform + */ + protected function draw(callable $callback, ?array $matrix = null): void + { + $this->renderer + ->saveDC() + ->setMapMode(Renderer::MM_TEXT) + ->setWindowOrg(0, 0) + ->setViewportOrg(0, 0) + ->setWorldTransform($matrix ? self::multiply($matrix, $this->getMatrix()) : $this->getMatrix()) + ->setClipSpans($this->state['clip']) + ->setBkMode(1) + ->setTextAlign(0) + ->setPolyFillMode(Renderer::ALTERNATE); + try { + $callback(); + } finally { + $this->renderer->restoreDC(-1); + } + } + + /** + * Returns spans computed with the state of EMF+ + * + * @param callable(): array>> $callback + * + * @return array>> + */ + protected function getSpans(callable $callback): array + { + $spans = []; + $this->draw(function () use ($callback, &$spans): void { + $spans = $callback(); + }); + + return $spans; + } + + /** + * Fills (with a brush) or strokes (with a pen) figures + * + * @param array>, types: array, closed: bool}> $figures + * @param array $paint Brush or pen + */ + protected function drawFigures(array $figures, array $paint, bool $isWinding = false): void + { + $this->draw(function () use ($figures, $paint, $isWinding): void { + if ($paint['type'] == 'brush') { + $this->renderer + ->setPolyFillMode($isWinding ? Renderer::WINDING : Renderer::ALTERNATE) + ->selectObject($paint) + ->drawPathFigures($figures, true, false); + + return; + } + $this->renderer + ->selectObject($this->getRendererPen($paint)) + ->setMiterLimit($paint['miterLimit'] ?? 10) + ->drawPathFigures($figures, false, true); + }); + } + + /** + * Converts the width of a pen to world units + * + * @param array $pen + * + * @return array + */ + protected function getRendererPen(array $pen): array + { + if ($pen['unit'] != 0 && $pen['width'] > 0) { + $pen['width'] = $pen['width'] * $this->getUnitPixels($pen['unit'], $this->dpiX) / $this->getWorldPixels(); + } + // A pen with a width of 0 is one pixel wide + $pen['geometric'] = $pen['width'] > 0; + + return $pen; + } + + /** + * Returns the spans of a region node (see ObjectReader::readRegionNode()) + * + * @param array $node + * + * @return array>> + */ + protected function getRegionSpans(array $node): array + { + switch ($node['type']) { + case ObjectReader::REGION_RECT: + return $this->renderer->getFiguresSpans([$this->getRectFigure($node['rect'])], false); + case ObjectReader::REGION_PATH: + return $this->renderer->getFiguresSpans($node['path']['figures'], false); + case ObjectReader::REGION_EMPTY: + return []; + case ObjectReader::REGION_INFINITE: + return $this->renderer->getFullSpans(); + default: + $left = $this->getRegionSpans($node['left']); + $right = $this->getRegionSpans($node['right']); + switch ($node['type']) { + case ObjectReader::REGION_AND: + return Rasterizer::combineSpans($left, $right, Rasterizer::RGN_AND); + case ObjectReader::REGION_UNION: + return Rasterizer::combineSpans($left, $right, Rasterizer::RGN_OR); + case ObjectReader::REGION_XOR: + return Rasterizer::combineSpans($left, $right, Rasterizer::RGN_XOR); + case ObjectReader::REGION_EXCLUDE: + return Rasterizer::combineSpans($left, $right, Rasterizer::RGN_DIFF); + default: // REGION_COMPLEMENT + return Rasterizer::combineSpans($right, $left, Rasterizer::RGN_DIFF); + } + } + } + + /** + * Combines spans with the clipping region + * + * @param array>> $spans + * @param int $mode Replace (0), Intersect (1), Union (2), XOR (3), Exclude (4) or Complement (5) + */ + protected function combineClip(array $spans, int $mode): void + { + if ($mode == 0) { + $this->state['clip'] = $spans; + + return; + } + $current = $this->state['clip'] ?? $this->getSpans(function (): array { + return $this->renderer->getFullSpans(); + }); + $modes = [1 => Rasterizer::RGN_AND, 2 => Rasterizer::RGN_OR, 3 => Rasterizer::RGN_XOR, 4 => Rasterizer::RGN_DIFF]; + $this->state['clip'] = $mode == 5 + ? Rasterizer::combineSpans($spans, $current, Rasterizer::RGN_DIFF) + : Rasterizer::combineSpans($current, $spans, $modes[$mode] ?? Rasterizer::RGN_COPY); + } + + /** + * @param array $rect [x, y, width, height] + * + * @return array{points: array>, types: array, closed: bool} + */ + protected function getRectFigure(array $rect): array + { + list($x, $y, $width, $height) = $rect; + + return $this->getPolylineFigure([[$x, $y], [$x + $width, $y], [$x + $width, $y + $height], [$x, $y + $height]], true); + } + + /** + * @param array> $points + * + * @return array{points: array>, types: array, closed: bool} + */ + protected function getPolylineFigure(array $points, bool $closed): array + { + $types = []; + foreach ($points as $i => $point) { + $types[] = $i == 0 ? 0 : 1; + } + + return ['points' => $points, 'types' => $types, 'closed' => $closed]; + } + + /** + * An ellipse made of 4 Bézier curves + * + * @param array $rect [x, y, width, height] + * + * @return array{points: array>, types: array, closed: bool} + */ + protected function getEllipseFigure(array $rect): array + { + $radiusX = $rect[2] / 2; + $radiusY = $rect[3] / 2; + $centerX = $rect[0] + $radiusX; + $centerY = $rect[1] + $radiusY; + // Distance of the control points (4 / 3 * tan(PI / 8)) + $kappaX = 0.5522847498 * $radiusX; + $kappaY = 0.5522847498 * $radiusY; + + return [ + 'points' => [ + [$centerX + $radiusX, $centerY], + [$centerX + $radiusX, $centerY + $kappaY], [$centerX + $kappaX, $centerY + $radiusY], [$centerX, $centerY + $radiusY], + [$centerX - $kappaX, $centerY + $radiusY], [$centerX - $radiusX, $centerY + $kappaY], [$centerX - $radiusX, $centerY], + [$centerX - $radiusX, $centerY - $kappaY], [$centerX - $kappaX, $centerY - $radiusY], [$centerX, $centerY - $radiusY], + [$centerX + $kappaX, $centerY - $radiusY], [$centerX + $radiusX, $centerY - $kappaY], [$centerX + $radiusX, $centerY], + ], + 'types' => [0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], + 'closed' => true, + ]; + } + + /** + * Returns the points of an elliptic arc (angles in degrees, clockwise) + * + * @param array $rect [x, y, width, height] + * + * @return array> + */ + protected function getArcPoints(array $rect, float $startAngle, float $sweepAngle): array + { + $radiusX = $rect[2] / 2; + $radiusY = $rect[3] / 2; + $centerX = $rect[0] + $radiusX; + $centerY = $rect[1] + $radiusY; + $steps = (int) max(4, min(360, ceil(abs($sweepAngle) / 3))); + + $points = []; + for ($i = 0; $i <= $steps; ++$i) { + $angle = deg2rad($startAngle + $sweepAngle * $i / $steps); + // The angles are measured on the ellipse (not on the circle) + $parameter = atan2($radiusX * sin($angle), $radiusY * cos($angle)); + $points[] = [$centerX + $radiusX * cos($parameter), $centerY + $radiusY * sin($parameter)]; + } + + return $points; + } + + /** + * Converts a cardinal spline to Bézier curves + * + * @param array> $points + * + * @return array{points: array>, types: array, closed: bool} + */ + protected function getCurveFigure(array $points, float $tension, bool $closed, int $offset = 0, ?int $segments = null): array + { + $count = count($points); + if ($count < 2) { + return $this->getPolylineFigure($points, $closed); + } + $getPoint = function (int $index) use ($points, $count, $closed): array { + if ($closed) { + return $points[($index % $count + $count) % $count]; + } + + return $points[max(0, min($count - 1, $index))]; + }; + + $segments = $segments ?? ($closed ? $count : $count - 1); + $factor = $tension / 3; + $result = [$getPoint($offset)]; + $types = [0]; + for ($i = $offset; $i < $offset + $segments; ++$i) { + list($previousX, $previousY) = $getPoint($i - 1); + list($startX, $startY) = $getPoint($i); + list($endX, $endY) = $getPoint($i + 1); + list($nextX, $nextY) = $getPoint($i + 2); + $result[] = [$startX + $factor * ($endX - $previousX), $startY + $factor * ($endY - $previousY)]; + $result[] = [$endX - $factor * ($nextX - $startX), $endY - $factor * ($nextY - $startY)]; + $result[] = [$endX, $endY]; + array_push($types, 3, 3, 3); + } + + return ['points' => $result, 'types' => $types, 'closed' => $closed]; + } + + protected function drawImage(int $type, int $id, bool $isCompressed, bool $isRelative, Buffer $data): void + { + $image = $this->getObject($id, 'image'); + $data->skip(8); + $source = $data->readRect(); + if ($type == self::EMFPLUS_DRAW_IMAGE) { + list($x, $y, $width, $height) = $data->readRect($isCompressed); + $points = [[$x, $y], [$x + $width, $y], [$x, $y + $height]]; + } else { + $points = $data->readPoints($data->readUInt32(), $isCompressed, $isRelative); + if (count($points) < 3) { + throw new WMFException('Reader : Invalid file : EMF+ image points'); + } + } + + $bitmap = $image['bitmap']; + // Metafiles are rendered as a whole + if ($image['isMetafile']) { + $source = [0, 0, $bitmap['width'], $bitmap['height']]; + } + $this->draw(function () use ($bitmap, $points, $source): void { + $this->renderer->drawImage($bitmap, $points, $source); + }); + } + + /** + * Converts a font to a font of the renderer (its height is in world units) + * + * @param array $font + * + * @return array + */ + protected function getRendererFont(array $font): array + { + $height = $font['emSize']; + if ($font['unit'] != 0) { + $height = $height * $this->getUnitPixels($font['unit'], $this->dpiY) / $this->getWorldPixels(); + } + + return [ + 'type' => 'font', + 'height' => -$height, + 'escapement' => 0, + 'weight' => $font['weight'], + 'italic' => $font['italic'], + 'underline' => $font['underline'], + 'strikeOut' => $font['strikeOut'], + 'charset' => 0, + 'pitchAndFamily' => 0, + 'face' => $font['face'], + ]; + } + + protected function drawString(int $flags, int $id, Buffer $data): void + { + $font = $this->getRendererFont($this->getObject($id, 'font')); + $brush = $this->getBrush($flags, $data->readUInt32()); + $formatId = $data->readUInt32(); + $length = $data->readUInt32(); + list($x, $y, $width, $height) = $data->readRect(); + $text = Encoding::decodeUTF16($data->readString($length)); + $format = $this->objects[$formatId] ?? null; + $isFormat = $format && $format['type'] == 'stringFormat'; + $alignment = $isFormat ? $format['alignment'] : 0; + $lineAlignment = $isFormat ? $format['lineAlignment'] : 0; + $formatFlags = $isFormat ? $format['flags'] : 0; + + $this->draw(function () use ($font, $brush, $text, $x, $y, $width, $height, $alignment, $lineAlignment, $formatFlags): void { + $this->renderer->selectObject($font)->setTextColor($brush['color']); + $layout = [$x, $y, $width, $height]; + + // Lines are wrapped in the layout rectangle (except with StringFormatFlagsNoWrap) + $lines = []; + foreach (explode("\n", str_replace("\r\n", "\n", $text)) as $paragraph) { + $lines = array_merge($lines, $width > 0 && !($formatFlags & 0x1000) ? $this->wrapText($paragraph, $width) : [$paragraph]); + } + $lineHeight = -$font['height'] * 1.15; + $totalHeight = count($lines) * $lineHeight; + if ($lineAlignment == 1 && $height > 0) { + $y += ($height - $totalHeight) / 2; + } elseif ($lineAlignment == 2 && $height > 0) { + $y += $height - $totalHeight; + } + // StringAlignmentNear (left), StringAlignmentCenter, StringAlignmentFar (right) + $textAlign = [0 => 0, 1 => 6, 2 => 2][$alignment] ?? 0; + if ($width > 0) { + $x += [0 => 0, 1 => $width / 2, 2 => $width][$alignment] ?? 0; + } + + // The text is clipped by the layout rectangle (except with StringFormatFlagsNoClip) + if ($width > 0 && $height > 0 && !($formatFlags & 0x4000)) { + $spans = $this->renderer->getFiguresSpans([$this->getRectFigure($layout)], false); + $clip = $this->renderer->getClipSpans(); + $this->renderer->setClipSpans($clip === null ? $spans : Rasterizer::combineSpans($clip, $spans, Rasterizer::RGN_AND)); + } + + $this->renderer->setTextAlign($textAlign); + foreach ($lines as $index => $line) { + $this->renderer->textOut($x, $y + $index * $lineHeight, $line); + } + }); + } + + /** + * Splits a paragraph into lines (at spaces) which fit in a width (world units) + * + * @return array + */ + protected function wrapText(string $paragraph, float $width): array + { + $words = preg_split('/(?<= )/u', $paragraph, -1, PREG_SPLIT_NO_EMPTY) ?: ['']; + $lines = []; + $line = ''; + foreach ($words as $word) { + if ($line !== '' && $this->renderer->getTextWidth(rtrim($line . $word)) > $width) { + $lines[] = rtrim($line); + $line = ''; + } + $line .= $word; + } + $lines[] = rtrim($line); + + return $lines; + } + + protected function drawDriverString(int $flags, int $id, Buffer $data): void + { + $font = $this->getRendererFont($this->getObject($id, 'font')); + $brush = $this->getBrush($flags, $data->readUInt32()); + $options = $data->readUInt32(); + $hasMatrix = $data->readUInt32() != 0; + $count = $data->readUInt32(); + // DriverStringOptionsCmapLookup : the glyphs are characters, else they are indexes of glyphs in the font + if (!($options & 0x01)) { + throw new WMFException('Reader : EMF+ glyph indexes not implemented'); + } + $characters = []; + for ($i = 0; $i < $count; ++$i) { + $characters[] = Encoding::encodeUTF8($data->readUInt16()); + } + $positions = $data->readPoints($count); + $matrix = $hasMatrix ? $data->readMatrix() : null; + + $this->draw(function () use ($font, $brush, $options, $characters, $positions): void { + $this->renderer->selectObject($font)->setTextColor($brush['color']); + // DriverStringOptionsRealizedAdvance : only the first position is used + if ($options & 0x04) { + $this->renderer->setTextAlign(0x18)->textOut($positions[0][0] ?? 0, $positions[0][1] ?? 0, implode('', $characters)); + + return; + } + $glyphs = []; + foreach ($characters as $i => $character) { + $glyphs[] = [$character, $positions[$i][0], $positions[$i][1]]; + } + $this->renderer->glyphsOut($glyphs); + }, $matrix); + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/GDTrait.php b/vendor/phpoffice/wmf/src/WMF/Reader/GDTrait.php new file mode 100644 index 00000000..e2b18fef --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/GDTrait.php @@ -0,0 +1,143 @@ +|null + */ + protected $backgroundColor = [255, 255, 255]; + + /** + * Defines the color of the background [r, g, b] (white by default), or a transparent background (null) + * + * The background must be defined before loading the file. + * Formats without alpha channel (JPEG, WBMP & GIF) are saved with a white background. + * + * @param array|null $color + */ + public function setBackgroundColor(?array $color): self + { + $this->backgroundColor = $color === null ? null : array_values($color); + + return $this; + } + + /** + * @return array|null + */ + public function getBackgroundColor(): ?array + { + return $this->backgroundColor; + } + + /** + * Returns the image, on a white background if the background is transparent + * + * @phpstan-ignore-next-line + * + * @return GdImage|resource + */ + protected function getOpaqueResource() + { + $image = $this->getResource(); + if ($this->backgroundColor !== null) { + return $image; + } + $opaque = imagecreatetruecolor(imagesx($image), imagesy($image)); + imagefilledrectangle($opaque, 0, 0, imagesx($image), imagesy($image), 0xFFFFFF); + imagecopy($opaque, $image, 0, 0, 0, 0, imagesx($image), imagesy($image)); + + return $opaque; + } + + /** + * Returns if the GD extension is loaded + */ + public function isSupported(): bool + { + return extension_loaded('gd'); + } + + public function __destruct() + { + $this->destroyImage($this->gd); + } + + /** + * Returns the decoded bitmap, or throws an exception if the bitmap is not supported (like compressed bitmaps) + * + * @param array{width: int, height: int, pixels: array>}|null $bitmap Decoded bitmap (see PhpOffice\WMF\Renderer\Bitmap) + * @param int $recordType Type of the record containing the bitmap + * + * @return array{width: int, height: int, pixels: array>} + */ + protected function requireBitmap(?array $bitmap, int $recordType): array + { + if ($bitmap === null) { + throw new WMFException(sprintf('Reader : Bitmap not supported : 0x%04x', $recordType)); + } + + return $bitmap; + } + + /** + * Since PHP 8.0, images are objects freed automatically (and imagedestroy() is deprecated since PHP 8.5) + * + * @phpstan-ignore-next-line + * + * @param GdImage|resource|false|null $image + */ + protected function destroyImage($image): void + { + if ($image && \PHP_VERSION_ID < 80000) { + imagedestroy($image); + } + } + + /** + * Saves the image in a format supported by GD, or in its original format (`wmf` or `emf`) + */ + public function save(string $filename, string $format): bool + { + switch (strtolower($format)) { + case 'gif': + return imagegif($this->getOpaqueResource(), $filename); + case 'jpg': + case 'jpeg': + return imagejpeg($this->getOpaqueResource(), $filename); + case 'png': + return imagepng($this->getResource(), $filename); + case 'webp': + return imagewebp($this->getResource(), $filename); + case 'wbmp': + return imagewbmp($this->getOpaqueResource(), $filename); + case $this->getFormat(): + return (bool) (file_put_contents($filename, $this->content) > 0); + default: + if ($this->hasExceptionsEnabled()) { + throw new WMFException(sprintf('Format %s not supported', $format)); + } + + return false; + } + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/ImagickTrait.php b/vendor/phpoffice/wmf/src/WMF/Reader/ImagickTrait.php new file mode 100644 index 00000000..86ef696d --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/ImagickTrait.php @@ -0,0 +1,84 @@ +getFormat()), ImagickBase::queryFormats()); + } + + protected function loadContent(): bool + { + try { + $this->im = new ImagickBase(); + + return $this->im->readImageBlob($this->content); + } catch (ImagickException $e) { + $this->im->clear(); + + if ($this->hasExceptionsEnabled()) { + throw new WMFException(sprintf('Cannot load %s File from Imagick', strtoupper($this->getFormat()))); + } + + return false; + } + } + + /** + * Returns if the loaded image is in the format of the reader + */ + protected function isImagickFormat(): bool + { + return $this->im->getImageFormat() === strtoupper($this->getFormat()); + } + + public function getResource(): ImagickBase + { + return $this->im; + } + + /** + * Saves the image in a format supported by Imagick, or in its original format (`wmf` or `emf`) + */ + public function save(string $filename, string $format): bool + { + switch (strtolower($format)) { + case 'gif': + case 'jpg': + case 'jpeg': + case 'png': + case 'webp': + case 'wbmp': + $this->getResource()->setImageFormat(strtolower($format)); + + return $this->getResource()->writeImage($filename); + case $this->getFormat(): + return (bool) (file_put_contents($filename, $this->content) > 0); + default: + if ($this->hasExceptionsEnabled()) { + throw new WMFException(sprintf('Format %s not supported', $format)); + } + + return false; + } + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/MagicTrait.php b/vendor/phpoffice/wmf/src/WMF/Reader/MagicTrait.php new file mode 100644 index 00000000..ebd721ab --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/MagicTrait.php @@ -0,0 +1,104 @@ +reader) { + return $this->reader; + } + + foreach ($this->backends as $backend) { + $reader = new $backend(); + if ($reader->isSupported()) { + $this->reader = $reader; + + break; + } + } + + return $this->reader; + } + + /** + * Returns if a backend is supported + */ + public function isSupported(): bool + { + return $this->getBackend() !== null; + } + + protected function loadContent(): bool + { + return $this->getBackend()->loadFromString($this->content); + } + + public function save(string $filename, string $format): bool + { + return $this->getBackend()->save($filename, $format); + } + + public function getMediaType(): string + { + return $this->getBackend()->getMediaType(); + } + + /** + * @phpstan-ignore-next-line + * + * @return GDImage|ImagickBase + */ + public function getResource() + { + return $this->getBackend()->getResource(); + } + + /** + * @return array + */ + public function getBackends(): array + { + return $this->backends; + } + + /** + * @param array $backends + */ + public function setBackends(array $backends): self + { + $this->backends = []; + foreach ($backends as $backend) { + if ($this->isBackend($backend)) { + $this->backends[] = $backend; + } + } + + return $this; + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/ReaderAbstract.php b/vendor/phpoffice/wmf/src/WMF/Reader/ReaderAbstract.php new file mode 100644 index 00000000..d0abdc5e --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/ReaderAbstract.php @@ -0,0 +1,66 @@ +hasExceptionsEnabled = $enable; + + return $this; + } + + /** + * Returns if exceptions are thrown + */ + public function hasExceptionsEnabled(): bool + { + return $this->hasExceptionsEnabled; + } + + public function load(string $filename): bool + { + $this->content = file_get_contents($filename); + + return $this->loadContent(); + } + + public function loadFromString(string $content): bool + { + $this->content = $content; + + return $this->loadContent(); + } + + /** + * Loads the content stored in $this->content + */ + abstract protected function loadContent(): bool; + + /** + * Returns the format of the files read by the reader (`wmf` or `emf`) + */ + abstract protected function getFormat(): string; + + public function getMediaType(): string + { + return 'image/' . $this->getFormat(); + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/ReaderInterface.php b/vendor/phpoffice/wmf/src/WMF/Reader/ReaderInterface.php new file mode 100644 index 00000000..b9c1b9a2 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/ReaderInterface.php @@ -0,0 +1,29 @@ +> + */ + protected $objects = []; + + public function __construct() + { + $this->fontResolver = new FontResolver(); + } + + /** + * Placeable WMF files (the header defines the size of the image) & standard WMF files (the size is defined by the window) + */ + public function isWMF(): bool + { + return Detector::isWMF((string) $this->content); + } + + /** + * Defines the directories where TrueType/OpenType fonts are searched (recursively) + * + * By default, the system directories are used + * + * @param array $directories + */ + public function setFontDirectories(array $directories): self + { + $this->fontResolver->setDirectories($directories); + + return $this; + } + + /** + * @return array + */ + public function getFontDirectories(): array + { + return $this->fontResolver->getDirectories(); + } + + protected function loadContent(): bool + { + if (!$this->isWMF()) { + return false; + } + + // Corrupted files must not raise PHP errors + set_error_handler(function (int $errno, string $errstr): bool { + if (!(error_reporting() & $errno)) { + return false; + } + throw new WMFException('Reader : Invalid file : ' . $errstr); + }); + try { + $this->readRecords(); + } catch (WMFException $e) { + if ($this->hasExceptionsEnabled()) { + throw $e; + } + + return false; + } finally { + restore_error_handler(); + } + + return true; + } + + protected function readRecords(): void + { + $pos = $this->readHeader(); + $this->objects = []; + + $contentLen = strlen($this->content); + while ($pos + 6 <= $contentLen) { + $header = unpack('Vsize/vfunction', (string) substr($this->content, $pos, 6)); + // Size of the record in 16-bit words + $size = (int) $header['size']; + $function = (int) $header['function']; + if ($size < 3 || $pos + 2 * $size > $contentLen) { + break; + } + $params = (string) substr($this->content, $pos + 6, 2 * $size - 6); + $pos += 2 * $size; + + if ($function == self::META_EOF) { + break; + } + if (in_array($function, self::IGNORED_RECORDS)) { + continue; + } + if (!$this->readRecord($function, $params, $size)) { + throw new WMFException('Reader : Function not implemented : 0x' . str_pad(dechex($function), 4, '0', STR_PAD_LEFT)); + } + } + + $this->gd = $this->renderer->render(); + } + + /** + * Creates the renderer from the placeable header (or from the window for standard WMF files) : its bounding box is drawn in the image + * + * @return int Position of the first record + */ + protected function readHeader(): int + { + if (Detector::isPlaceableWMF((string) $this->content)) { + $header = unpack('Vkey/vhandle/sleft/stop/sright/sbottom/vinch', (string) substr($this->content, 0, 16)); + $offset = 22; + } else { + $header = $this->getWindowBounds(); + $offset = 0; + } + // Number of logical units per inch (1440 : twips) + $unitsPerInch = $header['inch'] ?: 1440; + $boundsWidth = $header['right'] - $header['left']; + $boundsHeight = $header['bottom'] - $header['top']; + $width = (int) max(1, ceil(abs($boundsWidth) / $unitsPerInch * self::DPI)); + $height = (int) max(1, ceil(abs($boundsHeight) / $unitsPerInch * self::DPI)); + + // The device units are the pixels of the image : the window (by default, the bounding box) is mapped to the image + $this->destroyImage($this->gd); + $this->gd = false; + $this->renderer = new Renderer($width, $height, 0, 0, 0, 0, $this->fontResolver, $this->backgroundColor); + $this->renderer + ->setMapMode(Renderer::MM_ANISOTROPIC) + ->setWindowOrg($header['left'], $header['top']) + ->setWindowExt($boundsWidth ?: 1, $boundsHeight ?: 1) + ->setViewportOrg(0, 0) + ->setViewportExt($width, $height); + + // META_HEADER follows the placeable header : its size is in 16-bit words + list(, $headerSize) = unpack('v', (string) substr($this->content, $offset + 2, 2)); + + return $offset + 2 * $headerSize; + } + + /** + * Returns the bounding box of a standard WMF file : the first window defined by the records + * + * The number of logical units per inch depends on the map mode (1440 for MM_ISOTROPIC & MM_ANISOTROPIC) + * + * @return array{left: int, top: int, right: int, bottom: int, inch: int} + */ + protected function getWindowBounds(): array + { + // Logical units per inch of the map modes : MM_TEXT (pixels at 96 DPI), MM_LOMETRIC, MM_HIMETRIC, MM_LOENGLISH, MM_HIENGLISH, MM_TWIPS + $unitsPerInch = [1 => 96, 2 => 254, 3 => 2540, 4 => 100, 5 => 1000, 6 => 1440]; + $mapMode = null; + $origin = [0, 0]; + $extent = null; + $contentLen = strlen((string) $this->content); + list(, $headerSize) = unpack('v', (string) substr((string) $this->content, 2, 2)); + $pos = 2 * $headerSize; + while ($pos + 6 <= $contentLen && $extent === null) { + $header = unpack('Vsize/vfunction', (string) substr((string) $this->content, $pos, 6)); + if ($header['size'] < 3 || $header['function'] == self::META_EOF) { + break; + } + $params = (string) substr((string) $this->content, $pos + 6, 4); + if ($header['function'] == self::META_SETMAPMODE && $mapMode === null) { + $mapMode = $this->readUShort($params, 0); + } elseif ($header['function'] == self::META_SETWINDOWORG && strlen($params) == 4) { + list($y, $x) = $this->readShorts($params, 0, 2); + $origin = [$x, $y]; + } elseif ($header['function'] == self::META_SETWINDOWEXT && strlen($params) == 4) { + list($y, $x) = $this->readShorts($params, 0, 2); + $extent = [$x, $y]; + } + $pos += 2 * $header['size']; + } + if (!$extent || !$extent[0] || !$extent[1]) { + throw new WMFException('Reader : Invalid file : the size of the image is not defined'); + } + + return [ + 'left' => $origin[0], + 'top' => $origin[1], + 'right' => $origin[0] + $extent[0], + 'bottom' => $origin[1] + $extent[1], + 'inch' => $unitsPerInch[$mapMode] ?? 1440, + ]; + } + + /** + * Returns false if the record is not supported + * + * @param string $params Parameters of the record + * @param int $size Size of the record in 16-bit words + */ + protected function readRecord(int $function, string $params, int $size): bool + { + $renderer = $this->renderer; + switch ($function) { + case self::META_SAVEDC: + $renderer->saveDC(); + break; + case self::META_RESTOREDC: + $renderer->restoreDC($this->readShorts($params, 0, 1)[0]); + break; + case self::META_SETWINDOWORG: + list($y, $x) = $this->readShorts($params, 0, 2); + $renderer->setWindowOrg($x, $y); + break; + case self::META_SETWINDOWEXT: + list($y, $x) = $this->readShorts($params, 0, 2); + $renderer->setWindowExt($x, $y); + break; + case self::META_OFFSETWINDOWORG: + list($y, $x) = $this->readShorts($params, 0, 2); + $renderer->offsetWindowOrg($x, $y); + break; + case self::META_SCALEWINDOWEXT: + list($yDenom, $yNum, $xDenom, $xNum) = $this->readShorts($params, 0, 4); + $renderer->scaleWindowExt($xNum, $xDenom, $yNum, $yDenom); + break; + case self::META_SETBKMODE: + $renderer->setBkMode($this->readUShort($params, 0)); + break; + case self::META_SETPOLYFILLMODE: + $renderer->setPolyFillMode($this->readUShort($params, 0)); + break; + case self::META_SETTEXTALIGN: + $renderer->setTextAlign($this->readUShort($params, 0)); + break; + case self::META_SETBKCOLOR: + $renderer->setBkColor($this->readColor($params, 0)); + break; + case self::META_SETTEXTCOLOR: + $renderer->setTextColor($this->readColor($params, 0)); + break; + + // Objects + case self::META_CREATEPENINDIRECT: + $pen = unpack('vstyle/swidth/sunused/Cr/Cg/Cb', (string) substr($params, 0, 9)); + $this->addObject([ + 'type' => 'pen', + 'style' => $pen['style'], + 'width' => $pen['width'], + 'geometric' => true, + 'color' => [$pen['r'], $pen['g'], $pen['b']], + // Dashes are drawn only for pens of one pixel + 'dashes' => $pen['width'] <= 1 ? Renderer::getPenDashes($pen['style'], true, $pen['width']) : null, + ]); + break; + case self::META_CREATEBRUSHINDIRECT: + $brush = unpack('vstyle/Cr/Cg/Cb/x/vhatch', (string) substr($params, 0, 8)); + $this->addObject([ + 'type' => 'brush', + 'style' => $brush['style'], + 'color' => [$brush['r'], $brush['g'], $brush['b']], + 'hatch' => $brush['hatch'], + ]); + break; + case self::META_CREATEFONTINDIRECT: + $font = unpack('sheight/swidth/sescapement/sorientation/sweight/Citalic/Cunderline/CstrikeOut/Ccharset/CoutPrecision/CclipPrecision/Cquality/CpitchAndFamily', (string) substr($params, 0, 18)); + $this->addObject([ + 'type' => 'font', + 'height' => $font['height'], + 'escapement' => $font['escapement'], + 'weight' => $font['weight'], + 'italic' => $font['italic'] > 0, + 'underline' => $font['underline'] > 0, + 'strikeOut' => $font['strikeOut'] > 0, + 'charset' => $font['charset'], + 'pitchAndFamily' => $font['pitchAndFamily'], + 'face' => Encoding::decodeANSI((string) substr($params, 18, 32)), + ]); + break; + case self::META_DIBCREATEPATTERNBRUSH: + case self::META_CREATEPATTERNBRUSH: + // The pattern is tiled (its average color is used when a color is needed) + if ($function == self::META_CREATEPATTERNBRUSH) { + // Bitmap16 header, 18 reserved bytes, bits + $bitmap = $this->requireBitmap(Bitmap::readBitmap16((string) substr($params, 0, 10) . (string) substr($params, 28)), $function); + } else { + list($style, $colorUsage) = array_values(unpack('v2', (string) substr($params, 0, 4))); + // BS_PATTERN : Bitmap16, else DIB + $bitmap = $this->requireBitmap( + $style == 3 + ? Bitmap::readBitmap16((string) substr($params, 4)) + : Bitmap::readPackedDIB((string) substr($params, 4), $colorUsage == Bitmap::DIB_PAL_COLORS), + $function + ); + } + $this->addObject([ + 'type' => 'brush', + 'style' => 3, + 'color' => Bitmap::getAverageColor($bitmap), + 'pattern' => $bitmap, + ]); + break; + case self::META_CREATEREGION: + $this->addObject(['type' => 'region', 'rectangles' => $this->readRegion($params)]); + break; + case self::META_CREATEPALETTE: + $this->addObject(['type' => 'other']); + break; + case self::META_SELECTOBJECT: + $object = $this->objects[$this->readUShort($params, 0)] ?? null; + if ($object && $object['type'] == 'region') { + $renderer->selectClipRegion($object['rectangles'], Rasterizer::RGN_COPY, false); + } elseif ($object) { + $renderer->selectObject($object); + } + break; + case self::META_DELETEOBJECT: + unset($this->objects[$this->readUShort($params, 0)]); + break; + + // Regions & clipping + case self::META_SELECTCLIPREGION: + $region = $this->getRegion($this->readUShort($params, 0)); + if ($region === null) { + $renderer->resetClipRegion(); + } else { + $renderer->selectClipRegion($region, Rasterizer::RGN_COPY, false); + } + break; + case self::META_INTERSECTCLIPRECT: + case self::META_EXCLUDECLIPRECT: + list($bottom, $right, $top, $left) = $this->readShorts($params, 0, 4); + if ($function == self::META_INTERSECTCLIPRECT) { + $renderer->intersectClipRect($left, $top, $right, $bottom); + } else { + $renderer->excludeClipRect($left, $top, $right, $bottom); + } + break; + case self::META_OFFSETCLIPRGN: + list($y, $x) = $this->readShorts($params, 0, 2); + $renderer->offsetClipRegion($x, $y); + break; + case self::META_PAINTREGION: + $renderer->fillRectangles($this->getRegion($this->readUShort($params, 0)) ?? []); + break; + case self::META_INVERTREGION: + // DSTINVERT on each rectangle of the region + foreach ($this->getRegion($this->readUShort($params, 0)) ?? [] as $rectangle) { + $renderer->patBlt(...array_merge($rectangle, [Renderer::ROP_DSTINVERT])); + } + break; + case self::META_FILLREGION: + case self::META_FRAMEREGION: + $region = $this->getRegion($this->readUShort($params, 0)) ?? []; + $brush = $this->objects[$this->readUShort($params, 2)] ?? null; + if (!$brush || $brush['type'] != 'brush' || $brush['style'] == 1) { + break; + } + if ($function == self::META_FRAMEREGION) { + // The frame of each rectangle of the region + list($frameHeight, $frameWidth) = $this->readShorts($params, 4, 2); + $frames = []; + foreach ($region as list($left, $top, $right, $bottom)) { + $frames[] = [$left, $top, $right, $top + $frameHeight]; + $frames[] = [$left, $bottom - $frameHeight, $right, $bottom]; + $frames[] = [$left, $top, $left + $frameWidth, $bottom]; + $frames[] = [$right - $frameWidth, $top, $right, $bottom]; + } + $region = $frames; + } + $renderer->fillRectangles($region, $brush); + break; + + // Shapes + case self::META_MOVETO: + list($y, $x) = $this->readShorts($params, 0, 2); + $renderer->moveTo($x, $y); + break; + case self::META_LINETO: + list($y, $x) = $this->readShorts($params, 0, 2); + $renderer->lineTo($x, $y); + break; + case self::META_POLYLINE: + $renderer->polyline($this->readPoints($params, 2, $this->readShorts($params, 0, 1)[0])); + break; + case self::META_POLYGON: + $renderer->polygon($this->readPoints($params, 2, $this->readShorts($params, 0, 1)[0])); + break; + case self::META_POLYPOLYGON: + $numPolys = $this->readUShort($params, 0); + $counts = $numPolys > 0 ? array_values(unpack('v' . $numPolys, (string) substr($params, 2, 2 * $numPolys))) : []; + $offset = 2 + 2 * $numPolys; + $polygons = []; + foreach ($counts as $count) { + $polygons[] = $this->readPoints($params, $offset, $count); + $offset += 4 * $count; + } + $renderer->polyPolygon($polygons); + break; + case self::META_RECTANGLE: + list($bottom, $right, $top, $left) = $this->readShorts($params, 0, 4); + $renderer->rectangle($left, $top, $right, $bottom); + break; + case self::META_ELLIPSE: + list($bottom, $right, $top, $left) = $this->readShorts($params, 0, 4); + $renderer->ellipse($left, $top, $right, $bottom); + break; + case self::META_ROUNDRECT: + list($cornerHeight, $cornerWidth, $bottom, $right, $top, $left) = $this->readShorts($params, 0, 6); + $renderer->roundRect($left, $top, $right, $bottom, $cornerWidth, $cornerHeight); + break; + case self::META_ARC: + case self::META_PIE: + case self::META_CHORD: + list($yEnd, $xEnd, $yStart, $xStart, $bottom, $right, $top, $left) = $this->readShorts($params, 0, 8); + if ($function == self::META_ARC) { + $renderer->arc($left, $top, $right, $bottom, $xStart, $yStart, $xEnd, $yEnd); + } elseif ($function == self::META_PIE) { + $renderer->pie($left, $top, $right, $bottom, $xStart, $yStart, $xEnd, $yEnd); + } else { + $renderer->chord($left, $top, $right, $bottom, $xStart, $yStart, $xEnd, $yEnd); + } + break; + case self::META_SETPIXEL: + list($y, $x) = $this->readShorts($params, 4, 2); + $renderer->setPixel($x, $y, $this->readColor($params, 0)); + break; + case self::META_FLOODFILL: + list($y, $x) = $this->readShorts($params, 4, 2); + $renderer->floodFill($x, $y, $this->readColor($params, 0), false); + break; + case self::META_EXTFLOODFILL: + list($y, $x) = $this->readShorts($params, 6, 2); + // FLOODFILLSURFACE (1) or FLOODFILLBORDER (0) + $renderer->floodFill($x, $y, $this->readColor($params, 2), $this->readUShort($params, 0) == 1); + break; + + // Texts + case self::META_TEXTOUT: + $length = $this->readShorts($params, 0, 1)[0]; + $text = Encoding::decodeANSI((string) substr($params, 2, max(0, $length))); + $offset = 2 + $length + $length % 2; + list($y, $x) = $this->readShorts($params, $offset, 2); + $renderer->textOut($x, $y, $text); + break; + case self::META_EXTTEXTOUT: + list($y, $x, $length) = $this->readShorts($params, 0, 3); + $options = $this->readUShort($params, 6); + $offset = 8; + $rectangle = [0, 0, 0, 0]; + // ETO_OPAQUE or ETO_CLIPPED : the rectangle is present + if ($options & 0x06) { + $rectangle = $this->readShorts($params, $offset, 4); + $offset += 8; + } + $length = max(0, $length); + $text = Encoding::decodeANSI((string) substr($params, $offset, $length)); + $offset += $length + $length % 2; + $dx = strlen($params) >= $offset + 2 * $length && $length > 0 ? $this->readShorts($params, $offset, $length) : []; + $renderer->textOut($x, $y, $text, $dx, $options, $rectangle); + break; + + // Bitmaps + case self::META_PATBLT: + $rop = $this->readUInt($params, 0); + list($height, $width, $y, $x) = $this->readShorts($params, 4, 4); + $renderer->patBlt($x, $y, $x + $width, $y + $height, $rop); + break; + case self::META_BITBLT: + case self::META_DIBBITBLT: + case self::META_STRETCHBLT: + case self::META_DIBSTRETCHBLT: + $this->readBitBlt($function, $params, $size); + break; + case self::META_STRETCHDIB: + $rop = $this->readUInt($params, 0); + $colorUsage = $this->readUShort($params, 4); + list($srcHeight, $srcWidth, $ySrc, $xSrc, $destHeight, $destWidth, $yDest, $xDest) = $this->readShorts($params, 6, 8); + if ($rop == Renderer::ROP_NOP) { + break; + } + $bitmap = $this->requireBitmap(Bitmap::readPackedDIB((string) substr($params, 22), $colorUsage == Bitmap::DIB_PAL_COLORS), $function); + $renderer->drawBitmap($bitmap, $xDest, $yDest, $destWidth, $destHeight, $xSrc, $ySrc, $srcWidth, $srcHeight, $rop); + break; + case self::META_SETDIBTODEV: + $colorUsage = $this->readUShort($params, 0); + list(, , $yDib, $xDib, $height, $width, $yDest, $xDest) = $this->readShorts($params, 2, 8); + $bitmap = $this->requireBitmap(Bitmap::readPackedDIB((string) substr($params, 18), $colorUsage == Bitmap::DIB_PAL_COLORS), $function); + $renderer->drawBitmap($bitmap, $xDest, $yDest, $width, $height, $xDib, $yDib, $width, $height); + break; + default: + return false; + } + + return true; + } + + /** + * Reads META_BITBLT, META_DIBBITBLT, META_STRETCHBLT & META_DIBSTRETCHBLT records + */ + protected function readBitBlt(int $function, string $params, int $size): void + { + $rop = $this->readUInt($params, 0); + if ($rop == Renderer::ROP_NOP) { + return; + } + $isStretch = in_array($function, [self::META_STRETCHBLT, self::META_DIBSTRETCHBLT]); + // Without bitmap, the size of the record is defined by the high byte of the function + $hasBitmap = $size != ($function >> 8) + 3; + + $values = $this->readShorts($params, 4, $isStretch ? 9 : 7); + $srcWidth = $srcHeight = 0; + if ($isStretch) { + list($srcHeight, $srcWidth, $ySrc, $xSrc) = $values; + $offset = 4; + } else { + list($ySrc, $xSrc) = $values; + $offset = 2; + } + // Without bitmap, a reserved field precedes the destination + if (!$hasBitmap) { + ++$offset; + } + list($destHeight, $destWidth, $yDest, $xDest) = array_slice($values, $offset, 4); + if (!$isStretch) { + $srcWidth = $destWidth; + $srcHeight = $destHeight; + } + + if (!$hasBitmap) { + $this->renderer->patBlt($xDest, $yDest, $xDest + $destWidth, $yDest + $destHeight, $rop); + + return; + } + + $data = (string) substr($params, 4 + 2 * ($offset + 4)); + $bitmap = $this->requireBitmap( + in_array($function, [self::META_BITBLT, self::META_STRETCHBLT]) + ? Bitmap::readBitmap16($data) + : Bitmap::readPackedDIB($data), + $function + ); + $this->renderer->drawBitmap($bitmap, $xDest, $yDest, $destWidth, $destHeight, $xSrc, $ySrc, $srcWidth, $srcHeight, $rop); + } + + /** + * Adds an object in the first free slot of the table of objects + * + * @param array $object + */ + protected function addObject(array $object): void + { + $index = 0; + while (isset($this->objects[$index])) { + ++$index; + } + $this->objects[$index] = $object; + } + + /** + * Returns the rectangles of a region object + * + * @return array>|null + */ + protected function getRegion(int $index): ?array + { + $object = $this->objects[$index] ?? null; + + return $object && $object['type'] == 'region' ? $object['rectangles'] : null; + } + + /** + * Reads a Region object : a list of scans, each one containing horizontal intervals + * + * @return array> Rectangles [left, top, right, bottom] + */ + protected function readRegion(string $params): array + { + $length = strlen($params); + if ($length < 22) { + return []; + } + // Some writers (like libUEMF) use a 16-bit ObjectCount : the RegionSize field is then at offset 6 + $isShortHeader = $this->readUShort($params, 6) == $length && $this->readUShort($params, 8) != $length; + $scanCount = $this->readShorts($params, $isShortHeader ? 8 : 10, 1)[0]; + $offset = $isShortHeader ? 20 : 22; + $rectangles = []; + for ($i = 0; $i < $scanCount && $offset + 6 <= $length; ++$i) { + list($count, $top, $bottom) = $this->readShorts($params, $offset, 3); + $offset += 6; + // Truncated scans are read up to the end of the record + $count = min(max(0, $count), intdiv($length - $offset, 2)); + for ($j = 0; $j + 1 < $count; $j += 2) { + list($left, $right) = $this->readShorts($params, $offset + 2 * $j, 2); + $rectangles[] = [$left, $top, $right, $bottom]; + } + // Coordinates & Count2 + $offset += 2 * $count + 2; + } + + return $rectangles; + } + + protected function readUShort(string $params, int $offset): int + { + list(, $value) = unpack('v', (string) substr($params, $offset, 2)); + + return (int) $value; + } + + protected function readUInt(string $params, int $offset): int + { + list(, $value) = unpack('V', (string) substr($params, $offset, 4)); + + return (int) $value; + } + + /** + * Reads signed 16-bit integers + * + * @return array + */ + protected function readShorts(string $params, int $offset, int $count): array + { + $values = array_values(unpack('v' . $count, (string) substr($params, $offset, 2 * $count))); + foreach ($values as $key => $value) { + $values[$key] = $value >= 0x8000 ? $value - 0x10000 : $value; + } + + return $values; + } + + /** + * Reads a COLORREF + * + * @return array + */ + protected function readColor(string $params, int $offset): array + { + return array_values(unpack('C3', (string) substr($params, $offset, 3))); + } + + /** + * @return array> Logical coordinates + */ + protected function readPoints(string $params, int $offset, int $count): array + { + if ($count <= 0) { + return []; + } + $values = $this->readShorts($params, $offset, 2 * $count); + + $points = []; + for ($i = 0; $i < $count; ++$i) { + $points[] = [$values[2 * $i], $values[2 * $i + 1]]; + } + + return $points; + } + + /** + * @phpstan-ignore-next-line + * + * @return GdImage|resource + */ + public function getResource() + { + return $this->gd; + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/WMF/Imagick.php b/vendor/phpoffice/wmf/src/WMF/Reader/WMF/Imagick.php new file mode 100644 index 00000000..3ef6ffd3 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/WMF/Imagick.php @@ -0,0 +1,17 @@ +isImagickFormat(); + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/WMF/Magic.php b/vendor/phpoffice/wmf/src/WMF/Reader/WMF/Magic.php new file mode 100644 index 00000000..b592c2f4 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/WMF/Magic.php @@ -0,0 +1,35 @@ + + */ + protected $backends = [ + ImagickReader::class, + GD::class, + ]; + + protected function isBackend(string $backend): bool + { + return is_a($backend, ReaderInterface::class, true); + } + + public function isWMF(): bool + { + $backend = $this->getBackend(); + + return $backend instanceof ReaderInterface && $backend->isWMF(); + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Reader/WMF/ReaderAbstract.php b/vendor/phpoffice/wmf/src/WMF/Reader/WMF/ReaderAbstract.php new file mode 100644 index 00000000..65d98150 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Reader/WMF/ReaderAbstract.php @@ -0,0 +1,15 @@ + int, 'height' => int, 'pixels' => array>]`, + * where pixels are top-down rows of GD colors (0xRRGGBB) + * + * Methods return null for bitmaps which are not supported, and throw an exception for truncated bitmaps + */ +class Bitmap +{ + /** + * Usage of the color table of a bitmap : it contains indexes in the palette of the file (else, it contains colors) + */ + public const DIB_PAL_COLORS = 1; + /** + * Transparent pixel (alpha channel of GD) + */ + public const TRANSPARENT = 0x7F000000; + + /** + * Decodes a device independent bitmap (DIB) + * + * @param string $data Data containing the bitmap + * @param int $offBmi Offset of the BITMAPINFO structure + * @param int $offBits Offset of the bits + * @param int $cbBmi Size of the BITMAPINFO structure (0 if unknown) + * @param int $cbBits Size of the bits (0 if unknown) + * @param bool $hasPaletteIndexes If the color table contains indexes in the palette (DIB_PAL_COLORS) instead of colors + * + * @return array{width: int, height: int, pixels: array>}|null + * + * @throws WMFException + */ + public static function readDIB(string $data, int $offBmi, int $offBits, int $cbBmi = 0, int $cbBits = 0, bool $hasPaletteIndexes = false): ?array + { + if ($offBmi < 0 || strlen($data) < $offBmi + 40) { + throw new WMFException('Reader : Invalid file : truncated bitmap'); + } + $header = unpack('VheaderSize/lwidth/lheight/vplanes/vbitCount/Vcompression/VsizeImage/lxPelsPerMeter/lyPelsPerMeter/VclrUsed', (string) substr($data, $offBmi, 36)); + if (!$header || $header['width'] <= 0 || $header['height'] == 0) { + return null; + } + // BI_JPEG & BI_PNG : the bits are a JPEG or PNG image + if (in_array($header['compression'], [4, 5])) { + // Some files have a wrong size of bits : the rest of the data is used + // A corrupted image is not drawn + return self::readImage((string) substr($data, $offBits, $cbBits ?: strlen($data))) + ?? self::readImage((string) substr($data, $offBits)) + ?? ['width' => 0, 'height' => 0, 'pixels' => []]; + } + + $width = $header['width']; + $height = abs($header['height']); + $bitCount = $header['bitCount']; + // BI_RLE8 & BI_RLE4 are only valid for 8 & 4 bits per pixel + $isRLE = ($header['compression'] == 1 && $bitCount == 8) || ($header['compression'] == 2 && $bitCount == 4); + if ((!$isRLE && !in_array($header['compression'], [0, 3])) || !in_array($bitCount, [1, 4, 8, 16, 24, 32])) { + return null; + } + + $palette = []; + if ($bitCount <= 8) { + $colors = min(1 << $bitCount, $header['clrUsed'] ?: (1 << $bitCount)); + if ($hasPaletteIndexes) { + // The palette of the metafile is not known : a gray scale is used + $palette = self::getGrayPalette($colors); + } else { + $offset = $offBmi + $header['headerSize']; + // The palette may be truncated : missing colors are black (or white for the second color of monochrome bitmaps) + $available = (int) floor((min(strlen($data), $offBmi + ($cbBmi ?: strlen($data))) - $offset) / 4); + $palette = $bitCount == 1 ? [0x000000, 0xFFFFFF] : []; + for ($i = 0; $i < min($colors, $available); ++$i) { + list(, $blue, $green, $red) = unpack('C3', (string) substr($data, $offset + 4 * $i, 3)); + $palette[$i] = ($red << 16) | ($green << 8) | $blue; + } + } + } + + if ($isRLE) { + // Compressed bitmaps are always bottom-up + $rows = self::readRLE((string) substr($data, $offBits, $cbBits ?: strlen($data)), $width, $height, $bitCount == 4); + $pixels = []; + for ($row = $height - 1; $row >= 0; --$row) { + $line = []; + foreach ($rows[$row] as $index) { + // Skipped pixels are transparent + $line[] = $index < 0 ? self::TRANSPARENT : ($palette[$index] ?? 0); + } + $pixels[] = $line; + } + + return ['width' => $width, 'height' => $height, 'pixels' => $pixels]; + } + + $stride = (($width * $bitCount + 31) >> 5) << 2; + $pixels = []; + for ($row = 0; $row < $height; ++$row) { + // Positive height means a bottom-up bitmap + $sourceRow = $header['height'] > 0 ? $height - 1 - $row : $row; + $pixels[] = self::readRow((string) substr($data, $offBits + $sourceRow * $stride, $stride), $width, $bitCount, $palette); + } + + return ['width' => $width, 'height' => $height, 'pixels' => $pixels]; + } + + /** + * Decodes a packed DIB : the bits follow the BITMAPINFO structure + * + * @return array{width: int, height: int, pixels: array>}|null + */ + public static function readPackedDIB(string $data, bool $hasPaletteIndexes = false): ?array + { + if (strlen($data) < 40) { + throw new WMFException('Reader : Invalid file : truncated bitmap'); + } + $header = unpack('VheaderSize/lwidth/lheight/vplanes/vbitCount/Vcompression/VsizeImage/lxPelsPerMeter/lyPelsPerMeter/VclrUsed', (string) substr($data, 0, 36)); + // Only BITMAPINFOHEADER (and its extensions) are supported + if (!$header || $header['headerSize'] < 40) { + return null; + } + + $colors = $header['clrUsed']; + if ($header['bitCount'] <= 8) { + $colors = min(1 << $header['bitCount'], $colors ?: (1 << $header['bitCount'])); + } + $offBits = $header['headerSize'] + $colors * ($hasPaletteIndexes ? 2 : 4); + // BI_BITFIELDS : the masks follow a BITMAPINFOHEADER + if ($header['compression'] == 3 && $header['headerSize'] == 40) { + $offBits += 12; + } + + return self::readDIB($data, 0, $offBits, $offBits, 0, $hasPaletteIndexes); + } + + /** + * Decodes a device dependent bitmap of a WMF file (Bitmap16 object) + * + * Monochrome bitmaps are black & white, and indexed bitmaps use a gray scale (their palette is not known) + * + * @return array{width: int, height: int, pixels: array>}|null + */ + public static function readBitmap16(string $data): ?array + { + if (strlen($data) < 10) { + throw new WMFException('Reader : Invalid file : truncated bitmap'); + } + $header = unpack('vtype/swidth/sheight/swidthBytes/Cplanes/CbitsPixel', (string) substr($data, 0, 10)); + if (!$header || $header['width'] <= 0 || $header['height'] <= 0 || $header['widthBytes'] <= 0) { + return null; + } + $bitCount = $header['bitsPixel'] * $header['planes']; + if (!in_array($bitCount, [1, 4, 8, 16, 24, 32])) { + return null; + } + + $palette = $bitCount == 1 ? [0x000000, 0xFFFFFF] : self::getGrayPalette($bitCount <= 8 ? 1 << $bitCount : 0); + $pixels = []; + for ($row = 0; $row < $header['height']; ++$row) { + $pixels[] = self::readRow((string) substr($data, 10 + $row * $header['widthBytes'], $header['widthBytes']), $header['width'], $bitCount, $palette); + } + + return ['width' => $header['width'], 'height' => $header['height'], 'pixels' => $pixels]; + } + + /** + * Decodes an image supported by GD (JPEG, PNG, GIF, BMP...) + * + * @param bool $keepAlpha If the pixels keep their GD alpha channel + * + * @return array{width: int, height: int, pixels: array>}|null + */ + public static function readImage(string $data, bool $keepAlpha = false): ?array + { + $image = @imagecreatefromstring($data); + if (!$image) { + return null; + } + imagepalettetotruecolor($image); + $width = imagesx($image); + $height = imagesy($image); + + $pixels = []; + for ($y = 0; $y < $height; ++$y) { + $line = []; + for ($x = 0; $x < $width; ++$x) { + $line[] = $keepAlpha ? imagecolorat($image, $x, $y) : imagecolorat($image, $x, $y) & 0xFFFFFF; + } + $pixels[] = $line; + } + if (\PHP_VERSION_ID < 80000) { + imagedestroy($image); + } + + return ['width' => $width, 'height' => $height, 'pixels' => $pixels]; + } + + /** + * @param array{width: int, height: int, pixels: array>} $bitmap + * + * @return array + */ + public static function getAverageColor(array $bitmap): array + { + $red = $green = $blue = 0; + foreach ($bitmap['pixels'] as $line) { + foreach ($line as $pixel) { + $red += ($pixel >> 16) & 0xFF; + $green += ($pixel >> 8) & 0xFF; + $blue += $pixel & 0xFF; + } + } + $count = max(1, $bitmap['width'] * $bitmap['height']); + + return [(int) round($red / $count), (int) round($green / $count), (int) round($blue / $count)]; + } + + /** + * Decodes the bits of a BI_RLE8 or BI_RLE4 bitmap : returns the palette indexes, from the bottom row (-1 for skipped pixels) + * + * @return array> + */ + protected static function readRLE(string $data, int $width, int $height, bool $isRLE4): array + { + $rows = array_fill(0, $height, array_fill(0, $width, -1)); + $bytes = array_values(unpack('C*', $data ?: "\0")); + $length = count($bytes); + $x = $y = 0; + $position = 0; + while ($position + 1 < $length && $y < $height) { + $first = $bytes[$position]; + $second = $bytes[$position + 1]; + $position += 2; + if ($first > 0) { + // Encoded mode : $first pixels of the same index (or of two alternating indexes for RLE4) + for ($i = 0; $i < $first; ++$i, ++$x) { + if ($x < $width) { + $rows[$y][$x] = $isRLE4 ? ($i & 1 ? $second & 0x0F : $second >> 4) : $second; + } + } + } elseif ($second == 0) { + // End of line + $x = 0; + ++$y; + } elseif ($second == 1) { + // End of bitmap + break; + } elseif ($second == 2) { + // Delta : moves the current position + $x += $bytes[$position] ?? 0; + $y += $bytes[$position + 1] ?? 0; + $position += 2; + } else { + // Absolute mode : $second indexes, padded to a word + $size = $isRLE4 ? ($second + 1) >> 1 : $second; + for ($i = 0; $i < $second; ++$i, ++$x) { + $byte = $bytes[$position + ($isRLE4 ? $i >> 1 : $i)] ?? 0; + if ($x < $width) { + $rows[$y][$x] = $isRLE4 ? ($i & 1 ? $byte & 0x0F : $byte >> 4) : $byte; + } + } + $position += $size + ($size & 1); + } + } + + return $rows; + } + + /** + * Decodes a row of pixels + * + * @param array $palette + * + * @return array + */ + protected static function readRow(string $data, int $width, int $bitCount, array $palette): array + { + $bytes = array_values(unpack('C*', $data ?: "\0")); + $line = []; + for ($column = 0; $column < $width; ++$column) { + switch ($bitCount) { + case 1: + $index = ($bytes[$column >> 3] ?? 0) >> (7 - ($column & 7)) & 0x01; + $line[] = $palette[$index] ?? 0; + break; + case 4: + $index = ($bytes[$column >> 1] ?? 0) >> (($column & 1) ? 0 : 4) & 0x0F; + $line[] = $palette[$index] ?? 0; + break; + case 8: + $line[] = $palette[$bytes[$column] ?? 0] ?? 0; + break; + case 16: + // RGB 555 + $value = ($bytes[2 * $column] ?? 0) | (($bytes[2 * $column + 1] ?? 0) << 8); + $line[] = intdiv((($value >> 10) & 0x1F) * 255, 31) << 16 | intdiv((($value >> 5) & 0x1F) * 255, 31) << 8 | intdiv(($value & 0x1F) * 255, 31); + break; + default: + $offset = $column * ($bitCount >> 3); + $line[] = (($bytes[$offset + 2] ?? 0) << 16) | (($bytes[$offset + 1] ?? 0) << 8) | ($bytes[$offset] ?? 0); + break; + } + } + + return $line; + } + + /** + * @return array + */ + protected static function getGrayPalette(int $colors): array + { + $palette = []; + for ($i = 0; $i < $colors; ++$i) { + $gray = $colors > 1 ? (int) round($i * 255 / ($colors - 1)) : 0; + $palette[] = ($gray << 16) | ($gray << 8) | $gray; + } + + return $palette; + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Renderer/Encoding.php b/vendor/phpoffice/wmf/src/WMF/Renderer/Encoding.php new file mode 100644 index 00000000..75daecaa --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Renderer/Encoding.php @@ -0,0 +1,147 @@ + 0x2200, 0x24 => 0x2203, 0x27 => 0x220B, 0x2A => 0x2217, 0x2D => 0x2212, 0x40 => 0x2245, 0x41 => 0x0391, 0x42 => 0x0392, + 0x43 => 0x03A7, 0x44 => 0x0394, 0x45 => 0x0395, 0x46 => 0x03A6, 0x47 => 0x0393, 0x48 => 0x0397, 0x49 => 0x0399, 0x4A => 0x03D1, + 0x4B => 0x039A, 0x4C => 0x039B, 0x4D => 0x039C, 0x4E => 0x039D, 0x4F => 0x039F, 0x50 => 0x03A0, 0x51 => 0x0398, 0x52 => 0x03A1, + 0x53 => 0x03A3, 0x54 => 0x03A4, 0x55 => 0x03A5, 0x56 => 0x03C2, 0x57 => 0x03A9, 0x58 => 0x039E, 0x59 => 0x03A8, 0x5A => 0x0396, + 0x5C => 0x2234, 0x5E => 0x22A5, 0x60 => 0x203E, 0x61 => 0x03B1, 0x62 => 0x03B2, 0x63 => 0x03C7, 0x64 => 0x03B4, 0x65 => 0x03B5, + 0x66 => 0x03C6, 0x67 => 0x03B3, 0x68 => 0x03B7, 0x69 => 0x03B9, 0x6A => 0x03D5, 0x6B => 0x03BA, 0x6C => 0x03BB, 0x6D => 0x03BC, + 0x6E => 0x03BD, 0x6F => 0x03BF, 0x70 => 0x03C0, 0x71 => 0x03B8, 0x72 => 0x03C1, 0x73 => 0x03C3, 0x74 => 0x03C4, 0x75 => 0x03C5, + 0x76 => 0x03D6, 0x77 => 0x03C9, 0x78 => 0x03BE, 0x79 => 0x03C8, 0x7A => 0x03B6, 0x7E => 0x223C, 0xA0 => 0x20AC, 0xA1 => 0x03D2, + 0xA2 => 0x2032, 0xA3 => 0x2264, 0xA4 => 0x2044, 0xA5 => 0x221E, 0xA6 => 0x0192, 0xA7 => 0x2663, 0xA8 => 0x2666, 0xA9 => 0x2665, + 0xAA => 0x2660, 0xAB => 0x2194, 0xAC => 0x2190, 0xAD => 0x2191, 0xAE => 0x2192, 0xAF => 0x2193, 0xB0 => 0x00B0, 0xB1 => 0x00B1, + 0xB2 => 0x2033, 0xB3 => 0x2265, 0xB4 => 0x00D7, 0xB5 => 0x221D, 0xB6 => 0x2202, 0xB7 => 0x2022, 0xB8 => 0x00F7, 0xB9 => 0x2260, + 0xBA => 0x2261, 0xBB => 0x2248, 0xBC => 0x2026, 0xBD => 0x23D0, 0xBE => 0x23AF, 0xBF => 0x21B5, 0xC0 => 0x2135, 0xC1 => 0x2111, + 0xC2 => 0x211C, 0xC3 => 0x2118, 0xC4 => 0x2297, 0xC5 => 0x2295, 0xC6 => 0x2205, 0xC7 => 0x2229, 0xC8 => 0x222A, 0xC9 => 0x2283, + 0xCA => 0x2287, 0xCB => 0x2284, 0xCC => 0x2282, 0xCD => 0x2286, 0xCE => 0x2208, 0xCF => 0x2209, 0xD0 => 0x2220, 0xD1 => 0x2207, + 0xD2 => 0x00AE, 0xD3 => 0x00A9, 0xD4 => 0x2122, 0xD5 => 0x220F, 0xD6 => 0x221A, 0xD7 => 0x22C5, 0xD8 => 0x00AC, 0xD9 => 0x2227, + 0xDA => 0x2228, 0xDB => 0x21D4, 0xDC => 0x21D0, 0xDD => 0x21D1, 0xDE => 0x21D2, 0xDF => 0x21D3, 0xE0 => 0x25CA, 0xE1 => 0x2329, + 0xE2 => 0x00AE, 0xE3 => 0x00A9, 0xE4 => 0x2122, 0xE5 => 0x2211, 0xE6 => 0x239B, 0xE7 => 0x239C, 0xE8 => 0x239D, 0xE9 => 0x23A1, + 0xEA => 0x23A2, 0xEB => 0x23A3, 0xEC => 0x23A7, 0xED => 0x23A8, 0xEE => 0x23A9, 0xEF => 0x23AA, 0xF1 => 0x232A, 0xF2 => 0x222B, + 0xF3 => 0x2320, 0xF4 => 0x23AE, 0xF5 => 0x2321, 0xF6 => 0x239E, 0xF7 => 0x239F, 0xF8 => 0x23A0, 0xF9 => 0x23A4, 0xFA => 0x23A5, + 0xFB => 0x23A6, 0xFC => 0x23AB, 0xFD => 0x23AC, 0xFE => 0x23AD, + ]; + + /** + * Converts a text drawn with the Symbol font to Unicode (Greek letters, mathematical symbols...) + * + * The characters of the Symbol font are ASCII characters (0x20 to 0xFF) or private characters (U+F020 to U+F0FF) + */ + public static function decodeSymbol(string $text): string + { + $result = ''; + foreach (preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY) ?: [] as $character) { + $codePoint = self::getCodePoint($character); + if ($codePoint >= 0xF020 && $codePoint <= 0xF0FF) { + $codePoint -= 0xF000; + } + $result .= isset(self::SYMBOL[$codePoint]) ? self::encodeUTF8(self::SYMBOL[$codePoint]) : ($codePoint < 0x100 ? self::encodeUTF8($codePoint) : $character); + } + + return $result; + } + + /** + * Returns the code point of a UTF-8 character + */ + protected static function getCodePoint(string $character): int + { + $bytes = array_values(unpack('C*', $character) ?: [0]); + switch (count($bytes)) { + case 1: + return $bytes[0]; + case 2: + return (($bytes[0] & 0x1F) << 6) | ($bytes[1] & 0x3F); + case 3: + return (($bytes[0] & 0x0F) << 12) | (($bytes[1] & 0x3F) << 6) | ($bytes[2] & 0x3F); + default: + return (($bytes[0] & 0x07) << 18) | (($bytes[1] & 0x3F) << 12) | (($bytes[2] & 0x3F) << 6) | ($bytes[3] & 0x3F); + } + } + + /** + * Decodes a UTF-16LE string (stopping at the first NUL character) to UTF-8 + */ + public static function decodeUTF16(string $data): string + { + $data = (string) substr($data, 0, strlen($data) - strlen($data) % 2); + if ($data === '') { + return ''; + } + $units = array_values(unpack('v*', $data)); + $count = count($units); + + $result = ''; + for ($i = 0; $i < $count; ++$i) { + $codePoint = $units[$i]; + if ($codePoint == 0) { + break; + } + if ($codePoint >= 0xD800 && $codePoint < 0xDC00 && $i + 1 < $count && $units[$i + 1] >= 0xDC00 && $units[$i + 1] < 0xE000) { + $codePoint = 0x10000 + (($codePoint - 0xD800) << 10) + ($units[$i + 1] - 0xDC00); + ++$i; + } + $result .= self::encodeUTF8($codePoint); + } + + return $result; + } + + /** + * Decodes a Windows-1252 string (stopping at the first NUL character) to UTF-8 + */ + public static function decodeANSI(string $data): string + { + $result = ''; + $length = strlen($data); + for ($i = 0; $i < $length; ++$i) { + $byte = ord($data[$i]); + if ($byte == 0) { + break; + } + $result .= self::encodeUTF8($byte >= 0x80 && $byte < 0xA0 ? self::WINDOWS_1252[$byte - 0x80] : $byte); + } + + return $result; + } + + public static function encodeUTF8(int $codePoint): string + { + if ($codePoint >= 0xD800 && $codePoint < 0xE000) { + // Lone surrogate + $codePoint = 0xFFFD; + } + if ($codePoint < 0x80) { + return chr($codePoint); + } + if ($codePoint < 0x800) { + return chr(0xC0 | ($codePoint >> 6)) . chr(0x80 | ($codePoint & 0x3F)); + } + if ($codePoint < 0x10000) { + return chr(0xE0 | ($codePoint >> 12)) . chr(0x80 | (($codePoint >> 6) & 0x3F)) . chr(0x80 | ($codePoint & 0x3F)); + } + + return chr(0xF0 | ($codePoint >> 18)) . chr(0x80 | (($codePoint >> 12) & 0x3F)) . chr(0x80 | (($codePoint >> 6) & 0x3F)) . chr(0x80 | ($codePoint & 0x3F)); + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Renderer/FontResolver.php b/vendor/phpoffice/wmf/src/WMF/Renderer/FontResolver.php new file mode 100644 index 00000000..9067d2e7 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Renderer/FontResolver.php @@ -0,0 +1,214 @@ + ['arial', 'liberationsans', 'arimo', 'helvetica', 'dejavusans', 'freesans', 'notosans', 'verdana'], + 'serif' => ['timesnewroman', 'liberationserif', 'tinos', 'times', 'dejavuserif', 'freeserif', 'notoserif'], + 'mono' => ['couriernew', 'liberationmono', 'cousine', 'courier', 'dejavusansmono', 'freemono', 'notosansmono'], + ]; + + /** + * Families of common fonts + */ + protected const FONT_ALIASES = [ + 'arial' => 'sans', + 'arialnarrow' => 'sans', + 'calibri' => 'sans', + 'helvetica' => 'sans', + 'microsoftsansserif' => 'sans', + 'mssansserif' => 'sans', + 'segoeui' => 'sans', + 'tahoma' => 'sans', + 'verdana' => 'sans', + 'bookantiqua' => 'serif', + 'cambria' => 'serif', + 'garamond' => 'serif', + 'georgia' => 'serif', + 'msserif' => 'serif', + // The texts of the Symbol font are converted to Unicode (see Encoding::decodeSymbol()) + 'symbol' => 'serif', + 'times' => 'serif', + 'timesnewroman' => 'serif', + 'consolas' => 'mono', + 'courier' => 'mono', + 'couriernew' => 'mono', + 'lucidaconsole' => 'mono', + ]; + + /** + * Suffixes of font files for each style + */ + protected const FONT_STYLES = [ + 'regular' => ['', 'regular', 'r', 'book', 'roman', 'normal', 'medium'], + 'bold' => ['bold', 'bd', 'b'], + 'italic' => ['italic', 'i', 'oblique', 'it'], + 'bolditalic' => ['bolditalic', 'bi', 'z', 'boldoblique'], + ]; + + /** + * Directories where fonts are searched (null for the system directories) + * + * @var array|null + */ + protected $directories; + + /** + * Font files indexed by normalized name, for each set of directories + * + * @var array> + */ + protected static $indexes = []; + + /** + * Defines the directories where TrueType/OpenType fonts are searched (recursively) + * + * By default, the system directories are used + * + * @param array $directories + */ + public function setDirectories(array $directories): self + { + $this->directories = array_values($directories); + + return $this; + } + + /** + * @return array + */ + public function getDirectories(): array + { + if ($this->directories !== null) { + return $this->directories; + } + + $home = getenv('HOME') ?: getenv('USERPROFILE'); + $directories = [ + // Windows + (getenv('WINDIR') ?: 'C:\\Windows') . '\\Fonts', + getenv('LOCALAPPDATA') ? getenv('LOCALAPPDATA') . '\\Microsoft\\Windows\\Fonts' : '', + // MacOS + '/Library/Fonts', + '/System/Library/Fonts', + $home ? $home . '/Library/Fonts' : '', + // Linux + '/usr/share/fonts', + '/usr/local/share/fonts', + $home ? $home . '/.fonts' : '', + $home ? $home . '/.local/share/fonts' : '', + ]; + + return array_values(array_filter($directories, function (string $directory): bool { + return $directory !== '' && @is_dir($directory); + })); + } + + /** + * Returns the font file matching a logical font + * + * @param array $font Logical font (keys `face`, `weight`, `italic` & `pitchAndFamily`) + */ + public function resolve(array $font): ?string + { + $index = $this->getIndex(); + if (empty($index)) { + return null; + } + + $face = $this->normalize($font['face']); + $family = self::FONT_ALIASES[$face] ?? null; + if (!$family) { + // FF_ROMAN, FF_MODERN or FIXED_PITCH + $pitchAndFamily = $font['pitchAndFamily']; + $family = 'sans'; + if (($pitchAndFamily & 0xF0) == 0x10) { + $family = 'serif'; + } elseif (($pitchAndFamily & 0xF0) == 0x30 || ($pitchAndFamily & 0x03) == 1) { + $family = 'mono'; + } + } + // The Symbol font itself is not used : its characters are not Unicode characters + $names = array_unique(array_merge($face == 'symbol' ? [] : [$face], self::FONT_FAMILIES[$family])); + + $isBold = $font['weight'] >= 600; + $styles = ['regular']; + if ($isBold && $font['italic']) { + $styles = ['bolditalic', 'bold', 'italic', 'regular']; + } elseif ($isBold) { + $styles = ['bold', 'regular']; + } elseif ($font['italic']) { + $styles = ['italic', 'regular']; + } + + foreach ($styles as $style) { + foreach ($names as $name) { + foreach (self::FONT_STYLES[$style] as $suffix) { + if ($name !== '' && isset($index[$name . $suffix])) { + return $index[$name . $suffix]; + } + } + } + } + + return null; + } + + /** + * @return array + */ + protected function getIndex(): array + { + $directories = $this->getDirectories(); + $key = implode('|', $directories); + if (isset(self::$indexes[$key])) { + return self::$indexes[$key]; + } + + $index = []; + foreach ($directories as $directory) { + try { + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS), + RecursiveIteratorIterator::LEAVES_ONLY, + RecursiveIteratorIterator::CATCH_GET_CHILD + ); + foreach ($iterator as $file) { + $extension = strtolower($file->getExtension()); + if ($extension != 'ttf' && $extension != 'otf') { + continue; + } + $name = $this->normalize($file->getBasename('.' . $file->getExtension())); + if (!isset($index[$name])) { + $index[$name] = $file->getPathname(); + } + } + } catch (Exception $e) { + // Unreadable directory + } + } + self::$indexes[$key] = $index; + + return $index; + } + + protected function normalize(string $name): string + { + return (string) preg_replace('/[^a-z0-9]/', '', strtolower($name)); + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Renderer/GD.php b/vendor/phpoffice/wmf/src/WMF/Renderer/GD.php new file mode 100644 index 00000000..ad437ec9 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Renderer/GD.php @@ -0,0 +1,2444 @@ + + */ + protected $dc = []; + /** + * @var array> + */ + protected $dcStack = []; + /** + * Figures of the current path (in canvas coordinates) + * + * @var array>, closed: bool}>|null + */ + protected $path; + /** + * @var bool + */ + protected $inPath = false; + /** + * @var FontResolver + */ + protected $fontResolver; + /** + * If the background of the image is transparent + * + * @var bool + */ + protected $isTransparent = false; + + /** + * @param int $width Width of the output image (in pixels) + * @param int $height Height of the output image (in pixels) + * @param float $deviceWidth Width of the image in device units (0 : the width of the image) + * @param float $deviceHeight Height of the image in device units (0 : the height of the image) + * @param float $originX Device coordinates of the top left corner of the image + * @param float $originY + * @param array|null $backgroundColor Color of the background [r, g, b], or null for a transparent background + */ + public function __construct(int $width, int $height, float $deviceWidth = 0, float $deviceHeight = 0, float $originX = 0, float $originY = 0, ?FontResolver $fontResolver = null, ?array $backgroundColor = [255, 255, 255]) + { + $this->width = max(1, $width); + $this->height = max(1, $height); + $deviceWidth = $deviceWidth > 0 ? $deviceWidth : $this->width; + $deviceHeight = $deviceHeight > 0 ? $deviceHeight : $this->height; + + if ($this->width * $this->height > self::MAX_IMAGE_PIXELS) { + // Big images are scaled down + $ratio = sqrt(self::MAX_IMAGE_PIXELS / ($this->width * $this->height)); + $this->width = (int) max(1, floor($this->width * $ratio)); + $this->height = (int) max(1, floor($this->height * $ratio)); + } + + $this->supersampling = (int) max(1, min(self::SUPERSAMPLING, floor(sqrt(self::MAX_CANVAS_PIXELS / ($this->width * $this->height))))); + $this->canvasWidth = $this->width * $this->supersampling; + $this->canvasHeight = $this->height * $this->supersampling; + $this->deviceScaleX = $this->canvasWidth / $deviceWidth; + $this->deviceScaleY = $this->canvasHeight / $deviceHeight; + $this->originX = $originX; + $this->originY = $originY; + $this->fontResolver = $fontResolver ?? new FontResolver(); + + $this->canvas = imagecreatetruecolor($this->canvasWidth, $this->canvasHeight); + $this->isTransparent = $backgroundColor === null; + // The transparent background is drawn without blending + imagealphablending($this->canvas, false); + imagefilledrectangle($this->canvas, 0, 0, $this->canvasWidth, $this->canvasHeight, $backgroundColor === null ? 0x7F000000 : $this->toGDColor($backgroundColor)); + imagealphablending($this->canvas, true); + + $this->dc = $this->getDefaultDC(); + } + + public function __destruct() + { + if ($this->canvas && \PHP_VERSION_ID < 80000) { + imagedestroy($this->canvas); + } + } + + /** + * Defines the number of device units per millimeter (used by the metric map modes) + */ + public function setPixelsPerMm(float $pixelsPerMmX, float $pixelsPerMmY): self + { + $this->pixelsPerMmX = $pixelsPerMmX; + $this->pixelsPerMmY = $pixelsPerMmY; + + return $this; + } + + public function getFontResolver(): FontResolver + { + return $this->fontResolver; + } + + /** + * Downscales the supersampled canvas into the output image + * + * The renderer can not be used after + * + * @phpstan-ignore-next-line + * + * @return GdImage|resource + */ + public function render() + { + $image = imagecreatetruecolor($this->width, $this->height); + if ($this->isTransparent) { + // The alpha channel is copied (without blending) and saved + imagealphablending($image, false); + imagesavealpha($image, true); + } + imagecopyresampled($image, $this->canvas, 0, 0, 0, 0, $this->width, $this->height, $this->canvasWidth, $this->canvasHeight); + if (\PHP_VERSION_ID < 80000) { + imagedestroy($this->canvas); + } + $this->canvas = false; + + return $image; + } + + // --------------------------------------------------------------------- + // Device context + // --------------------------------------------------------------------- + + /** + * @return array + */ + protected function getDefaultDC(): array + { + return [ + 'mapMode' => self::MM_TEXT, + 'windowOrg' => [0, 0], + 'windowExt' => [1, 1], + 'viewportOrg' => [0, 0], + 'viewportExt' => [1, 1], + 'xform' => [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], + 'polyFillMode' => self::ALTERNATE, + 'pen' => self::getStockObject(7), + 'brush' => self::getStockObject(0), + 'clip' => null, + 'position' => [0, 0], + 'miterLimit' => 10, + 'arcDirection' => 1, + 'textColor' => [0, 0, 0], + 'bkColor' => [255, 255, 255], + 'bkMode' => 2, + 'textAlign' => 0, + 'font' => self::getStockObject(13), + ]; + } + + /** + * Returns a stock object (pen, brush or font) + * + * Pens are arrays with keys `type` (`pen`), `style`, `width` (logical units), `geometric` (bool) & `color` ([r, g, b]). + * Brushes are arrays with keys `type` (`brush`), `style` (1 for a null brush) & `color`. + * Fonts are arrays with keys `type` (`font`), `height` (logical units), `escapement` (tenths of degrees), `weight`, + * `italic`, `underline`, `strikeOut`, `charset`, `pitchAndFamily` & `face`. + * + * @return array|null + */ + public static function getStockObject(int $index): ?array + { + switch ($index) { + case 0: // WHITE_BRUSH + return ['type' => 'brush', 'style' => 0, 'color' => [255, 255, 255]]; + case 1: // LTGRAY_BRUSH + return ['type' => 'brush', 'style' => 0, 'color' => [192, 192, 192]]; + case 2: // GRAY_BRUSH + return ['type' => 'brush', 'style' => 0, 'color' => [128, 128, 128]]; + case 3: // DKGRAY_BRUSH + return ['type' => 'brush', 'style' => 0, 'color' => [64, 64, 64]]; + case 4: // BLACK_BRUSH + return ['type' => 'brush', 'style' => 0, 'color' => [0, 0, 0]]; + case 5: // NULL_BRUSH + return ['type' => 'brush', 'style' => 1, 'color' => [0, 0, 0]]; + case 6: // WHITE_PEN + return ['type' => 'pen', 'style' => 0, 'width' => 0, 'geometric' => false, 'color' => [255, 255, 255]]; + case 7: // BLACK_PEN + return ['type' => 'pen', 'style' => 0, 'width' => 0, 'geometric' => false, 'color' => [0, 0, 0]]; + case 8: // NULL_PEN + return ['type' => 'pen', 'style' => 5, 'width' => 0, 'geometric' => false, 'color' => [0, 0, 0]]; + case 10: // OEM_FIXED_FONT + case 11: // ANSI_FIXED_FONT + case 16: // SYSTEM_FIXED_FONT + case 12: // ANSI_VAR_FONT + case 13: // SYSTEM_FONT + case 14: // DEVICE_DEFAULT_FONT + case 17: // DEFAULT_GUI_FONT + $isFixed = in_array($index, [10, 11, 16]); + + return [ + 'type' => 'font', + 'height' => -12, + 'escapement' => 0, + 'weight' => $index == 13 ? 700 : 400, + 'italic' => false, + 'underline' => false, + 'strikeOut' => false, + 'charset' => 0, + 'pitchAndFamily' => $isFixed ? 0x31 : 0x22, + 'face' => $isFixed ? 'Courier New' : 'Arial', + ]; + default: + return null; + } + } + + /** + * Selects a pen, a brush or a font (see getStockObject() for their structure) + * + * @param array $object + */ + public function selectObject(array $object): self + { + if (in_array($object['type'] ?? null, ['pen', 'brush', 'font'])) { + $this->dc[$object['type']] = $object; + } + + return $this; + } + + public function setMapMode(int $mapMode): self + { + $this->dc['mapMode'] = $mapMode; + + return $this; + } + + public function setWindowOrg(int $x, int $y): self + { + $this->dc['windowOrg'] = [$x, $y]; + + return $this; + } + + public function setWindowExt(int $x, int $y): self + { + $this->dc['windowExt'] = [$x, $y]; + + return $this; + } + + public function setViewportOrg(int $x, int $y): self + { + $this->dc['viewportOrg'] = [$x, $y]; + + return $this; + } + + public function setViewportExt(int $x, int $y): self + { + $this->dc['viewportExt'] = [$x, $y]; + + return $this; + } + + public function offsetWindowOrg(int $x, int $y): self + { + $this->dc['windowOrg'] = [$this->dc['windowOrg'][0] + $x, $this->dc['windowOrg'][1] + $y]; + + return $this; + } + + public function offsetViewportOrg(int $x, int $y): self + { + $this->dc['viewportOrg'] = [$this->dc['viewportOrg'][0] + $x, $this->dc['viewportOrg'][1] + $y]; + + return $this; + } + + public function scaleWindowExt(int $xNum, int $xDenom, int $yNum, int $yDenom): self + { + return $this->scaleExtent('windowExt', $xNum, $xDenom, $yNum, $yDenom); + } + + public function scaleViewportExt(int $xNum, int $xDenom, int $yNum, int $yDenom): self + { + return $this->scaleExtent('viewportExt', $xNum, $xDenom, $yNum, $yDenom); + } + + protected function scaleExtent(string $key, int $xNum, int $xDenom, int $yNum, int $yDenom): self + { + if ($xDenom != 0 && $yDenom != 0) { + $this->dc[$key] = [ + intdiv($this->dc[$key][0] * $xNum, $xDenom), + intdiv($this->dc[$key][1] * $yNum, $yDenom), + ]; + } + + return $this; + } + + /** + * @param array $xform [eM11, eM12, eM21, eM22, eDx, eDy] + */ + public function setWorldTransform(array $xform): self + { + $this->dc['xform'] = array_values($xform); + + return $this; + } + + /** + * @param array $xform [eM11, eM12, eM21, eM22, eDx, eDy] + * @param int $mode MWT_IDENTITY (1), MWT_LEFTMULTIPLY (2), MWT_RIGHTMULTIPLY (3) or MWT_SET (4) + */ + public function modifyWorldTransform(array $xform, int $mode): self + { + $xform = array_values($xform); + switch ($mode) { + case 1: // MWT_IDENTITY + $this->dc['xform'] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + break; + case 2: // MWT_LEFTMULTIPLY + $this->dc['xform'] = $this->multiplyXForm($xform, $this->dc['xform']); + break; + case 3: // MWT_RIGHTMULTIPLY + $this->dc['xform'] = $this->multiplyXForm($this->dc['xform'], $xform); + break; + case 4: // MWT_SET + $this->dc['xform'] = $xform; + break; + } + + return $this; + } + + public function setPolyFillMode(int $mode): self + { + $this->dc['polyFillMode'] = $mode; + + return $this; + } + + public function setArcDirection(int $direction): self + { + $this->dc['arcDirection'] = $direction; + + return $this; + } + + public function setMiterLimit(float $limit): self + { + $this->dc['miterLimit'] = $limit; + + return $this; + } + + /** + * @param array $color [r, g, b] + */ + public function setTextColor(array $color): self + { + $this->dc['textColor'] = array_values($color); + + return $this; + } + + /** + * @param array $color [r, g, b] + */ + public function setBkColor(array $color): self + { + $this->dc['bkColor'] = array_values($color); + + return $this; + } + + /** + * @param int $mode TRANSPARENT (1) or OPAQUE (2) + */ + public function setBkMode(int $mode): self + { + $this->dc['bkMode'] = $mode; + + return $this; + } + + public function setTextAlign(int $align): self + { + $this->dc['textAlign'] = $align; + + return $this; + } + + public function saveDC(): self + { + $this->dcStack[] = $this->dc; + + return $this; + } + + /** + * @param int $relative Negative : relative to the last saved context, positive : index of the saved context + */ + public function restoreDC(int $relative): self + { + $index = $relative < 0 ? count($this->dcStack) + $relative : $relative - 1; + if (isset($this->dcStack[$index])) { + $this->dc = $this->dcStack[$index]; + $this->dcStack = array_slice($this->dcStack, 0, $index); + } + + return $this; + } + + // --------------------------------------------------------------------- + // Coordinates + // --------------------------------------------------------------------- + + /** + * @param array $first + * @param array $second + * + * @return array + */ + protected function multiplyXForm(array $first, array $second): array + { + return [ + $first[0] * $second[0] + $first[1] * $second[2], + $first[0] * $second[1] + $first[1] * $second[3], + $first[2] * $second[0] + $first[3] * $second[2], + $first[2] * $second[1] + $first[3] * $second[3], + $first[4] * $second[0] + $first[5] * $second[2] + $second[4], + $first[4] * $second[1] + $first[5] * $second[3] + $second[5], + ]; + } + + /** + * Returns the matrix converting logical coordinates to canvas coordinates + * (world transform, then page transform, then device to canvas) + * + * @return array + */ + protected function getMatrix(): array + { + $windowExt = $this->dc['windowExt']; + $viewportExt = $this->dc['viewportExt']; + + switch ($this->dc['mapMode']) { + case self::MM_LOMETRIC: + case self::MM_HIMETRIC: + case self::MM_LOENGLISH: + case self::MM_HIENGLISH: + case self::MM_TWIPS: + $mmPerUnit = [ + self::MM_LOMETRIC => 0.1, + self::MM_HIMETRIC => 0.01, + self::MM_LOENGLISH => 0.254, + self::MM_HIENGLISH => 0.0254, + self::MM_TWIPS => 25.4 / 1440, + ][$this->dc['mapMode']]; + $scaleX = $mmPerUnit * $this->pixelsPerMmX; + $scaleY = -$mmPerUnit * $this->pixelsPerMmY; + break; + case self::MM_ISOTROPIC: + case self::MM_ANISOTROPIC: + $scaleX = $windowExt[0] != 0 ? $viewportExt[0] / $windowExt[0] : 1; + $scaleY = $windowExt[1] != 0 ? $viewportExt[1] / $windowExt[1] : 1; + if ($this->dc['mapMode'] == self::MM_ISOTROPIC) { + $scale = min(abs($scaleX), abs($scaleY)); + $scaleX = $scaleX < 0 ? -$scale : $scale; + $scaleY = $scaleY < 0 ? -$scale : $scale; + } + break; + case self::MM_TEXT: + default: + $scaleX = $scaleY = 1; + break; + } + + $offsetX = $this->dc['viewportOrg'][0] - $this->dc['windowOrg'][0] * $scaleX - $this->originX; + $offsetY = $this->dc['viewportOrg'][1] - $this->dc['windowOrg'][1] * $scaleY - $this->originY; + + list($m11, $m12, $m21, $m22, $dx, $dy) = $this->dc['xform']; + $deviceScaleX = $this->deviceScaleX; + $deviceScaleY = $this->deviceScaleY; + + return [ + $m11 * $scaleX * $deviceScaleX, + $m12 * $scaleY * $deviceScaleY, + $m21 * $scaleX * $deviceScaleX, + $m22 * $scaleY * $deviceScaleY, + ($dx * $scaleX + $offsetX) * $deviceScaleX, + ($dy * $scaleY + $offsetY) * $deviceScaleY, + ]; + } + + /** + * @param array> $points Logical coordinates + * + * @return array> Canvas coordinates + */ + protected function toCanvasPoints(array $points): array + { + list($m11, $m12, $m21, $m22, $dx, $dy) = $this->getMatrix(); + + $result = []; + foreach ($points as $point) { + $result[] = [ + $point[0] * $m11 + $point[1] * $m21 + $dx, + $point[0] * $m12 + $point[1] * $m22 + $dy, + ]; + } + + return $result; + } + + /** + * @return array + */ + protected function deviceToCanvas(float $x, float $y): array + { + return [ + ($x - $this->originX) * $this->deviceScaleX, + ($y - $this->originY) * $this->deviceScaleY, + ]; + } + + /** + * @param array>> $polygons Canvas coordinates + * + * @return array>> + */ + protected function rasterize(array $polygons, bool $nonZero): array + { + return Rasterizer::rasterize($polygons, $nonZero, $this->canvasWidth, $this->canvasHeight); + } + + /** + * @return array> Canvas coordinates + */ + protected function getRectanglePoints(float $left, float $top, float $right, float $bottom): array + { + return $this->toCanvasPoints([[$left, $top], [$right, $top], [$right, $bottom], [$left, $bottom]]); + } + + /** + * @return array> Canvas coordinates + */ + protected function getEllipsePoints(float $left, float $top, float $right, float $bottom): array + { + $centerX = ($left + $right) / 2; + $centerY = ($top + $bottom) / 2; + $radiusX = ($right - $left) / 2; + $radiusY = ($bottom - $top) / 2; + + $points = []; + for ($i = 0; $i < 64; ++$i) { + $angle = 2 * M_PI * $i / 64; + $points[] = [$centerX + $radiusX * cos($angle), $centerY + $radiusY * sin($angle)]; + } + + return $this->toCanvasPoints($points); + } + + /** + * @return array> Canvas coordinates + */ + protected function getRoundRectPoints(float $left, float $top, float $right, float $bottom, float $cornerWidth, float $cornerHeight): array + { + $radiusX = min(abs($cornerWidth) / 2, abs($right - $left) / 2); + $radiusY = min(abs($cornerHeight) / 2, abs($bottom - $top) / 2); + $corners = [ + [$right - $radiusX, $top + $radiusY, -M_PI / 2], + [$right - $radiusX, $bottom - $radiusY, 0], + [$left + $radiusX, $bottom - $radiusY, M_PI / 2], + [$left + $radiusX, $top + $radiusY, M_PI], + ]; + + $points = []; + foreach ($corners as $corner) { + for ($i = 0; $i <= 16; ++$i) { + $angle = $corner[2] + M_PI / 2 * $i / 16; + $points[] = [$corner[0] + $radiusX * cos($angle), $corner[1] + $radiusY * sin($angle)]; + } + } + + return $this->toCanvasPoints($points); + } + + /** + * Returns the points of an elliptic arc, from the radial through the start point to the radial through the end point + * + * @return array> Logical coordinates + */ + protected function getArcPoints(float $left, float $top, float $right, float $bottom, float $startX, float $startY, float $endX, float $endY): array + { + $centerX = ($left + $right) / 2; + $centerY = ($top + $bottom) / 2; + $radiusX = ($right - $left) / 2; + $radiusY = ($bottom - $top) / 2; + if ($radiusX == 0 || $radiusY == 0) { + return [[$startX, $startY], [$endX, $endY]]; + } + + $startAngle = atan2(($startY - $centerY) * $radiusX, ($startX - $centerX) * $radiusY); + $endAngle = atan2(($endY - $centerY) * $radiusX, ($endX - $centerX) * $radiusY); + + // The direction is defined on the device : counterclockwise is a decreasing angle if the y axis goes down + list($m11, $m12, $m21, $m22) = $this->getMatrix(); + $isCounterClockwise = $this->dc['arcDirection'] != 2; + $sign = (($m11 * $m22 - $m12 * $m21) > 0) == $isCounterClockwise ? -1 : 1; + + $sweep = $endAngle - $startAngle; + if ($sign < 0) { + while ($sweep >= 0) { + $sweep -= 2 * M_PI; + } + } else { + while ($sweep <= 0) { + $sweep += 2 * M_PI; + } + } + + $steps = (int) max(4, ceil(abs($sweep) / (2 * M_PI) * 64)); + $points = []; + for ($i = 0; $i <= $steps; ++$i) { + $angle = $startAngle + $sweep * $i / $steps; + $points[] = [$centerX + $radiusX * cos($angle), $centerY + $radiusY * sin($angle)]; + } + + return $points; + } + + // --------------------------------------------------------------------- + // Shapes + // --------------------------------------------------------------------- + + public function moveTo(float $x, float $y): self + { + $this->dc['position'] = [$x, $y]; + if ($this->inPath) { + $this->path[] = ['points' => $this->toCanvasPoints([$this->dc['position']]), 'closed' => false]; + } + + return $this; + } + + public function lineTo(float $x, float $y): self + { + $this->drawTo([[$x, $y]], false); + + return $this; + } + + /** + * Draws lines (or Bézier curves) from the current position + * + * @param array> $points + */ + public function polylineTo(array $points, bool $isBezier = false): self + { + $this->drawTo($points, $isBezier); + + return $this; + } + + /** + * @param array> $points + */ + public function polyline(array $points): self + { + $this->drawFigures([['points' => $this->toCanvasPoints($points), 'closed' => false]], false); + + return $this; + } + + /** + * @param array> $points + */ + public function polygon(array $points): self + { + $this->drawFigures([['points' => $this->toCanvasPoints($points), 'closed' => true]], true); + + return $this; + } + + /** + * @param array> $points Start point followed by groups of 3 points (2 control points + end point) + */ + public function polyBezier(array $points): self + { + $this->drawFigures([['points' => Rasterizer::flattenBeziers($this->toCanvasPoints($points)), 'closed' => false]], false); + + return $this; + } + + /** + * Draws polygons (filled together) or polylines + * + * @param array>> $polygons + */ + public function polyPolygon(array $polygons, bool $closed = true): self + { + $figures = []; + foreach ($polygons as $points) { + $figures[] = ['points' => $this->toCanvasPoints($points), 'closed' => $closed]; + } + $this->drawFigures($figures, $closed); + + return $this; + } + + public function rectangle(float $left, float $top, float $right, float $bottom): self + { + $this->drawFigures([['points' => $this->getRectanglePoints($left, $top, $right, $bottom), 'closed' => true]], true); + + return $this; + } + + public function roundRect(float $left, float $top, float $right, float $bottom, float $cornerWidth, float $cornerHeight): self + { + $points = $this->getRoundRectPoints($left, $top, $right, $bottom, $cornerWidth, $cornerHeight); + $this->drawFigures([['points' => $points, 'closed' => true]], true); + + return $this; + } + + public function ellipse(float $left, float $top, float $right, float $bottom): self + { + $this->drawFigures([['points' => $this->getEllipsePoints($left, $top, $right, $bottom), 'closed' => true]], true); + + return $this; + } + + public function arc(float $left, float $top, float $right, float $bottom, float $startX, float $startY, float $endX, float $endY): self + { + $points = $this->getArcPoints($left, $top, $right, $bottom, $startX, $startY, $endX, $endY); + $this->drawFigures([['points' => $this->toCanvasPoints($points), 'closed' => false]], false); + + return $this; + } + + /** + * Draws a line from the current position to the start of the arc, then the arc + */ + public function arcTo(float $left, float $top, float $right, float $bottom, float $startX, float $startY, float $endX, float $endY): self + { + $this->drawTo($this->getArcPoints($left, $top, $right, $bottom, $startX, $startY, $endX, $endY), false); + + return $this; + } + + public function chord(float $left, float $top, float $right, float $bottom, float $startX, float $startY, float $endX, float $endY): self + { + $points = $this->getArcPoints($left, $top, $right, $bottom, $startX, $startY, $endX, $endY); + $this->drawFigures([['points' => $this->toCanvasPoints($points), 'closed' => true]], true); + + return $this; + } + + public function pie(float $left, float $top, float $right, float $bottom, float $startX, float $startY, float $endX, float $endY): self + { + $points = $this->getArcPoints($left, $top, $right, $bottom, $startX, $startY, $endX, $endY); + $points[] = [($left + $right) / 2, ($top + $bottom) / 2]; + $this->drawFigures([['points' => $this->toCanvasPoints($points), 'closed' => true]], true); + + return $this; + } + + /** + * Draws a line from the current position to the start of the arc, then the arc of a circle + * + * @param float $startAngle Degrees, counterclockwise + * @param float $sweepAngle Degrees, counterclockwise + */ + public function angleArc(float $x, float $y, float $radius, float $startAngle, float $sweepAngle): self + { + $points = []; + $steps = (int) max(2, min(128, ceil(abs($sweepAngle) / 3))); + for ($i = 0; $i <= $steps; ++$i) { + $angle = deg2rad($startAngle + $sweepAngle * $i / $steps); + $points[] = [$x + $radius * cos($angle), $y - $radius * sin($angle)]; + } + $this->drawTo($points, false); + + return $this; + } + + /** + * Draws a device pixel + * + * @param array $color [r, g, b] + */ + public function setPixel(float $x, float $y, array $color): self + { + list($point) = $this->toCanvasPoints([[$x, $y]]); + $half = $this->supersampling / 2; + $square = [ + [$point[0] - $half, $point[1] - $half], + [$point[0] + $half, $point[1] - $half], + [$point[0] + $half, $point[1] + $half], + [$point[0] - $half, $point[1] + $half], + ]; + $this->drawSpans($this->rasterize([$square], false), $color); + + return $this; + } + + /** + * Fills a rectangle with a raster operation without source (PATCOPY, BLACKNESS or WHITENESS) + */ + public function patBlt(float $left, float $top, float $right, float $bottom, int $rop): self + { + if ($rop == self::ROP_NOP) { + return $this; + } + $spans = $this->rasterize([$this->getRectanglePoints($left, $top, $right, $bottom)], false); + $brush = $this->dc['brush']; + $hasBrush = $brush && $brush['style'] != 1; + if ($rop == self::ROP_PATCOPY) { + if ($hasBrush) { + $this->drawPaint($spans, $brush); + } + + return $this; + } + + // Other raster operations : the pattern is the color of the brush (black for the null brush) + $pattern = $hasBrush ? self::toRGB($brush['color']) : 0x000000; + if (!self::isRopDependent($rop, 1)) { + $color = self::applyRop($rop, $pattern, 0, 0); + $this->drawSpans($spans, [($color >> 16) & 0xFF, ($color >> 8) & 0xFF, $color & 0xFF]); + + return $this; + } + if ($this->dc['clip'] !== null) { + $spans = Rasterizer::combineSpans($spans, $this->dc['clip'], Rasterizer::RGN_AND); + } + foreach ($spans as $y => $row) { + foreach ($row as $span) { + for ($x = $span[0]; $x <= $span[1]; ++$x) { + imagesetpixel($this->canvas, $x, $y, self::applyRop($rop, $pattern, 0, $this->getDestinationColor($x, $y))); + } + } + } + + return $this; + } + + /** + * Applies a ternary raster operation to colors (0xRRGGBB) : the third byte of the operation is a truth table + * of the pattern (P), the source (S) & the destination (D) + */ + public static function applyRop(int $rop, int $pattern, int $source, int $destination): int + { + $table = ($rop >> 16) & 0xFF; + // Common operations + switch ($table) { + case 0x88: // SRCAND + return $source & $destination; + case 0xEE: // SRCPAINT + return $source | $destination; + case 0x66: // SRCINVERT + return $source ^ $destination; + case 0x44: // SRCERASE + return $source & ~$destination & 0xFFFFFF; + case 0x33: // NOTSRCCOPY + return ~$source & 0xFFFFFF; + case 0x55: // DSTINVERT + return ~$destination & 0xFFFFFF; + case 0x5A: // PATINVERT + return $pattern ^ $destination; + case 0xCC: // SRCCOPY + return $source; + } + $result = 0; + for ($bit = 0; $bit < 8; ++$bit) { + if ($table & (1 << $bit)) { + $result |= (($bit & 4) ? $pattern : ~$pattern) + & (($bit & 2) ? $source : ~$source) + & (($bit & 1) ? $destination : ~$destination); + } + } + + return $result & 0xFFFFFF; + } + + /** + * Returns the color (0xRRGGBB) of a pixel of the canvas for a raster operation : a transparent background is white (like paper) + */ + protected function getDestinationColor(int $x, int $y): int + { + $color = imagecolorat($this->canvas, $x, $y); + $alpha = ($color >> 24) & 0x7F; + if ($alpha == 0) { + return $color & 0xFFFFFF; + } + // Composition over white + $ratio = $alpha / 127; + $red = (int) round((($color >> 16) & 0xFF) * (1 - $ratio) + 255 * $ratio); + $green = (int) round((($color >> 8) & 0xFF) * (1 - $ratio) + 255 * $ratio); + $blue = (int) round(($color & 0xFF) * (1 - $ratio) + 255 * $ratio); + + return ($red << 16) | ($green << 8) | $blue; + } + + /** + * Returns if a raster operation depends on the pattern (4), the source (2) or the destination (1) + */ + public static function isRopDependent(int $rop, int $operand): bool + { + $table = ($rop >> 16) & 0xFF; + for ($bit = 0; $bit < 8; ++$bit) { + if ((($table >> $bit) & 1) != (($table >> ($bit ^ $operand)) & 1)) { + return true; + } + } + + return false; + } + + /** + * @param array $color [r, g, b] + */ + protected static function toRGB(array $color): int + { + return ((int) $color[0] << 16) | ((int) $color[1] << 8) | (int) $color[2]; + } + + /** + * Fills rectangles (a region) with a brush, or with the current brush + * + * @param array> $rectangles [[left, top, right, bottom], ...] + * @param array|null $brush See getStockObject() + */ + public function fillRectangles(array $rectangles, ?array $brush = null): self + { + $brush = $brush ?? $this->dc['brush']; + if (!$brush || $brush['style'] == 1) { + return $this; + } + $polygons = []; + foreach ($rectangles as $rectangle) { + $polygons[] = $this->getRectanglePoints(...$rectangle); + } + $this->drawPaint($this->rasterize($polygons, true), $brush); + + return $this; + } + + /** + * Fills an area with the current brush + * + * @param array $color [r, g, b] + * @param bool $isSurface FLOODFILLSURFACE : the area has the color $color, else FLOODFILLBORDER : the area is bounded by the color $color + */ + public function floodFill(float $x, float $y, array $color, bool $isSurface): self + { + if (!$this->dc['brush'] || $this->dc['brush']['style'] == 1) { + return $this; + } + list($point) = $this->toCanvasPoints([[$x, $y]]); + $pointX = (int) floor($point[0]); + $pointY = (int) floor($point[1]); + if ($pointX < 0 || $pointY < 0 || $pointX >= $this->canvasWidth || $pointY >= $this->canvasHeight) { + return $this; + } + $brushColor = $this->dc['brush']['color']; + $gdBrushColor = ($brushColor[0] << 16) | ($brushColor[1] << 8) | $brushColor[2]; + $gdColor = ($color[0] << 16) | ($color[1] << 8) | $color[2]; + if ($isSurface) { + if (imagecolorat($this->canvas, $pointX, $pointY) == $gdColor) { + imagefill($this->canvas, $pointX, $pointY, $gdBrushColor); + } + } else { + imagefilltoborder($this->canvas, $pointX, $pointY, $gdColor, $gdBrushColor); + } + + return $this; + } + + /** + * Adds the figures to the current path, or draws them + * + * @param array>, closed: bool}> $figures + */ + protected function drawFigures(array $figures, bool $fill): void + { + if ($this->inPath) { + foreach ($figures as $figure) { + $this->path[] = $figure; + } + + return; + } + if ($fill) { + $this->fillFigures($figures); + } + $this->strokeFigures($figures); + } + + /** + * Draws lines or bezier curves from the current position (LineTo, PolylineTo, PolyBezierTo) + * + * @param array> $points Logical coordinates + */ + protected function drawTo(array $points, bool $isBezier): void + { + if (empty($points)) { + return; + } + $canvasPoints = $this->toCanvasPoints(array_merge([$this->dc['position']], $points)); + if ($isBezier) { + $canvasPoints = Rasterizer::flattenBeziers($canvasPoints); + } + $this->dc['position'] = $points[count($points) - 1]; + + if ($this->inPath) { + $last = count($this->path) - 1; + if ($last < 0 || $this->path[$last]['closed']) { + $this->path[] = ['points' => $canvasPoints, 'closed' => false]; + } else { + array_shift($canvasPoints); + $this->path[$last]['points'] = array_merge($this->path[$last]['points'], $canvasPoints); + } + + return; + } + $this->strokeFigures([['points' => $canvasPoints, 'closed' => false]]); + } + + /** + * @param array>, closed: bool}> $figures + */ + protected function fillFigures(array $figures): void + { + $brush = $this->dc['brush']; + if (!$brush || $brush['style'] == 1) { + return; + } + + $polygons = []; + foreach ($figures as $figure) { + if (count($figure['points']) >= 3) { + $polygons[] = $figure['points']; + } + } + + $this->drawPaint($this->rasterize($polygons, $this->dc['polyFillMode'] == self::WINDING), $brush); + } + + /** + * @param array>, closed: bool}> $figures + */ + protected function strokeFigures(array $figures): void + { + $pen = $this->dc['pen']; + if (!$pen || ($pen['style'] & 0x0F) == 5) { + return; + } + + // Pen width (in canvas units) + // Cosmetic pens are one pixel wide + $width = $this->supersampling; + if ($pen['geometric'] && $pen['width'] > 0) { + list($m11, $m12, $m21, $m22) = $this->getMatrix(); + $width = max($width, $pen['width'] * sqrt(abs($m11 * $m22 - $m12 * $m21))); + } + $endCap = $pen['endCap'] ?? $pen['style'] & 0x0F00; + $startCap = $pen['startCap'] ?? $endCap; + $join = $pen['geometric'] ? $pen['style'] & 0xF000 : 0x0000; + + // Shapes of the caps (like arrows) at the ends of open figures + $capPolygons = []; + foreach ($figures as $figure) { + if ($figure['closed'] || count($figure['points']) < 2) { + continue; + } + if (!empty($pen['startCapShape'])) { + $capPolygons[] = $this->getCapPolygon(array_reverse($figure['points']), $pen['startCapShape'], $width); + } + if (!empty($pen['endCapShape'])) { + $capPolygons[] = $this->getCapPolygon($figure['points'], $pen['endCapShape'], $width); + } + } + + // Compound lines : parallel lines, defined by pairs of positions in the width (from 0 to 1) + $strokes = [[$figures, $width]]; + $compound = $pen['compound'] ?? []; + if (count($compound) >= 2) { + $strokes = []; + for ($i = 0; $i + 1 < count($compound); $i += 2) { + $offset = (($compound[$i] + $compound[$i + 1]) / 2 - 0.5) * $width; + $offsetFigures = []; + foreach ($figures as $figure) { + $offsetFigures[] = ['points' => $this->getOffsetPoints($figure['points'], $figure['closed'], $offset), 'closed' => $figure['closed']]; + } + $strokes[] = [$offsetFigures, max($this->supersampling, ($compound[$i + 1] - $compound[$i]) * $width)]; + } + } + + $polygons = array_filter($capPolygons); + foreach ($strokes as list($strokeFigures, $strokeWidth)) { + // Dashes : each dash is an open figure + if (!empty($pen['dashes'])) { + $dashed = []; + foreach ($strokeFigures as $figure) { + $dashed = array_merge($dashed, $this->getDashes($figure, $pen['dashes'], $pen['dashOffset'] ?? 0, $width)); + } + $strokeFigures = $dashed; + $startCap = $endCap = $pen['dashCap'] ?? 0x0200; + } + foreach ($strokeFigures as $figure) { + $polygons = array_merge($polygons, Rasterizer::getStrokePolygons($figure['points'], $figure['closed'], $strokeWidth / 2, $endCap, $join, $this->dc['miterLimit'], $startCap)); + } + } + + $this->drawPaint($this->rasterize($polygons, true), $pen); + } + + /** + * Returns the points of a polyline moved perpendicularly (on the left of the direction for a positive offset) + * + * @param array> $points + * + * @return array> + */ + protected function getOffsetPoints(array $points, bool $closed, float $offset): array + { + $count = count($points); + if ($offset == 0 || $count < 2) { + return $points; + } + // Unit normals of the segments + $normals = []; + for ($i = 0; $i < $count; ++$i) { + $next = $points[($i + 1) % $count]; + $length = hypot($next[0] - $points[$i][0], $next[1] - $points[$i][1]); + $normals[$i] = $length > 0 ? [($points[$i][1] - $next[1]) / $length, ($next[0] - $points[$i][0]) / $length] : null; + } + + $result = []; + for ($i = 0; $i < $count; ++$i) { + $incoming = $i > 0 || $closed ? $normals[($i - 1 + $count) % $count] : null; + $outgoing = $i < $count - 1 || $closed ? $normals[$i] : null; + $normal = $incoming ?? $outgoing ?? [0, 0]; + $scale = 1.0; + if ($incoming && $outgoing) { + // Miter of the two normals (limited for sharp angles) + $sum = [$incoming[0] + $outgoing[0], $incoming[1] + $outgoing[1]]; + $length = hypot($sum[0], $sum[1]); + if ($length > 0) { + $normal = [$sum[0] / $length, $sum[1] / $length]; + $scale = min(4.0, 1 / max(0.25, $normal[0] * $outgoing[0] + $normal[1] * $outgoing[1])); + } + } + $result[] = [$points[$i][0] + $normal[0] * $offset * $scale, $points[$i][1] + $normal[1] * $offset * $scale]; + } + + return $result; + } + + /** + * Splits a figure into dashes + * + * @param array{points: array>, closed: bool} $figure + * @param array $dashes Lengths of dashes & spaces, in pen widths + * + * @return array>, closed: bool}> + */ + protected function getDashes(array $figure, array $dashes, float $offset, float $width): array + { + $lengths = []; + foreach ($dashes as $dash) { + $lengths[] = max(0.01, $dash) * $width; + } + $points = $figure['points']; + if ($figure['closed'] && count($points) > 1) { + $points[] = $points[0]; + } + + $result = []; + $index = 0; + $remaining = $lengths[0]; + // The offset moves the start of the pattern + $offset *= $width; + while ($offset > 0 && $lengths) { + if ($offset < $remaining) { + $remaining -= $offset; + break; + } + $offset -= $remaining; + $index = ($index + 1) % count($lengths); + $remaining = $lengths[$index]; + } + + $current = ($index % 2 == 0) ? [$points[0] ?? [0, 0]] : null; + for ($i = 0; $i + 1 < count($points); ++$i) { + list($x1, $y1) = $points[$i]; + list($x2, $y2) = $points[$i + 1]; + $length = hypot($x2 - $x1, $y2 - $y1); + $position = 0; + while ($length - $position > $remaining) { + $position += $remaining; + $point = [$x1 + ($x2 - $x1) * $position / $length, $y1 + ($y2 - $y1) * $position / $length]; + if ($current !== null) { + $current[] = $point; + $result[] = ['points' => $current, 'closed' => false]; + $current = null; + } else { + $current = [$point]; + } + $index = ($index + 1) % count($lengths); + $remaining = $lengths[$index]; + } + $remaining -= $length - $position; + if ($current !== null) { + $current[] = [$x2, $y2]; + } + } + if ($current !== null && count($current) > 1) { + $result[] = ['points' => $current, 'closed' => false]; + } + + return $result; + } + + /** + * Returns the polygon of a cap (like an arrow) at the end of a line + * + * The shape is defined in pen widths : the end of the line is the origin, the y axis follows the direction of the line + * + * @param array> $points Points of the line (canvas coordinates), the cap is drawn at the last one + * @param array> $shape + * + * @return array> + */ + protected function getCapPolygon(array $points, array $shape, float $width): array + { + $end = array_pop($points); + // Direction of the last segment which is not empty + do { + $from = array_pop($points); + $length = $from === null ? 0 : hypot($end[0] - $from[0], $end[1] - $from[1]); + } while ($from !== null && $length == 0); + if ($from === null || count($shape) < 3) { + return []; + } + $ux = ($end[0] - $from[0]) / $length; + $uy = ($end[1] - $from[1]) / $length; + + $polygon = []; + foreach ($shape as list($x, $y)) { + $polygon[] = [$end[0] + ($ux * $y - $uy * $x) * $width, $end[1] + ($uy * $y + $ux * $x) * $width]; + } + + return Rasterizer::getSignedArea($polygon) < 0 ? array_reverse($polygon) : $polygon; + } + + /** + * Draws spans with a pen or a brush : its color, or its shader + * + * A shader is a callable returning the color [r, g, b, a] of a point, in logical coordinates (`space` : `logical`), + * or in pixels of the image (`space` : `device`) + * + * @param array>> $spans + * @param array $paint + */ + protected function drawPaint(array $spans, array $paint): void + { + // Pattern brush : the bitmap is tiled (one pixel of the bitmap is one pixel of the image) + if (!empty($paint['pattern']['pixels'])) { + $this->drawPattern($spans, $paint['pattern']); + + return; + } + // Hatched brush (BS_HATCHED) : lines of the color of the brush, on the background color (OPAQUE background mode) + if (($paint['style'] ?? 0) == 2 && isset($paint['hatch']) && !isset($paint['shader'])) { + $hatch = $paint['hatch']; + $foreground = $paint['color']; + $background = $this->dc['bkMode'] == 2 ? $this->dc['bkColor'] : [0, 0, 0, 0]; + $paint['space'] = 'device'; + $paint['shader'] = function (float $x, float $y) use ($hatch, $foreground, $background): array { + return self::isHatchForeground($hatch, (int) floor($x), (int) floor($y)) ? $foreground : $background; + }; + } + if (!isset($paint['shader'])) { + $this->drawSpans($spans, $paint['color']); + + return; + } + + $shader = $paint['shader']; + if (($paint['space'] ?? 'logical') == 'device') { + $supersampling = $this->supersampling; + $this->drawShadedSpans($spans, function (float $x, float $y) use ($shader, $supersampling): array { + return $shader($x / $supersampling, $y / $supersampling); + }); + + return; + } + + list($m11, $m12, $m21, $m22, $dx, $dy) = $this->getMatrix(); + $determinant = $m11 * $m22 - $m21 * $m12; + if ($determinant == 0) { + return; + } + $this->drawShadedSpans($spans, function (float $x, float $y) use ($shader, $m11, $m12, $m21, $m22, $dx, $dy, $determinant): array { + $x -= $dx; + $y -= $dy; + + return $shader(($x * $m22 - $y * $m21) / $determinant, ($y * $m11 - $x * $m12) / $determinant); + }); + } + + /** + * Returns the dashes of a GDI pen (in pen widths, see the key `dashes` of pens), or null for a solid pen + * + * @param int $style Style of the pen : PS_DASH (1), PS_DOT (2), PS_DASHDOT (3), PS_DASHDOTDOT (4), PS_USERSTYLE (7), PS_ALTERNATE (8) + * @param bool $isCosmetic If the pen is cosmetic (one pixel wide) : the dashes are in pixels + * @param array $userStyle Lengths of dashes & spaces of PS_USERSTYLE, in logical units (geometric pens) or pixels (cosmetic pens) + * + * @return array|null + */ + public static function getPenDashes(int $style, bool $isCosmetic, float $width, array $userStyle = []): ?array + { + switch ($style & 0x0F) { + case 1: + return $isCosmetic ? [18, 6] : [3, 1]; + case 2: + return $isCosmetic ? [3, 3] : [1, 1]; + case 3: + return $isCosmetic ? [9, 6, 3, 6] : [3, 1, 1, 1]; + case 4: + return $isCosmetic ? [9, 3, 3, 3, 3, 3] : [3, 1, 1, 1, 1, 1]; + case 7: + if (count($userStyle) < 2) { + return null; + } + + return array_map(function (float $length) use ($isCosmetic, $width): float { + return $isCosmetic || $width <= 0 ? $length : $length / $width; + }, $userStyle); + case 8: + return [1, 1]; + default: + return null; + } + } + + /** + * Returns if a pixel of the image is in the lines of a hatch (8x8 pattern) + * + * @param int $style Horizontal (0), vertical (1), forward diagonal (2), backward diagonal (3), cross (4), diagonal cross (5), + * percent of foreground (6 to 17, EMF+ only) or other EMF+ styles (pattern of 50%) + */ + public static function isHatchForeground(int $style, int $x, int $y): bool + { + $x = abs($x); + $y = abs($y); + switch ($style) { + case 0: + return $y % 8 == 0; + case 1: + return $x % 8 == 0; + case 2: + return ($x - $y) % 8 == 0; + case 3: + return ($x + $y) % 8 == 0; + case 4: + return $x % 8 == 0 || $y % 8 == 0; + case 5: + return ($x - $y) % 8 == 0 || ($x + $y) % 8 == 0; + default: + // Ordered dither + $percent = [6 => 5, 7 => 10, 8 => 20, 9 => 25, 10 => 30, 11 => 40, 12 => 50, 13 => 60, 14 => 70, 15 => 75, 16 => 80, 17 => 90][$style] ?? 50; + + return self::BAYER[$y % 8][$x % 8] < $percent * 64 / 100; + } + } + + /** + * Fills spans with a tiled bitmap + * + * @param array>> $spans + * @param array{width: int, height: int, pixels: array>} $pattern + */ + protected function drawPattern(array $spans, array $pattern): void + { + if ($this->dc['clip'] !== null) { + $spans = Rasterizer::combineSpans($spans, $this->dc['clip'], Rasterizer::RGN_AND); + } + $size = $this->supersampling; + $tile = imagecreatetruecolor($pattern['width'] * $size, $pattern['height'] * $size); + imagealphablending($tile, false); + foreach ($pattern['pixels'] as $y => $line) { + foreach ($line as $x => $pixel) { + imagefilledrectangle($tile, $x * $size, $y * $size, ($x + 1) * $size - 1, ($y + 1) * $size - 1, $pixel); + } + } + imagesettile($this->canvas, $tile); + foreach ($spans as $y => $row) { + foreach ($row as $span) { + imagefilledrectangle($this->canvas, $span[0], $y, $span[1], $y, IMG_COLOR_TILED); + } + } + if (\PHP_VERSION_ID < 80000) { + imagedestroy($tile); + } + } + + /** + * Converts a color [r, g, b] or [r, g, b, a] (alpha from 0 : transparent to 255 : opaque) to a GD color + * + * @param array $color + */ + protected function toGDColor(array $color): int + { + $gdColor = ((int) $color[0] << 16) | ((int) $color[1] << 8) | (int) $color[2]; + if (isset($color[3]) && $color[3] < 255) { + $gdColor |= (127 - (int) round(max(0, $color[3]) * 127 / 255)) << 24; + } + + return $gdColor; + } + + /** + * @param array>> $spans + * @param array $color + */ + protected function drawSpans(array $spans, array $color): void + { + if (isset($color[3]) && $color[3] <= 0) { + return; + } + if ($this->dc['clip'] !== null) { + $spans = Rasterizer::combineSpans($spans, $this->dc['clip'], Rasterizer::RGN_AND); + } + $gdColor = $this->toGDColor($color); + foreach ($spans as $y => $row) { + foreach ($row as $span) { + imagefilledrectangle($this->canvas, $span[0], $y, $span[1], $y, $gdColor); + } + } + } + + // --------------------------------------------------------------------- + // Figures (paths of EMF+ files) + // --------------------------------------------------------------------- + + /** + * Fills and/or strokes figures with the current brush & pen + * + * @param array>, types: array, closed: bool}> $figures Logical points and their type : + * 0 (start), 1 (line) or 3 (Bézier control or end point) + */ + public function drawPathFigures(array $figures, bool $fill, bool $stroke): self + { + $canvasFigures = $this->getCanvasFigures($figures); + if ($fill) { + $this->fillFigures($canvasFigures); + } + if ($stroke) { + $this->strokeFigures($canvasFigures); + } + + return $this; + } + + /** + * Returns the spans of figures (to define a clipping region) + * + * @param array>, types: array, closed: bool}> $figures See drawPathFigures() + * + * @return array>> + */ + public function getFiguresSpans(array $figures, bool $nonZero): array + { + $polygons = []; + foreach ($this->getCanvasFigures($figures) as $figure) { + $polygons[] = $figure['points']; + } + + return $this->rasterize($polygons, $nonZero); + } + + /** + * Returns the spans covering the whole image + * + * @return array>> + */ + public function getFullSpans(): array + { + $spans = []; + for ($row = 0; $row < $this->canvasHeight; ++$row) { + $spans[$row] = [[0, $this->canvasWidth - 1]]; + } + + return $spans; + } + + /** + * Returns the clipping region (spans of the canvas), or null if there is no clipping region + * + * @return array>>|null + */ + public function getClipSpans(): ?array + { + return $this->dc['clip']; + } + + /** + * Defines the clipping region (spans of the canvas, see getClipSpans()), or removes it (null) + * + * @param array>>|null $spans + */ + public function setClipSpans(?array $spans): self + { + $this->dc['clip'] = $spans; + + return $this; + } + + /** + * Converts figures to canvas coordinates, flattening Bézier curves + * + * @param array>, types: array, closed: bool}> $figures + * + * @return array>, closed: bool}> + */ + protected function getCanvasFigures(array $figures): array + { + $result = []; + foreach ($figures as $figure) { + $points = $this->toCanvasPoints($figure['points']); + $count = count($points); + if ($count == 0) { + continue; + } + $flattened = [$points[0]]; + for ($i = 1; $i < $count; ++$i) { + if (($figure['types'][$i] ?? 1) == 3 && $i + 2 < $count) { + $flattened = array_merge($flattened, Rasterizer::flattenBezier($points[$i - 1], $points[$i], $points[$i + 1], $points[$i + 2])); + $i += 2; + } else { + $flattened[] = $points[$i]; + } + } + $result[] = ['points' => $flattened, 'closed' => $figure['closed']]; + } + + return $result; + } + + /** + * Fills the clipping region (or the whole image) with a color + * + * @param array $color [r, g, b] or [r, g, b, a] + */ + public function clear(array $color): self + { + $this->drawSpans($this->getFullSpans(), $color); + + return $this; + } + + // --------------------------------------------------------------------- + // Paths + // --------------------------------------------------------------------- + + public function beginPath(): self + { + $this->path = []; + $this->inPath = true; + + return $this; + } + + public function endPath(): self + { + $this->inPath = false; + + return $this; + } + + public function abortPath(): self + { + $this->path = null; + $this->inPath = false; + + return $this; + } + + public function closeFigure(): self + { + if (!empty($this->path)) { + $this->path[count($this->path) - 1]['closed'] = true; + } + + return $this; + } + + public function fillPath(): self + { + return $this->drawPath(true, false); + } + + public function strokePath(): self + { + return $this->drawPath(false, true); + } + + public function strokeAndFillPath(): self + { + return $this->drawPath(true, true); + } + + protected function drawPath(bool $fill, bool $stroke): self + { + if ($this->path) { + if ($fill) { + $this->fillFigures($this->path); + } + if ($stroke) { + $this->strokeFigures($this->path); + } + } + $this->path = null; + + return $this; + } + + // --------------------------------------------------------------------- + // Clipping + // --------------------------------------------------------------------- + + /** + * Combines the current path with the clipping region + * + * @param int $mode RGN_AND, RGN_OR, RGN_XOR, RGN_DIFF or RGN_COPY + */ + public function selectClipPath(int $mode): self + { + $polygons = []; + foreach ($this->path ?? [] as $figure) { + $polygons[] = $figure['points']; + } + $this->combineClip($this->rasterize($polygons, $this->dc['polyFillMode'] == self::WINDING), $mode); + $this->path = null; + + return $this; + } + + public function intersectClipRect(float $left, float $top, float $right, float $bottom): self + { + $this->combineClip($this->rasterize([$this->getRectanglePoints($left, $top, $right, $bottom)], false), Rasterizer::RGN_AND); + + return $this; + } + + public function excludeClipRect(float $left, float $top, float $right, float $bottom): self + { + $this->combineClip($this->rasterize([$this->getRectanglePoints($left, $top, $right, $bottom)], false), Rasterizer::RGN_DIFF); + + return $this; + } + + public function offsetClipRegion(float $offsetX, float $offsetY): self + { + if ($this->dc['clip'] !== null) { + list($origin, $offset) = $this->toCanvasPoints([[0, 0], [$offsetX, $offsetY]]); + $shiftX = (int) round($offset[0] - $origin[0]); + $shiftY = (int) round($offset[1] - $origin[1]); + $clip = []; + foreach ($this->dc['clip'] as $row => $spans) { + foreach ($spans as $span) { + $clip[$row + $shiftY][] = [$span[0] + $shiftX, $span[1] + $shiftX]; + } + } + $this->dc['clip'] = $clip; + } + + return $this; + } + + /** + * Removes the clipping region + */ + public function resetClipRegion(): self + { + $this->dc['clip'] = null; + + return $this; + } + + /** + * Combines a region (rectangles) with the clipping region + * + * @param array> $rectangles [[left, top, right, bottom], ...] + * @param int $mode RGN_AND, RGN_OR, RGN_XOR, RGN_DIFF or RGN_COPY + * @param bool $isDevice If the rectangles are in device units (else in logical units) + */ + public function selectClipRegion(array $rectangles, int $mode, bool $isDevice): self + { + $polygons = []; + foreach ($rectangles as $rectangle) { + list($left, $top, $right, $bottom) = $rectangle; + $polygons[] = $isDevice + ? [ + $this->deviceToCanvas($left, $top), + $this->deviceToCanvas($right, $top), + $this->deviceToCanvas($right, $bottom), + $this->deviceToCanvas($left, $bottom), + ] + : $this->getRectanglePoints($left, $top, $right, $bottom); + } + $this->combineClip($this->rasterize($polygons, true), $mode); + + return $this; + } + + /** + * @param array>> $spans + */ + protected function combineClip(array $spans, int $mode): void + { + if ($mode == Rasterizer::RGN_COPY) { + $this->dc['clip'] = $spans; + + return; + } + if ($this->dc['clip'] === null && $mode == Rasterizer::RGN_AND) { + $this->dc['clip'] = $spans; + + return; + } + if ($this->dc['clip'] === null) { + // No clipping region means the whole canvas + $this->dc['clip'] = []; + for ($row = 0; $row < $this->canvasHeight; ++$row) { + $this->dc['clip'][$row] = [[0, $this->canvasWidth - 1]]; + } + } + $this->dc['clip'] = Rasterizer::combineSpans($this->dc['clip'], $spans, $mode); + } + + // --------------------------------------------------------------------- + // Text + // --------------------------------------------------------------------- + + /** + * Draws a text with the current font + * + * @param string $text UTF-8 text + * @param array $dx Advances of each character (logical units) + * @param int $options ETO_OPAQUE (0x02), ETO_CLIPPED (0x04) + * @param array $rectangle Logical rectangle used by ETO_OPAQUE & ETO_CLIPPED [left, top, right, bottom] + * @param array $dy Vertical advances of each character (ETO_PDY : logical units, upwards in the direction of the font) + */ + public function textOut(float $x, float $y, string $text, array $dx = [], int $options = 0, array $rectangle = [0, 0, 0, 0], array $dy = []): self + { + $font = $this->dc['font']; + $text = $this->convertSymbols($text); + $clip = $this->dc['clip']; + $hasRectangle = $rectangle[2] > $rectangle[0] && $rectangle[3] > $rectangle[1]; + + // ETO_OPAQUE : the rectangle is filled with the background color + if (($options & 0x02) && $hasRectangle) { + $this->drawSpans($this->rasterize([$this->getRectanglePoints(...$rectangle)], false), $this->dc['bkColor']); + } + // ETO_CLIPPED : the text is clipped by the rectangle + if (($options & 0x04) && $hasRectangle) { + $spans = $this->rasterize([$this->getRectanglePoints(...$rectangle)], false); + $clip = $clip === null ? $spans : Rasterizer::combineSpans($clip, $spans, Rasterizer::RGN_AND); + } + if ($text === '') { + return $this; + } + + // TA_UPDATECP : the current position is used as reference point + $updatePosition = ($this->dc['textAlign'] & 0x01) > 0; + if ($updatePosition) { + list($x, $y) = $this->dc['position']; + } + + $metrics = $this->getTextMetrics(); + if ($metrics === null) { + return $this; + } + list($fontFile, $pointSize, $emSize, $angle, $scaleX) = $metrics; + $ux = cos(deg2rad($angle)); + $uy = -sin(deg2rad($angle)); + $vx = -$uy; + $vy = $ux; + + if (!empty($dx)) { + $width = array_sum($dx) * $scaleX; + } else { + $box = imagettfbbox($pointSize, 0, $fontFile, $this->escapeText($text)); + $width = $box ? $box[2] - $box[0] : 0; + } + $ascent = 0.905 * $emSize; + $descent = 0.212 * $emSize; + + // Alignment + $align = $this->dc['textAlign']; + $shiftX = 0; + if (($align & 0x06) == 0x06) { + $shiftX = -$width / 2; + } elseif ($align & 0x02) { + $shiftX = -$width; + } + $shiftY = $ascent; + if (($align & 0x18) == 0x18) { + $shiftY = 0; + } elseif ($align & 0x08) { + $shiftY = -$descent; + } + list($origin) = $this->toCanvasPoints([[$x, $y]]); + $baseX = $origin[0] + $ux * $shiftX + $vx * $shiftY; + $baseY = $origin[1] + $uy * $shiftX + $vy * $shiftY; + + // Polygon covering the text from $top to $bottom (offsets from the baseline) + $getBand = function (float $top, float $bottom) use ($baseX, $baseY, $ux, $uy, $vx, $vy, $width): array { + return [ + [$baseX + $vx * $top, $baseY + $vy * $top], + [$baseX + $ux * $width + $vx * $top, $baseY + $uy * $width + $vy * $top], + [$baseX + $ux * $width + $vx * $bottom, $baseY + $uy * $width + $vy * $bottom], + [$baseX + $vx * $bottom, $baseY + $vy * $bottom], + ]; + }; + + $savedClip = $this->dc['clip']; + $this->dc['clip'] = $clip; + + // OPAQUE background mode + if ($this->dc['bkMode'] == 2) { + $this->drawSpans($this->rasterize([$getBand(-$ascent, $descent)], false), $this->dc['bkColor']); + } + + // Position of each glyph + $glyphs = [[$text, $baseX, $baseY]]; + if (!empty($dx)) { + list(, , $m21, $m22) = $this->getMatrix(); + $scaleY = hypot($m21, $m22); + $glyphs = []; + $advance = $rise = 0; + foreach (preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY) ?: [] as $i => $char) { + $glyphs[] = [$char, $baseX + $ux * $advance - $vx * $rise, $baseY + $uy * $advance - $vy * $rise]; + $advance += ($dx[$i] ?? 0) * $scaleX; + $rise += ($dy[$i] ?? 0) * $scaleY; + } + } + $this->drawGlyphs($glyphs, $pointSize, $angle, $fontFile, $this->dc['textColor'], $clip); + + // Decorations + $thickness = max($this->supersampling, 0.06 * $emSize); + if ($font['underline']) { + $this->drawSpans($this->rasterize([$getBand(0.1 * $emSize, 0.1 * $emSize + $thickness)], false), $this->dc['textColor']); + } + if ($font['strikeOut']) { + $this->drawSpans($this->rasterize([$getBand(-0.3 * $emSize - $thickness, -0.3 * $emSize)], false), $this->dc['textColor']); + } + + $this->dc['clip'] = $savedClip; + + if ($updatePosition) { + $this->dc['position'] = [$x + ($scaleX > 0 ? $width / $scaleX : 0), $y]; + } + + return $this; + } + + /** + * Returns the metrics of the current font : [font file, point size, em size (canvas pixels), angle (degrees), horizontal scale] + * + * @return array{0: string, 1: float, 2: float, 3: float, 4: float}|null Null if no font is found or if the text is too small + */ + protected function getTextMetrics(): ?array + { + $font = $this->dc['font']; + list($m11, $m12, $m21, $m22) = $this->getMatrix(); + $scaleX = hypot($m11, $m12); + $scaleY = hypot($m21, $m22); + + // Size of the em square, in canvas pixels (a positive height is the height of the cell) + $height = $font['height'] == 0 ? -12 : $font['height']; + $emSize = ($height < 0 ? -$height : $height * 0.89) * $scaleY; + $fontFile = $this->fontResolver->resolve($font); + if (!$fontFile || $emSize < 1) { + return null; + } + // GD renders fonts at 96 DPI + $pointSize = $emSize * 72 / 96; + + // Direction of the baseline (canvas coordinates) + // The escapement is counterclockwise in logical space : it is mirrored if the transform flips the y axis + $escapement = $font['escapement'] / 10; + if ($m11 * $m22 - $m12 * $m21 < 0) { + $escapement = -$escapement; + } + $angle = $escapement + rad2deg(atan2(-$m12, $m11)); + + return [$fontFile, $pointSize, $emSize, $angle, $scaleX]; + } + + /** + * Returns the width of a text with the current font, in logical units (0 if no font is found) + */ + public function getTextWidth(string $text): float + { + $metrics = $this->getTextMetrics(); + if ($metrics === null || $text === '') { + return 0.0; + } + list($fontFile, $pointSize, , , $scaleX) = $metrics; + $box = imagettfbbox($pointSize, 0, $fontFile, $this->escapeText($this->convertSymbols($text))); + + return $box && $scaleX > 0 ? ($box[2] - $box[0]) / $scaleX : 0.0; + } + + /** + * Draws glyphs with the current font, each one at its position (logical coordinates of the baseline) + * + * @param array $glyphs UTF-8 character & position + */ + public function glyphsOut(array $glyphs): self + { + $metrics = $this->getTextMetrics(); + if ($metrics === null || empty($glyphs)) { + return $this; + } + list($fontFile, $pointSize, , $angle) = $metrics; + + $points = $this->toCanvasPoints(array_map(function (array $glyph): array { + return [$glyph[1], $glyph[2]]; + }, $glyphs)); + $canvasGlyphs = []; + foreach ($glyphs as $key => $glyph) { + $canvasGlyphs[] = [$this->convertSymbols($glyph[0]), $points[$key][0], $points[$key][1]]; + } + $this->drawGlyphs($canvasGlyphs, $pointSize, $angle, $fontFile, $this->dc['textColor'], $this->dc['clip']); + + return $this; + } + + /** + * @param array $glyphs Text & position (canvas coordinates) + * @param array $color + * @param array>>|null $clip + */ + protected function drawGlyphs(array $glyphs, float $pointSize, float $angle, string $fontFile, array $color, ?array $clip): void + { + $gdColor = $this->toGDColor($color); + $alpha = ($color[3] ?? 255) / 255; + if ($clip === null) { + foreach ($glyphs as $glyph) { + imagettftext($this->canvas, $pointSize, $angle, (int) round($glyph[1]), (int) round($glyph[2]), $gdColor, $fontFile, $this->escapeText($glyph[0])); + } + + return; + } + + // The text is drawn in a mask, which is applied through the clipping region + $minX = $minY = PHP_INT_MAX; + $maxX = $maxY = PHP_INT_MIN; + foreach ($glyphs as $glyph) { + $box = imagettfbbox($pointSize, $angle, $fontFile, $this->escapeText($glyph[0])); + if (!$box) { + continue; + } + for ($i = 0; $i < 8; $i += 2) { + $minX = min($minX, (int) floor($glyph[1] + $box[$i]) - 1); + $maxX = max($maxX, (int) ceil($glyph[1] + $box[$i]) + 1); + $minY = min($minY, (int) floor($glyph[2] + $box[$i + 1]) - 1); + $maxY = max($maxY, (int) ceil($glyph[2] + $box[$i + 1]) + 1); + } + } + $minX = max(0, $minX); + $minY = max(0, $minY); + $maxX = min($this->canvasWidth - 1, $maxX); + $maxY = min($this->canvasHeight - 1, $maxY); + if ($minX > $maxX || $minY > $maxY) { + return; + } + + $mask = imagecreatetruecolor($maxX - $minX + 1, $maxY - $minY + 1); + imagefilledrectangle($mask, 0, 0, $maxX - $minX, $maxY - $minY, 0xFFFFFF); + foreach ($glyphs as $glyph) { + imagettftext($mask, $pointSize, $angle, (int) round($glyph[1]) - $minX, (int) round($glyph[2]) - $minY, 0x000000, $fontFile, $this->escapeText($glyph[0])); + } + + for ($y = $minY; $y <= $maxY; ++$y) { + foreach (Rasterizer::combineRow($clip[$y] ?? [], [[$minX, $maxX]], Rasterizer::RGN_AND) as $span) { + for ($x = $span[0]; $x <= $span[1]; ++$x) { + $coverage = (1 - (imagecolorat($mask, $x - $minX, $y - $minY) & 0xFF) / 255) * $alpha; + if ($coverage <= 0) { + continue; + } + $background = imagecolorat($this->canvas, $x, $y); + // A background with an alpha channel is blended by GD + if ($background & 0x7F000000) { + imagesetpixel($this->canvas, $x, $y, $this->toGDColor([$color[0], $color[1], $color[2], $coverage * 255])); + continue; + } + $red = (int) round($color[0] * $coverage + (($background >> 16) & 0xFF) * (1 - $coverage)); + $green = (int) round($color[1] * $coverage + (($background >> 8) & 0xFF) * (1 - $coverage)); + $blue = (int) round($color[2] * $coverage + ($background & 0xFF) * (1 - $coverage)); + imagesetpixel($this->canvas, $x, $y, ($red << 16) | ($green << 8) | $blue); + } + } + } + if (\PHP_VERSION_ID < 80000) { + imagedestroy($mask); + } + } + + /** + * Converts the characters of the Symbol font to Unicode : the text is drawn with another font + */ + protected function convertSymbols(string $text): string + { + return strtolower(trim((string) ($this->dc['font']['face'] ?? ''))) == 'symbol' ? Encoding::decodeSymbol($text) : $text; + } + + /** + * GD interprets HTML entities in texts + */ + protected function escapeText(string $text): string + { + return str_replace('&', '&', $text); + } + + // --------------------------------------------------------------------- + // Gradients + // --------------------------------------------------------------------- + + /** + * @param array}> $vertices Logical position & color ([x, y, [r, g, b]]) + * @param array> $objects Indexes of the vertices of each rectangle (2) or triangle (3) + * @param int $mode GRADIENT_FILL_RECT_H (0), GRADIENT_FILL_RECT_V (1) or GRADIENT_FILL_TRIANGLE (2) + */ + public function gradientFill(array $vertices, array $objects, int $mode): self + { + foreach ($vertices as $key => $vertex) { + list($point) = $this->toCanvasPoints([[$vertex[0], $vertex[1]]]); + $vertices[$key] = [$point[0], $point[1], $vertex[2]]; + } + + // GRADIENT_FILL_TRIANGLE + if ($mode == 2) { + foreach ($objects as $object) { + list($first, $second, $third) = $object; + if (isset($vertices[$first], $vertices[$second], $vertices[$third])) { + $this->drawGradientTriangle($vertices[$first], $vertices[$second], $vertices[$third]); + } + } + + return $this; + } + + // GRADIENT_FILL_RECT_H or GRADIENT_FILL_RECT_V + foreach ($objects as $object) { + list($upperLeft, $lowerRight) = $object; + if (!isset($vertices[$upperLeft], $vertices[$lowerRight])) { + continue; + } + list($x1, $y1, $color1) = $vertices[$upperLeft]; + list($x2, $y2, $color2) = $vertices[$lowerRight]; + $polygon = [[$x1, $y1], [$x2, $y1], [$x2, $y2], [$x1, $y2]]; + $isHorizontal = $mode == 0; + $this->drawShadedSpans($this->rasterize([$polygon], false), function (float $x, float $y) use ($x1, $y1, $x2, $y2, $color1, $color2, $isHorizontal): array { + $ratio = $isHorizontal + ? ($x2 != $x1 ? ($x - $x1) / ($x2 - $x1) : 0) + : ($y2 != $y1 ? ($y - $y1) / ($y2 - $y1) : 0); + $ratio = max(0, min(1, $ratio)); + + return [ + $color1[0] + ($color2[0] - $color1[0]) * $ratio, + $color1[1] + ($color2[1] - $color1[1]) * $ratio, + $color1[2] + ($color2[2] - $color1[2]) * $ratio, + ]; + }); + } + + return $this; + } + + /** + * @param array{0: float, 1: float, 2: array} $first + * @param array{0: float, 1: float, 2: array} $second + * @param array{0: float, 1: float, 2: array} $third + */ + protected function drawGradientTriangle(array $first, array $second, array $third): void + { + $determinant = ($second[1] - $third[1]) * ($first[0] - $third[0]) + ($third[0] - $second[0]) * ($first[1] - $third[1]); + if ($determinant == 0) { + return; + } + $polygon = [[$first[0], $first[1]], [$second[0], $second[1]], [$third[0], $third[1]]]; + $this->drawShadedSpans($this->rasterize([$polygon], false), function (float $x, float $y) use ($first, $second, $third, $determinant): array { + // Barycentric coordinates + $weight1 = (($second[1] - $third[1]) * ($x - $third[0]) + ($third[0] - $second[0]) * ($y - $third[1])) / $determinant; + $weight2 = (($third[1] - $first[1]) * ($x - $third[0]) + ($first[0] - $third[0]) * ($y - $third[1])) / $determinant; + $weight3 = 1 - $weight1 - $weight2; + + return [ + $first[2][0] * $weight1 + $second[2][0] * $weight2 + $third[2][0] * $weight3, + $first[2][1] * $weight1 + $second[2][1] * $weight2 + $third[2][1] * $weight3, + $first[2][2] * $weight1 + $second[2][2] * $weight2 + $third[2][2] * $weight3, + ]; + }); + } + + /** + * Draws spans with a color computed for each pixel + * + * @param array>> $spans + * @param callable(float, float): array $getColor + */ + protected function drawShadedSpans(array $spans, callable $getColor): void + { + if ($this->dc['clip'] !== null) { + $spans = Rasterizer::combineSpans($spans, $this->dc['clip'], Rasterizer::RGN_AND); + } + foreach ($spans as $y => $row) { + foreach ($row as $span) { + for ($x = $span[0]; $x <= $span[1]; ++$x) { + $color = $getColor($x + 0.5, $y + 0.5); + $red = (int) max(0, min(255, round($color[0]))); + $green = (int) max(0, min(255, round($color[1]))); + $blue = (int) max(0, min(255, round($color[2]))); + if (!isset($color[3])) { + imagesetpixel($this->canvas, $x, $y, ($red << 16) | ($green << 8) | $blue); + } elseif ($color[3] > 0) { + imagesetpixel($this->canvas, $x, $y, $this->toGDColor([$red, $green, $blue, $color[3]])); + } + } + } + } + } + + // --------------------------------------------------------------------- + // Bitmaps + // --------------------------------------------------------------------- + + /** + * Draws a (part of a) bitmap in a logical parallelogram + * + * @param array{width: int, height: int, pixels: array>} $bitmap Decoded bitmap (see Bitmap), pixels may have a GD alpha channel + * @param array> $points Logical points of the upper-left, upper-right & lower-left corners of the destination + * @param array $source Source rectangle in the bitmap [x, y, width, height] + */ + public function drawImage(array $bitmap, array $points, array $source): self + { + if (empty($bitmap['pixels']) || $source[2] == 0 || $source[3] == 0) { + return $this; + } + list($origin, $right, $bottom) = $this->toCanvasPoints($points); + // Axes of the parallelogram in the canvas + $ux = $right[0] - $origin[0]; + $uy = $right[1] - $origin[1]; + $vx = $bottom[0] - $origin[0]; + $vy = $bottom[1] - $origin[1]; + $determinant = $ux * $vy - $vx * $uy; + if ($determinant == 0) { + return $this; + } + + if ($uy == 0 && $vx == 0 && $ux > 0 && $vy > 0 && $this->dc['clip'] === null && $this->copyImage($bitmap, $origin, $ux, $vy, $source)) { + return $this; + } + + $xs = [$origin[0], $right[0], $bottom[0], $right[0] + $vx]; + $ys = [$origin[1], $right[1], $bottom[1], $right[1] + $vy]; + $minX = (int) max(0, floor(min($xs))); + $maxX = (int) min($this->canvasWidth - 1, ceil(max($xs))); + $minY = (int) max(0, floor(min($ys))); + $maxY = (int) min($this->canvasHeight - 1, ceil(max($ys))); + + $clip = $this->dc['clip']; + for ($y = $minY; $y <= $maxY; ++$y) { + $rowSpans = [[$minX, $maxX]]; + if ($clip !== null) { + $rowSpans = Rasterizer::combineRow($rowSpans, $clip[$y] ?? [], Rasterizer::RGN_AND); + } + foreach ($rowSpans as $span) { + for ($x = $span[0]; $x <= $span[1]; ++$x) { + // Coordinates of the pixel center in the parallelogram + $px = $x + 0.5 - $origin[0]; + $py = $y + 0.5 - $origin[1]; + $u = ($px * $vy - $py * $vx) / $determinant; + $v = ($py * $ux - $px * $uy) / $determinant; + if ($u < 0 || $u >= 1 || $v < 0 || $v >= 1) { + continue; + } + $sourceX = (int) floor($source[0] + $u * $source[2]); + $sourceY = (int) floor($source[1] + $v * $source[3]); + if (isset($bitmap['pixels'][$sourceY][$sourceX])) { + imagesetpixel($this->canvas, $x, $y, $bitmap['pixels'][$sourceY][$sourceX]); + } + } + } + } + + return $this; + } + + /** + * Copies a bitmap in a rectangle of the canvas (fast path of drawImage()), its alpha channel is blended + * + * @param array{width: int, height: int, pixels: array>} $bitmap + * @param array $origin Upper-left corner (canvas coordinates) + * @param array $source Source rectangle in the bitmap [x, y, width, height] + * + * @return bool False if the source rectangle is not in the bitmap + */ + protected function copyImage(array $bitmap, array $origin, float $width, float $height, array $source): bool + { + list($sourceX, $sourceY, $sourceWidth, $sourceHeight) = $source; + if ($sourceX != (int) $sourceX || $sourceY != (int) $sourceY || $sourceWidth != (int) $sourceWidth || $sourceHeight != (int) $sourceHeight + || $sourceX < 0 || $sourceY < 0 || $sourceX + $sourceWidth > $bitmap['width'] || $sourceY + $sourceHeight > $bitmap['height']) { + return false; + } + + $image = imagecreatetruecolor($bitmap['width'], $bitmap['height']); + // The alpha channel of pixels is kept + imagealphablending($image, false); + foreach ($bitmap['pixels'] as $y => $line) { + foreach ($line as $x => $pixel) { + imagesetpixel($image, $x, $y, $pixel); + } + } + $left = (int) round($origin[0]); + $top = (int) round($origin[1]); + imagecopyresized( + $this->canvas, + $image, + $left, + $top, + (int) $sourceX, + (int) $sourceY, + (int) round($origin[0] + $width) - $left, + (int) round($origin[1] + $height) - $top, + (int) $sourceWidth, + (int) $sourceHeight + ); + if (\PHP_VERSION_ID < 80000) { + imagedestroy($image); + } + + return true; + } + + /** + * Draws a (part of a) bitmap in a logical rectangle + * + * @param array{width: int, height: int, pixels: array>} $bitmap Decoded bitmap (see Bitmap) + */ + public function drawBitmap(array $bitmap, int $xDest, int $yDest, int $cxDest, int $cyDest, int $xSrc, int $ySrc, int $cxSrc, int $cySrc, int $rop = self::ROP_SRCCOPY): self + { + if ($cxDest == 0 || $cyDest == 0 || empty($bitmap['pixels']) || $rop == self::ROP_NOP) { + return $this; + } + // Raster operation (other than SRCCOPY) : the pattern is the color of the brush (black for the null brush) + $isCopy = $rop == self::ROP_SRCCOPY; + $hasDestination = self::isRopDependent($rop, 1); + $brush = $this->dc['brush']; + $pattern = $brush && $brush['style'] != 1 ? self::toRGB($brush['color']) : 0x000000; + list($m11, $m12, $m21, $m22, $dx, $dy) = $this->getMatrix(); + $determinant = $m11 * $m22 - $m21 * $m12; + if ($determinant == 0) { + return $this; + } + + // Bounding box of the destination in the canvas + $corners = $this->toCanvasPoints([ + [$xDest, $yDest], + [$xDest + $cxDest, $yDest], + [$xDest, $yDest + $cyDest], + [$xDest + $cxDest, $yDest + $cyDest], + ]); + $xs = array_column($corners, 0); + $ys = array_column($corners, 1); + $minX = (int) max(0, floor(min($xs))); + $maxX = (int) min($this->canvasWidth - 1, ceil(max($xs))); + $minY = (int) max(0, floor(min($ys))); + $maxY = (int) min($this->canvasHeight - 1, ceil(max($ys))); + + $clip = $this->dc['clip']; + for ($y = $minY; $y <= $maxY; ++$y) { + $rowSpans = [[$minX, $maxX]]; + if ($clip !== null) { + $rowSpans = Rasterizer::combineSpans([$y => $rowSpans], [$y => $clip[$y] ?? []], Rasterizer::RGN_AND)[$y] ?? []; + } + foreach ($rowSpans as $span) { + for ($x = $span[0]; $x <= $span[1]; ++$x) { + // Inverse transform of the pixel center to logical coordinates + $canvasX = $x + 0.5 - $dx; + $canvasY = $y + 0.5 - $dy; + $logicalX = ($canvasX * $m22 - $canvasY * $m21) / $determinant; + $logicalY = ($canvasY * $m11 - $canvasX * $m12) / $determinant; + + $u = ($logicalX - $xDest) / $cxDest; + $v = ($logicalY - $yDest) / $cyDest; + if ($u < 0 || $u >= 1 || $v < 0 || $v >= 1) { + continue; + } + $sourceX = $xSrc + (int) floor($u * $cxSrc); + $sourceY = $ySrc + (int) floor($v * $cySrc); + if (!isset($bitmap['pixels'][$sourceY][$sourceX])) { + continue; + } + $pixel = $bitmap['pixels'][$sourceY][$sourceX]; + if (!$isCopy) { + $pixel = self::applyRop($rop, $pattern, $pixel & 0xFFFFFF, $hasDestination ? $this->getDestinationColor($x, $y) : 0); + } + imagesetpixel($this->canvas, $x, $y, $pixel); + } + } + } + + return $this; + } +} diff --git a/vendor/phpoffice/wmf/src/WMF/Renderer/Rasterizer.php b/vendor/phpoffice/wmf/src/WMF/Renderer/Rasterizer.php new file mode 100644 index 00000000..8c7d74e5 --- /dev/null +++ b/vendor/phpoffice/wmf/src/WMF/Renderer/Rasterizer.php @@ -0,0 +1,452 @@ + [[xStart, xEnd], ...]]` (inclusive, sorted & disjoint) + */ +class Rasterizer +{ + public const RGN_AND = 1; + public const RGN_OR = 2; + public const RGN_XOR = 3; + public const RGN_DIFF = 4; + public const RGN_COPY = 5; + + /** + * Converts polygons into spans of pixels (scanline algorithm) + * + * @param array>> $polygons + * @param bool $nonZero Nonzero winding rule (else even-odd rule) + * + * @return array>> + */ + public static function rasterize(array $polygons, bool $nonZero, int $width, int $height): array + { + // Edges bucketed by their first row + $edges = []; + $minRow = PHP_INT_MAX; + $maxRow = PHP_INT_MIN; + foreach ($polygons as $polygon) { + $count = count($polygon); + for ($i = 0; $i < $count; ++$i) { + list($x1, $y1) = $polygon[$i]; + list($x2, $y2) = $polygon[($i + 1) % $count]; + if ($y1 == $y2) { + continue; + } + $direction = 1; + if ($y1 > $y2) { + list($x1, $y1, $x2, $y2) = [$x2, $y2, $x1, $y1]; + $direction = -1; + } + // Rows whose center is in [y1, y2) + $firstRow = (int) max(0, ceil($y1 - 0.5)); + $lastRow = (int) min($height - 1, ceil($y2 - 0.5) - 1); + if ($firstRow > $lastRow) { + continue; + } + $slope = ($x2 - $x1) / ($y2 - $y1); + $edges[$firstRow][] = [$lastRow, $x1 + ($firstRow + 0.5 - $y1) * $slope, $slope, $direction]; + $minRow = min($minRow, $firstRow); + $maxRow = max($maxRow, $lastRow); + } + } + + $spans = []; + $active = []; + for ($row = $minRow; $row <= $maxRow; ++$row) { + if (isset($edges[$row])) { + foreach ($edges[$row] as $edge) { + $active[] = $edge; + } + } + if (empty($active)) { + continue; + } + + $crossings = []; + foreach ($active as $key => $edge) { + if ($edge[0] < $row) { + unset($active[$key]); + continue; + } + $crossings[] = [$edge[1], $edge[3]]; + $active[$key][1] += $edge[2]; + } + usort($crossings, function (array $a, array $b): int { + return $a[0] <=> $b[0]; + }); + + $rowSpans = []; + $winding = 0; + $start = 0.0; + foreach ($crossings as $crossing) { + $wasInside = $nonZero ? $winding != 0 : ($winding % 2) != 0; + $winding += $nonZero ? $crossing[1] : 1; + $isInside = $nonZero ? $winding != 0 : ($winding % 2) != 0; + if (!$wasInside && $isInside) { + $start = $crossing[0]; + } elseif ($wasInside && !$isInside) { + // Pixels whose center is in [start, end) + $xStart = (int) max(0, ceil($start - 0.5)); + $xEnd = (int) min($width - 1, ceil($crossing[0] - 0.5) - 1); + if ($xStart <= $xEnd) { + $rowSpans[] = [$xStart, $xEnd]; + } + } + } + if (!empty($rowSpans)) { + $spans[$row] = $rowSpans; + } + } + + return $spans; + } + + /** + * @param array>> $first + * @param array>> $second + * @param int $mode RGN_AND, RGN_OR, RGN_XOR, RGN_DIFF or RGN_COPY + * + * @return array>> + */ + public static function combineSpans(array $first, array $second, int $mode): array + { + switch ($mode) { + case self::RGN_COPY: + return $second; + case self::RGN_AND: + $rows = array_keys(array_intersect_key($first, $second)); + break; + case self::RGN_DIFF: + $rows = array_keys($first); + break; + default: + $rows = array_keys($first + $second); + break; + } + + $result = []; + foreach ($rows as $row) { + $rowSpans = self::combineRow($first[$row] ?? [], $second[$row] ?? [], $mode); + if (!empty($rowSpans)) { + $result[$row] = $rowSpans; + } + } + ksort($result); + + return $result; + } + + /** + * Combines two rows of sorted & disjoint spans + * + * @param array> $first + * @param array> $second + * + * @return array> + */ + public static function combineRow(array $first, array $second, int $mode): array + { + $countFirst = count($first); + $countSecond = count($second); + $result = []; + + if ($mode == self::RGN_AND) { + $i = $j = 0; + while ($i < $countFirst && $j < $countSecond) { + $start = max($first[$i][0], $second[$j][0]); + $end = min($first[$i][1], $second[$j][1]); + if ($start <= $end) { + $result[] = [$start, $end]; + } + if ($first[$i][1] < $second[$j][1]) { + ++$i; + } else { + ++$j; + } + } + + return $result; + } + + // Boundaries of half-open intervals + $boundaries = []; + foreach ($first as $span) { + $boundaries[] = $span[0]; + $boundaries[] = $span[1] + 1; + } + foreach ($second as $span) { + $boundaries[] = $span[0]; + $boundaries[] = $span[1] + 1; + } + sort($boundaries); + + $i = $j = 0; + $countBoundaries = count($boundaries); + for ($k = 0; $k < $countBoundaries - 1; ++$k) { + $x = $boundaries[$k]; + if ($x == $boundaries[$k + 1]) { + continue; + } + while ($i < $countFirst && $first[$i][1] < $x) { + ++$i; + } + while ($j < $countSecond && $second[$j][1] < $x) { + ++$j; + } + $inFirst = $i < $countFirst && $first[$i][0] <= $x; + $inSecond = $j < $countSecond && $second[$j][0] <= $x; + switch ($mode) { + case self::RGN_OR: + $inside = $inFirst || $inSecond; + break; + case self::RGN_XOR: + $inside = ($inFirst xor $inSecond); + break; + case self::RGN_DIFF: + $inside = $inFirst && !$inSecond; + break; + default: + $inside = $inSecond; + } + if (!$inside) { + continue; + } + $last = count($result) - 1; + if ($last >= 0 && $result[$last][1] + 1 == $x) { + $result[$last][1] = $boundaries[$k + 1] - 1; + } else { + $result[] = [$x, $boundaries[$k + 1] - 1]; + } + } + + return $result; + } + + /** + * Converts a polyline into polygons covering its stroke + * + * @param array> $points + * @param int $endCap PS_ENDCAP_ROUND (0x0000), PS_ENDCAP_SQUARE (0x0100) or PS_ENDCAP_FLAT (0x0200) + * @param int $join PS_JOIN_ROUND (0x0000), PS_JOIN_BEVEL (0x1000) or PS_JOIN_MITER (0x2000) + * @param int|null $startCap Cap of the start of the line (null : $endCap) + * + * @return array>> + */ + public static function getStrokePolygons(array $points, bool $closed, float $halfWidth, int $endCap, int $join, float $miterLimit, ?int $startCap = null): array + { + // Remove duplicated points + $cleaned = []; + foreach ($points as $point) { + $last = end($cleaned); + if (!$last || abs($last[0] - $point[0]) > 0.001 || abs($last[1] - $point[1]) > 0.001) { + $cleaned[] = $point; + } + } + if ($closed && count($cleaned) > 1) { + $last = end($cleaned); + if (abs($last[0] - $cleaned[0][0]) <= 0.001 && abs($last[1] - $cleaned[0][1]) <= 0.001) { + array_pop($cleaned); + } + $cleaned[] = $cleaned[0]; + } + + $count = count($cleaned); + if ($count == 0) { + return []; + } + if ($count == 1) { + return [self::getDiscPolygon($cleaned[0], $halfWidth)]; + } + + $startCap = $startCap ?? $endCap; + $polygons = []; + // Normals of each segment + $normals = []; + for ($i = 0; $i < $count - 1; ++$i) { + list($x1, $y1) = $cleaned[$i]; + list($x2, $y2) = $cleaned[$i + 1]; + $length = hypot($x2 - $x1, $y2 - $y1); + $ux = ($x2 - $x1) / $length; + $uy = ($y2 - $y1) / $length; + $normals[$i] = [-$uy * $halfWidth, $ux * $halfWidth]; + + // Square end caps extend the line by the half width + if (!$closed) { + if ($i == 0 && $startCap == 0x0100) { + $x1 -= $ux * $halfWidth; + $y1 -= $uy * $halfWidth; + } + if ($i == $count - 2 && $endCap == 0x0100) { + $x2 += $ux * $halfWidth; + $y2 += $uy * $halfWidth; + } + } + + list($nx, $ny) = $normals[$i]; + $polygons[] = [ + [$x1 + $nx, $y1 + $ny], + [$x2 + $nx, $y2 + $ny], + [$x2 - $nx, $y2 - $ny], + [$x1 - $nx, $y1 - $ny], + ]; + } + + // Round end caps + if (!$closed && $startCap == 0x0000) { + $polygons[] = self::getDiscPolygon($cleaned[0], $halfWidth); + } + if (!$closed && $endCap == 0x0000) { + $polygons[] = self::getDiscPolygon($cleaned[$count - 1], $halfWidth); + } + + // Joins between segments (for closed figures, the last segment is joined to the first one) + $lastSegment = $count - 2; + for ($i = 0; $i < ($closed ? $count - 1 : $count - 2); ++$i) { + $next = $i == $lastSegment ? 0 : $i + 1; + $polygons[] = self::getJoinPolygon($cleaned[$i + 1], $normals[$i], $normals[$next], $halfWidth, $join, $miterLimit); + } + + // All polygons must have the same orientation, so their union is filled with the nonzero rule + foreach ($polygons as $key => $polygon) { + if (self::getSignedArea($polygon) < 0) { + $polygons[$key] = array_reverse($polygon); + } + } + + return $polygons; + } + + /** + * Returns the polygon filling the outer side of the join between two segments + * + * @param array $vertex + * @param array $normalIn Normal of the incoming segment + * @param array $normalOut Normal of the outgoing segment + * + * @return array> + */ + public static function getJoinPolygon(array $vertex, array $normalIn, array $normalOut, float $halfWidth, int $join, float $miterLimit): array + { + if ($join == 0x0000) { + return self::getDiscPolygon($vertex, $halfWidth); + } + + // The outer side is the opposite of the direction of the turn + $cross = $normalIn[0] * $normalOut[1] - $normalIn[1] * $normalOut[0]; + $side = $cross > 0 ? -1 : 1; + $outerIn = [$vertex[0] + $side * $normalIn[0], $vertex[1] + $side * $normalIn[1]]; + $outerOut = [$vertex[0] + $side * $normalOut[0], $vertex[1] + $side * $normalOut[1]]; + + if ($join == 0x2000) { + // Miter : the offset lines meet at a distance of halfWidth / cos(angle / 2) + $sumX = $normalIn[0] + $normalOut[0]; + $sumY = $normalIn[1] + $normalOut[1]; + $sumSquared = $sumX * $sumX + $sumY * $sumY; + if ($sumSquared > 0) { + $ratio = 2 * $halfWidth / sqrt($sumSquared); + if ($ratio <= $miterLimit) { + $factor = 2 * $halfWidth * $halfWidth / $sumSquared; + + return [ + $vertex, + $outerIn, + [$vertex[0] + $side * $sumX * $factor, $vertex[1] + $side * $sumY * $factor], + $outerOut, + ]; + } + } + } + + // Bevel + return [$vertex, $outerIn, $outerOut]; + } + + /** + * @param array $center + * + * @return array> + */ + public static function getDiscPolygon(array $center, float $radius): array + { + $steps = (int) max(8, min(48, ceil(2 * M_PI * $radius / 3))); + $points = []; + for ($i = 0; $i < $steps; ++$i) { + $angle = 2 * M_PI * $i / $steps; + $points[] = [$center[0] + $radius * cos($angle), $center[1] + $radius * sin($angle)]; + } + + return $points; + } + + /** + * @param array> $polygon + */ + public static function getSignedArea(array $polygon): float + { + $area = 0; + $count = count($polygon); + for ($i = 0; $i < $count; ++$i) { + $next = $polygon[($i + 1) % $count]; + $area += $polygon[$i][0] * $next[1] - $next[0] * $polygon[$i][1]; + } + + return $area / 2; + } + + /** + * @param array> $points Start point followed by groups of 3 points (2 control points + end point) + * + * @return array> + */ + public static function flattenBeziers(array $points): array + { + if (empty($points)) { + return []; + } + $result = [$points[0]]; + for ($i = 1; $i + 2 < count($points); $i += 3) { + $result = array_merge($result, self::flattenBezier($points[$i - 1], $points[$i], $points[$i + 1], $points[$i + 2])); + } + + return $result; + } + + /** + * @param array $p0 + * @param array $p1 + * @param array $p2 + * @param array $p3 + * + * @return array> Points of the curve, without the start point + */ + public static function flattenBezier(array $p0, array $p1, array $p2, array $p3): array + { + $length = hypot($p1[0] - $p0[0], $p1[1] - $p0[1]) + + hypot($p2[0] - $p1[0], $p2[1] - $p1[1]) + + hypot($p3[0] - $p2[0], $p3[1] - $p2[1]); + $steps = (int) max(2, min(128, ceil($length / 3))); + + $points = []; + for ($i = 1; $i <= $steps; ++$i) { + $t = $i / $steps; + $mt = 1 - $t; + $a = $mt * $mt * $mt; + $b = 3 * $mt * $mt * $t; + $c = 3 * $mt * $t * $t; + $d = $t * $t * $t; + $points[] = [ + $a * $p0[0] + $b * $p1[0] + $c * $p2[0] + $d * $p3[0], + $a * $p0[1] + $b * $p1[1] + $c * $p2[1] + $d * $p3[1], + ]; + } + + return $points; + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/AbstractTestReader.php b/vendor/phpoffice/wmf/tests/WMF/Reader/AbstractTestReader.php new file mode 100644 index 00000000..720dd46f --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/AbstractTestReader.php @@ -0,0 +1,292 @@ +compareImages($imOutput, Imagick::METRIC_MEANSQUAREERROR); + $this->assertLessThanOrEqual($threshold, $result[1]); + } + + /** + * @return array> + */ + public static function dataProviderFilesWMF(): array + { + return [ + [ + 'burger.wmf', + ], + [ + 'chicken.wmf', + ], + [ + 'fish.wmf', + ], + [ + 'vegetable.wmf', + ], + ]; + } + + /** + * @return array> + */ + public static function dataProviderFilesWMFNotImplemented(): array + { + return [ + [ + 'test_libuemf.wmf', + ], + ]; + } + + /** + * @return array> + */ + public static function dataProviderMediaTypeWMF(): array + { + return [ + [ + 'gif', + 'image/gif', + ], + [ + 'jpg', + 'image/jpeg', + ], + [ + 'jpeg', + 'image/jpeg', + ], + [ + 'png', + 'image/png', + ], + [ + 'webp', + 'image/webp', + ], + [ + 'wbmp', + 'image/vnd.wap.wbmp', + ], + [ + 'wmf', + 'image/x-wmf', + ], + ]; + } + + /** + * @return array> + */ + public static function dataProviderFilesEMF(): array + { + return [ + [ + 'computer_mail.emf', + ], + [ + 'inkscape_shapes.emf', + ], + ]; + } + + /** + * @return array> + */ + public static function dataProviderMediaTypeEMF(): array + { + return [ + [ + 'gif', + 'image/gif', + ], + [ + 'jpg', + 'image/jpeg', + ], + [ + 'jpeg', + 'image/jpeg', + ], + [ + 'png', + 'image/png', + ], + [ + 'webp', + 'image/webp', + ], + [ + 'wbmp', + 'image/vnd.wap.wbmp', + ], + ]; + } + + /** + * Returns an EMF file (header of computer_mail.emf) with a record not implemented (EMR_ALPHABLEND) + */ + public function getContentEMFNotImplemented(): string + { + $content = file_get_contents($this->getResourceDir() . 'computer_mail.emf'); + list(, $headerSize) = unpack('V', substr($content, 4, 4)); + + return substr($content, 0, $headerSize) + . pack('V2', 0x72, 8) + . pack('V5', 0x0E, 20, 0, 16, 20); + } + + /** + * Returns a WMF file (headers of burger.wmf) with a record not implemented (META_DRAWTEXT) + */ + public function getContentWMFNotImplemented(): string + { + $content = file_get_contents($this->getResourceDir() . 'burger.wmf'); + + return substr($content, 0, 22 + 18) + . pack('Vv', 3, 0x062F) + . pack('Vv', 3, 0x0000); + } + + /** + * Returns a 2x1 DIB (bitmap info & bits) : the first pixel uses the color 0, the second one the color 1 + * + * The color table contains red & blue, or indexes in the palette of the file (DIB_PAL_COLORS) + */ + private function getDIB(int $compression, bool $hasPaletteIndexes): string + { + $colorTable = $hasPaletteIndexes ? "\x00\x00\x01\x00" : "\x00\x00\xFF\x00\xFF\x00\x00\x00"; + + return pack('VllvvVVllVV', 40, 2, 1, 1, 1, $compression, 4, 0, 0, 2, 0) . $colorTable . "\x40\0\0\0"; + } + + /** + * Returns an EMF file (header of inkscape_shapes.emf) with a EMR_STRETCHDIBITS record covering the image + * + * @param int $compression BI_RGB (0) or a compression not supported by monochrome bitmaps (BI_RLE8 : 1) + * @param int $usage DIB_RGB_COLORS (0) or DIB_PAL_COLORS (1) + */ + public function getContentEMFWithBitmap(int $compression, int $usage): string + { + $content = file_get_contents($this->getResourceDir() . 'inkscape_shapes.emf'); + list(, $headerSize) = unpack('V', substr($content, 4, 4)); + + $dib = $this->getDIB($compression, $usage == 1); + $bmiSize = strlen($dib) - 4; + $record = pack('l4', 0, 0, 2503, 1889) + // xDest, yDest, xSrc, ySrc, cxSrc, cySrc + . pack('l6', 0, 0, 0, 0, 2, 1) + // offBmi, cbBmi, offBits, cbBits, usage, SRCCOPY + . pack('V6', 80, $bmiSize, 80 + $bmiSize, 4, $usage, 0x00CC0020) + // cxDest, cyDest + . pack('l2', 2504, 1890) + . $dib; + + return substr($content, 0, $headerSize) + . pack('V2', 0x51, 8 + strlen($record)) . $record + . pack('V5', 0x0E, 20, 0, 16, 20); + } + + /** + * Colors of the rows of the 8x8 DIB of getContentEMFWithDIBitsToDevice(), from top to bottom + */ + public const DIBITS_COLORS = [0xFF0000, 0xFF0000, 0x00FF00, 0x00FF00, 0x0000FF, 0x0000FF, 0xFFFF00, 0xFFFF00]; + + /** + * Returns a 8x8 EMF file (1 logical unit = 1 pixel) drawing a 8x8 DIB with EMR_SETDIBITSTODEVICE records + * + * The rows of the DIB use the colors DIBITS_COLORS. Each record contains a band of $scansPerBand scan lines. + * + * @param bool $isTopDown If the DIB is top-down (else bottom-up) + * @param int $scansPerBand Number of scan lines of each record + * @param int $ySrc Y of the source rectangle (from the bottom of a bottom-up DIB, from the top of a top-down DIB) + * @param int $cySrc Height of the source rectangle + */ + public function getContentEMFWithDIBitsToDevice(bool $isTopDown, int $scansPerBand, int $ySrc = 0, int $cySrc = 8): string + { + $size = 8; + $records = ''; + $count = 0; + for ($startScan = 0; $startScan < $size; $startScan += $scansPerBand) { + $scans = min($scansPerBand, $size - $startScan); + $bits = ''; + for ($scan = $startScan; $scan < $startScan + $scans; ++$scan) { + // The scan line 0 is the bottom row of a bottom-up DIB + $color = self::DIBITS_COLORS[$isTopDown ? $scan : $size - 1 - $scan]; + $bits .= str_repeat(pack('CCC', $color & 0xFF, ($color >> 8) & 0xFF, $color >> 16), $size); + } + $bmi = pack('VllvvVVllVV', 40, $size, $isTopDown ? -$size : $size, 1, 24, 0, 0, 0, 0, 0, 0); + $record = pack('l4', 0, 0, $size - 1, $size - 1) + // xDest, yDest, xSrc, ySrc, cxSrc, cySrc + . pack('l6', 0, 0, 0, $ySrc, $size, $cySrc) + // offBmi, cbBmi, offBits, cbBits, usage, iStartScan, cScans + . pack('V7', 76, strlen($bmi), 76 + strlen($bmi), strlen($bits), 0, $startScan, $scans) + . $bmi . $bits; + $records .= pack('V2', 0x50, 8 + strlen($record)) . $record; + ++$count; + } + $records .= pack('V5', 0x0E, 20, 0, 16, 20); + + // Bounds, Frame (0.01 mm at 96 DPI), signature, version, bytes, records, handles, reserved, description & palette + $header = pack('l4', 0, 0, $size - 1, $size - 1) + . pack('l4', 0, 0, (int) round($size * 2540 / 96), (int) round($size * 2540 / 96)) + . pack('VVVVvvVVV', 0x464D4520, 0x10000, 88 + strlen($records), $count + 2, 1, 0, 0, 0, 0) + // Device (pixels) & Millimeters + . pack('l4', 1024, 768, 271, 203); + + return pack('V2', 0x01, 88) . $header . $records; + } + + /** + * Returns a WMF file (headers of burger.wmf) with a META_STRETCHDIB record covering the image + * + * @param int $compression BI_RGB (0) or a compression not supported by monochrome bitmaps (BI_RLE8 : 1) + * @param int $usage DIB_RGB_COLORS (0) or DIB_PAL_COLORS (1) + */ + public function getContentWMFWithBitmap(int $compression, int $usage): string + { + $content = file_get_contents($this->getResourceDir() . 'burger.wmf'); + + // The window of burger.wmf : origin (-1225, 1137), extent (2290, -2035) + $params = pack('Vv', 0x00CC0020, $usage) + // srcHeight, srcWidth, ySrc, xSrc, destHeight, destWidth, yDest, xDest + . pack('v8', 1, 2, 0, 0, -2035 & 0xFFFF, 2290, 1137, -1225 & 0xFFFF) + . $this->getDIB($compression, $usage == 1); + + return substr($content, 0, 22 + 18) + . pack('Vv', 3 + strlen($params) / 2, 0x0F43) . $params + . pack('Vv', 3, 0x0000); + } + + public function assertMimeType(string $filename, string $expectedMimeType): void + { + // Use GD + $gdInfo = getimagesize($filename); + if (is_array($gdInfo)) { + $this->assertEquals($expectedMimeType, $gdInfo['mime']); + + return; + } + + // Use Imagick + $this->assertEquals($expectedMimeType, (new Imagick($filename))->getImageMimeType()); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/DetectorTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/DetectorTest.php new file mode 100644 index 00000000..a914a034 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/DetectorTest.php @@ -0,0 +1,113 @@ +> + */ + public static function dataProviderFiles(): array + { + return [ + ['burger.wmf', Detector::TYPE_WMF], + ['chicken.wmf', Detector::TYPE_WMF], + ['fish.wmf', Detector::TYPE_WMF], + ['test_libuemf.wmf', Detector::TYPE_WMF], + ['vegetable.wmf', Detector::TYPE_WMF], + ['computer_mail.emf', Detector::TYPE_EMF], + ['inkscape_shapes.emf', Detector::TYPE_EMF], + ['libemf2svg/emf/test-001.emf', Detector::TYPE_EMF], + ['libemf2svg/emf/test-000.emf', Detector::TYPE_EMFPLUS], + ['libemf2svg/emf/test-180.emf', Detector::TYPE_EMFPLUS], + ['libemf2svg/emf-ea/EA-test-file-101.emf', Detector::TYPE_EMFPLUS], + ['computer_mail.png', Detector::TYPE_UNKNOWN], + ['files.txt', Detector::TYPE_UNKNOWN], + ]; + } + + /** + * @dataProvider dataProviderFiles + */ + public function testDetect(string $file, string $expectedType): void + { + $this->assertEquals($expectedType, Detector::detect(file_get_contents($this->getResourceDir() . $file))); + } + + /** + * @dataProvider dataProviderFiles + */ + public function testDetectFile(string $file, string $expectedType): void + { + $this->assertEquals($expectedType, Detector::detectFile($this->getResourceDir() . $file)); + } + + /** + * @dataProvider dataProviderFiles + */ + public function testIsMethods(string $file, string $expectedType): void + { + $content = file_get_contents($this->getResourceDir() . $file); + + $this->assertEquals($expectedType == Detector::TYPE_WMF, Detector::isWMF($content)); + // EMF+ files are EMF files too + $this->assertEquals(in_array($expectedType, [Detector::TYPE_EMF, Detector::TYPE_EMFPLUS]), Detector::isEMF($content)); + $this->assertEquals($expectedType == Detector::TYPE_EMFPLUS, Detector::isEMFPlus($content)); + } + + public function testDetectFileNotFound(): void + { + $this->assertEquals(Detector::TYPE_UNKNOWN, Detector::detectFile($this->getResourceDir() . 'notfound.emf')); + } + + /** + * @return array> + */ + public static function dataProviderInvalidContents(): array + { + return [ + [''], + ['WMF'], + [str_repeat("\0", 128)], + // Placeable key without META_HEADER + [pack('V', 0x9AC6CDD7) . str_repeat("\0", 60)], + // EMF header without the signature + [pack('V2', 1, 88) . str_repeat("\0", 80)], + ]; + } + + /** + * @dataProvider dataProviderInvalidContents + */ + public function testDetectInvalidContent(string $content): void + { + $this->assertEquals(Detector::TYPE_UNKNOWN, Detector::detect($content)); + } + + /** + * A WMF file without the placeable header is detected as WMF, but not as placeable WMF + */ + public function testStandardWMF(): void + { + $content = substr(file_get_contents($this->getResourceDir() . 'burger.wmf'), 22); + + $this->assertEquals(Detector::TYPE_WMF, Detector::detect($content)); + $this->assertTrue(Detector::isWMF($content)); + $this->assertFalse(Detector::isPlaceableWMF($content)); + } + + /** + * A EMF file with a truncated EMF+ header is a EMF file + */ + public function testTruncatedEMFPlus(): void + { + $content = file_get_contents($this->getResourceDir() . 'libemf2svg/emf/test-000.emf'); + list(, $headerSize) = unpack('V', substr($content, 4, 4)); + + $this->assertEquals(Detector::TYPE_EMF, Detector::detect(substr($content, 0, $headerSize + 10))); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/GDTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/GDTest.php new file mode 100644 index 00000000..a534783a --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/GDTest.php @@ -0,0 +1,328 @@ +assertTrue($reader->load($this->getResourceDir() . $file)); + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testLoadFromString(string $file): void + { + $reader = new GD(); + $this->assertTrue($reader->loadFromString(file_get_contents($this->getResourceDir() . $file))); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testLoadWMF(string $file): void + { + $reader = new GD(); + $this->assertFalse($reader->load($this->getResourceDir() . $file)); + $this->assertFalse($reader->isEMF()); + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testGetResource(string $file): void + { + $reader = new GD(); + $reader->load($this->getResourceDir() . $file); + if (\PHP_VERSION_ID < 80000) { + $this->assertIsResource($reader->getResource()); + } else { + /* @phpstan-ignore-next-line */ + $this->assertInstanceOf(GdImage::class, $reader->getResource()); + } + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testOutput(string $file): void + { + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + $similarFile = $this->getResourceDir() . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $reader = new GD(); + $reader->load($this->getResourceDir() . $file); + $this->assertTrue($reader->save($outputFile, 'png')); + + $this->assertImageCompare($outputFile, $similarFile, 0.02); + + @unlink($outputFile); + } + + /** + * @dataProvider dataProviderMediaTypeEMF + */ + public function testSave(string $extension, string $mediatype): void + { + $outputFile = $this->getResourceDir() . 'output_save.' . $extension; + + $reader = new GD(); + $reader->load($this->getResourceDir() . 'computer_mail.emf'); + $reader->save($outputFile, $extension); + $this->assertMimeType($outputFile, $mediatype); + + @unlink($outputFile); + } + + public function testSaveEMF(): void + { + $file = $this->getResourceDir() . 'computer_mail.emf'; + $outputFile = $this->getResourceDir() . 'output_save.emf'; + + $reader = new GD(); + $reader->load($file); + $this->assertTrue($reader->save($outputFile, 'emf')); + $this->assertFileEquals($file, $outputFile); + + @unlink($outputFile); + } + + public function testSaveWithException(): void + { + $file = 'computer_mail.emf'; + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $this->expectException(WMFException::class); + + $reader = new GD(); + $reader->load($this->getResourceDir() . $file); + $reader->save($outputFile, 'notanextension'); + } + + public function testSaveWithoutException(): void + { + $file = 'computer_mail.emf'; + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $reader = new GD(); + $reader->enableExceptions(false); + $reader->load($this->getResourceDir() . $file); + $this->assertFalse($reader->save($outputFile, 'notanextension')); + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testIsEMF(string $file): void + { + $reader = new GD(); + $reader->load($this->getResourceDir() . $file); + $this->assertTrue($reader->isEMF()); + } + + public function testMediaType(): void + { + $reader = new GD(); + $this->assertEquals('image/emf', $reader->getMediaType()); + } + + public function testNotImplementedWithExceptions(): void + { + $this->expectException(WMFException::class); + $this->expectExceptionMessage('Reader : Function not implemented : 0x0072'); + + $reader = new GD(); + $reader->loadFromString($this->getContentEMFNotImplemented()); + } + + public function testNotImplementedWithoutExceptions(): void + { + $reader = new GD(); + $reader->enableExceptions(false); + $this->assertFalse($reader->loadFromString($this->getContentEMFNotImplemented())); + } + + /** + * @return array> + */ + public static function dataProviderBitmapColors(): array + { + return [ + // DIB_RGB_COLORS : the colors of the color table (red & blue) + [0, 0xFF0000, 0x0000FF], + // DIB_PAL_COLORS : the palette of the file is not known, a gray scale is used + [1, 0x000000, 0xFFFFFF], + ]; + } + + /** + * @dataProvider dataProviderBitmapColors + */ + public function testBitmapColors(int $usage, int $leftColor, int $rightColor): void + { + $reader = new GD(); + $this->assertTrue($reader->loadFromString($this->getContentEMFWithBitmap(0, $usage))); + $image = $reader->getResource(); + + $this->assertEquals($leftColor, imagecolorat($image, (int) (imagesx($image) / 4), (int) (imagesy($image) / 2)) & 0xFFFFFF); + $this->assertEquals($rightColor, imagecolorat($image, (int) (imagesx($image) * 3 / 4), (int) (imagesy($image) / 2)) & 0xFFFFFF); + } + + public function testBitmapNotSupportedWithExceptions(): void + { + $this->expectException(WMFException::class); + $this->expectExceptionMessage('Reader : Bitmap not supported : 0x0051'); + + $reader = new GD(); + $reader->loadFromString($this->getContentEMFWithBitmap(1, 0)); + } + + public function testBitmapNotSupportedWithoutExceptions(): void + { + $reader = new GD(); + $reader->enableExceptions(false); + $this->assertFalse($reader->loadFromString($this->getContentEMFWithBitmap(1, 0))); + } + + /** + * EMF file of PhpSpreadsheet issue #274 : a bitmap drawn by EMR_SETDIBITSTODEVICE records of 1 scan line, + * over a black background (EMR_BITBLT with PATCOPY) + * + * @see https://github.com/PHPOffice/PhpSpreadsheet/issues/274 + */ + public function testSetDIBitsToDeviceByScanLine(): void + { + $file = $this->getResourceDir() . 'phpspreadsheet/issue274.emf'; + $outputFile = $this->getResourceDir() . 'phpspreadsheet/output_issue274.png'; + + $reader = new GD(); + $this->assertTrue($reader->load($file)); + $image = $reader->getResource(); + $this->assertEquals(131, imagesx($image)); + $this->assertEquals(131, imagesy($image)); + // The black background is covered by the bitmap + $this->assertNotEquals(0x000000, imagecolorat($image, 64, 64) & 0xFFFFFF); + + $this->assertTrue($reader->save($outputFile, 'png')); + $this->assertImageCompare($outputFile, $this->getResourceDir() . 'phpspreadsheet/issue274.png', 0.02); + @unlink($outputFile); + } + + /** + * @return array}> + */ + public static function dataProviderDIBitsToDevice(): array + { + $colors = self::DIBITS_COLORS; + // The lower half of the DIB, drawn at the top of the image (the rest stays white) + $lowerHalf = [0x0000FF, 0x0000FF, 0xFFFF00, 0xFFFF00, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF]; + + return [ + 'bottom-up, whole DIB' => [false, 8, 0, 8, $colors], + 'bottom-up, bands of 1 scan line' => [false, 1, 0, 8, $colors], + 'bottom-up, bands of 3 scan lines' => [false, 3, 0, 8, $colors], + 'top-down, whole DIB' => [true, 8, 0, 8, $colors], + 'top-down, bands of 3 scan lines' => [true, 3, 0, 8, $colors], + // The origin of a bottom-up DIB is its lower-left corner + 'bottom-up, lower half' => [false, 8, 0, 4, $lowerHalf], + 'bottom-up, lower half, bands of 3 scan lines' => [false, 3, 0, 4, $lowerHalf], + // The origin of a top-down DIB is its upper-left corner + 'top-down, lower half' => [true, 8, 4, 4, $lowerHalf], + 'top-down, lower half, bands of 3 scan lines' => [true, 3, 4, 4, $lowerHalf], + ]; + } + + /** + * @dataProvider dataProviderDIBitsToDevice + * + * @param array $expectedColors Expected colors of the rows of the image, from top to bottom + */ + public function testSetDIBitsToDevice(bool $isTopDown, int $scansPerBand, int $ySrc, int $cySrc, array $expectedColors): void + { + $reader = new GD(); + $this->assertTrue($reader->loadFromString($this->getContentEMFWithDIBitsToDevice($isTopDown, $scansPerBand, $ySrc, $cySrc))); + $image = $reader->getResource(); + + $this->assertEquals(8, imagesx($image)); + $this->assertEquals(8, imagesy($image)); + $colors = []; + for ($y = 0; $y < 8; ++$y) { + $colors[] = imagecolorat($image, 4, $y) & 0xFFFFFF; + } + $this->assertEquals($expectedColors, $colors); + } + + public function testEMFPlus(): void + { + $file = $this->getResourceDir() . 'libemf2svg/emf/test-000.emf'; + + $reader = new GD(); + $this->assertTrue($reader->isEMFPlusEnabled()); + $this->assertFalse($reader->isEMFPlusRendered()); + $this->assertTrue($reader->load($file)); + $this->assertTrue($reader->isEMFPlusRendered()); + + // EMF+ disabled : only the EMF records are drawn + $this->assertInstanceOf(GD::class, $reader->setEMFPlusEnabled(false)); + $this->assertFalse($reader->isEMFPlusEnabled()); + $this->assertTrue($reader->load($file)); + $this->assertFalse($reader->isEMFPlusRendered()); + + // EMF files have no EMF+ records + $reader->setEMFPlusEnabled(true); + $this->assertTrue($reader->load($this->getResourceDir() . 'computer_mail.emf')); + $this->assertFalse($reader->isEMFPlusRendered()); + } + + /** + * If the EMF+ records can not be drawn, the EMF records are drawn + */ + public function testEMFPlusFallback(): void + { + $content = (string) file_get_contents($this->getResourceDir() . 'libemf2svg/emf/test-000.emf'); + // The type of the first EMF+ record after the EMF+ header is replaced by an unknown type + list(, $headerSize) = unpack('V', substr($content, 4, 4)); + list(, $commentSize) = unpack('V', substr($content, $headerSize + 4, 4)); + $content = substr_replace($content, pack('v', 0x40FF), $headerSize + $commentSize + 16, 2); + + $reader = new GD(); + $this->assertTrue($reader->loadFromString($content)); + $this->assertFalse($reader->isEMFPlusRendered()); + } + + public function testBackgroundColor(): void + { + $file = $this->getResourceDir() . 'computer_mail.emf'; + $outputFile = $this->getResourceDir() . 'output_background.jpg'; + + $reader = new GD(); + $this->assertEquals([255, 255, 255], $reader->getBackgroundColor()); + + // Transparent background + $this->assertInstanceOf(GD::class, $reader->setBackgroundColor(null)); + $this->assertNull($reader->getBackgroundColor()); + $reader->load($file); + $this->assertEquals(127, (imagecolorat($reader->getResource(), 0, 0) >> 24) & 0x7F); + // Formats without alpha channel are saved on a white background + $this->assertTrue($reader->save($outputFile, 'jpg')); + $this->assertGreaterThan(0xF0, imagecolorat(imagecreatefromjpeg($outputFile), 0, 0) & 0xFF); + @unlink($outputFile); + + // Colored background + $reader->setBackgroundColor([0, 0, 255]); + $reader->load($file); + $this->assertEquals(0x0000FF, imagecolorat($reader->getResource(), 0, 0)); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/ImagickTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/ImagickTest.php new file mode 100644 index 00000000..1aecfea1 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/ImagickTest.php @@ -0,0 +1,78 @@ +markTestSkipped('Imagick does not support EMF files (only available on Windows)'); + } + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testLoad(string $file): void + { + $reader = new ImagickReader(); + $this->assertTrue($reader->load($this->getResourceDir() . $file)); + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testLoadFromString(string $file): void + { + $reader = new ImagickReader(); + $this->assertTrue($reader->loadFromString(file_get_contents($this->getResourceDir() . $file))); + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testGetResource(string $file): void + { + $reader = new ImagickReader(); + $reader->load($this->getResourceDir() . $file); + $this->assertInstanceOf(ImagickBase::class, $reader->getResource()); + } + + /** + * @dataProvider dataProviderMediaTypeEMF + */ + public function testSave(string $extension, string $mediatype): void + { + $outputFile = $this->getResourceDir() . 'output_save.' . $extension; + + $reader = new ImagickReader(); + $reader->load($this->getResourceDir() . 'computer_mail.emf'); + $reader->save($outputFile, $extension); + $this->assertMimeType($outputFile, $mediatype); + + @unlink($outputFile); + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testIsEMF(string $file): void + { + $reader = new ImagickReader(); + $reader->load($this->getResourceDir() . $file); + $this->assertTrue($reader->isEMF()); + } + + public function testMediaType(): void + { + $reader = new ImagickReader(); + $this->assertEquals('image/emf', $reader->getMediaType()); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/LibEMF2SVGTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/LibEMF2SVGTest.php new file mode 100644 index 00000000..9be60de1 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/LibEMF2SVGTest.php @@ -0,0 +1,96 @@ +> + */ + public static function dataProviderFiles(): array + { + return self::getFiles(['emf', 'emf-ea']); + } + + /** + * @return array> + */ + public static function dataProviderFilesCorrupted(): array + { + return self::getFiles(['emf-corrupted']); + } + + /** + * @param array $directories + * + * @return array> + */ + private static function getFiles(array $directories): array + { + $files = []; + foreach ($directories as $directory) { + foreach (glob(dirname(__DIR__, 3) . '/resources/libemf2svg/' . $directory . '/*.emf') ?: [] as $file) { + $files[$directory . '/' . basename($file)] = [$file]; + } + } + + return $files; + } + + /** + * @dataProvider dataProviderFiles + */ + public function testLoadAndSave(string $file): void + { + $outputFile = $this->getResourceDir() . 'output_libemf2svg_' . basename($file, '.emf') . '.png'; + + $reader = new GD(); + $this->assertTrue($reader->load($file)); + $this->assertTrue($reader->isEMF()); + // EMF+ files are drawn with their EMF+ records + $this->assertEquals(Detector::detectFile($file) == Detector::TYPE_EMFPLUS, $reader->isEMFPlusRendered()); + $this->assertTrue($reader->save($outputFile, 'png')); + $this->assertMimeType($outputFile, 'image/png'); + + @unlink($outputFile); + } + + /** + * Corrupted files must not raise PHP errors + * + * @dataProvider dataProviderFilesCorrupted + */ + public function testLoadCorruptedWithExceptions(string $file): void + { + $reader = new GD(); + try { + $this->assertIsBool($reader->load($file)); + } catch (WMFException $e) { + $this->assertStringStartsWith('Reader : ', $e->getMessage()); + } + } + + /** + * @dataProvider dataProviderFilesCorrupted + */ + public function testLoadCorruptedWithoutExceptions(string $file): void + { + $reader = new GD(); + $reader->enableExceptions(false); + $this->assertIsBool($reader->load($file)); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/MagicGDTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/MagicGDTest.php new file mode 100644 index 00000000..cf133fab --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/MagicGDTest.php @@ -0,0 +1,107 @@ +setBackends([ + GD::class, + Imagick::class, + ]); + + return $reader; + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testLoad(string $file): void + { + $reader = $this->getReader(); + $this->assertTrue($reader->load($this->getResourceDir() . $file)); + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testLoadFromString(string $file): void + { + $reader = $this->getReader(); + $this->assertTrue($reader->loadFromString(file_get_contents($this->getResourceDir() . $file))); + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testGetResource(string $file): void + { + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . $file); + if (\PHP_VERSION_ID < 80000) { + $this->assertIsResource($reader->getResource()); + } else { + /* @phpstan-ignore-next-line */ + $this->assertInstanceOf(GdImage::class, $reader->getResource()); + } + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testOutput(string $file): void + { + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + $similarFile = $this->getResourceDir() . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . $file); + $reader->save($outputFile, 'png'); + + $this->assertImageCompare($outputFile, $similarFile, 0.02); + + @unlink($outputFile); + } + + /** + * @dataProvider dataProviderMediaTypeEMF + */ + public function testSave(string $extension, string $mediatype): void + { + $outputFile = $this->getResourceDir() . 'output_save.' . $extension; + + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . 'computer_mail.emf'); + $reader->save($outputFile, $extension); + $this->assertMimeType($outputFile, $mediatype); + + @unlink($outputFile); + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testIsEMF(string $file): void + { + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . $file); + $this->assertTrue($reader->isEMF()); + } + + public function testMediaType(): void + { + $reader = $this->getReader(); + $this->assertEquals('image/emf', $reader->getMediaType()); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/MagicTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/MagicTest.php new file mode 100644 index 00000000..ddf9bebc --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/EMF/MagicTest.php @@ -0,0 +1,91 @@ +assertEquals([ + Imagick::class, + GD::class, + ], $reader->getBackends()); + } + + public function testSetBackends(): void + { + $reader = new Magic(); + $this->assertInstanceOf(Magic::class, $reader->setBackends([ + GD::class, + Imagick::class, + 'NotABackend', + ])); + $this->assertEquals([ + GD::class, + Imagick::class, + ], $reader->getBackends()); + } + + /** + * @dataProvider dataProviderFilesEMF + */ + public function testLoadWithDefaultBackends(string $file): void + { + $reader = new Magic(); + $this->assertTrue($reader->load($this->getResourceDir() . $file)); + $this->assertTrue($reader->isEMF()); + + // Imagick is used only if it supports EMF, else GD is used + if (extension_loaded('imagick') && in_array('EMF', ImagickBase::queryFormats())) { + $this->assertInstanceOf(ImagickBase::class, $reader->getResource()); + } elseif (\PHP_VERSION_ID >= 80000) { + /* @phpstan-ignore-next-line */ + $this->assertInstanceOf(GdImage::class, $reader->getResource()); + } + } + + public function testIsSupported(): void + { + $this->assertTrue((new GD())->isSupported()); + $this->assertTrue((new Magic())->isSupported()); + + $reader = new Magic(); + $reader->setBackends([]); + $this->assertFalse($reader->isSupported()); + } + + /** + * A backend not supported is skipped + */ + public function testBackendNotSupported(): void + { + $unsupported = new class extends Imagick { + public function isSupported(): bool + { + return false; + } + }; + + $reader = new Magic(); + $reader->setBackends([ + get_class($unsupported), + GD::class, + ]); + $this->assertTrue($reader->load($this->getResourceDir() . 'computer_mail.emf')); + $this->assertTrue($reader->isEMF()); + if (\PHP_VERSION_ID >= 80000) { + /* @phpstan-ignore-next-line */ + $this->assertInstanceOf(GdImage::class, $reader->getResource()); + } + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/EMFPlus/BufferTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/EMFPlus/BufferTest.php new file mode 100644 index 00000000..817a131b --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/EMFPlus/BufferTest.php @@ -0,0 +1,72 @@ +assertEquals(0xAB, $buffer->readUInt8()); + $this->assertEquals(0xFFFF, $buffer->readUInt16()); + $this->assertEquals(-1, $buffer->readInt16()); + $this->assertEquals(0x1234, $buffer->readUInt16()); + $this->assertEquals(-2, $buffer->readInt32()); + $this->assertEquals(1.5, $buffer->readFloat()); + $this->assertEquals(0, $buffer->getRemaining()); + } + + public function testColor(): void + { + // ARGB : 0x80112233 + $buffer = new Buffer(pack('V', 0x80112233)); + + $this->assertEquals([0x11, 0x22, 0x33, 0x80], $buffer->readColor()); + } + + public function testRects(): void + { + $buffer = new Buffer(pack('v4', 1, 2, 3, 0xFFFF) . pack('g4', 1.5, 2.5, 3.5, 4.5)); + + $this->assertEquals([1, 2, 3, -1], $buffer->readRect(true)); + $this->assertEquals([1.5, 2.5, 3.5, 4.5], $buffer->readRect()); + } + + public function testPoints(): void + { + $this->assertEquals([[1.5, -2.5]], (new Buffer(pack('g2', 1.5, -2.5)))->readPoints(1)); + $this->assertEquals([[1, -2]], (new Buffer(pack('v2', 1, 0xFFFE)))->readPoints(1, true)); + } + + public function testRelativePoints(): void + { + // EmfPlusInteger7 : 10 & -3 (0x7D), then EmfPlusInteger15 (big-endian) : 1000 (0x83E8) & -1000 (0xFC18) + $buffer = new Buffer("\x0A\x7D\x83\xE8\xFC\x18"); + + $this->assertEquals([[10, -3], [1010, -1003]], $buffer->readPoints(2, false, true)); + } + + public function testAlign(): void + { + $buffer = new Buffer(str_repeat("\0", 8)); + $buffer->readUInt8(); + $buffer->align(); + + $this->assertEquals(4, $buffer->getPosition()); + } + + public function testTruncated(): void + { + $this->expectException(WMFException::class); + $this->expectExceptionMessage('Reader : Invalid file : truncated EMF+ data'); + + (new Buffer("\0\0"))->readUInt32(); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/EMFPlus/ObjectReaderTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/EMFPlus/ObjectReaderTest.php new file mode 100644 index 00000000..7e101380 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/EMFPlus/ObjectReaderTest.php @@ -0,0 +1,213 @@ + + */ + private function read(int $type, string $data): array + { + return (new ObjectReader())->read($type, $data); + } + + private function getSolidBrush(int $argb): string + { + return pack('V3', self::VERSION, ObjectReader::BRUSH_SOLID, $argb); + } + + private function getPath(): string + { + // A closed square : start, line, line, line & close + return pack('V2v2', self::VERSION, 4, 0, 0) + . pack('g8', 0, 0, 10, 0, 10, 10, 0, 10) + . pack('C4', 0, 1, 1, 0x81); + } + + public function testSolidBrush(): void + { + $this->assertEquals( + ['type' => 'brush', 'style' => 0, 'color' => [0x11, 0x22, 0x33, 0x80]], + $this->read(ObjectReader::OBJECT_BRUSH, $this->getSolidBrush(0x80112233)) + ); + } + + public function testLinearGradientBrush(): void + { + // From black (x = 0) to white (x = 10), tiled + $data = pack('V4', self::VERSION, ObjectReader::BRUSH_LINEAR_GRADIENT, 0, 0) + . pack('g4', 0, 0, 10, 10) + . pack('V4', 0xFF000000, 0xFFFFFFFF, 0, 0); + $brush = $this->read(ObjectReader::OBJECT_BRUSH, $data); + + $this->assertEquals([0, 0, 0, 255], $brush['shader'](0, 5)); + $this->assertEquals([128, 128, 128, 255], $brush['shader'](5, 5)); + // Tiled + $this->assertEquals([128, 128, 128, 255], $brush['shader'](15, 5)); + } + + public function testPathGradientBrushSurroundingColors(): void + { + // Square from (0, 0) to (10, 10), white in the center : red on the top edge, blue on the bottom edge + $data = pack('V3', self::VERSION, ObjectReader::BRUSH_PATH_GRADIENT, 0) . pack('l', 0) + . pack('V', 0xFFFFFFFF) . pack('g2', 5, 5) + . pack('V5', 4, 0xFFFF0000, 0xFFFF0000, 0xFF0000FF, 0xFF0000FF) + . pack('V', 4) . pack('g8', 0, 0, 10, 0, 10, 10, 0, 10); + $brush = $this->read(ObjectReader::OBJECT_BRUSH, $data); + + $top = $brush['shader'](5, 0.1); + $bottom = $brush['shader'](5, 9.9); + $this->assertGreaterThan(200, $top[0]); + $this->assertLessThan(50, $top[2]); + $this->assertLessThan(50, $bottom[0]); + $this->assertGreaterThan(200, $bottom[2]); + $this->assertEquals([255, 255, 255, 255], $brush['shader'](5, 5)); + } + + public function testHatchBrush(): void + { + // HatchStyleHorizontal : red lines on white + $data = pack('V5', self::VERSION, ObjectReader::BRUSH_HATCH, 0, 0xFFFF0000, 0xFFFFFFFF); + $brush = $this->read(ObjectReader::OBJECT_BRUSH, $data); + + $this->assertEquals('device', $brush['space']); + $this->assertEquals([255, 0, 0, 255], $brush['shader'](3, 8)); + $this->assertEquals([255, 255, 255, 255], $brush['shader'](3, 9)); + } + + public function testPen(): void + { + // Start cap round, end cap arrow anchor, join bevel, dashes + $data = pack('V4', self::VERSION, 0, 0x0002 | 0x0004 | 0x0008 | 0x0020, 0) . pack('g', 2.0) + . pack('l4', 2, 0x14, 1, 1) + . $this->getSolidBrush(0xFF0000FF); + $pen = $this->read(ObjectReader::OBJECT_PEN, $data); + + $this->assertEquals('pen', $pen['type']); + $this->assertEquals(2.0, $pen['width']); + $this->assertEquals(0x0000, $pen['startCap']); + $this->assertCount(3, $pen['endCapShape']); + $this->assertEquals(0x00011000, $pen['style']); + $this->assertEquals([3, 1], $pen['dashes']); + $this->assertEquals([0, 0, 255, 255], $pen['color']); + } + + public function testPenCompound(): void + { + // Compound line : two lines + $data = pack('V4', self::VERSION, 0, 0x0400, 0) . pack('g', 4.0) + . pack('V', 4) . pack('g4', 0, 0.25, 0.75, 1) + . $this->getSolidBrush(0xFF000000); + $pen = $this->read(ObjectReader::OBJECT_PEN, $data); + + $this->assertEquals([0, 0.25, 0.75, 1], $pen['compound']); + + // A single line on the whole width is a simple line + $data = pack('V4', self::VERSION, 0, 0x0400, 0) . pack('g', 4.0) + . pack('V', 2) . pack('g2', 0, 1) + . $this->getSolidBrush(0xFF000000); + $this->assertArrayNotHasKey('compound', $this->read(ObjectReader::OBJECT_PEN, $data)); + } + + public function testPenWithArrowCap(): void + { + // Custom end cap : adjustable arrow (width 3, height 4, middle inset 1) + $cap = pack('V2', self::VERSION, 1) . pack('g3', 3, 4, 1) . str_repeat("\0", 40); + $data = pack('V3', self::VERSION, 0, 0x1000) . pack('V', 0) . pack('g', 1.0) + . pack('V', strlen($cap)) . $cap + . $this->getSolidBrush(0xFF000000); + $pen = $this->read(ObjectReader::OBJECT_PEN, $data); + + $this->assertEquals([[0, 0], [1.5, -4], [0, -3], [-1.5, -4]], $pen['endCapShape']); + } + + public function testPath(): void + { + $path = $this->read(ObjectReader::OBJECT_PATH, $this->getPath()); + + $this->assertEquals([ + ['points' => [[0, 0], [10, 0], [10, 10], [0, 10]], 'types' => [0, 1, 1, 1], 'closed' => true], + ], $path['figures']); + } + + public function testRegion(): void + { + // Union of a rectangle & a path + $path = $this->getPath(); + $data = pack('V3', self::VERSION, 2, ObjectReader::REGION_UNION) + . pack('V', ObjectReader::REGION_RECT) . pack('g4', 0, 0, 5, 5) + . pack('V2', ObjectReader::REGION_PATH, strlen($path)) . $path; + $region = $this->read(ObjectReader::OBJECT_REGION, $data); + + $this->assertEquals(ObjectReader::REGION_UNION, $region['node']['type']); + $this->assertEquals([0, 0, 5, 5], $region['node']['left']['rect']); + $this->assertCount(1, $region['node']['right']['path']['figures']); + } + + public function testImageARGB(): void + { + // 2x1 bitmap : opaque red, half transparent blue + $data = pack('V2l3V2', self::VERSION, 1, 2, 1, 8, 0x0026200A, 0) . "\x00\x00\xFF\xFF\xFF\x00\x00\x80"; + $image = $this->read(ObjectReader::OBJECT_IMAGE, $data); + + $this->assertFalse($image['isMetafile']); + $this->assertEquals(0xFF0000, $image['bitmap']['pixels'][0][0]); + $this->assertEquals(0x0000FF | (63 << 24), $image['bitmap']['pixels'][0][1]); + } + + public function testImageIndexed(): void + { + // 2x1 bitmap, 8bpp with a palette (green, blue) + $data = pack('V2l3V2', self::VERSION, 1, 2, 1, 4, 0x00030803, 0) + . pack('V4', 0, 2, 0xFF00FF00, 0xFF0000FF) + . "\x01\x00\x00\x00"; + $image = $this->read(ObjectReader::OBJECT_IMAGE, $data); + + $this->assertEquals([[0x0000FF, 0x00FF00]], $image['bitmap']['pixels']); + } + + public function testImageMetafile(): void + { + // A placeable WMF file, rendered with the WMF reader + $wmf = (string) file_get_contents(dirname(__DIR__, 3) . '/resources/burger.wmf'); + $data = pack('V4', self::VERSION, 2, 2, strlen($wmf) - 22) . substr($wmf, 0, 22) . "\0\0" . substr($wmf, 22); + $image = $this->read(ObjectReader::OBJECT_IMAGE, $data); + + $this->assertTrue($image['isMetafile']); + $this->assertEquals(165, $image['bitmap']['width']); + $this->assertEquals(147, $image['bitmap']['height']); + } + + public function testFont(): void + { + // 12 points, bold & italic + $data = pack('V', self::VERSION) . pack('g', 12) . pack('V', 3) . pack('l', 3) . pack('V2', 0, 5) . "A\0r\0i\0a\0l\0"; + $font = $this->read(ObjectReader::OBJECT_FONT, $data); + + $this->assertEquals(12.0, $font['emSize']); + $this->assertEquals(3, $font['unit']); + $this->assertEquals(700, $font['weight']); + $this->assertTrue($font['italic']); + $this->assertEquals('Arial', $font['face']); + } + + public function testObjectNotImplemented(): void + { + $this->expectException(WMFException::class); + $this->expectExceptionMessage('Reader : EMF+ object not implemented : 10'); + + $this->read(10, ''); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/EMFPlus/PlayerTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/EMFPlus/PlayerTest.php new file mode 100644 index 00000000..4c7b5f38 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/EMFPlus/PlayerTest.php @@ -0,0 +1,242 @@ +record(Player::EMFPLUS_HEADER, 1, pack('V4', self::VERSION, 1, 96, 96)); + } + + /** + * Fills a rectangle with a solid color + */ + private function fillRect(float $x, float $y, float $width, float $height, int $argb = self::RED): string + { + return $this->record(Player::EMFPLUS_FILL_RECTS, 0x8000, pack('V2', $argb, 1) . pack('g4', $x, $y, $width, $height)); + } + + /** + * Plays records on a renderer of 20x20 pixels, and returns the image + * + * @phpstan-ignore-next-line + * + * @return GdImage|resource + */ + private function play(string $records) + { + $renderer = new Renderer(20, 20); + (new Player($renderer))->play($this->header() . $records); + + return $renderer->render(); + } + + /** + * @phpstan-ignore-next-line + * + * @param GdImage|resource $image + */ + private function assertColorAt($image, int $x, int $y, int $expected): void + { + $this->assertEquals(sprintf('%06X', $expected), sprintf('%06X', imagecolorat($image, $x, $y) & 0xFFFFFF), sprintf('Color at (%d, %d)', $x, $y)); + } + + public function testFillRects(): void + { + $image = $this->play($this->fillRect(5, 5, 10, 10)); + + $this->assertColorAt($image, 10, 10, 0xFF0000); + $this->assertColorAt($image, 2, 2, 0xFFFFFF); + } + + public function testAlpha(): void + { + // Half transparent red on white (the alpha channel of GD has 7 bits) + $image = $this->play($this->fillRect(0, 0, 20, 20, 0x80FF0000)); + $color = imagecolorat($image, 10, 10); + + $this->assertEquals(0xFF, ($color >> 16) & 0xFF); + $this->assertEqualsWithDelta(0x7F, ($color >> 8) & 0xFF, 2); + $this->assertEqualsWithDelta(0x7F, $color & 0xFF, 2); + } + + public function testWorldTransform(): void + { + $image = $this->play( + $this->record(Player::EMFPLUS_SET_WORLD_TRANSFORM, 0, pack('g6', 2, 0, 0, 2, 0, 0)) + . $this->fillRect(5, 5, 5, 5) + ); + + $this->assertColorAt($image, 15, 15, 0xFF0000); + $this->assertColorAt($image, 8, 8, 0xFFFFFF); + } + + public function testPageTransform(): void + { + // UnitInch with a scale of 1/96 : 1 unit = 1 pixel at 96 DPI + $image = $this->play( + $this->record(Player::EMFPLUS_SET_PAGE_TRANSFORM, 4, pack('g', 1 / 96)) + . $this->fillRect(10, 10, 10, 10) + ); + + $this->assertColorAt($image, 15, 15, 0xFF0000); + $this->assertColorAt($image, 5, 5, 0xFFFFFF); + } + + public function testSaveRestore(): void + { + $image = $this->play( + $this->record(Player::EMFPLUS_SAVE, 0, pack('V', 1)) + . $this->record(Player::EMFPLUS_SET_WORLD_TRANSFORM, 0, pack('g6', 1, 0, 0, 1, 10, 10)) + . $this->record(Player::EMFPLUS_RESTORE, 0, pack('V', 1)) + . $this->fillRect(0, 0, 5, 5) + ); + + $this->assertColorAt($image, 2, 2, 0xFF0000); + $this->assertColorAt($image, 12, 12, 0xFFFFFF); + } + + public function testClipRect(): void + { + // Intersect (1) : only the left half is drawn + $image = $this->play( + $this->record(Player::EMFPLUS_SET_CLIP_RECT, 0x0100, pack('g4', 0, 0, 10, 20)) + . $this->fillRect(0, 0, 20, 20) + . $this->record(Player::EMFPLUS_RESET_CLIP, 0) + . $this->fillRect(0, 18, 20, 2, 0xFF0000FF) + ); + + $this->assertColorAt($image, 5, 10, 0xFF0000); + $this->assertColorAt($image, 15, 10, 0xFFFFFF); + $this->assertColorAt($image, 15, 19, 0x0000FF); + } + + public function testFillPath(): void + { + // Path object (id 1) : triangle above the diagonal + $path = pack('V2v2', self::VERSION, 3, 0, 0) . pack('g6', 0, 0, 20, 0, 20, 20) . pack('C3x', 0, 1, 0x81); + $image = $this->play( + $this->record(Player::EMFPLUS_OBJECT, 0x0301, $path) + . $this->record(Player::EMFPLUS_FILL_PATH, 0x8001, pack('V', 0xFF00FF00)) + ); + + $this->assertColorAt($image, 17, 3, 0x00FF00); + $this->assertColorAt($image, 3, 17, 0xFFFFFF); + } + + public function testDrawLines(): void + { + // Pen object (id 0) : black, 2 pixels wide + $pen = pack('V4', self::VERSION, 0, 0, 2) . pack('g', 2) . pack('V3', self::VERSION, 0, 0xFF000000); + $image = $this->play( + $this->record(Player::EMFPLUS_OBJECT, 0x0200, $pen) + . $this->record(Player::EMFPLUS_DRAW_LINES, 0x0000, pack('V', 2) . pack('g4', 0, 10, 20, 10)) + ); + + $this->assertColorAt($image, 10, 10, 0x000000); + $this->assertColorAt($image, 10, 3, 0xFFFFFF); + } + + public function testFillEllipse(): void + { + $image = $this->play($this->record(Player::EMFPLUS_FILL_ELLIPSE, 0x8000, pack('V', self::RED) . pack('g4', 0, 0, 20, 20))); + + $this->assertColorAt($image, 10, 10, 0xFF0000); + $this->assertColorAt($image, 1, 1, 0xFFFFFF); + } + + public function testGetDC(): void + { + $player = new Player(new Renderer(20, 20)); + + $this->assertTrue($player->play($this->header() . $this->record(Player::EMFPLUS_GET_DC, 0))); + $this->assertFalse($player->play($this->record(Player::EMFPLUS_GET_DC, 0) . $this->fillRect(0, 0, 1, 1))); + } + + public function testRecordNotImplemented(): void + { + $this->expectException(WMFException::class); + $this->expectExceptionMessage('Reader : EMF+ record not implemented : 0x40ff'); + + $this->play($this->record(0x40FF, 0)); + } + + public function testInvalidRecordSize(): void + { + $this->expectException(WMFException::class); + + $this->play(pack('v2V2', Player::EMFPLUS_CLEAR, 0, 4, 0)); + } + + /** + * Returns the number of rows containing dark pixels + * + * @phpstan-ignore-next-line + * + * @param GdImage|resource $image + */ + private function countDarkRows($image): int + { + $rows = 0; + for ($y = 0; $y < imagesy($image); ++$y) { + for ($x = 0; $x < imagesx($image); ++$x) { + if ((imagecolorat($image, $x, $y) & 0xFF) < 0x80) { + ++$rows; + break; + } + } + } + + return $rows; + } + + public function testDrawStringWrapped(): void + { + if ((new FontResolver())->resolve(['face' => 'Arial', 'weight' => 400, 'italic' => false, 'pitchAndFamily' => 0]) === null) { + $this->markTestSkipped('No font available'); + } + // Font object (id 0) : Arial, 10 pixels + $font = pack('V', self::VERSION) . pack('g', 10) . pack('V', 2) . pack('l', 0) . pack('V2', 0, 5) . "A\0r\0i\0a\0l\0"; + $text = 'aaa bbb ccc ddd'; + $drawString = function (float $width) use ($text): string { + return $this->record( + Player::EMFPLUS_DRAW_STRING, + 0x8000, + pack('V3', 0xFF000000, 0xFFFFFFFF, strlen($text)) . pack('g4', 0, 0, $width, $width > 0 ? 100 : 0) . iconv('UTF-8', 'UTF-16LE', $text) + ); + }; + + $renderer = new Renderer(100, 100); + (new Player($renderer))->play($this->header() . $this->record(Player::EMFPLUS_OBJECT, 0x0600, $font) . $drawString(0)); + $singleLine = $this->countDarkRows($renderer->render()); + + // The layout rectangle is narrow : the text is wrapped + $renderer = new Renderer(100, 100); + (new Player($renderer))->play($this->header() . $this->record(Player::EMFPLUS_OBJECT, 0x0600, $font) . $drawString(25)); + $wrapped = $this->countDarkRows($renderer->render()); + + $this->assertGreaterThan(0, $singleLine); + $this->assertGreaterThan(2 * $singleLine, $wrapped); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/GDTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/GDTest.php new file mode 100644 index 00000000..f26d1521 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/GDTest.php @@ -0,0 +1,262 @@ +assertTrue($reader->load($this->getResourceDir() . $file)); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testLoadFromString(string $file): void + { + $reader = new GD(); + $this->assertTrue($reader->loadFromString(file_get_contents($this->getResourceDir() . $file))); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testGetResource(string $file): void + { + $reader = new GD(); + $reader->load($this->getResourceDir() . $file); + if (\PHP_VERSION_ID < 80000) { + $this->assertIsResource($reader->getResource()); + } else { + /* @phpstan-ignore-next-line */ + $this->assertInstanceOf(GdImage::class, $reader->getResource()); + } + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testOutput(string $file): void + { + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + $similarFile = $this->getResourceDir() . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $reader = new GD(); + $reader->load($this->getResourceDir() . $file); + $this->assertTrue($reader->save($outputFile, 'png')); + + $this->assertImageCompare($outputFile, $similarFile, 0.02); + + @unlink($outputFile); + } + + /** + * @dataProvider dataProviderMediaTypeWMF + */ + public function testSave(string $extension, string $mediatype): void + { + $outputFile = $this->getResourceDir() . 'output_save.' . $extension; + + $reader = new GD(); + $reader->load($this->getResourceDir() . 'burger.wmf'); + $reader->save($outputFile, $extension); + $this->assertMimeType($outputFile, $mediatype); + + @unlink($outputFile); + } + + public function testSaveWithException(): void + { + $file = 'vegetable.wmf'; + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $this->expectException(WMFException::class); + + $reader = new GD(); + $reader->load($this->getResourceDir() . $file); + $reader->save($outputFile, 'notanextension'); + } + + public function testSaveWithoutException(): void + { + $file = 'vegetable.wmf'; + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $reader = new GD(); + $reader->enableExceptions(false); + $reader->load($this->getResourceDir() . $file); + $this->assertFalse($reader->save($outputFile, 'notanextension')); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testIsWMF(string $file): void + { + $reader = new GD(); + $reader->load($this->getResourceDir() . $file); + $this->assertTrue($reader->isWMF()); + } + + public function testMediaType(): void + { + $reader = new GD(); + $this->assertEquals('image/wmf', $reader->getMediaType()); + } + + public function testNotImplementedWithExceptions(): void + { + $this->expectException(WMFException::class); + $this->expectExceptionMessage('Reader : Function not implemented : 0x062f'); + + $reader = new GD(); + $reader->loadFromString($this->getContentWMFNotImplemented()); + } + + public function testNotImplementedWithoutExceptions(): void + { + $reader = new GD(); + $reader->enableExceptions(false); + $this->assertFalse($reader->loadFromString($this->getContentWMFNotImplemented())); + } + + /** + * The test file of libUEMF uses most of the WMF records + */ + public function testLoadLibUEMF(): void + { + $outputFile = $this->getResourceDir() . 'output_test_libuemf.png'; + + $reader = new GD(); + $this->assertTrue($reader->load($this->getResourceDir() . 'test_libuemf.wmf')); + $this->assertTrue($reader->save($outputFile, 'png')); + $this->assertMimeType($outputFile, 'image/png'); + + @unlink($outputFile); + } + + /** + * @return array> + */ + public static function dataProviderBitmapColors(): array + { + return [ + // DIB_RGB_COLORS : the colors of the color table (red & blue) + [0, 0xFF0000, 0x0000FF], + // DIB_PAL_COLORS : the palette of the file is not known, a gray scale is used + [1, 0x000000, 0xFFFFFF], + ]; + } + + /** + * @dataProvider dataProviderBitmapColors + */ + public function testBitmapColors(int $usage, int $leftColor, int $rightColor): void + { + $reader = new GD(); + $this->assertTrue($reader->loadFromString($this->getContentWMFWithBitmap(0, $usage))); + $image = $reader->getResource(); + + $this->assertEquals($leftColor, imagecolorat($image, (int) (imagesx($image) / 4), (int) (imagesy($image) / 2)) & 0xFFFFFF); + $this->assertEquals($rightColor, imagecolorat($image, (int) (imagesx($image) * 3 / 4), (int) (imagesy($image) / 2)) & 0xFFFFFF); + } + + public function testBitmapNotSupportedWithExceptions(): void + { + $this->expectException(WMFException::class); + $this->expectExceptionMessage('Reader : Bitmap not supported : 0x0f43'); + + $reader = new GD(); + $reader->loadFromString($this->getContentWMFWithBitmap(1, 0)); + } + + public function testBitmapNotSupportedWithoutExceptions(): void + { + $reader = new GD(); + $reader->enableExceptions(false); + $this->assertFalse($reader->loadFromString($this->getContentWMFWithBitmap(1, 0))); + } + + public function testLoadStandardWMF(): void + { + // Without the placeable header, the size is defined by the window (MM_ANISOTROPIC : 1440 units per inch) + $content = (string) file_get_contents($this->getResourceDir() . 'burger.wmf'); + $reader = new GD(); + $this->assertTrue($reader->loadFromString(substr($content, 22))); + $this->assertTrue($reader->isWMF()); + + // The window of burger.wmf : extent (2290, -2035) + $image = $reader->getResource(); + $this->assertEquals((int) ceil(2290 / 1440 * 72), imagesx($image)); + $this->assertEquals((int) ceil(2035 / 1440 * 72), imagesy($image)); + } + + public function testLoadStandardWMFWithoutWindow(): void + { + $this->expectException(WMFException::class); + $this->expectExceptionMessage('Reader : Invalid file : the size of the image is not defined'); + + // META_HEADER followed by META_EOF + $reader = new GD(); + $reader->loadFromString(pack('v3Vv2Vv', 1, 9, 0x0300, 12, 0, 3, 0, 0) . pack('Vv', 3, 0x0000)); + } + + public function testInvertRegion(): void + { + $content = (string) file_get_contents($this->getResourceDir() . 'burger.wmf'); + // The window of burger.wmf : origin (-1225, 1137), extent (2290, -2035) + // Region (object 0) : a single scan covering the image + // nextInChain, objectType, objectCount, regionSize, scanCount, maxScan, bounding box + $region = pack('v2Vv3', 0, 6, 0, 36, 1, 2) . pack('s4', -1225, -898, 1065, 1137) + // Scan : count, top, bottom, left, right, count + . pack('v', 2) . pack('s4', -898, 1137, -1225, 1065) . pack('v', 2); + $records = pack('Vv', 3 + strlen($region) / 2, 0x06FF) . $region + . pack('Vv', 4, 0x012A) . pack('v', 0) + . pack('Vv', 3, 0x0000); + + // META_HEADER : maximum number of objects + $header = substr($content, 22, 18); + $header = substr($header, 0, 10) . pack('v', 1) . substr($header, 12); + + $reader = new GD(); + $this->assertTrue($reader->loadFromString(substr($content, 0, 22) . $header . $records)); + $image = $reader->getResource(); + // White becomes black + $this->assertEquals(0x000000, imagecolorat($image, (int) (imagesx($image) / 2), (int) (imagesy($image) / 2)) & 0xFFFFFF); + } + + public function testBackgroundColor(): void + { + $file = $this->getResourceDir() . 'burger.wmf'; + $outputFile = $this->getResourceDir() . 'output_background.jpg'; + + $reader = new GD(); + $this->assertEquals([255, 255, 255], $reader->getBackgroundColor()); + + // Transparent background + $this->assertInstanceOf(GD::class, $reader->setBackgroundColor(null)); + $this->assertNull($reader->getBackgroundColor()); + $reader->load($file); + $this->assertEquals(127, (imagecolorat($reader->getResource(), 0, 0) >> 24) & 0x7F); + // Formats without alpha channel are saved on a white background + $this->assertTrue($reader->save($outputFile, 'jpg')); + $this->assertGreaterThan(0xF0, imagecolorat(imagecreatefromjpeg($outputFile), 0, 0) & 0xFF); + @unlink($outputFile); + + // Colored background + $reader->setBackgroundColor([0, 0, 255]); + $reader->load($file); + $this->assertEquals(0x0000FF, imagecolorat($reader->getResource(), 0, 0)); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/ImagickTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/ImagickTest.php new file mode 100644 index 00000000..98371740 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/ImagickTest.php @@ -0,0 +1,133 @@ +assertTrue($reader->load($this->getResourceDir() . $file)); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testLoadFromString(string $file): void + { + $reader = new ImagickReader(); + $this->assertTrue($reader->loadFromString(file_get_contents($this->getResourceDir() . $file))); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testGetResource(string $file): void + { + $reader = new ImagickReader(); + $reader->load($this->getResourceDir() . $file); + $this->assertInstanceOf(ImagickBase::class, $reader->getResource()); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testOutput(string $file): void + { + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + $similarFile = $this->getResourceDir() . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $reader = new ImagickReader(); + $reader->load($this->getResourceDir() . $file); + $this->assertTrue($reader->save($outputFile, 'png')); + + $this->assertImageCompare($outputFile, $similarFile, 0.02); + + @unlink($outputFile); + } + + /** + * @dataProvider dataProviderMediaTypeWMF + */ + public function testSave(string $extension, string $mediatype): void + { + $outputFile = $this->getResourceDir() . 'output_save.' . $extension; + + $reader = new ImagickReader(); + $reader->load($this->getResourceDir() . 'burger.wmf'); + $reader->save($outputFile, $extension); + $this->assertMimeType($outputFile, $mediatype); + + @unlink($outputFile); + } + + public function testSaveWithException(): void + { + $file = 'vegetable.wmf'; + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $this->expectException(WMFException::class); + + $reader = new ImagickReader(); + $reader->load($this->getResourceDir() . $file); + $reader->save($outputFile, 'notanextension'); + } + + public function testSaveWithoutException(): void + { + $file = 'vegetable.wmf'; + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $reader = new ImagickReader(); + $reader->enableExceptions(false); + $reader->load($this->getResourceDir() . $file); + $this->assertFalse($reader->save($outputFile, 'notanextension')); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testIsWMF(string $file): void + { + $reader = new ImagickReader(); + $reader->load($this->getResourceDir() . $file); + $this->assertTrue($reader->isWMF()); + } + + public function testMediaType(): void + { + $reader = new ImagickReader(); + $this->assertEquals('image/wmf', $reader->getMediaType()); + } + + /** + * @dataProvider dataProviderFilesWMFNotImplemented + */ + public function testNotImplementedWithExceptions(string $file): void + { + $this->expectException(WMFException::class); + + $reader = new ImagickReader(); + $reader->load($this->getResourceDir() . $file); + } + + /** + * @dataProvider dataProviderFilesWMFNotImplemented + */ + public function testNotImplementedWithoutExceptions(string $file): void + { + $reader = new ImagickReader(); + $reader->enableExceptions(false); + $this->assertFalse($reader->load($this->getResourceDir() . $file)); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/MagicGDTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/MagicGDTest.php new file mode 100644 index 00000000..975e63ac --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/MagicGDTest.php @@ -0,0 +1,107 @@ +setBackends([ + GD::class, + Imagick::class, + ]); + + return $reader; + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testLoad(string $file): void + { + $reader = $this->getReader(); + $this->assertTrue($reader->load($this->getResourceDir() . $file)); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testLoadFromString(string $file): void + { + $reader = $this->getReader(); + $this->assertTrue($reader->loadFromString(file_get_contents($this->getResourceDir() . $file))); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testGetResource(string $file): void + { + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . $file); + if (\PHP_VERSION_ID < 80000) { + $this->assertIsResource($reader->getResource()); + } else { + /* @phpstan-ignore-next-line */ + $this->assertInstanceOf(GdImage::class, $reader->getResource()); + } + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testOutput(string $file): void + { + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + $similarFile = $this->getResourceDir() . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . $file); + $reader->save($outputFile, 'png'); + + $this->assertImageCompare($outputFile, $similarFile, 0.02); + + @unlink($outputFile); + } + + /** + * @dataProvider dataProviderMediaTypeWMF + */ + public function testSave(string $extension, string $mediatype): void + { + $outputFile = $this->getResourceDir() . 'output_save.' . $extension; + + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . 'burger.wmf'); + $reader->save($outputFile, $extension); + $this->assertMimeType($outputFile, $mediatype); + + @unlink($outputFile); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testIsWMF(string $file): void + { + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . $file); + $this->assertTrue($reader->isWMF()); + } + + public function testMediaType(): void + { + $reader = $this->getReader(); + $this->assertEquals('image/wmf', $reader->getMediaType()); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/MagicImagickTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/MagicImagickTest.php new file mode 100644 index 00000000..490bba2f --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/MagicImagickTest.php @@ -0,0 +1,101 @@ +setBackends([ + Imagick::class, + GD::class, + ]); + + return $reader; + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testLoad(string $file): void + { + $reader = $this->getReader(); + $this->assertTrue($reader->load($this->getResourceDir() . $file)); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testLoadFromString(string $file): void + { + $reader = $this->getReader(); + $this->assertTrue($reader->loadFromString(file_get_contents($this->getResourceDir() . $file))); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testGetResource(string $file): void + { + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . $file); + $this->assertIsObject($reader->getResource()); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testOutput(string $file): void + { + $outputFile = $this->getResourceDir() . 'output_' . pathinfo($file, PATHINFO_FILENAME) . '.png'; + $similarFile = $this->getResourceDir() . pathinfo($file, PATHINFO_FILENAME) . '.png'; + + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . $file); + $reader->save($outputFile, 'png'); + + $this->assertImageCompare($outputFile, $similarFile, 0.02); + + @unlink($outputFile); + } + + /** + * @dataProvider dataProviderMediaTypeWMF + */ + public function testSave(string $extension, string $mediatype): void + { + $outputFile = $this->getResourceDir() . 'output_save.' . $extension; + + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . 'burger.wmf'); + $reader->save($outputFile, $extension); + $this->assertMimeType($outputFile, $mediatype); + + @unlink($outputFile); + } + + /** + * @dataProvider dataProviderFilesWMF + */ + public function testIsWMF(string $file): void + { + $reader = $this->getReader(); + $reader->load($this->getResourceDir() . $file); + $this->assertTrue($reader->isWMF()); + } + + public function testMediaType(): void + { + $reader = $this->getReader(); + $this->assertEquals('image/wmf', $reader->getMediaType()); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/MagicTest.php b/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/MagicTest.php new file mode 100644 index 00000000..d80d8e0c --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Reader/WMF/MagicTest.php @@ -0,0 +1,71 @@ +assertEquals([ + Imagick::class, + GD::class, + ], $reader->getBackends()); + } + + public function testSetBackends(): void + { + $reader = new Magic(); + $this->assertInstanceOf(Magic::class, $reader->setBackends([ + GD::class, + Imagick::class, + ])); + $this->assertEquals([ + GD::class, + Imagick::class, + ], $reader->getBackends()); + } + + public function testIsSupported(): void + { + $this->assertTrue((new GD())->isSupported()); + $this->assertTrue((new Magic())->isSupported()); + + $reader = new Magic(); + $reader->setBackends([]); + $this->assertFalse($reader->isSupported()); + } + + /** + * A backend not supported is skipped + */ + public function testBackendNotSupported(): void + { + $unsupported = new class extends Imagick { + public function isSupported(): bool + { + return false; + } + }; + + $reader = new Magic(); + $reader->setBackends([ + get_class($unsupported), + GD::class, + ]); + $this->assertTrue($reader->load($this->getResourceDir() . 'burger.wmf')); + $this->assertTrue($reader->isWMF()); + if (\PHP_VERSION_ID >= 80000) { + /* @phpstan-ignore-next-line */ + $this->assertInstanceOf(GdImage::class, $reader->getResource()); + } + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Renderer/BitmapTest.php b/vendor/phpoffice/wmf/tests/WMF/Renderer/BitmapTest.php new file mode 100644 index 00000000..96f977d7 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Renderer/BitmapTest.php @@ -0,0 +1,170 @@ +getPackedDIB(2, 2, 24, '', $bits)); + + $this->assertEquals([ + 'width' => 2, + 'height' => 2, + 'pixels' => [ + [0x0000FF, 0xFFFFFF], + [0xFF0000, 0x00FF00], + ], + ], $bitmap); + } + + public function testReadPackedDIBTopDown(): void + { + $bits = "\x00\x00\xFF\0\xFF\x00\x00\0"; + $bitmap = Bitmap::readPackedDIB($this->getPackedDIB(1, -2, 24, '', $bits)); + + $this->assertEquals([[0xFF0000], [0x0000FF]], $bitmap['pixels']); + } + + public function testReadPackedDIBPalette(): void + { + // 1-bit bitmap with a palette of 2 colors (red & blue) + $palette = "\x00\x00\xFF\x00\xFF\x00\x00\x00"; + $bitmap = Bitmap::readPackedDIB($this->getPackedDIB(3, 1, 1, $palette, "\xA0\0\0\0", 2)); + + $this->assertEquals([[0x0000FF, 0xFF0000, 0x0000FF]], $bitmap['pixels']); + } + + public function testReadPackedDIBPaletteIndexes(): void + { + // DIB_PAL_COLORS : the palette is not known, a gray scale is used + $bitmap = Bitmap::readPackedDIB($this->getPackedDIB(2, 1, 1, "\0\0\1\0", "\x40\0\0\0", 2), true); + + $this->assertEquals([[0x000000, 0xFFFFFF]], $bitmap['pixels']); + } + + public function testReadDIBRLE8(): void + { + // 4x2 bitmap, colors : red (0), green (1), blue (2) + $palette = "\x00\x00\xFF\x00\x00\xFF\x00\x00\xFF\x00\x00\x00"; + // Bottom row : 2 red pixels, then absolute mode (green, blue, padding) ; end of line + // Top row : delta (2, 0), then 1 green pixel ; end of bitmap + $bits = "\x02\x00\x00\x03\x01\x02\x00\x00\x00\x00\x00\x02\x02\x00\x01\x01\x00\x01"; + $dib = pack('VllvvVVllVV', 40, 5, 2, 1, 8, 1, strlen($bits), 0, 0, 3, 0) . $palette . $bits; + $bitmap = Bitmap::readDIB($dib, 0, 52); + + $this->assertNotNull($bitmap); + $this->assertEquals([ + // Skipped pixels are transparent + [Bitmap::TRANSPARENT, Bitmap::TRANSPARENT, 0x00FF00, Bitmap::TRANSPARENT, Bitmap::TRANSPARENT], + [0xFF0000, 0xFF0000, 0x00FF00, 0x0000FF, 0xFF0000], + ], $bitmap['pixels']); + } + + public function testReadDIBRLE4(): void + { + // 6x1 bitmap, colors : red (0), green (1) + $palette = "\x00\x00\xFF\x00\x00\xFF\x00\x00"; + // 3 pixels alternating red & green, then absolute mode (green, red, green) ; end of bitmap + $bits = "\x03\x01\x00\x03\x10\x10\x00\x01"; + $dib = pack('VllvvVVllVV', 40, 6, 1, 1, 4, 2, strlen($bits), 0, 0, 2, 0) . $palette . $bits; + $bitmap = Bitmap::readDIB($dib, 0, 48); + + $this->assertNotNull($bitmap); + $this->assertEquals([[0xFF0000, 0x00FF00, 0xFF0000, 0x00FF00, 0xFF0000, 0x00FF00]], $bitmap['pixels']); + } + + public function testReadDIBNotSupported(): void + { + // BI_RLE8 is only valid for 8 bits per pixel + $dib = pack('VllvvVVllVV', 40, 1, 1, 1, 4, 1, 0, 0, 0, 0, 0); + $this->assertNull(Bitmap::readDIB($dib, 0, 40)); + // Empty bitmap + $this->assertNull(Bitmap::readPackedDIB($this->getPackedDIB(0, 1, 24, '', ''))); + // BITMAPCOREHEADER + $this->assertNull(Bitmap::readPackedDIB(pack('VvvvV', 12, 1, 1, 1, 24) . str_repeat("\0", 28))); + } + + /** + * @return array> + */ + public static function dataProviderTruncated(): array + { + return [ + [function () { + return Bitmap::readDIB(str_repeat("\0", 20), 0, 40); + }], + [function () { + return Bitmap::readPackedDIB(pack('VvvvV', 12, 1, 1, 1, 24)); + }], + [function () { + return Bitmap::readBitmap16("\0\0\1\0"); + }], + ]; + } + + /** + * @dataProvider dataProviderTruncated + */ + public function testTruncated(callable $read): void + { + $this->expectException(WMFException::class); + $this->expectExceptionMessage('Reader : Invalid file : truncated bitmap'); + + $read(); + } + + public function testReadDIBImage(): void + { + // BI_PNG : the bits are a PNG image + $image = imagecreatetruecolor(2, 1); + imagesetpixel($image, 0, 0, 0x112233); + imagesetpixel($image, 1, 0, 0x445566); + ob_start(); + imagepng($image); + $png = (string) ob_get_clean(); + + $dib = pack('VllvvVVllVV', 40, 2, 1, 1, 0, 5, strlen($png), 0, 0, 0, 0) . $png; + $this->assertEquals([[0x112233, 0x445566]], Bitmap::readDIB($dib, 0, 40, 40, strlen($png))['pixels']); + + // A corrupted image is empty + $dib = pack('VllvvVVllVV', 40, 2, 1, 1, 0, 5, 4, 0, 0, 0, 0) . 'fake'; + $this->assertEquals(['width' => 0, 'height' => 0, 'pixels' => []], Bitmap::readDIB($dib, 0, 40, 40, 4)); + } + + public function testReadBitmap16(): void + { + // Monochrome 3x2 bitmap, rows of 2 bytes + $bitmap = Bitmap::readBitmap16(pack('vvvvCC', 0, 3, 2, 2, 1, 1) . "\xA0\0\x40\0"); + + $this->assertEquals([ + [0xFFFFFF, 0x000000, 0xFFFFFF], + [0x000000, 0xFFFFFF, 0x000000], + ], $bitmap['pixels']); + $this->assertNull(Bitmap::readBitmap16(pack('vvvvCC', 0, 0, 2, 2, 1, 1))); + } + + public function testGetAverageColor(): void + { + $bitmap = ['width' => 2, 'height' => 1, 'pixels' => [[0xFF0000, 0x0000FF]]]; + + $this->assertEquals([128, 0, 128], Bitmap::getAverageColor($bitmap)); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Renderer/EncodingTest.php b/vendor/phpoffice/wmf/tests/WMF/Renderer/EncodingTest.php new file mode 100644 index 00000000..073f5605 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Renderer/EncodingTest.php @@ -0,0 +1,41 @@ +assertEquals('Café €', Encoding::decodeANSI("Caf\xE9 \x80")); + // Stops at the first NUL character + $this->assertEquals('Arial', Encoding::decodeANSI("Arial\0\0garbage")); + $this->assertEquals('', Encoding::decodeANSI('')); + } + + public function testDecodeUTF16(): void + { + $this->assertEquals('Café', Encoding::decodeUTF16("C\0a\0f\0\xE9\0")); + // Surrogate pair + $this->assertEquals('A😀', Encoding::decodeUTF16("A\0\x3D\xD8\x00\xDE")); + // Stops at the first NUL character + $this->assertEquals('A', Encoding::decodeUTF16("A\0\0\0B\0")); + // Odd length + $this->assertEquals('A', Encoding::decodeUTF16("A\0B")); + // Lone surrogate + $this->assertEquals("\u{FFFD}", Encoding::decodeUTF16("\x3D\xD8")); + } + + public function testDecodeSymbol(): void + { + // ASCII & private characters (U+F0xx) of the Symbol font + $this->assertEquals('αβχ ≤ Σ', Encoding::decodeSymbol("ab\u{F063} \u{F0A3} S")); + // Characters which are not in the Symbol font are kept + $this->assertEquals('1+2=3 €', Encoding::decodeSymbol('1+2=3 €')); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Renderer/FontResolverTest.php b/vendor/phpoffice/wmf/tests/WMF/Renderer/FontResolverTest.php new file mode 100644 index 00000000..670e0a73 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Renderer/FontResolverTest.php @@ -0,0 +1,81 @@ +directory = sys_get_temp_dir() . '/wmf_fonts_' . uniqid(); + mkdir($this->directory . '/liberation', 0777, true); + foreach (['LiberationSans-Regular.ttf', 'LiberationSans-Bold.ttf', 'LiberationSerif-Regular.ttf', 'arialbd.ttf', 'readme.txt'] as $file) { + touch($this->directory . '/liberation/' . $file); + } + } + + protected function tearDown(): void + { + foreach (glob($this->directory . '/liberation/*') ?: [] as $file) { + unlink($file); + } + rmdir($this->directory . '/liberation'); + rmdir($this->directory); + } + + /** + * @param array $font + * + * @return array + */ + private function getFont(array $font): array + { + return $font + ['face' => 'Arial', 'weight' => 400, 'italic' => false, 'pitchAndFamily' => 0]; + } + + public function testDirectories(): void + { + $resolver = new FontResolver(); + foreach ($resolver->getDirectories() as $directory) { + $this->assertDirectoryExists($directory); + } + + $this->assertInstanceOf(FontResolver::class, $resolver->setDirectories([$this->directory])); + $this->assertEquals([$this->directory], $resolver->getDirectories()); + } + + public function testResolve(): void + { + $resolver = (new FontResolver())->setDirectories([$this->directory]); + $path = $this->directory . '/liberation/'; + + // Font available + $this->assertEquals($path . 'arialbd.ttf', $resolver->resolve($this->getFont(['weight' => 700]))); + // Font not available : similar font + $this->assertEquals($path . 'LiberationSans-Regular.ttf', $resolver->resolve($this->getFont([]))); + $this->assertEquals($path . 'LiberationSerif-Regular.ttf', $resolver->resolve($this->getFont(['face' => 'Times New Roman']))); + // Unknown font : family defined by pitchAndFamily (FF_ROMAN) + $this->assertEquals($path . 'LiberationSerif-Regular.ttf', $resolver->resolve($this->getFont(['face' => 'Unknown', 'pitchAndFamily' => 0x12]))); + // Style not available : regular style + $this->assertEquals($path . 'LiberationSans-Regular.ttf', $resolver->resolve($this->getFont(['face' => 'Helvetica', 'italic' => true]))); + // No similar font + $this->assertNull($resolver->resolve($this->getFont(['face' => 'Courier New']))); + } + + public function testResolveWithoutFonts(): void + { + $resolver = (new FontResolver())->setDirectories([$this->directory . '/notfound']); + + $this->assertNull($resolver->resolve($this->getFont([]))); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Renderer/GDTest.php b/vendor/phpoffice/wmf/tests/WMF/Renderer/GDTest.php new file mode 100644 index 00000000..88afee68 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Renderer/GDTest.php @@ -0,0 +1,379 @@ +assertEquals(sprintf('%06X', $expected), sprintf('%06X', imagecolorat($image, $x, $y) & 0xFFFFFF), sprintf('Color at (%d, %d)', $x, $y)); + } + + /** + * @param array $color + * + * @return array + */ + private function getBrush(array $color): array + { + return ['type' => 'brush', 'style' => 0, 'color' => $color]; + } + + public function testRender(): void + { + $image = (new GD(20, 10))->render(); + + $this->assertEquals(20, imagesx($image)); + $this->assertEquals(10, imagesy($image)); + $this->assertColorAt($image, 5, 5, 0xFFFFFF); + } + + public function testBigImageIsScaledDown(): void + { + $image = (new GD(8000, 4000))->render(); + + $this->assertLessThanOrEqual(16000000, imagesx($image) * imagesy($image)); + $this->assertEqualsWithDelta(2, imagesx($image) / imagesy($image), 0.01); + } + + public function testRectangle(): void + { + $renderer = new GD(20, 20); + $renderer->selectObject(GD::getStockObject(8)) + ->selectObject($this->getBrush([255, 0, 0])) + ->rectangle(5, 5, 15, 15); + $image = $renderer->render(); + + $this->assertColorAt($image, 10, 10, 0xFF0000); + $this->assertColorAt($image, 2, 2, 0xFFFFFF); + $this->assertColorAt($image, 17, 17, 0xFFFFFF); + } + + public function testMapping(): void + { + // The window (0, 0) - (200, 100) is mapped to the image, with the y axis going up + $renderer = new GD(20, 10); + $renderer->setMapMode(GD::MM_ANISOTROPIC) + ->setWindowOrg(0, 100) + ->setWindowExt(200, -100) + ->setViewportExt(20, 10) + ->selectObject(GD::getStockObject(8)) + ->selectObject($this->getBrush([0, 0, 255])) + // Bottom left quarter + ->rectangle(0, 0, 100, 50); + $image = $renderer->render(); + + $this->assertColorAt($image, 5, 7, 0x0000FF); + $this->assertColorAt($image, 5, 2, 0xFFFFFF); + $this->assertColorAt($image, 15, 7, 0xFFFFFF); + } + + public function testSaveRestoreDC(): void + { + $renderer = new GD(20, 20); + $renderer->selectObject(GD::getStockObject(8)) + ->selectObject($this->getBrush([255, 0, 0])) + ->saveDC() + ->selectObject($this->getBrush([0, 255, 0])) + ->restoreDC(-1) + ->rectangle(0, 0, 20, 20); + + $this->assertColorAt($renderer->render(), 10, 10, 0xFF0000); + } + + public function testClipping(): void + { + $renderer = new GD(20, 20); + $renderer->selectObject(GD::getStockObject(8)) + ->selectObject($this->getBrush([255, 0, 0])) + ->intersectClipRect(0, 0, 10, 20) + ->excludeClipRect(0, 0, 10, 5) + ->rectangle(0, 0, 20, 20); + $image = $renderer->render(); + + $this->assertColorAt($image, 5, 10, 0xFF0000); + $this->assertColorAt($image, 5, 2, 0xFFFFFF); + $this->assertColorAt($image, 15, 10, 0xFFFFFF); + } + + public function testClipRegionXOR(): void + { + $renderer = new GD(20, 20); + $renderer->selectObject(GD::getStockObject(8)) + ->selectObject($this->getBrush([255, 0, 0])) + ->selectClipRegion([[0, 0, 10, 20]], Rasterizer::RGN_COPY, false) + ->selectClipRegion([[5, 0, 15, 20]], Rasterizer::RGN_XOR, false) + ->rectangle(0, 0, 20, 20); + $image = $renderer->render(); + + $this->assertColorAt($image, 2, 10, 0xFF0000); + $this->assertColorAt($image, 7, 10, 0xFFFFFF); + $this->assertColorAt($image, 12, 10, 0xFF0000); + $this->assertColorAt($image, 17, 10, 0xFFFFFF); + } + + public function testPath(): void + { + $renderer = new GD(20, 20); + $renderer->selectObject(GD::getStockObject(8)) + ->selectObject($this->getBrush([0, 255, 0])) + ->beginPath() + ->moveTo(0, 0) + ->polylineTo([[20, 0], [20, 10]]) + ->closeFigure() + ->endPath() + ->fillPath(); + $image = $renderer->render(); + + // Triangle above the diagonal + $this->assertColorAt($image, 18, 2, 0x00FF00); + $this->assertColorAt($image, 2, 15, 0xFFFFFF); + } + + public function testStroke(): void + { + $renderer = new GD(20, 20); + $renderer->selectObject(['type' => 'pen', 'style' => 0, 'width' => 4, 'geometric' => true, 'color' => [0, 0, 0]]) + ->moveTo(0, 10) + ->lineTo(20, 10); + $image = $renderer->render(); + + $this->assertColorAt($image, 10, 9, 0x000000); + $this->assertColorAt($image, 10, 3, 0xFFFFFF); + } + + public function testBitmap(): void + { + $renderer = new GD(20, 20); + $renderer->drawBitmap(['width' => 2, 'height' => 1, 'pixels' => [[0xFF0000, 0x0000FF]]], 0, 0, 20, 20, 0, 0, 2, 1); + $image = $renderer->render(); + + $this->assertColorAt($image, 5, 10, 0xFF0000); + $this->assertColorAt($image, 15, 10, 0x0000FF); + } + + public function testGradientFill(): void + { + $renderer = new GD(20, 10); + $renderer->gradientFill([[0, 0, [0, 0, 0]], [20, 10, [255, 255, 255]]], [[0, 1]], 0); + $image = $renderer->render(); + + $this->assertLessThan(0x20, imagecolorat($image, 0, 5) & 0xFF); + $this->assertGreaterThan(0xE0, imagecolorat($image, 19, 5) & 0xFF); + } + + public function testPatBlt(): void + { + $renderer = new GD(20, 20); + $renderer->patBlt(0, 0, 10, 20, GD::ROP_BLACKNESS) + ->patBlt(10, 0, 20, 20, GD::ROP_NOP); + $image = $renderer->render(); + + $this->assertColorAt($image, 5, 10, 0x000000); + $this->assertColorAt($image, 15, 10, 0xFFFFFF); + } + + public function testFloodFill(): void + { + $renderer = new GD(20, 20); + $renderer->selectObject(['type' => 'pen', 'style' => 0, 'width' => 2, 'geometric' => true, 'color' => [0, 0, 0]]) + ->selectObject(GD::getStockObject(5)) + ->rectangle(2, 2, 18, 18) + ->selectObject($this->getBrush([255, 0, 0])) + ->floodFill(10, 10, [0, 0, 0], false); + $image = $renderer->render(); + + $this->assertColorAt($image, 10, 10, 0xFF0000); + $this->assertColorAt($image, 0, 0, 0xFFFFFF); + } + + public function testStockObjects(): void + { + $this->assertEquals('brush', GD::getStockObject(0)['type']); + $this->assertEquals('pen', GD::getStockObject(7)['type']); + $this->assertEquals('font', GD::getStockObject(13)['type']); + $this->assertNull(GD::getStockObject(9)); + } + + public function testHatchedBrush(): void + { + // HS_HORIZONTAL : red lines every 8 pixels on the background color (OPAQUE background mode) + $renderer = new GD(20, 20); + $renderer->selectObject(GD::getStockObject(8)) + ->selectObject(['type' => 'brush', 'style' => 2, 'color' => [255, 0, 0], 'hatch' => 0]) + ->setBkColor([0, 0, 255]) + ->rectangle(0, 0, 20, 20); + $image = $renderer->render(); + + $this->assertColorAt($image, 5, 8, 0xFF0000); + $this->assertColorAt($image, 5, 10, 0x0000FF); + + // TRANSPARENT background mode + $renderer = new GD(20, 20); + $renderer->selectObject(GD::getStockObject(8)) + ->selectObject(['type' => 'brush', 'style' => 2, 'color' => [255, 0, 0], 'hatch' => 1]) + ->setBkMode(1) + ->rectangle(0, 0, 20, 20); + $image = $renderer->render(); + + $this->assertColorAt($image, 8, 5, 0xFF0000); + $this->assertColorAt($image, 10, 5, 0xFFFFFF); + } + + public function testDashedPen(): void + { + // Dashes of 4 pixels, spaces of 4 pixels + $renderer = new GD(20, 20); + $renderer->selectObject(['type' => 'pen', 'style' => 0, 'width' => 0, 'geometric' => false, 'color' => [0, 0, 0], 'dashes' => [4, 4]]) + // In the middle of a row of pixels + ->moveTo(0, 10.5) + ->lineTo(20, 10.5); + $image = $renderer->render(); + + $this->assertColorAt($image, 1, 10, 0x000000); + $this->assertColorAt($image, 6, 10, 0xFFFFFF); + $this->assertColorAt($image, 9, 10, 0x000000); + } + + public function testPatternBrush(): void + { + // Pattern of 2x1 pixels (red & blue) : tiled from the origin of the image + $renderer = new GD(20, 20); + $renderer->selectObject(GD::getStockObject(8)) + ->selectObject(['type' => 'brush', 'style' => 3, 'color' => [128, 0, 128], 'pattern' => ['width' => 2, 'height' => 1, 'pixels' => [[0xFF0000, 0x0000FF]]]]) + ->rectangle(5, 5, 15, 15); + $image = $renderer->render(); + + $this->assertColorAt($image, 6, 10, 0xFF0000); + $this->assertColorAt($image, 7, 10, 0x0000FF); + $this->assertColorAt($image, 12, 7, 0xFF0000); + $this->assertColorAt($image, 2, 2, 0xFFFFFF); + } + + public function testCompoundPen(): void + { + // Two lines : the first quarter & the last quarter of the width + $renderer = new GD(40, 40); + $renderer->selectObject(['type' => 'pen', 'style' => 0, 'width' => 12, 'geometric' => true, 'color' => [0, 0, 0], 'compound' => [0, 0.25, 0.75, 1]]) + ->moveTo(0, 20) + ->lineTo(40, 20); + $image = $renderer->render(); + + $this->assertColorAt($image, 20, 15, 0x000000); + $this->assertColorAt($image, 20, 20, 0xFFFFFF); + $this->assertColorAt($image, 20, 24, 0x000000); + $this->assertColorAt($image, 20, 10, 0xFFFFFF); + } + + public function testTextOutVerticalAdvances(): void + { + $font = ['type' => 'font', 'height' => -10, 'escapement' => 0, 'weight' => 400, 'italic' => false, 'underline' => false, 'strikeOut' => false, 'charset' => 0, 'pitchAndFamily' => 0x22, 'face' => 'Arial']; + if ((new FontResolver())->resolve($font) === null) { + $this->markTestSkipped('No font available'); + } + // Returns the rows containing dark pixels + $getRows = function (array $dy) use ($font): array { + $renderer = new GD(60, 60); + $renderer->selectObject($font) + ->setBkMode(1) + ->textOut(10, 30, 'II', [20, 20], 0, [0, 0, 0, 0], $dy); + $image = $renderer->render(); + $rows = []; + for ($y = 0; $y < 60; ++$y) { + for ($x = 0; $x < 60; ++$x) { + if ((imagecolorat($image, $x, $y) & 0xFF) < 0x80) { + $rows[] = $y; + break; + } + } + } + + return $rows; + }; + + $rows = $getRows([]); + // ETO_PDY : the second glyph is 20 units higher + $shiftedRows = $getRows([20, 0]); + $this->assertNotEmpty($rows); + $this->assertEquals(min($rows) - 20, min($shiftedRows)); + $this->assertEquals(max($rows), max($shiftedRows)); + } + + public function testRasterOperations(): void + { + // SRCAND : the bitmap (red & white) is combined with the green background + $renderer = new GD(20, 20); + $renderer->selectObject(GD::getStockObject(8)) + ->selectObject(['type' => 'brush', 'style' => 0, 'color' => [0, 255, 0]]) + ->rectangle(0, 0, 20, 20) + ->drawBitmap(['width' => 2, 'height' => 1, 'pixels' => [[0xFF0000, 0xFFFFFF]]], 0, 0, 20, 20, 0, 0, 2, 1, 0x008800C6) + // DSTINVERT on the bottom + ->patBlt(0, 15, 20, 20, 0x00550009); + $image = $renderer->render(); + + $this->assertColorAt($image, 5, 5, 0x000000); + $this->assertColorAt($image, 15, 5, 0x00FF00); + $this->assertColorAt($image, 15, 18, 0xFF00FF); + } + + public function testTransparentBackground(): void + { + $renderer = new GD(20, 20, 0, 0, 0, 0, null, null); + $renderer->selectObject(GD::getStockObject(8)) + ->selectObject($this->getBrush([255, 0, 0])) + ->rectangle(5, 5, 15, 15); + $image = $renderer->render(); + + $this->assertEquals(127, (imagecolorat($image, 1, 1) >> 24) & 0x7F); + $this->assertEquals(0xFF0000, imagecolorat($image, 10, 10)); + + // Raster operations use a white background + $renderer = new GD(20, 20, 0, 0, 0, 0, null, null); + $renderer->drawBitmap(['width' => 1, 'height' => 1, 'pixels' => [[0xFF0000]]], 0, 0, 20, 20, 0, 0, 1, 1, 0x008800C6); + $this->assertEquals(0xFF0000, imagecolorat($renderer->render(), 10, 10)); + } + + public function testApplyRop(): void + { + $this->assertEquals(0x00FF00 & 0x0F0F0F, GD::applyRop(0x008800C6, 0, 0x0F0F0F, 0x00FF00)); + $this->assertEquals(0xFF00FF, GD::applyRop(0x00550009, 0, 0, 0x00FF00)); + // PSDPxax (generic evaluation) : D ^ (S & (P ^ D)) + $this->assertEquals(0x00FF00 ^ (0x0F0F0F & (0xFF0000 ^ 0x00FF00)), GD::applyRop(0x00E20746, 0xFF0000, 0x0F0F0F, 0x00FF00)); + + $this->assertFalse(GD::isRopDependent(GD::ROP_PATCOPY, 1)); + $this->assertTrue(GD::isRopDependent(0x00550009, 1)); + $this->assertTrue(GD::isRopDependent(GD::ROP_SRCCOPY, 2)); + } + + public function testPenDashes(): void + { + $this->assertEquals([18, 6], GD::getPenDashes(1, true, 1)); + $this->assertEquals([3, 1], GD::getPenDashes(1, false, 4)); + $this->assertEquals([1, 1], GD::getPenDashes(8, true, 1)); + // PS_USERSTYLE : in pen widths for geometric pens + $this->assertEquals([4, 2], GD::getPenDashes(7, false, 8, [32, 16])); + $this->assertNull(GD::getPenDashes(0, true, 1)); + $this->assertNull(GD::getPenDashes(7, false, 8, [32])); + } + + public function testHatchPatterns(): void + { + $this->assertTrue(GD::isHatchForeground(0, 3, 16)); + $this->assertFalse(GD::isHatchForeground(0, 3, 17)); + $this->assertTrue(GD::isHatchForeground(5, 3, 5)); + $this->assertTrue(GD::isHatchForeground(5, 3, 3)); + } +} diff --git a/vendor/phpoffice/wmf/tests/WMF/Renderer/RasterizerTest.php b/vendor/phpoffice/wmf/tests/WMF/Renderer/RasterizerTest.php new file mode 100644 index 00000000..6e91bbd0 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/WMF/Renderer/RasterizerTest.php @@ -0,0 +1,129 @@ +assertEquals([ + 1 => [[1, 3]], + 2 => [[1, 3]], + ], $spans); + } + + public function testRasterizeClampedToCanvas(): void + { + $spans = Rasterizer::rasterize([[[-5, -5], [20, -5], [20, 2], [-5, 2]]], false, 10, 10); + + $this->assertEquals([ + 0 => [[0, 9]], + 1 => [[0, 9]], + ], $spans); + } + + public function testRasterizeFillRules(): void + { + // Two overlapping squares with the same orientation + $polygons = [ + [[0, 0], [4, 0], [4, 1], [0, 1]], + [[2, 0], [6, 0], [6, 1], [2, 1]], + ]; + + // Even-odd : the intersection is a hole + $this->assertEquals([0 => [[0, 1], [4, 5]]], Rasterizer::rasterize($polygons, false, 10, 10)); + // Nonzero : the union + $this->assertEquals([0 => [[0, 5]]], Rasterizer::rasterize($polygons, true, 10, 10)); + } + + /** + * @return array> + */ + public static function dataProviderCombineRow(): array + { + $first = [[0, 4], [8, 9]]; + $second = [[2, 8]]; + + return [ + [$first, $second, Rasterizer::RGN_AND, [[2, 4], [8, 8]]], + [$first, $second, Rasterizer::RGN_OR, [[0, 9]]], + [$first, $second, Rasterizer::RGN_XOR, [[0, 1], [5, 7], [9, 9]]], + [$first, $second, Rasterizer::RGN_DIFF, [[0, 1], [9, 9]]], + [$first, $second, Rasterizer::RGN_COPY, [[2, 8]]], + [$first, [], Rasterizer::RGN_AND, []], + ]; + } + + /** + * @dataProvider dataProviderCombineRow + * + * @param array> $first + * @param array> $second + * @param array> $expected + */ + public function testCombineRow(array $first, array $second, int $mode, array $expected): void + { + $this->assertEquals($expected, Rasterizer::combineRow($first, $second, $mode)); + } + + public function testCombineSpans(): void + { + $first = [0 => [[0, 4]], 1 => [[0, 4]]]; + $second = [1 => [[2, 6]], 2 => [[2, 6]]]; + + $this->assertEquals([1 => [[2, 4]]], Rasterizer::combineSpans($first, $second, Rasterizer::RGN_AND)); + $this->assertEquals([0 => [[0, 4]], 1 => [[0, 6]], 2 => [[2, 6]]], Rasterizer::combineSpans($first, $second, Rasterizer::RGN_OR)); + $this->assertEquals([0 => [[0, 4]], 1 => [[0, 1]]], Rasterizer::combineSpans($first, $second, Rasterizer::RGN_DIFF)); + } + + public function testStrokePolygons(): void + { + // A segment with flat end caps is a rectangle + $polygons = Rasterizer::getStrokePolygons([[0, 5], [10, 5]], false, 2, 0x0200, 0x0000, 10); + $this->assertCount(1, $polygons); + $this->assertEquals([3 => [[0, 9]], 4 => [[0, 9]], 5 => [[0, 9]], 6 => [[0, 9]]], Rasterizer::rasterize($polygons, true, 20, 20)); + + // Round end caps add discs + $this->assertCount(3, Rasterizer::getStrokePolygons([[0, 5], [10, 5]], false, 2, 0x0000, 0x0000, 10)); + // A single point is a disc + $this->assertCount(1, Rasterizer::getStrokePolygons([[5, 5], [5, 5]], false, 2, 0x0000, 0x0000, 10)); + // All polygons have the same orientation + foreach (Rasterizer::getStrokePolygons([[0, 0], [10, 0], [10, 10], [0, 10]], true, 2, 0x0000, 0x2000, 10) as $polygon) { + $this->assertGreaterThanOrEqual(0, Rasterizer::getSignedArea($polygon)); + } + } + + public function testMiterJoin(): void + { + $normalIn = [0, 1]; + $normalOut = [-1, 0]; + + // Square corner : the miter point is at the corner of the offset lines + $this->assertEquals([[10, 0], [10, -1], [11, -1], [11, 0]], Rasterizer::getJoinPolygon([10, 0], $normalIn, $normalOut, 1, 0x2000, 10)); + // Miter limit exceeded : bevel + $this->assertCount(3, Rasterizer::getJoinPolygon([10, 0], $normalIn, $normalOut, 1, 0x2000, 1)); + // Bevel + $this->assertCount(3, Rasterizer::getJoinPolygon([10, 0], $normalIn, $normalOut, 1, 0x1000, 10)); + } + + public function testFlattenBeziers(): void + { + // A straight Bézier curve + $points = Rasterizer::flattenBeziers([[0, 0], [10, 0], [20, 0], [30, 0]]); + + $this->assertEquals([0, 0], $points[0]); + $this->assertEquals([30, 0], end($points)); + foreach ($points as $point) { + $this->assertEqualsWithDelta(0, $point[1], 0.0001); + } + $this->assertEquals([], Rasterizer::flattenBeziers([])); + } +} diff --git a/vendor/phpoffice/wmf/tests/resources/burger.png b/vendor/phpoffice/wmf/tests/resources/burger.png new file mode 100644 index 00000000..c0221e8b Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/burger.png differ diff --git a/vendor/phpoffice/wmf/tests/resources/burger.wmf b/vendor/phpoffice/wmf/tests/resources/burger.wmf new file mode 100644 index 00000000..35b30c39 Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/burger.wmf differ diff --git a/vendor/phpoffice/wmf/tests/resources/chicken.png b/vendor/phpoffice/wmf/tests/resources/chicken.png new file mode 100644 index 00000000..7700e920 Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/chicken.png differ diff --git a/vendor/phpoffice/wmf/tests/resources/chicken.wmf b/vendor/phpoffice/wmf/tests/resources/chicken.wmf new file mode 100644 index 00000000..6be326d0 Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/chicken.wmf differ diff --git a/vendor/phpoffice/wmf/tests/resources/computer_mail.emf b/vendor/phpoffice/wmf/tests/resources/computer_mail.emf new file mode 100644 index 00000000..0dbf23f7 Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/computer_mail.emf differ diff --git a/vendor/phpoffice/wmf/tests/resources/computer_mail.png b/vendor/phpoffice/wmf/tests/resources/computer_mail.png new file mode 100644 index 00000000..ea73960b Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/computer_mail.png differ diff --git a/vendor/phpoffice/wmf/tests/resources/files.txt b/vendor/phpoffice/wmf/tests/resources/files.txt new file mode 100644 index 00000000..39c52eb0 --- /dev/null +++ b/vendor/phpoffice/wmf/tests/resources/files.txt @@ -0,0 +1,8 @@ +# Where to find EMF/WMF files + +## EMF +https://opengrok.libreoffice.org/xref/core/emfio/qa/cppunit/wmf/data/ + +## WMF +https://opengrok.libreoffice.org/xref/core/emfio/qa/cppunit/wmf/data/ +https://opengrok.libreoffice.org/xref/core/odk/examples/basic/forms_and_controls/ \ No newline at end of file diff --git a/vendor/phpoffice/wmf/tests/resources/fish.png b/vendor/phpoffice/wmf/tests/resources/fish.png new file mode 100644 index 00000000..2967e99e Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/fish.png differ diff --git a/vendor/phpoffice/wmf/tests/resources/fish.wmf b/vendor/phpoffice/wmf/tests/resources/fish.wmf new file mode 100644 index 00000000..d7060f28 Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/fish.wmf differ diff --git a/vendor/phpoffice/wmf/tests/resources/inkscape_shapes.emf b/vendor/phpoffice/wmf/tests/resources/inkscape_shapes.emf new file mode 100644 index 00000000..3677be8a Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/inkscape_shapes.emf differ diff --git a/vendor/phpoffice/wmf/tests/resources/inkscape_shapes.png b/vendor/phpoffice/wmf/tests/resources/inkscape_shapes.png new file mode 100644 index 00000000..d9ae685d Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/inkscape_shapes.png differ diff --git a/vendor/phpoffice/wmf/tests/resources/test_libuemf.png b/vendor/phpoffice/wmf/tests/resources/test_libuemf.png new file mode 100644 index 00000000..a8cefc68 Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/test_libuemf.png differ diff --git a/vendor/phpoffice/wmf/tests/resources/test_libuemf.wmf b/vendor/phpoffice/wmf/tests/resources/test_libuemf.wmf new file mode 100644 index 00000000..bdf06a9d Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/test_libuemf.wmf differ diff --git a/vendor/phpoffice/wmf/tests/resources/vegetable.png b/vendor/phpoffice/wmf/tests/resources/vegetable.png new file mode 100644 index 00000000..daf5d662 Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/vegetable.png differ diff --git a/vendor/phpoffice/wmf/tests/resources/vegetable.wmf b/vendor/phpoffice/wmf/tests/resources/vegetable.wmf new file mode 100644 index 00000000..364d122c Binary files /dev/null and b/vendor/phpoffice/wmf/tests/resources/vegetable.wmf differ