File manager - Edit - /home/u816558632/domains/postills.com/public_html/public/phpoffice.tar
Back
phpspreadsheet/CONTRIBUTING.md 0000644 00000006100 15002227416 0012010 0 ustar 00 # Want to contribute? If you would like to contribute, here are some notes and guidelines: - All new development should be on feature/fix branches, which are then merged to the `master` branch once stable and approved; so the `master` branch is always the most up-to-date, working code - If you are going to submit a pull request, please fork from `master`, and submit your pull request back as a fix/feature branch referencing the GitHub issue number - The code must work with all PHP versions that we support (currently PHP 7.4 to PHP 8.2). - You can call `composer versions` to test version compatibility. - Code style should be maintained. - `composer style` will identify any issues with Coding Style`. - `composer fix` will fix most issues with Coding Style. - All code changes must be validated by `composer check`. - Please include Unit Tests to verify that a bug exists, and that this PR fixes it. - Please include Unit Tests to show that a new Feature works as expected. - Please don't "bundle" several changes into a single PR; submit a PR for each discrete change/fix. - Remember to update documentation if necessary. - [Helpful article about forking](https://help.github.com/articles/fork-a-repo/ "Forking a GitHub repository") - [Helpful article about pull requests](https://help.github.com/articles/using-pull-requests/ "Pull Requests") ## Unit Tests When writing Unit Tests, please - Always try to write Unit Tests for both the happy and unhappy paths. - Put all assertions in the Test itself, not in an abstract class that the Test extends (even if this means code duplication between tests). - Include any necessary `setup()` and `tearDown()` in the Test itself. - If you change any global settings (such as system locale, or Compatibility Mode for Excel Function tests), make sure that you reset to the default in the `tearDown()`. - Use the `ExcelError` functions in assertions for Excel Error values in Excel Function implementations. <br />Not only does it reduce the risk of typos; but at some point in the future, ExcelError values will be an object rather than a string, and we won't then need to update all the tests. - Don't over-complicate test code by testing happy and unhappy paths in the same test. This makes it easier to see exactly what is being tested when reviewing the PR. I want to be able to see it in the PR, not have to hunt in other unchanged classes to see what the test is doing. ## How to release 1. Complete CHANGELOG.md and commit 2. 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. Github seems to remove markdown headings in the Release Notes, so you should edit to restore these. > **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.) phpspreadsheet/phpstan-conditional.php 0000644 00000010005 15002227416 0014245 0 ustar 00 <?php $config = []; if (PHP_VERSION_ID < 80000) { // GdImage not available before PHP8 $config['parameters']['ignoreErrors'][] = [ 'message' => '~^Method .* has invalid return type GdImage\.$~', 'path' => __DIR__ . '/src/PhpSpreadsheet/Shared/Drawing.php', 'count' => 1, ]; $config['parameters']['ignoreErrors'][] = [ 'message' => '~^Property .* has unknown class GdImage as its type\.$~', 'path' => __DIR__ . '/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php', 'count' => 1, ]; $config['parameters']['ignoreErrors'][] = [ 'message' => '~^Method .* has invalid return type GdImage\.$~', 'path' => __DIR__ . '/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php', 'count' => 1, ]; $config['parameters']['ignoreErrors'][] = [ 'message' => '~^Parameter .* of method .* has invalid type GdImage\.$~', 'path' => __DIR__ . '/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php', 'count' => 1, ]; $config['parameters']['ignoreErrors'][] = [ 'message' => '~^Class GdImage not found\.$~', 'path' => __DIR__ . '/src/PhpSpreadsheet/Writer/Xls/Worksheet.php', 'count' => 1, ]; $config['parameters']['ignoreErrors'][] = [ 'message' => '~^Parameter .* of method .* has invalid type GdImage\.$~', 'path' => __DIR__ . '/src/PhpSpreadsheet/Writer/Xls/Worksheet.php', 'count' => 1, ]; // GdImage with Phpstan 1.9.2 $config['parameters']['ignoreErrors'][] = [ 'message' => '~Class GdImage not found.*$~', 'path' => __DIR__ . '/tests/PhpSpreadsheetTests/Worksheet/MemoryDrawingTest.php', 'count' => 3, ]; // Erroneous analysis by Phpstan before PHP8 - 3rd parameter is nullable // Fixed for Php7 with Phpstan 1.9. //$config['parameters']['ignoreErrors'][] = [ // 'message' => '#^Parameter \\#3 \\$namespace of method XMLWriter\\:\\:startElementNs\\(\\) expects string, null given\\.$#', // 'path' => __DIR__ . '/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php', // 'count' => 8, //]; // Erroneous analysis by Phpstan before PHP8 - mb_strlen does not return false $config['parameters']['ignoreErrors'][] = [ 'message' => '#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:countCharacters\\(\\) should return int but returns int(<0, max>)?\\|false\\.$#', 'path' => __DIR__ . '/src/PhpSpreadsheet/Shared/StringHelper.php', 'count' => 1, ]; // New with Phpstan 1.9.2 for Php7 only $config['parameters']['ignoreErrors'][] = [ 'message' => '#^Parameter \\#2 \\.\\.\\.\\$args of function array_merge expects array, array<int, mixed>\\|false given.$#', 'path' => __DIR__ . '/src/PhpSpreadsheet/Calculation/LookupRef/Sort.php', 'count' => 1, ]; $config['parameters']['ignoreErrors'][] = [ 'message' => '#^Parameter \\#1 \\$input of function array_chunk expects array, array<int, float\\|int>\\|false given.$#', 'path' => __DIR__ . '/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php', 'count' => 1, ]; $config['parameters']['ignoreErrors'][] = [ 'message' => '#^Parameter \\#2 \\$array of function array_map expects array, array<int, float|int>\\|false given.$#', 'path' => __DIR__ . '/src/PhpSpreadsheet/Calculation/MathTrig/Random.php', 'count' => 1, ]; $config['parameters']['ignoreErrors'][] = [ 'message' => '#^Parameter \\#2 \\.\\.\\.\\$args of function array_merge expects array, array<int, mixed>\\|false given.$#', 'path' => __DIR__ . '/src/PhpSpreadsheet/Calculation/TextData/Text.php', 'count' => 1, ]; } else { // Flagged in Php8+ - unsure how to correct code $config['parameters']['ignoreErrors'][] = [ 'message' => '#^Binary operation "/" between float and array[|]float[|]int[|]string results in an error.#', 'path' => __DIR__ . '/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php', 'count' => 1, ]; } return $config; phpspreadsheet/composer.json 0000644 00000007327 15002227416 0012315 0 ustar 00 { "name": "phpoffice/phpspreadsheet", "description": "PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine", "keywords": [ "PHP", "OpenXML", "Excel", "xlsx", "xls", "ods", "gnumeric", "spreadsheet" ], "config": { "sort-packages": true, "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true } }, "homepage": "https://github.com/PHPOffice/PhpSpreadsheet", "type": "library", "license": "MIT", "authors": [ { "name": "Maarten Balliauw", "homepage": "https://blog.maartenballiauw.be" }, { "name": "Mark Baker", "homepage": "https://markbakeruk.net" }, { "name": "Franck Lefevre", "homepage": "https://rootslabs.net" }, { "name": "Erik Tilt" }, { "name": "Adrien Crivelli" } ], "scripts": { "check": [ "phpcs src/ tests/ --report=checkstyle", "phpcs --report-width=200 samples/ src/ tests/ --ignore=samples/Header.php --standard=PHPCompatibility --runtime-set testVersion 7.4- -n", "php-cs-fixer fix --ansi --dry-run --diff", "phpunit --color=always", "phpstan analyse --ansi --memory-limit=2048M" ], "style": [ "phpcs src/ tests/ --report=checkstyle", "php-cs-fixer fix --ansi --dry-run --diff" ], "fix": [ "phpcbf src/ tests/ --report=checkstyle", "php-cs-fixer fix" ], "versions": [ "phpcs --report-width=200 samples/ src/ tests/ --ignore=samples/Header.php --standard=PHPCompatibility --runtime-set testVersion 7.4- -n" ] }, "require": { "php": "^7.4 || ^8.0", "ext-ctype": "*", "ext-dom": "*", "ext-fileinfo": "*", "ext-gd": "*", "ext-iconv": "*", "ext-libxml": "*", "ext-mbstring": "*", "ext-simplexml": "*", "ext-xml": "*", "ext-xmlreader": "*", "ext-xmlwriter": "*", "ext-zip": "*", "ext-zlib": "*", "ezyang/htmlpurifier": "^4.15", "maennchen/zipstream-php": "^2.1 || ^3.0", "markbaker/complex": "^3.0", "markbaker/matrix": "^3.0", "psr/http-client": "^1.0", "psr/http-factory": "^1.0", "psr/simple-cache": "^1.0 || ^2.0 || ^3.0" }, "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "dev-main", "dompdf/dompdf": "^1.0 || ^2.0", "friendsofphp/php-cs-fixer": "^3.2", "mitoteam/jpgraph": "^10.3", "mpdf/mpdf": "^8.1.1", "phpcompatibility/php-compatibility": "^9.3", "phpstan/phpstan": "^1.1", "phpstan/phpstan-phpunit": "^1.0", "phpunit/phpunit": "^8.5 || ^9.0 || ^10.0", "squizlabs/php_codesniffer": "^3.7", "tecnickcom/tcpdf": "^6.5" }, "suggest": { "ext-intl": "PHP Internationalization Functions", "mpdf/mpdf": "Option for rendering PDF with PDF Writer", "dompdf/dompdf": "Option for rendering PDF with PDF Writer", "tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer", "mitoteam/jpgraph": "Option for rendering charts, or including charts with PDF or HTML Writers" }, "autoload": { "psr-4": { "PhpOffice\\PhpSpreadsheet\\": "src/PhpSpreadsheet" } }, "autoload-dev": { "psr-4": { "PhpOffice\\PhpSpreadsheetTests\\": "tests/PhpSpreadsheetTests", "PhpOffice\\PhpSpreadsheetInfra\\": "infra" } } } phpspreadsheet/phpunit10.xml.dist 0000644 00000001151 15002227416 0013074 0 ustar 00 <?xml version="1.0" encoding="UTF-8"?> <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.1/phpunit.xsd" bootstrap="./tests/bootstrap.php" backupGlobals="true" colors="true" cacheResultFile="/tmp/.phpspreadsheet.phpunit.result.cache"> <coverage/> <php> <ini name="memory_limit" value="2048M"/> </php> <testsuite name="PhpSpreadsheet Unit Test Suite"> <directory>./tests/PhpSpreadsheetTests</directory> </testsuite> <source> <include> <directory suffix=".php">./src</directory> </include> </source> </phpunit> phpspreadsheet/.phpcs.xml.dist 0000644 00000001360 15002227416 0012441 0 ustar 00 <?xml version="1.0"?> <ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="PHP_CodeSniffer" xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd"> <file>samples</file> <file>src</file> <file>tests</file> <exclude-pattern>samples/Header.php</exclude-pattern> <exclude-pattern>*/tests/Core/*/*Test\.(inc|css|js)$</exclude-pattern> <arg name="report-width" value="200"/> <arg name="parallel" value="80"/> <arg name="cache" value="/tmp/.phpspreadsheet.phpcs-cache"/> <arg name="colors"/> <arg value="np"/> <!-- Include the whole PSR12 standard --> <rule ref="PSR12"> <exclude name="PSR2.Methods.MethodDeclaration.Underscore"/> </rule> </ruleset> phpspreadsheet/README.md 0000644 00000015013 15002227416 0011041 0 ustar 00 # PhpSpreadsheet [](https://github.com/PHPOffice/PhpSpreadsheet/actions) [](https://scrutinizer-ci.com/g/PHPOffice/PhpSpreadsheet/?branch=master) [](https://scrutinizer-ci.com/g/PHPOffice/PhpSpreadsheet/?branch=master) [](https://packagist.org/packages/phpoffice/phpspreadsheet) [](https://packagist.org/packages/phpoffice/phpspreadsheet) [](https://packagist.org/packages/phpoffice/phpspreadsheet) [](https://gitter.im/PHPOffice/PhpSpreadsheet) PhpSpreadsheet is a library written in pure PHP and offers a set of classes that allow you to read and write various spreadsheet file formats such as Excel and LibreOffice Calc. ## PHP Version Support LTS: Support for PHP versions will only be maintained for a period of six months beyond the [end of life](https://www.php.net/supported-versions) of that PHP version. Currently the required PHP minimum version is PHP __7.4__, and we [will support that version](https://www.php.net/eol.php) until 28th June 2023. See the `composer.json` for other requirements. ## Installation Use [composer](https://getcomposer.org) to install PhpSpreadsheet into your project: ```sh composer require phpoffice/phpspreadsheet ``` If you are building your installation on a development machine that is on a different PHP version to the server where it will be deployed, or if your PHP CLI version is not the same as your run-time such as `php-fpm` or Apache's `mod_php`, then you might want to add the following to your `composer.json` before installing: ```json { "require": { "phpoffice/phpspreadsheet": "^1.28" }, "config": { "platform": { "php": "7.4" } } } ``` and then run ```sh composer install ``` to ensure that the correct dependencies are retrieved to match your deployment environment. See [CLI vs Application run-time](https://php.watch/articles/composer-platform-check) for more details. ### Additional Installation Options If you want to write to PDF, or to include Charts when you write to HTML or PDF, then you will need to install additional libraries: #### PDF For PDF Generation, you can install any of the following, and then configure PhpSpreadsheet to indicate which library you are going to use: - mpdf/mpdf - dompdf/dompdf - tecnickcom/tcpdf and configure PhpSpreadsheet using: ```php // Dompdf, Mpdf or Tcpdf (as appropriate) $className = \PhpOffice\PhpSpreadsheet\Writer\Pdf\Dompdf::class; IOFactory::registerWriter('Pdf', $className); ``` or the appropriate PDF Writer wrapper for the library that you have chosen to install. #### Chart Export For Chart export, we support following packages, which you will also need to install yourself using `composer require` - [jpgraph/jpgraph](https://packagist.org/packages/jpgraph/jpgraph) (this package was abandoned at version 4.0. You can manually download the latest version that supports PHP 8 and above from [jpgraph.net](https://jpgraph.net/)) - [mitoteam/jpgraph](https://packagist.org/packages/mitoteam/jpgraph) - up to date fork with modern PHP versions support and some bugs fixed. and then configure PhpSpreadsheet using: ```php // to use jpgraph/jpgraph Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph::class); //or // to use mitoteam/jpgraph Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer::class); ``` One or the other of these libraries is necessary if you want to generate HTML or PDF files that include charts; or to render a Chart to an Image format from within your code. They are not necessary to define charts for writing to `Xlsx` files. Other file formats don't support writing Charts. ## Documentation Read more about it, including install instructions, in the [official documentation](https://phpspreadsheet.readthedocs.io). Or check out the [API documentation](https://phpoffice.github.io/PhpSpreadsheet). Please ask your support questions on [StackOverflow](https://stackoverflow.com/questions/tagged/phpspreadsheet), or have a quick chat on [Gitter](https://gitter.im/PHPOffice/PhpSpreadsheet). ## Patreon I am now running a [Patreon](https://www.patreon.com/MarkBaker) to support the work that I do on PhpSpreadsheet. Supporters will receive access to articles about working with PhpSpreadsheet, and how to use some of its more advanced features. Posts already available to Patreon supporters: - The Dating Game - A look at how MS Excel (and PhpSpreadsheet) handle date and time values. - Looping the Loop - Advice on Iterating through the rows and cells in a worksheet. And for Patrons at levels actively using PhpSpreadsheet: - Behind the Mask - A look at Number Format Masks. The Next Article (currently Work in Progress): - Formula for Success - How to debug formulae that don't produce the expected result. My aim is to post at least one article each month, taking a detailed look at some feature of MS Excel and how to use that feature in PhpSpreadsheet, or on how to perform different activities in PhpSpreadsheet. Planned posts for the future include topics like: - Tables - Structured References - AutoFiltering - Array Formulae - Conditional Formatting - Data Validation - Value Binders - Images - Charts After a period of six months exclusive to Patreon supporters, articles will be incorporated into the public documentation for the library. ## PHPExcel vs PhpSpreadsheet ? PhpSpreadsheet is the next version of PHPExcel. It breaks compatibility to dramatically improve the code base quality (namespaces, PSR compliance, use of latest PHP language features, etc.). Because all efforts have shifted to PhpSpreadsheet, PHPExcel will no longer be maintained. All contributions for PHPExcel, patches and new features, should target PhpSpreadsheet `master` branch. Do you need to migrate? There is [an automated tool](/docs/topics/migration-from-PHPExcel.md) for that. ## License PhpSpreadsheet is licensed under [MIT](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/LICENSE). phpspreadsheet/LICENSE 0000644 00000002067 15002227416 0010574 0 ustar 00 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. phpspreadsheet/phpstan-baseline.neon 0000644 00000002064 15002227416 0013702 0 ustar 00 parameters: ignoreErrors: - message: "#^Cannot call method getTokenSubType\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" count: 4 path: src/PhpSpreadsheet/Calculation/FormulaParser.php - message: "#^Cannot call method getTokenType\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" count: 9 path: src/PhpSpreadsheet/Calculation/FormulaParser.php - message: "#^Cannot call method setTokenSubType\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" count: 5 path: src/PhpSpreadsheet/Calculation/FormulaParser.php - message: "#^Cannot call method setValue\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" count: 5 path: src/PhpSpreadsheet/Calculation/FormulaParser.php - message: "#^Strict comparison using \\=\\=\\= between PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken and null will always evaluate to false\\.$#" count: 1 path: src/PhpSpreadsheet/Calculation/FormulaParser.php phpspreadsheet/src/PhpSpreadsheet/Writer/Xls.php 0000644 00000106340 15002227416 0016027 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; use PhpOffice\PhpSpreadsheet\Shared\Escher; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip; use PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\File; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\Root; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Writer\Xls\Parser; use PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook; use PhpOffice\PhpSpreadsheet\Writer\Xls\Worksheet; class Xls extends BaseWriter { /** * PhpSpreadsheet object. * * @var Spreadsheet */ private $spreadsheet; /** * Total number of shared strings in workbook. * * @var int */ private $strTotal = 0; /** * Number of unique shared strings in workbook. * * @var int */ private $strUnique = 0; /** * Array of unique shared strings in workbook. * * @var array */ private $strTable = []; /** * Color cache. Mapping between RGB value and color index. * * @var array */ private $colors; /** * Formula parser. * * @var Parser */ private $parser; /** * Identifier clusters for drawings. Used in MSODRAWINGGROUP record. * * @var array */ private $IDCLs; /** * Basic OLE object summary information. * * @var string */ private $summaryInformation; /** * Extended OLE object document summary information. * * @var string */ private $documentSummaryInformation; /** * @var Workbook */ private $writerWorkbook; /** * @var Worksheet[] */ private $writerWorksheets; /** * Create a new Xls Writer. * * @param Spreadsheet $spreadsheet PhpSpreadsheet object */ public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; $this->parser = new Xls\Parser($spreadsheet); } /** * Save Spreadsheet to file. * * @param resource|string $filename */ public function save($filename, int $flags = 0): void { $this->processFlags($flags); // garbage collect $this->spreadsheet->garbageCollect(); $saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog(); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false); $saveDateReturnType = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); // initialize colors array $this->colors = []; // Initialise workbook writer $this->writerWorkbook = new Xls\Workbook($this->spreadsheet, $this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser); // Initialise worksheet writers $countSheets = $this->spreadsheet->getSheetCount(); for ($i = 0; $i < $countSheets; ++$i) { $this->writerWorksheets[$i] = new Xls\Worksheet($this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser, $this->preCalculateFormulas, $this->spreadsheet->getSheet($i)); } // build Escher objects. Escher objects for workbooks needs to be build before Escher object for workbook. $this->buildWorksheetEschers(); $this->buildWorkbookEscher(); // add 15 identical cell style Xfs // for now, we use the first cellXf instead of cellStyleXf $cellXfCollection = $this->spreadsheet->getCellXfCollection(); for ($i = 0; $i < 15; ++$i) { $this->writerWorkbook->addXfWriter($cellXfCollection[0], true); } // add all the cell Xfs foreach ($this->spreadsheet->getCellXfCollection() as $style) { $this->writerWorkbook->addXfWriter($style, false); } // add fonts from rich text eleemnts for ($i = 0; $i < $countSheets; ++$i) { foreach ($this->writerWorksheets[$i]->phpSheet->getCellCollection()->getCoordinates() as $coordinate) { /** @var Cell $cell */ $cell = $this->writerWorksheets[$i]->phpSheet->getCellCollection()->get($coordinate); $cVal = $cell->getValue(); if ($cVal instanceof RichText) { $elements = $cVal->getRichTextElements(); foreach ($elements as $element) { if ($element instanceof Run) { $font = $element->getFont(); if ($font !== null) { $this->writerWorksheets[$i]->fontHashIndex[$font->getHashCode()] = $this->writerWorkbook->addFont($font); } } } } } } // initialize OLE file $workbookStreamName = 'Workbook'; $OLE = new File(OLE::ascToUcs($workbookStreamName)); // Write the worksheet streams before the global workbook stream, // because the byte sizes of these are needed in the global workbook stream $worksheetSizes = []; for ($i = 0; $i < $countSheets; ++$i) { $this->writerWorksheets[$i]->close(); $worksheetSizes[] = $this->writerWorksheets[$i]->_datasize; } // add binary data for global workbook stream $OLE->append($this->writerWorkbook->writeWorkbook($worksheetSizes)); // add binary data for sheet streams for ($i = 0; $i < $countSheets; ++$i) { $OLE->append($this->writerWorksheets[$i]->getData()); } $this->documentSummaryInformation = $this->writeDocumentSummaryInformation(); // initialize OLE Document Summary Information if (!empty($this->documentSummaryInformation)) { $OLE_DocumentSummaryInformation = new File(OLE::ascToUcs(chr(5) . 'DocumentSummaryInformation')); $OLE_DocumentSummaryInformation->append($this->documentSummaryInformation); } $this->summaryInformation = $this->writeSummaryInformation(); // initialize OLE Summary Information if (!empty($this->summaryInformation)) { $OLE_SummaryInformation = new File(OLE::ascToUcs(chr(5) . 'SummaryInformation')); $OLE_SummaryInformation->append($this->summaryInformation); } // define OLE Parts $arrRootData = [$OLE]; // initialize OLE Properties file if (isset($OLE_SummaryInformation)) { $arrRootData[] = $OLE_SummaryInformation; } // initialize OLE Extended Properties file if (isset($OLE_DocumentSummaryInformation)) { $arrRootData[] = $OLE_DocumentSummaryInformation; } $time = $this->spreadsheet->getProperties()->getModified(); $root = new Root($time, $time, $arrRootData); // save the OLE file $this->openFileHandle($filename); $root->save($this->fileHandle); $this->maybeCloseFileHandle(); Functions::setReturnDateType($saveDateReturnType); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); } /** * Build the Worksheet Escher objects. */ private function buildWorksheetEschers(): void { // 1-based index to BstoreContainer $blipIndex = 0; $lastReducedSpId = 0; $lastSpId = 0; foreach ($this->spreadsheet->getAllsheets() as $sheet) { // sheet index $sheetIndex = $sheet->getParentOrThrow()->getIndex($sheet); // check if there are any shapes for this sheet $filterRange = $sheet->getAutoFilter()->getRange(); if (count($sheet->getDrawingCollection()) == 0 && empty($filterRange)) { continue; } // create intermediate Escher object $escher = new Escher(); // dgContainer $dgContainer = new DgContainer(); // set the drawing index (we use sheet index + 1) $dgId = $sheet->getParentOrThrow()->getIndex($sheet) + 1; $dgContainer->setDgId($dgId); $escher->setDgContainer($dgContainer); // spgrContainer $spgrContainer = new SpgrContainer(); $dgContainer->setSpgrContainer($spgrContainer); // add one shape which is the group shape $spContainer = new SpContainer(); $spContainer->setSpgr(true); $spContainer->setSpType(0); $spContainer->setSpId(($sheet->getParentOrThrow()->getIndex($sheet) + 1) << 10); $spgrContainer->addChild($spContainer); // add the shapes $countShapes[$sheetIndex] = 0; // count number of shapes (minus group shape), in sheet foreach ($sheet->getDrawingCollection() as $drawing) { ++$blipIndex; ++$countShapes[$sheetIndex]; // add the shape $spContainer = new SpContainer(); // set the shape type $spContainer->setSpType(0x004B); // set the shape flag $spContainer->setSpFlag(0x02); // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index) $reducedSpId = $countShapes[$sheetIndex]; $spId = $reducedSpId | ($sheet->getParentOrThrow()->getIndex($sheet) + 1) << 10; $spContainer->setSpId($spId); // keep track of last reducedSpId $lastReducedSpId = $reducedSpId; // keep track of last spId $lastSpId = $spId; // set the BLIP index $spContainer->setOPT(0x4104, $blipIndex); // set coordinates and offsets, client anchor $coordinates = $drawing->getCoordinates(); $offsetX = $drawing->getOffsetX(); $offsetY = $drawing->getOffsetY(); $width = $drawing->getWidth(); $height = $drawing->getHeight(); $twoAnchor = \PhpOffice\PhpSpreadsheet\Shared\Xls::oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height); if (is_array($twoAnchor)) { $spContainer->setStartCoordinates($twoAnchor['startCoordinates']); $spContainer->setStartOffsetX($twoAnchor['startOffsetX']); $spContainer->setStartOffsetY($twoAnchor['startOffsetY']); $spContainer->setEndCoordinates($twoAnchor['endCoordinates']); $spContainer->setEndOffsetX($twoAnchor['endOffsetX']); $spContainer->setEndOffsetY($twoAnchor['endOffsetY']); $spgrContainer->addChild($spContainer); } } // AutoFilters if (!empty($filterRange)) { $rangeBounds = Coordinate::rangeBoundaries($filterRange); $iNumColStart = $rangeBounds[0][0]; $iNumColEnd = $rangeBounds[1][0]; $iInc = $iNumColStart; while ($iInc <= $iNumColEnd) { ++$countShapes[$sheetIndex]; // create an Drawing Object for the dropdown $oDrawing = new BaseDrawing(); // get the coordinates of drawing $cDrawing = Coordinate::stringFromColumnIndex($iInc) . $rangeBounds[0][1]; $oDrawing->setCoordinates($cDrawing); $oDrawing->setWorksheet($sheet); // add the shape $spContainer = new SpContainer(); // set the shape type $spContainer->setSpType(0x00C9); // set the shape flag $spContainer->setSpFlag(0x01); // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index) $reducedSpId = $countShapes[$sheetIndex]; $spId = $reducedSpId | ($sheet->getParentOrThrow()->getIndex($sheet) + 1) << 10; $spContainer->setSpId($spId); // keep track of last reducedSpId $lastReducedSpId = $reducedSpId; // keep track of last spId $lastSpId = $spId; $spContainer->setOPT(0x007F, 0x01040104); // Protection -> fLockAgainstGrouping $spContainer->setOPT(0x00BF, 0x00080008); // Text -> fFitTextToShape $spContainer->setOPT(0x01BF, 0x00010000); // Fill Style -> fNoFillHitTest $spContainer->setOPT(0x01FF, 0x00080000); // Line Style -> fNoLineDrawDash $spContainer->setOPT(0x03BF, 0x000A0000); // Group Shape -> fPrint // set coordinates and offsets, client anchor $endCoordinates = Coordinate::stringFromColumnIndex($iInc); $endCoordinates .= $rangeBounds[0][1] + 1; $spContainer->setStartCoordinates($cDrawing); $spContainer->setStartOffsetX(0); $spContainer->setStartOffsetY(0); $spContainer->setEndCoordinates($endCoordinates); $spContainer->setEndOffsetX(0); $spContainer->setEndOffsetY(0); $spgrContainer->addChild($spContainer); ++$iInc; } } // identifier clusters, used for workbook Escher object $this->IDCLs[$dgId] = $lastReducedSpId; // set last shape index $dgContainer->setLastSpId($lastSpId); // set the Escher object $this->writerWorksheets[$sheetIndex]->setEscher($escher); } } private function processMemoryDrawing(BstoreContainer &$bstoreContainer, MemoryDrawing $drawing, string $renderingFunctionx): void { switch ($renderingFunctionx) { case MemoryDrawing::RENDERING_JPEG: $blipType = BSE::BLIPTYPE_JPEG; $renderingFunction = 'imagejpeg'; break; default: $blipType = BSE::BLIPTYPE_PNG; $renderingFunction = 'imagepng'; break; } ob_start(); call_user_func($renderingFunction, $drawing->getImageResource()); $blipData = ob_get_contents(); ob_end_clean(); $blip = new Blip(); $blip->setData("$blipData"); $BSE = new BSE(); $BSE->setBlipType($blipType); $BSE->setBlip($blip); $bstoreContainer->addBSE($BSE); } private function processDrawing(BstoreContainer &$bstoreContainer, Drawing $drawing): void { $blipType = 0; $blipData = ''; $filename = $drawing->getPath(); $imageSize = getimagesize($filename); $imageFormat = empty($imageSize) ? 0 : ($imageSize[2] ?? 0); switch ($imageFormat) { case 1: // GIF, not supported by BIFF8, we convert to PNG $blipType = BSE::BLIPTYPE_PNG; $newImage = @imagecreatefromgif($filename); if ($newImage === false) { throw new Exception("Unable to create image from $filename"); } ob_start(); imagepng($newImage); $blipData = ob_get_contents(); ob_end_clean(); break; case 2: // JPEG $blipType = BSE::BLIPTYPE_JPEG; $blipData = file_get_contents($filename); break; case 3: // PNG $blipType = BSE::BLIPTYPE_PNG; $blipData = file_get_contents($filename); break; case 6: // Windows DIB (BMP), we convert to PNG $blipType = BSE::BLIPTYPE_PNG; $newImage = @imagecreatefrombmp($filename); if ($newImage === false) { throw new Exception("Unable to create image from $filename"); } ob_start(); imagepng($newImage); $blipData = ob_get_contents(); ob_end_clean(); break; } if ($blipData) { $blip = new Blip(); $blip->setData($blipData); $BSE = new BSE(); $BSE->setBlipType($blipType); $BSE->setBlip($blip); $bstoreContainer->addBSE($BSE); } } private function processBaseDrawing(BstoreContainer &$bstoreContainer, BaseDrawing $drawing): void { if ($drawing instanceof Drawing) { $this->processDrawing($bstoreContainer, $drawing); } elseif ($drawing instanceof MemoryDrawing) { $this->processMemoryDrawing($bstoreContainer, $drawing, $drawing->getRenderingFunction()); } } private function checkForDrawings(): bool { // any drawings in this workbook? $found = false; foreach ($this->spreadsheet->getAllSheets() as $sheet) { if (count($sheet->getDrawingCollection()) > 0) { $found = true; break; } } return $found; } /** * Build the Escher object corresponding to the MSODRAWINGGROUP record. */ private function buildWorkbookEscher(): void { // nothing to do if there are no drawings if (!$this->checkForDrawings()) { return; } // if we reach here, then there are drawings in the workbook $escher = new Escher(); // dggContainer $dggContainer = new DggContainer(); $escher->setDggContainer($dggContainer); // set IDCLs (identifier clusters) $dggContainer->setIDCLs($this->IDCLs); // this loop is for determining maximum shape identifier of all drawing $spIdMax = 0; $totalCountShapes = 0; $countDrawings = 0; foreach ($this->spreadsheet->getAllsheets() as $sheet) { $sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet $addCount = 0; foreach ($sheet->getDrawingCollection() as $drawing) { $addCount = 1; ++$sheetCountShapes; ++$totalCountShapes; $spId = $sheetCountShapes | ($this->spreadsheet->getIndex($sheet) + 1) << 10; $spIdMax = max($spId, $spIdMax); } $countDrawings += $addCount; } $dggContainer->setSpIdMax($spIdMax + 1); $dggContainer->setCDgSaved($countDrawings); $dggContainer->setCSpSaved($totalCountShapes + $countDrawings); // total number of shapes incl. one group shapes per drawing // bstoreContainer $bstoreContainer = new BstoreContainer(); $dggContainer->setBstoreContainer($bstoreContainer); // the BSE's (all the images) foreach ($this->spreadsheet->getAllsheets() as $sheet) { foreach ($sheet->getDrawingCollection() as $drawing) { $this->processBaseDrawing($bstoreContainer, $drawing); } } // Set the Escher object $this->writerWorkbook->setEscher($escher); } /** * Build the OLE Part for DocumentSummary Information. * * @return string */ private function writeDocumentSummaryInformation() { // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) $data = pack('v', 0xFFFE); // offset: 2; size: 2; $data .= pack('v', 0x0000); // offset: 4; size: 2; OS version $data .= pack('v', 0x0106); // offset: 6; size: 2; OS indicator $data .= pack('v', 0x0002); // offset: 8; size: 16 $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00); // offset: 24; size: 4; section count $data .= pack('V', 0x0001); // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae $data .= pack('vvvvvvvv', 0xD502, 0xD5CD, 0x2E9C, 0x101B, 0x9793, 0x0008, 0x2C2B, 0xAEF9); // offset: 44; size: 4; offset of the start $data .= pack('V', 0x30); // SECTION $dataSection = []; $dataSection_NumProps = 0; $dataSection_Summary = ''; $dataSection_Content = ''; // GKPIDDSI_CODEPAGE: CodePage $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x01], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x02], // 2 byte signed integer 'data' => ['data' => 1252], ]; ++$dataSection_NumProps; // GKPIDDSI_CATEGORY : Category $dataProp = $this->spreadsheet->getProperties()->getCategory(); if ($dataProp) { $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x02], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x1E], 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; ++$dataSection_NumProps; } // GKPIDDSI_VERSION :Version of the application that wrote the property storage $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x17], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x03], 'data' => ['pack' => 'V', 'data' => 0x000C0000], ]; ++$dataSection_NumProps; // GKPIDDSI_SCALE : FALSE $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x0B], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x0B], 'data' => ['data' => false], ]; ++$dataSection_NumProps; // GKPIDDSI_LINKSDIRTY : True if any of the values for the linked properties have changed outside of the application $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x10], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x0B], 'data' => ['data' => false], ]; ++$dataSection_NumProps; // GKPIDDSI_SHAREDOC : FALSE $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x13], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x0B], 'data' => ['data' => false], ]; ++$dataSection_NumProps; // GKPIDDSI_HYPERLINKSCHANGED : True if any of the values for the _PID_LINKS (hyperlink text) have changed outside of the application $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x16], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x0B], 'data' => ['data' => false], ]; ++$dataSection_NumProps; // GKPIDDSI_DOCSPARTS // MS-OSHARED p75 (2.3.3.2.2.1) // Structure is VtVecUnalignedLpstrValue (2.3.3.1.9) // cElements $dataProp = pack('v', 0x0001); $dataProp .= pack('v', 0x0000); // array of UnalignedLpstr // cch $dataProp .= pack('v', 0x000A); $dataProp .= pack('v', 0x0000); // value $dataProp .= 'Worksheet' . chr(0); $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x0D], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x101E], 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; ++$dataSection_NumProps; // GKPIDDSI_HEADINGPAIR // VtVecHeadingPairValue // cElements $dataProp = pack('v', 0x0002); $dataProp .= pack('v', 0x0000); // Array of vtHeadingPair // vtUnalignedString - headingString // stringType $dataProp .= pack('v', 0x001E); // padding $dataProp .= pack('v', 0x0000); // UnalignedLpstr // cch $dataProp .= pack('v', 0x0013); $dataProp .= pack('v', 0x0000); // value $dataProp .= 'Feuilles de calcul'; // vtUnalignedString - headingParts // wType : 0x0003 = 32 bit signed integer $dataProp .= pack('v', 0x0300); // padding $dataProp .= pack('v', 0x0000); // value $dataProp .= pack('v', 0x0100); $dataProp .= pack('v', 0x0000); $dataProp .= pack('v', 0x0000); $dataProp .= pack('v', 0x0000); $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x0C], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x100C], 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; ++$dataSection_NumProps; // 4 Section Length // 4 Property count // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4)) $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8; foreach ($dataSection as $dataProp) { // Summary $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']); // Offset $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset); // DataType $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']); // Data if ($dataProp['type']['data'] == 0x02) { // 2 byte signed integer $dataSection_Content .= pack('V', $dataProp['data']['data']); $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x03) { // 4 byte signed integer $dataSection_Content .= pack('V', $dataProp['data']['data']); $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x0B) { // Boolean $dataSection_Content .= pack('V', (int) $dataProp['data']['data']); $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length // Null-terminated string $dataProp['data']['data'] .= chr(0); ++$dataProp['data']['length']; // Complete the string with null string for being a %4 $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4)); $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); $dataSection_Content .= pack('V', $dataProp['data']['length']); $dataSection_Content .= $dataProp['data']['data']; $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']); /* Condition below can never be true } elseif ($dataProp['type']['data'] == 0x40) { // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) $dataSection_Content .= $dataProp['data']['data']; $dataSection_Content_Offset += 4 + 8; */ } else { $dataSection_Content .= $dataProp['data']['data']; $dataSection_Content_Offset += 4 + $dataProp['data']['length']; } } // Now $dataSection_Content_Offset contains the size of the content // section header // offset: $secOffset; size: 4; section length // + x Size of the content (summary + content) $data .= pack('V', $dataSection_Content_Offset); // offset: $secOffset+4; size: 4; property count $data .= pack('V', $dataSection_NumProps); // Section Summary $data .= $dataSection_Summary; // Section Content $data .= $dataSection_Content; return $data; } /** * @param float|int $dataProp */ private function writeSummaryPropOle($dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void { if ($dataProp) { $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => $sumdata], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => $typdata], // null-terminated string prepended by dword string length 'data' => ['data' => OLE::localDateToOLE($dataProp)], ]; ++$dataSection_NumProps; } } private function writeSummaryProp(string $dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void { if ($dataProp) { $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => $sumdata], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => $typdata], // null-terminated string prepended by dword string length 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], ]; ++$dataSection_NumProps; } } /** * Build the OLE Part for Summary Information. * * @return string */ private function writeSummaryInformation() { // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) $data = pack('v', 0xFFFE); // offset: 2; size: 2; $data .= pack('v', 0x0000); // offset: 4; size: 2; OS version $data .= pack('v', 0x0106); // offset: 6; size: 2; OS indicator $data .= pack('v', 0x0002); // offset: 8; size: 16 $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00); // offset: 24; size: 4; section count $data .= pack('V', 0x0001); // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9 $data .= pack('vvvvvvvv', 0x85E0, 0xF29F, 0x4FF9, 0x1068, 0x91AB, 0x0008, 0x272B, 0xD9B3); // offset: 44; size: 4; offset of the start $data .= pack('V', 0x30); // SECTION $dataSection = []; $dataSection_NumProps = 0; $dataSection_Summary = ''; $dataSection_Content = ''; // CodePage : CP-1252 $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x01], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x02], // 2 byte signed integer 'data' => ['data' => 1252], ]; ++$dataSection_NumProps; $props = $this->spreadsheet->getProperties(); $this->writeSummaryProp($props->getTitle(), $dataSection_NumProps, $dataSection, 0x02, 0x1e); $this->writeSummaryProp($props->getSubject(), $dataSection_NumProps, $dataSection, 0x03, 0x1e); $this->writeSummaryProp($props->getCreator(), $dataSection_NumProps, $dataSection, 0x04, 0x1e); $this->writeSummaryProp($props->getKeywords(), $dataSection_NumProps, $dataSection, 0x05, 0x1e); $this->writeSummaryProp($props->getDescription(), $dataSection_NumProps, $dataSection, 0x06, 0x1e); $this->writeSummaryProp($props->getLastModifiedBy(), $dataSection_NumProps, $dataSection, 0x08, 0x1e); $this->writeSummaryPropOle($props->getCreated(), $dataSection_NumProps, $dataSection, 0x0c, 0x40); $this->writeSummaryPropOle($props->getModified(), $dataSection_NumProps, $dataSection, 0x0d, 0x40); // Security $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x13], 'offset' => ['pack' => 'V'], 'type' => ['pack' => 'V', 'data' => 0x03], // 4 byte signed integer 'data' => ['data' => 0x00], ]; ++$dataSection_NumProps; // 4 Section Length // 4 Property count // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4)) $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8; foreach ($dataSection as $dataProp) { // Summary $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']); // Offset $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset); // DataType $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']); // Data if ($dataProp['type']['data'] == 0x02) { // 2 byte signed integer $dataSection_Content .= pack('V', $dataProp['data']['data']); $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x03) { // 4 byte signed integer $dataSection_Content .= pack('V', $dataProp['data']['data']); $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length // Null-terminated string $dataProp['data']['data'] .= chr(0); ++$dataProp['data']['length']; // Complete the string with null string for being a %4 $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4)); $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); $dataSection_Content .= pack('V', $dataProp['data']['length']); $dataSection_Content .= $dataProp['data']['data']; $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']); } elseif ($dataProp['type']['data'] == 0x40) { // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) $dataSection_Content .= $dataProp['data']['data']; $dataSection_Content_Offset += 4 + 8; } // Data Type Not Used at the moment } // Now $dataSection_Content_Offset contains the size of the content // section header // offset: $secOffset; size: 4; section length // + x Size of the content (summary + content) $data .= pack('V', $dataSection_Content_Offset); // offset: $secOffset+4; size: 4; property count $data .= pack('V', $dataSection_NumProps); // Section Summary $data .= $dataSection_Summary; // Section Content $data .= $dataSection_Content; return $data; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Csv.php 0000644 00000020065 15002227416 0016013 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Spreadsheet; class Csv extends BaseWriter { /** * PhpSpreadsheet object. * * @var Spreadsheet */ private $spreadsheet; /** * Delimiter. * * @var string */ private $delimiter = ','; /** * Enclosure. * * @var string */ private $enclosure = '"'; /** * Line ending. * * @var string */ private $lineEnding = PHP_EOL; /** * Sheet index to write. * * @var int */ private $sheetIndex = 0; /** * Whether to write a UTF8 BOM. * * @var bool */ private $useBOM = false; /** * Whether to write a Separator line as the first line of the file * sep=x. * * @var bool */ private $includeSeparatorLine = false; /** * Whether to write a fully Excel compatible CSV file. * * @var bool */ private $excelCompatibility = false; /** * Output encoding. * * @var string */ private $outputEncoding = ''; /** * Create a new CSV. */ public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; } /** * Save PhpSpreadsheet to file. * * @param resource|string $filename */ public function save($filename, int $flags = 0): void { $this->processFlags($flags); // Fetch sheet $sheet = $this->spreadsheet->getSheet($this->sheetIndex); $saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog(); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false); $saveArrayReturnType = Calculation::getArrayReturnType(); Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE); // Open file $this->openFileHandle($filename); if ($this->excelCompatibility) { $this->setUseBOM(true); // Enforce UTF-8 BOM Header $this->setIncludeSeparatorLine(true); // Set separator line $this->setEnclosure('"'); // Set enclosure to " $this->setDelimiter(';'); // Set delimiter to a semi-colon $this->setLineEnding("\r\n"); } if ($this->useBOM) { // Write the UTF-8 BOM code if required fwrite($this->fileHandle, "\xEF\xBB\xBF"); } if ($this->includeSeparatorLine) { // Write the separator line if required fwrite($this->fileHandle, 'sep=' . $this->getDelimiter() . $this->lineEnding); } // Identify the range that we need to extract from the worksheet $maxCol = $sheet->getHighestDataColumn(); $maxRow = $sheet->getHighestDataRow(); // Write rows to file for ($row = 1; $row <= $maxRow; ++$row) { // Convert the row to an array... $cellsArray = $sheet->rangeToArray('A' . $row . ':' . $maxCol . $row, '', $this->preCalculateFormulas); // ... and write to the file $this->writeLine($this->fileHandle, $cellsArray[0]); } $this->maybeCloseFileHandle(); Calculation::setArrayReturnType($saveArrayReturnType); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); } public function getDelimiter(): string { return $this->delimiter; } public function setDelimiter(string $delimiter): self { $this->delimiter = $delimiter; return $this; } public function getEnclosure(): string { return $this->enclosure; } public function setEnclosure(string $enclosure = '"'): self { $this->enclosure = $enclosure; return $this; } public function getLineEnding(): string { return $this->lineEnding; } public function setLineEnding(string $lineEnding): self { $this->lineEnding = $lineEnding; return $this; } /** * Get whether BOM should be used. */ public function getUseBOM(): bool { return $this->useBOM; } /** * Set whether BOM should be used, typically when non-ASCII characters are used. */ public function setUseBOM(bool $useBOM): self { $this->useBOM = $useBOM; return $this; } /** * Get whether a separator line should be included. */ public function getIncludeSeparatorLine(): bool { return $this->includeSeparatorLine; } /** * Set whether a separator line should be included as the first line of the file. */ public function setIncludeSeparatorLine(bool $includeSeparatorLine): self { $this->includeSeparatorLine = $includeSeparatorLine; return $this; } /** * Get whether the file should be saved with full Excel Compatibility. */ public function getExcelCompatibility(): bool { return $this->excelCompatibility; } /** * Set whether the file should be saved with full Excel Compatibility. * * @param bool $excelCompatibility Set the file to be written as a fully Excel compatible csv file * Note that this overrides other settings such as useBOM, enclosure and delimiter */ public function setExcelCompatibility(bool $excelCompatibility): self { $this->excelCompatibility = $excelCompatibility; return $this; } public function getSheetIndex(): int { return $this->sheetIndex; } public function setSheetIndex(int $sheetIndex): self { $this->sheetIndex = $sheetIndex; return $this; } public function getOutputEncoding(): string { return $this->outputEncoding; } public function setOutputEncoding(string $outputEnconding): self { $this->outputEncoding = $outputEnconding; return $this; } /** @var bool */ private $enclosureRequired = true; public function setEnclosureRequired(bool $value): self { $this->enclosureRequired = $value; return $this; } public function getEnclosureRequired(): bool { return $this->enclosureRequired; } /** * Convert boolean to TRUE/FALSE; otherwise return element cast to string. * * @param mixed $element */ private static function elementToString($element): string { if (is_bool($element)) { return $element ? 'TRUE' : 'FALSE'; } return (string) $element; } /** * Write line to CSV file. * * @param resource $fileHandle PHP filehandle * @param array $values Array containing values in a row */ private function writeLine($fileHandle, array $values): void { // No leading delimiter $delimiter = ''; // Build the line $line = ''; foreach ($values as $element) { $element = self::elementToString($element); // Add delimiter $line .= $delimiter; $delimiter = $this->delimiter; // Escape enclosures $enclosure = $this->enclosure; if ($enclosure) { // If enclosure is not required, use enclosure only if // element contains newline, delimiter, or enclosure. if (!$this->enclosureRequired && strpbrk($element, "$delimiter$enclosure\n") === false) { $enclosure = ''; } else { $element = str_replace($enclosure, $enclosure . $enclosure, $element); } } // Add enclosed string $line .= $enclosure . $element . $enclosure; } // Add line ending $line .= $this->lineEnding; // Write to file if ($this->outputEncoding != '') { $line = mb_convert_encoding($line, $this->outputEncoding); } fwrite($fileHandle, /** @scrutinizer ignore-type */ $line); } } phpspreadsheet/src/PhpSpreadsheet/Writer/ZipStream2.php 0000644 00000000651 15002227416 0017257 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; use ZipStream\Option\Archive; use ZipStream\ZipStream; class ZipStream2 { /** * @param resource $fileHandle */ public static function newZipStream($fileHandle): ZipStream { $options = new Archive(); $options->setEnableZip64(false); $options->setOutputStream($fileHandle); return new ZipStream(null, $options); } } phpspreadsheet/src/PhpSpreadsheet/Writer/BaseWriter.php 0000644 00000007102 15002227416 0017324 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; abstract class BaseWriter implements IWriter { /** * Write charts that are defined in the workbook? * Identifies whether the Writer should write definitions for any charts that exist in the PhpSpreadsheet object. * * @var bool */ protected $includeCharts = false; /** * Pre-calculate formulas * Forces PhpSpreadsheet to recalculate all formulae in a workbook when saving, so that the pre-calculated values are * immediately available to MS Excel or other office spreadsheet viewer when opening the file. * * @var bool */ protected $preCalculateFormulas = true; /** * Use disk caching where possible? * * @var bool */ private $useDiskCaching = false; /** * Disk caching directory. * * @var string */ private $diskCachingDirectory = './'; /** * @var resource */ protected $fileHandle; /** * @var bool */ private $shouldCloseFile; public function getIncludeCharts() { return $this->includeCharts; } public function setIncludeCharts($includeCharts) { $this->includeCharts = (bool) $includeCharts; return $this; } public function getPreCalculateFormulas() { return $this->preCalculateFormulas; } public function setPreCalculateFormulas($precalculateFormulas) { $this->preCalculateFormulas = (bool) $precalculateFormulas; return $this; } public function getUseDiskCaching() { return $this->useDiskCaching; } public function setUseDiskCaching($useDiskCache, $cacheDirectory = null) { $this->useDiskCaching = $useDiskCache; if ($cacheDirectory !== null) { if (is_dir($cacheDirectory)) { $this->diskCachingDirectory = $cacheDirectory; } else { throw new Exception("Directory does not exist: $cacheDirectory"); } } return $this; } public function getDiskCachingDirectory() { return $this->diskCachingDirectory; } protected function processFlags(int $flags): void { if (((bool) ($flags & self::SAVE_WITH_CHARTS)) === true) { $this->setIncludeCharts(true); } if (((bool) ($flags & self::DISABLE_PRECALCULATE_FORMULAE)) === true) { $this->setPreCalculateFormulas(false); } } /** * Open file handle. * * @param resource|string $filename */ public function openFileHandle($filename): void { if (is_resource($filename)) { $this->fileHandle = $filename; $this->shouldCloseFile = false; return; } $mode = 'wb'; $scheme = parse_url($filename, PHP_URL_SCHEME); if ($scheme === 's3') { // @codeCoverageIgnoreStart $mode = 'w'; // @codeCoverageIgnoreEnd } $fileHandle = $filename ? fopen($filename, $mode) : false; if ($fileHandle === false) { throw new Exception('Could not open file "' . $filename . '" for writing.'); } $this->fileHandle = $fileHandle; $this->shouldCloseFile = true; } /** * Close file handle only if we opened it ourselves. */ protected function maybeCloseFileHandle(): void { if ($this->shouldCloseFile) { if (!fclose($this->fileHandle)) { throw new Exception('Could not close file after writing.'); } } } } phpspreadsheet/src/PhpSpreadsheet/Writer/ZipStream3.php 0000644 00000000677 15002227416 0017270 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; use ZipStream\Option\Archive; use ZipStream\ZipStream; class ZipStream3 { /** * @param resource $fileHandle */ public static function newZipStream($fileHandle): ZipStream { return new ZipStream( enableZip64: false, outputStream: $fileHandle, sendHttpHeaders: false, defaultEnableZeroHeader: false, ); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php 0000644 00000006545 15002227416 0016666 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Pdf; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Writer\Html; use PhpOffice\PhpSpreadsheet\Writer\Pdf; class Mpdf extends Pdf { /** @var bool */ protected $isMPdf = true; /** * Gets the implementation of external PDF library that should be used. * * @param array $config Configuration array * * @return \Mpdf\Mpdf implementation */ protected function createExternalWriterInstance($config) { return new \Mpdf\Mpdf($config); } /** * Save Spreadsheet to file. * * @param string $filename Name of the file to save as */ public function save($filename, int $flags = 0): void { $fileHandle = parent::prepareForSave($filename); // Check for paper size and page orientation $setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup(); $orientation = $this->getOrientation() ?? $setup->getOrientation(); $orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; $printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize(); $paperSize = self::$paperSizes[$printPaperSize] ?? PageSetup::getPaperSizeDefault(); // Create PDF $config = ['tempDir' => $this->tempDir . '/mpdf']; $pdf = $this->createExternalWriterInstance($config); $ortmp = $orientation; $pdf->_setPageSize($paperSize, $ortmp); $pdf->DefOrientation = $orientation; $pdf->AddPageByArray([ 'orientation' => $orientation, 'margin-left' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getLeft()), 'margin-right' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getRight()), 'margin-top' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getTop()), 'margin-bottom' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getBottom()), ]); // Document info $pdf->SetTitle($this->spreadsheet->getProperties()->getTitle()); $pdf->SetAuthor($this->spreadsheet->getProperties()->getCreator()); $pdf->SetSubject($this->spreadsheet->getProperties()->getSubject()); $pdf->SetKeywords($this->spreadsheet->getProperties()->getKeywords()); $pdf->SetCreator($this->spreadsheet->getProperties()->getCreator()); $html = $this->generateHTMLAll(); $bodyLocation = strpos($html, Html::BODY_LINE); // Make sure first data presented to Mpdf includes body tag // so that Mpdf doesn't parse it as content. Issue 2432. if ($bodyLocation !== false) { $bodyLocation += strlen(Html::BODY_LINE); $pdf->WriteHTML(substr($html, 0, $bodyLocation)); $html = substr($html, $bodyLocation); } foreach (\array_chunk(\explode(PHP_EOL, $html), 1000) as $lines) { $pdf->WriteHTML(\implode(PHP_EOL, $lines)); } // Write to file fwrite($fileHandle, $pdf->Output('', 'S')); parent::restoreStateAfterSave(); } /** * Convert inches to mm. * * @param float $inches * * @return float */ private function inchesToMm($inches) { return $inches * 25.4; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php 0000644 00000005722 15002227416 0017034 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Pdf; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Writer\Pdf; class Tcpdf extends Pdf { /** * Create a new PDF Writer instance. * * @param Spreadsheet $spreadsheet Spreadsheet object */ public function __construct(Spreadsheet $spreadsheet) { parent::__construct($spreadsheet); $this->setUseInlineCss(true); } /** * Gets the implementation of external PDF library that should be used. * * @param string $orientation Page orientation * @param string $unit Unit measure * @param array|string $paperSize Paper size * * @return \TCPDF implementation */ protected function createExternalWriterInstance($orientation, $unit, $paperSize) { return new \TCPDF($orientation, $unit, $paperSize); } /** * Save Spreadsheet to file. * * @param string $filename Name of the file to save as */ public function save($filename, int $flags = 0): void { $fileHandle = parent::prepareForSave($filename); // Default PDF paper size $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) // Check for paper size and page orientation $setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup(); $orientation = $this->getOrientation() ?? $setup->getOrientation(); $orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; $printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize(); $paperSize = self::$paperSizes[$printPaperSize] ?? PageSetup::getPaperSizeDefault(); $printMargins = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageMargins(); // Create PDF $pdf = $this->createExternalWriterInstance($orientation, 'pt', $paperSize); $pdf->setFontSubsetting(false); // Set margins, converting inches to points (using 72 dpi) $pdf->SetMargins($printMargins->getLeft() * 72, $printMargins->getTop() * 72, $printMargins->getRight() * 72); $pdf->SetAutoPageBreak(true, $printMargins->getBottom() * 72); $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); $pdf->AddPage(); // Set the appropriate font $pdf->SetFont($this->getFont()); $pdf->writeHTML($this->generateHTMLAll()); // Document info $pdf->SetTitle($this->spreadsheet->getProperties()->getTitle()); $pdf->SetAuthor($this->spreadsheet->getProperties()->getCreator()); $pdf->SetSubject($this->spreadsheet->getProperties()->getSubject()); $pdf->SetKeywords($this->spreadsheet->getProperties()->getKeywords()); $pdf->SetCreator($this->spreadsheet->getProperties()->getCreator()); // Write to file fwrite($fileHandle, $pdf->output('', 'S')); parent::restoreStateAfterSave(); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php 0000644 00000003406 15002227416 0017202 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Pdf; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Writer\Pdf; class Dompdf extends Pdf { /** * embed images, or link to images. * * @var bool */ protected $embedImages = true; /** * Gets the implementation of external PDF library that should be used. * * @return \Dompdf\Dompdf implementation */ protected function createExternalWriterInstance() { return new \Dompdf\Dompdf(); } /** * Save Spreadsheet to file. * * @param string $filename Name of the file to save as */ public function save($filename, int $flags = 0): void { $fileHandle = parent::prepareForSave($filename); // Check for paper size and page orientation $setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup(); $orientation = $this->getOrientation() ?? $setup->getOrientation(); $orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; $printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize(); $paperSize = self::$paperSizes[$printPaperSize] ?? PageSetup::getPaperSizeDefault(); if (is_array($paperSize) && count($paperSize) === 2) { $paperSize = [0.0, 0.0, $paperSize[0], $paperSize[1]]; } $orientation = ($orientation == 'L') ? 'landscape' : 'portrait'; // Create PDF $pdf = $this->createExternalWriterInstance(); $pdf->setPaper($paperSize, $orientation); $pdf->loadHtml($this->generateHTMLAll()); $pdf->render(); // Write to file fwrite($fileHandle, $pdf->output() ?? ''); parent::restoreStateAfterSave(); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsVBA.php 0000644 00000002365 15002227416 0017457 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; class RelsVBA extends WriterPart { /** * Write relationships for a signed VBA Project. * * @return string XML Output */ public function writeVBARelationships() { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); $objWriter->startElement('Relationship'); $objWriter->writeAttribute('Id', 'rId1'); $objWriter->writeAttribute('Type', Namespaces::VBA_SIGNATURE); $objWriter->writeAttribute('Target', 'vbaProjectSignature.bin'); $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/AutoFilter.php 0000644 00000011516 15002227416 0020275 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as ActualWorksheet; class AutoFilter extends WriterPart { /** * Write AutoFilter. */ public static function writeAutoFilter(XMLWriter $objWriter, ActualWorksheet $worksheet): void { $autoFilterRange = $worksheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { // autoFilter $objWriter->startElement('autoFilter'); // Strip any worksheet reference from the filter coordinates $range = Coordinate::splitRange($autoFilterRange); $range = $range[0]; // Strip any worksheet ref [$ws, $range[0]] = ActualWorksheet::extractSheetTitle($range[0], true); $range = implode(':', $range); $objWriter->writeAttribute('ref', str_replace('$', '', $range)); $columns = $worksheet->getAutoFilter()->getColumns(); if (count($columns) > 0) { foreach ($columns as $columnID => $column) { $colId = $worksheet->getAutoFilter()->getColumnOffset($columnID); self::writeAutoFilterColumn($objWriter, $column, $colId); } } $objWriter->endElement(); } } /** * Write AutoFilter's filterColumn. */ public static function writeAutoFilterColumn(XMLWriter $objWriter, Column $column, int $colId): void { $rules = $column->getRules(); if (count($rules) > 0) { $objWriter->startElement('filterColumn'); $objWriter->writeAttribute('colId', "$colId"); $objWriter->startElement($column->getFilterType()); if ($column->getJoin() == Column::AUTOFILTER_COLUMN_JOIN_AND) { $objWriter->writeAttribute('and', '1'); } foreach ($rules as $rule) { self::writeAutoFilterColumnRule($column, $rule, $objWriter); } $objWriter->endElement(); $objWriter->endElement(); } } /** * Write AutoFilter's filterColumn Rule. */ private static function writeAutoFilterColumnRule(Column $column, Rule $rule, XMLWriter $objWriter): void { if ( ($column->getFilterType() === Column::AUTOFILTER_FILTERTYPE_FILTER) && ($rule->getOperator() === Rule::AUTOFILTER_COLUMN_RULE_EQUAL) && ($rule->getValue() === '') ) { // Filter rule for Blanks $objWriter->writeAttribute('blank', '1'); } elseif ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) { // Dynamic Filter Rule $objWriter->writeAttribute('type', $rule->getGrouping()); $val = $column->getAttribute('val'); if ($val !== null) { $objWriter->writeAttribute('val', "$val"); } $maxVal = $column->getAttribute('maxVal'); if ($maxVal !== null) { $objWriter->writeAttribute('maxVal', "$maxVal"); } } elseif ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) { // Top 10 Filter Rule $ruleValue = $rule->getValue(); if (!is_array($ruleValue)) { $objWriter->writeAttribute('val', "$ruleValue"); } $objWriter->writeAttribute('percent', (($rule->getOperator() === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0')); $objWriter->writeAttribute('top', (($rule->getGrouping() === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1' : '0')); } else { // Filter, DateGroupItem or CustomFilter $objWriter->startElement($rule->getRuleType()); if ($rule->getOperator() !== Rule::AUTOFILTER_COLUMN_RULE_EQUAL) { $objWriter->writeAttribute('operator', $rule->getOperator()); } if ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_DATEGROUP) { // Date Group filters $ruleValue = $rule->getValue(); if (is_array($ruleValue)) { foreach ($ruleValue as $key => $value) { $objWriter->writeAttribute($key, "$value"); } } $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping()); } else { $ruleValue = $rule->getValue(); if (!is_array($ruleValue)) { $objWriter->writeAttribute('val', "$ruleValue"); } } $objWriter->endElement(); } } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php 0000644 00000027532 15002227416 0020663 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; class ContentTypes extends WriterPart { /** * Write content types to XML format. * * @param bool $includeCharts Flag indicating if we should include drawing details for charts * * @return string XML Output */ public function writeContentTypes(Spreadsheet $spreadsheet, $includeCharts = false) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Types $objWriter->startElement('Types'); $objWriter->writeAttribute('xmlns', Namespaces::CONTENT_TYPES); // Theme $this->writeOverrideContentType($objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'); // Styles $this->writeOverrideContentType($objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'); // Rels $this->writeDefaultContentType($objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml'); // XML $this->writeDefaultContentType($objWriter, 'xml', 'application/xml'); // VML $this->writeDefaultContentType($objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'); // Workbook if ($spreadsheet->hasMacros()) { //Macros in workbook ? // Yes : not standard content but "macroEnabled" $this->writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.ms-excel.sheet.macroEnabled.main+xml'); //... and define a new type for the VBA project // Better use Override, because we can use 'bin' also for xl\printerSettings\printerSettings1.bin $this->writeOverrideContentType($objWriter, '/xl/vbaProject.bin', 'application/vnd.ms-office.vbaProject'); if ($spreadsheet->hasMacrosCertificate()) { // signed macros ? // Yes : add needed information $this->writeOverrideContentType($objWriter, '/xl/vbaProjectSignature.bin', 'application/vnd.ms-office.vbaProjectSignature'); } } else { // no macros in workbook, so standard type $this->writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'); } // DocProps $this->writeOverrideContentType($objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml'); $this->writeOverrideContentType($objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml'); $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); if (!empty($customPropertyList)) { $this->writeOverrideContentType($objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml'); } // Worksheets $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { $this->writeOverrideContentType($objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'); } // Shared strings $this->writeOverrideContentType($objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'); // Table $table = 1; for ($i = 0; $i < $sheetCount; ++$i) { $tableCount = $spreadsheet->getSheet($i)->getTableCollection()->count(); for ($t = 1; $t <= $tableCount; ++$t) { $this->writeOverrideContentType($objWriter, '/xl/tables/table' . $table++ . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml'); } } // Add worksheet relationship content types $unparsedLoadedData = $spreadsheet->getUnparsedLoadedData(); $chart = 1; for ($i = 0; $i < $sheetCount; ++$i) { $drawings = $spreadsheet->getSheet($i)->getDrawingCollection(); $drawingCount = count($drawings); $chartCount = ($includeCharts) ? $spreadsheet->getSheet($i)->getChartCount() : 0; $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$spreadsheet->getSheet($i)->getCodeName()]['drawingOriginalIds']); // We need a drawing relationship for the worksheet if we have either drawings or charts if (($drawingCount > 0) || ($chartCount > 0) || $hasUnparsedDrawing) { $this->writeOverrideContentType($objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml'); } // If we have charts, then we need a chart relationship for every individual chart if ($chartCount > 0) { for ($c = 0; $c < $chartCount; ++$c) { $this->writeOverrideContentType($objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'); } } } // Comments for ($i = 0; $i < $sheetCount; ++$i) { if (count($spreadsheet->getSheet($i)->getComments()) > 0) { $this->writeOverrideContentType($objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml'); } } // Add media content-types $aMediaContentTypes = []; $mediaCount = $this->getParentWriter()->getDrawingHashTable()->count(); for ($i = 0; $i < $mediaCount; ++$i) { $extension = ''; $mimeType = ''; if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing) { $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension()); $mimeType = $this->getImageMimeType($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath()); } elseif ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) { $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType()); $extension = explode('/', $extension); $extension = $extension[1]; $mimeType = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType(); } if (!isset($aMediaContentTypes[$extension])) { $aMediaContentTypes[$extension] = $mimeType; $this->writeDefaultContentType($objWriter, $extension, $mimeType); } } if ($spreadsheet->hasRibbonBinObjects()) { // Some additional objects in the ribbon ? // we need to write "Extension" but not already write for media content $tabRibbonTypes = array_diff($spreadsheet->getRibbonBinObjects('types') ?? [], array_keys($aMediaContentTypes)); foreach ($tabRibbonTypes as $aRibbonType) { $mimeType = 'image/.' . $aRibbonType; //we wrote $mimeType like customUI Editor $this->writeDefaultContentType($objWriter, $aRibbonType, $mimeType); } } $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { if (count($spreadsheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { foreach ($spreadsheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { if (!isset($aMediaContentTypes[strtolower($image->getExtension())])) { $aMediaContentTypes[strtolower($image->getExtension())] = $this->getImageMimeType($image->getPath()); $this->writeDefaultContentType($objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]); } } } if (count($spreadsheet->getSheet($i)->getComments()) > 0) { foreach ($spreadsheet->getSheet($i)->getComments() as $comment) { if (!$comment->hasBackgroundImage()) { continue; } $bgImage = $comment->getBackgroundImage(); $bgImageExtentionKey = strtolower($bgImage->getImageFileExtensionForSave(false)); if (!isset($aMediaContentTypes[$bgImageExtentionKey])) { $aMediaContentTypes[$bgImageExtentionKey] = $bgImage->getImageMimeType(); $this->writeDefaultContentType($objWriter, $bgImageExtentionKey, $aMediaContentTypes[$bgImageExtentionKey]); } } } } // unparsed defaults if (isset($unparsedLoadedData['default_content_types'])) { foreach ($unparsedLoadedData['default_content_types'] as $extName => $contentType) { $this->writeDefaultContentType($objWriter, $extName, $contentType); } } // unparsed overrides if (isset($unparsedLoadedData['override_content_types'])) { foreach ($unparsedLoadedData['override_content_types'] as $partName => $overrideType) { $this->writeOverrideContentType($objWriter, $partName, $overrideType); } } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Get image mime type. * * @param string $filename Filename * * @return string Mime Type */ private function getImageMimeType($filename) { if (File::fileExists($filename)) { $image = getimagesize($filename); return image_type_to_mime_type((is_array($image) && count($image) >= 3) ? $image[2] : 0); } throw new WriterException("File $filename does not exist"); } /** * Write Default content type. * * @param string $partName Part name * @param string $contentType Content type */ private function writeDefaultContentType(XMLWriter $objWriter, $partName, $contentType): void { if ($partName != '' && $contentType != '') { // Write content type $objWriter->startElement('Default'); $objWriter->writeAttribute('Extension', $partName); $objWriter->writeAttribute('ContentType', $contentType); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); } } /** * Write Override content type. * * @param string $partName Part name * @param string $contentType Content type */ private function writeOverrideContentType(XMLWriter $objWriter, $partName, $contentType): void { if ($partName != '' && $contentType != '') { // Write content type $objWriter->startElement('Override'); $objWriter->writeAttribute('PartName', $partName); $objWriter->writeAttribute('ContentType', $contentType); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); } } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php 0000644 00000021025 15002227416 0020535 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Exception; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as ActualWorksheet; class DefinedNames { /** @var XMLWriter */ private $objWriter; /** @var Spreadsheet */ private $spreadsheet; public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet) { $this->objWriter = $objWriter; $this->spreadsheet = $spreadsheet; } public function write(): void { // Write defined names $this->objWriter->startElement('definedNames'); // Named ranges if (count($this->spreadsheet->getDefinedNames()) > 0) { // Named ranges $this->writeNamedRangesAndFormulae(); } // Other defined names $sheetCount = $this->spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { // NamedRange for autoFilter $this->writeNamedRangeForAutofilter($this->spreadsheet->getSheet($i), $i); // NamedRange for Print_Titles $this->writeNamedRangeForPrintTitles($this->spreadsheet->getSheet($i), $i); // NamedRange for Print_Area $this->writeNamedRangeForPrintArea($this->spreadsheet->getSheet($i), $i); } $this->objWriter->endElement(); } /** * Write defined names. */ private function writeNamedRangesAndFormulae(): void { // Loop named ranges $definedNames = $this->spreadsheet->getDefinedNames(); foreach ($definedNames as $definedName) { $this->writeDefinedName($definedName); } } /** * Write Defined Name for named range. */ private function writeDefinedName(DefinedName $definedName): void { // definedName for named range $local = -1; if ($definedName->getLocalOnly() && $definedName->getScope() !== null) { try { $local = $definedName->getScope()->getParentOrThrow()->getIndex($definedName->getScope()); } catch (Exception $e) { // See issue 2266 - deleting sheet which contains // defined names will cause Exception above. return; } } $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', $definedName->getName()); if ($local >= 0) { $this->objWriter->writeAttribute( 'localSheetId', "$local" ); } $definedRange = $this->getDefinedRange($definedName); $this->objWriter->writeRawData($definedRange); $this->objWriter->endElement(); } /** * Write Defined Name for autoFilter. */ private function writeNamedRangeForAutofilter(ActualWorksheet $worksheet, int $worksheetId = 0): void { // NamedRange for autoFilter $autoFilterRange = $worksheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase'); $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); $this->objWriter->writeAttribute('hidden', '1'); // Create absolute coordinate and write as raw text $range = Coordinate::splitRange($autoFilterRange); $range = $range[0]; // Strip any worksheet ref so we can make the cell ref absolute [, $range[0]] = ActualWorksheet::extractSheetTitle($range[0], true); $range[0] = Coordinate::absoluteCoordinate($range[0]); if (count($range) > 1) { $range[1] = Coordinate::absoluteCoordinate($range[1]); } $range = implode(':', $range); $this->objWriter->writeRawData('\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!' . $range); $this->objWriter->endElement(); } } /** * Write Defined Name for PrintTitles. */ private function writeNamedRangeForPrintTitles(ActualWorksheet $worksheet, int $worksheetId = 0): void { // NamedRange for PrintTitles if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) { $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', '_xlnm.Print_Titles'); $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); // Setting string $settingString = ''; // Columns to repeat if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { $repeat = $worksheet->getPageSetup()->getColumnsToRepeatAtLeft(); $settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; } // Rows to repeat if ($worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) { if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { $settingString .= ','; } $repeat = $worksheet->getPageSetup()->getRowsToRepeatAtTop(); $settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; } $this->objWriter->writeRawData($settingString); $this->objWriter->endElement(); } } /** * Write Defined Name for PrintTitles. */ private function writeNamedRangeForPrintArea(ActualWorksheet $worksheet, int $worksheetId = 0): void { // NamedRange for PrintArea if ($worksheet->getPageSetup()->isPrintAreaSet()) { $this->objWriter->startElement('definedName'); $this->objWriter->writeAttribute('name', '_xlnm.Print_Area'); $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); // Print area $printArea = Coordinate::splitRange($worksheet->getPageSetup()->getPrintArea()); $chunks = []; foreach ($printArea as $printAreaRect) { $printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]); $printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]); $chunks[] = '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!' . implode(':', $printAreaRect); } $this->objWriter->writeRawData(implode(',', $chunks)); $this->objWriter->endElement(); } } private function getDefinedRange(DefinedName $definedName): string { $definedRange = $definedName->getValue(); $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', $definedRange, $splitRanges, PREG_OFFSET_CAPTURE ); $lengths = array_map('strlen', array_column($splitRanges[0], 0)); $offsets = array_column($splitRanges[0], 1); $worksheets = $splitRanges[2]; $columns = $splitRanges[6]; $rows = $splitRanges[7]; while ($splitCount > 0) { --$splitCount; $length = $lengths[$splitCount]; $offset = $offsets[$splitCount]; $worksheet = $worksheets[$splitCount][0]; $column = $columns[$splitCount][0]; $row = $rows[$splitCount][0]; $newRange = ''; if (empty($worksheet)) { if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) { // We should have a worksheet $ws = $definedName->getWorksheet(); $worksheet = ($ws === null) ? null : $ws->getTitle(); } } else { $worksheet = str_replace("''", "'", trim($worksheet, "'")); } if (!empty($worksheet)) { $newRange = "'" . str_replace("'", "''", $worksheet) . "'!"; } $newRange = "{$newRange}{$column}{$row}"; $definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length); } if (substr($definedRange, 0, 1) === '=') { $definedRange = substr($definedRange, 1); } return $definedRange; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php 0000644 00000031550 15002227416 0020435 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Chart\ChartColor; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as ActualWorksheet; class StringTable extends WriterPart { /** * Create worksheet stringtable. * * @param string[] $existingTable Existing table to eventually merge with * * @return string[] String table for worksheet */ public function createStringTable(ActualWorksheet $worksheet, $existingTable = null) { // Create string lookup table $aStringTable = []; // Is an existing table given? if (($existingTable !== null) && is_array($existingTable)) { $aStringTable = $existingTable; } // Fill index array $aFlippedStringTable = $this->flipStringTable($aStringTable); // Loop through cells foreach ($worksheet->getCellCollection()->getCoordinates() as $coordinate) { /** @var Cell $cell */ $cell = $worksheet->getCellCollection()->get($coordinate); $cellValue = $cell->getValue(); if ( !is_object($cellValue) && ($cellValue !== null) && $cellValue !== '' && ($cell->getDataType() == DataType::TYPE_STRING || $cell->getDataType() == DataType::TYPE_STRING2 || $cell->getDataType() == DataType::TYPE_NULL) && !isset($aFlippedStringTable[$cellValue]) ) { $aStringTable[] = $cellValue; $aFlippedStringTable[$cellValue] = true; } elseif ( $cellValue instanceof RichText && ($cellValue !== null) && !isset($aFlippedStringTable[$cellValue->getHashCode()]) ) { $aStringTable[] = $cellValue; $aFlippedStringTable[$cellValue->getHashCode()] = true; } } return $aStringTable; } /** * Write string table to XML format. * * @param (RichText|string)[] $stringTable * * @return string XML Output */ public function writeStringTable(array $stringTable) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // String table $objWriter->startElement('sst'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); $objWriter->writeAttribute('uniqueCount', (string) count($stringTable)); // Loop through string table foreach ($stringTable as $textElement) { $objWriter->startElement('si'); if (!($textElement instanceof RichText)) { $textToWrite = StringHelper::controlCharacterPHP2OOXML($textElement); $objWriter->startElement('t'); if ($textToWrite !== trim($textToWrite)) { $objWriter->writeAttribute('xml:space', 'preserve'); } $objWriter->writeRawData($textToWrite); $objWriter->endElement(); } else { $this->writeRichText($objWriter, $textElement); } $objWriter->endElement(); } $objWriter->endElement(); return $objWriter->getData(); } /** * Write Rich Text. * * @param string $prefix Optional Namespace prefix */ public function writeRichText(XMLWriter $objWriter, RichText $richText, $prefix = null): void { if ($prefix !== null) { $prefix .= ':'; } // Loop through rich text elements $elements = $richText->getRichTextElements(); foreach ($elements as $element) { // r $objWriter->startElement($prefix . 'r'); // rPr if ($element instanceof Run && $element->getFont() !== null) { // rPr $objWriter->startElement($prefix . 'rPr'); // rFont if ($element->getFont()->getName() !== null) { $objWriter->startElement($prefix . 'rFont'); $objWriter->writeAttribute('val', $element->getFont()->getName()); $objWriter->endElement(); } // Bold $objWriter->startElement($prefix . 'b'); $objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false')); $objWriter->endElement(); // Italic $objWriter->startElement($prefix . 'i'); $objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false')); $objWriter->endElement(); // Superscript / subscript if ($element->getFont()->getSuperscript() || $element->getFont()->getSubscript()) { $objWriter->startElement($prefix . 'vertAlign'); if ($element->getFont()->getSuperscript()) { $objWriter->writeAttribute('val', 'superscript'); } elseif ($element->getFont()->getSubscript()) { $objWriter->writeAttribute('val', 'subscript'); } $objWriter->endElement(); } // Strikethrough $objWriter->startElement($prefix . 'strike'); $objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false')); $objWriter->endElement(); // Color if ($element->getFont()->getColor()->getARGB() !== null) { $objWriter->startElement($prefix . 'color'); $objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB()); $objWriter->endElement(); } // Size if ($element->getFont()->getSize() !== null) { $objWriter->startElement($prefix . 'sz'); $objWriter->writeAttribute('val', (string) $element->getFont()->getSize()); $objWriter->endElement(); } // Underline if ($element->getFont()->getUnderline() !== null) { $objWriter->startElement($prefix . 'u'); $objWriter->writeAttribute('val', $element->getFont()->getUnderline()); $objWriter->endElement(); } $objWriter->endElement(); } // t $objWriter->startElement($prefix . 't'); $objWriter->writeAttribute('xml:space', 'preserve'); $objWriter->writeRawData(StringHelper::controlCharacterPHP2OOXML($element->getText())); $objWriter->endElement(); $objWriter->endElement(); } } /** * Write Rich Text. * * @param RichText|string $richText text string or Rich text * @param string $prefix Optional Namespace prefix */ public function writeRichTextForCharts(XMLWriter $objWriter, $richText = null, $prefix = ''): void { if (!($richText instanceof RichText)) { $textRun = $richText; $richText = new RichText(); $run = $richText->createTextRun($textRun ?? ''); $run->setFont(null); } if ($prefix !== '') { $prefix .= ':'; } // Loop through rich text elements $elements = $richText->getRichTextElements(); foreach ($elements as $element) { // r $objWriter->startElement($prefix . 'r'); if ($element->getFont() !== null) { // rPr $objWriter->startElement($prefix . 'rPr'); $fontSize = $element->getFont()->getSize(); if (is_numeric($fontSize)) { $fontSize *= (($fontSize < 100) ? 100 : 1); $objWriter->writeAttribute('sz', (string) $fontSize); } // Bold $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? '1' : '0')); // Italic $objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? '1' : '0')); // Underline $underlineType = $element->getFont()->getUnderline(); switch ($underlineType) { case 'single': $underlineType = 'sng'; break; case 'double': $underlineType = 'dbl'; break; } if ($underlineType !== null) { $objWriter->writeAttribute('u', $underlineType); } // Strikethrough $objWriter->writeAttribute('strike', ($element->getFont()->getStriketype() ?: 'noStrike')); // Superscript/subscript if ($element->getFont()->getBaseLine()) { $objWriter->writeAttribute('baseline', (string) $element->getFont()->getBaseLine()); } // Color $this->writeChartTextColor($objWriter, $element->getFont()->getChartColor(), $prefix); // Underscore Color $this->writeChartTextColor($objWriter, $element->getFont()->getUnderlineColor(), $prefix, 'uFill'); // fontName if ($element->getFont()->getLatin()) { $objWriter->startElement($prefix . 'latin'); $objWriter->writeAttribute('typeface', $element->getFont()->getLatin()); $objWriter->endElement(); } if ($element->getFont()->getEastAsian()) { $objWriter->startElement($prefix . 'ea'); $objWriter->writeAttribute('typeface', $element->getFont()->getEastAsian()); $objWriter->endElement(); } if ($element->getFont()->getComplexScript()) { $objWriter->startElement($prefix . 'cs'); $objWriter->writeAttribute('typeface', $element->getFont()->getComplexScript()); $objWriter->endElement(); } $objWriter->endElement(); } // t $objWriter->startElement($prefix . 't'); $objWriter->writeRawData(StringHelper::controlCharacterPHP2OOXML($element->getText())); $objWriter->endElement(); $objWriter->endElement(); } } private function writeChartTextColor(XMLWriter $objWriter, ?ChartColor $underlineColor, string $prefix, ?string $openTag = ''): void { if ($underlineColor !== null) { $type = $underlineColor->getType(); $value = $underlineColor->getValue(); if (!empty($type) && !empty($value)) { if ($openTag !== '') { $objWriter->startElement($prefix . $openTag); } $objWriter->startElement($prefix . 'solidFill'); $objWriter->startElement($prefix . $type); $objWriter->writeAttribute('val', $value); $alpha = $underlineColor->getAlpha(); if (is_numeric($alpha)) { $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', ChartColor::alphaToXml((int) $alpha)); $objWriter->endElement(); } $objWriter->endElement(); // srgbClr/schemeClr/prstClr $objWriter->endElement(); // solidFill if ($openTag !== '') { $objWriter->endElement(); // uFill } } } } /** * Flip string table (for index searching). * * @param array $stringTable Stringtable * * @return array */ public function flipStringTable(array $stringTable) { // Return value $returnValue = []; // Loop through stringtable and add flipped items to $returnValue foreach ($stringTable as $key => $value) { if (!$value instanceof RichText) { $returnValue[$value] = $key; } elseif ($value instanceof RichText) { $returnValue[$value->getHashCode()] = $key; } } return $returnValue; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Theme.php 0000644 00000052234 15002227416 0017263 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Theme as SpreadsheetTheme; class Theme extends WriterPart { /** * Write theme to XML format. * * @return string XML Output */ public function writeTheme(Spreadsheet $spreadsheet) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } $theme = $spreadsheet->getTheme(); // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // a:theme $objWriter->startElement('a:theme'); $objWriter->writeAttribute('xmlns:a', Namespaces::DRAWINGML); $objWriter->writeAttribute('name', 'Office Theme'); // a:themeElements $objWriter->startElement('a:themeElements'); // a:clrScheme $objWriter->startElement('a:clrScheme'); $objWriter->writeAttribute('name', $theme->getThemeColorName()); $this->writeColourScheme($objWriter, $theme); $objWriter->endElement(); // a:fontScheme $objWriter->startElement('a:fontScheme'); $objWriter->writeAttribute('name', $theme->getThemeFontName()); // a:majorFont $objWriter->startElement('a:majorFont'); $this->writeFonts( $objWriter, $theme->getMajorFontLatin(), $theme->getMajorFontEastAsian(), $theme->getMajorFontComplexScript(), $theme->getMajorFontSubstitutions() ); $objWriter->endElement(); // a:majorFont // a:minorFont $objWriter->startElement('a:minorFont'); $this->writeFonts( $objWriter, $theme->getMinorFontLatin(), $theme->getMinorFontEastAsian(), $theme->getMinorFontComplexScript(), $theme->getMinorFontSubstitutions() ); $objWriter->endElement(); // a:minorFont $objWriter->endElement(); // a:fontScheme // a:fmtScheme $objWriter->startElement('a:fmtScheme'); $objWriter->writeAttribute('name', 'Office'); // a:fillStyleLst $objWriter->startElement('a:fillStyleLst'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); $objWriter->endElement(); $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '50000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '300000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '35000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '37000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '300000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '15000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '350000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:lin $objWriter->startElement('a:lin'); $objWriter->writeAttribute('ang', '16200000'); $objWriter->writeAttribute('scaled', '1'); $objWriter->endElement(); $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '51000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '130000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '80000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '93000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '130000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '94000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '135000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:lin $objWriter->startElement('a:lin'); $objWriter->writeAttribute('ang', '16200000'); $objWriter->writeAttribute('scaled', '0'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:lnStyleLst $objWriter->startElement('a:lnStyleLst'); // a:ln $objWriter->startElement('a:ln'); $objWriter->writeAttribute('w', '9525'); $objWriter->writeAttribute('cap', 'flat'); $objWriter->writeAttribute('cmpd', 'sng'); $objWriter->writeAttribute('algn', 'ctr'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '95000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '105000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:prstDash $objWriter->startElement('a:prstDash'); $objWriter->writeAttribute('val', 'solid'); $objWriter->endElement(); $objWriter->endElement(); // a:ln $objWriter->startElement('a:ln'); $objWriter->writeAttribute('w', '25400'); $objWriter->writeAttribute('cap', 'flat'); $objWriter->writeAttribute('cmpd', 'sng'); $objWriter->writeAttribute('algn', 'ctr'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); $objWriter->endElement(); $objWriter->endElement(); // a:prstDash $objWriter->startElement('a:prstDash'); $objWriter->writeAttribute('val', 'solid'); $objWriter->endElement(); $objWriter->endElement(); // a:ln $objWriter->startElement('a:ln'); $objWriter->writeAttribute('w', '38100'); $objWriter->writeAttribute('cap', 'flat'); $objWriter->writeAttribute('cmpd', 'sng'); $objWriter->writeAttribute('algn', 'ctr'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); $objWriter->endElement(); $objWriter->endElement(); // a:prstDash $objWriter->startElement('a:prstDash'); $objWriter->writeAttribute('val', 'solid'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:effectStyleLst $objWriter->startElement('a:effectStyleLst'); // a:effectStyle $objWriter->startElement('a:effectStyle'); // a:effectLst $objWriter->startElement('a:effectLst'); // a:outerShdw $objWriter->startElement('a:outerShdw'); $objWriter->writeAttribute('blurRad', '40000'); $objWriter->writeAttribute('dist', '20000'); $objWriter->writeAttribute('dir', '5400000'); $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); $objWriter->writeAttribute('val', '000000'); // a:alpha $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', '38000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:effectStyle $objWriter->startElement('a:effectStyle'); // a:effectLst $objWriter->startElement('a:effectLst'); // a:outerShdw $objWriter->startElement('a:outerShdw'); $objWriter->writeAttribute('blurRad', '40000'); $objWriter->writeAttribute('dist', '23000'); $objWriter->writeAttribute('dir', '5400000'); $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); $objWriter->writeAttribute('val', '000000'); // a:alpha $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', '35000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:effectStyle $objWriter->startElement('a:effectStyle'); // a:effectLst $objWriter->startElement('a:effectLst'); // a:outerShdw $objWriter->startElement('a:outerShdw'); $objWriter->writeAttribute('blurRad', '40000'); $objWriter->writeAttribute('dist', '23000'); $objWriter->writeAttribute('dir', '5400000'); $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); $objWriter->writeAttribute('val', '000000'); // a:alpha $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', '35000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:scene3d $objWriter->startElement('a:scene3d'); // a:camera $objWriter->startElement('a:camera'); $objWriter->writeAttribute('prst', 'orthographicFront'); // a:rot $objWriter->startElement('a:rot'); $objWriter->writeAttribute('lat', '0'); $objWriter->writeAttribute('lon', '0'); $objWriter->writeAttribute('rev', '0'); $objWriter->endElement(); $objWriter->endElement(); // a:lightRig $objWriter->startElement('a:lightRig'); $objWriter->writeAttribute('rig', 'threePt'); $objWriter->writeAttribute('dir', 't'); // a:rot $objWriter->startElement('a:rot'); $objWriter->writeAttribute('lat', '0'); $objWriter->writeAttribute('lon', '0'); $objWriter->writeAttribute('rev', '1200000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:sp3d $objWriter->startElement('a:sp3d'); // a:bevelT $objWriter->startElement('a:bevelT'); $objWriter->writeAttribute('w', '63500'); $objWriter->writeAttribute('h', '25400'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:bgFillStyleLst $objWriter->startElement('a:bgFillStyleLst'); // a:solidFill $objWriter->startElement('a:solidFill'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); $objWriter->endElement(); $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '40000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '350000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '40000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '45000'); $objWriter->endElement(); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '99000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '350000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '20000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '255000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:path $objWriter->startElement('a:path'); $objWriter->writeAttribute('path', 'circle'); // a:fillToRect $objWriter->startElement('a:fillToRect'); $objWriter->writeAttribute('l', '50000'); $objWriter->writeAttribute('t', '-80000'); $objWriter->writeAttribute('r', '50000'); $objWriter->writeAttribute('b', '180000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gradFill $objWriter->startElement('a:gradFill'); $objWriter->writeAttribute('rotWithShape', '1'); // a:gsLst $objWriter->startElement('a:gsLst'); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '0'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:tint $objWriter->startElement('a:tint'); $objWriter->writeAttribute('val', '80000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '300000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:gs $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', '100000'); // a:schemeClr $objWriter->startElement('a:schemeClr'); $objWriter->writeAttribute('val', 'phClr'); // a:shade $objWriter->startElement('a:shade'); $objWriter->writeAttribute('val', '30000'); $objWriter->endElement(); // a:satMod $objWriter->startElement('a:satMod'); $objWriter->writeAttribute('val', '200000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:path $objWriter->startElement('a:path'); $objWriter->writeAttribute('path', 'circle'); // a:fillToRect $objWriter->startElement('a:fillToRect'); $objWriter->writeAttribute('l', '50000'); $objWriter->writeAttribute('t', '50000'); $objWriter->writeAttribute('r', '50000'); $objWriter->writeAttribute('b', '50000'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // a:objectDefaults $objWriter->writeElement('a:objectDefaults', null); // a:extraClrSchemeLst $objWriter->writeElement('a:extraClrSchemeLst', null); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write fonts to XML format. * * @param string[] $fontSet */ private function writeFonts(XMLWriter $objWriter, string $latinFont, string $eastAsianFont, string $complexScriptFont, array $fontSet): void { // a:latin $objWriter->startElement('a:latin'); $objWriter->writeAttribute('typeface', $latinFont); $objWriter->endElement(); // a:ea $objWriter->startElement('a:ea'); $objWriter->writeAttribute('typeface', $eastAsianFont); $objWriter->endElement(); // a:cs $objWriter->startElement('a:cs'); $objWriter->writeAttribute('typeface', $complexScriptFont); $objWriter->endElement(); foreach ($fontSet as $fontScript => $typeface) { $objWriter->startElement('a:font'); $objWriter->writeAttribute('script', $fontScript); $objWriter->writeAttribute('typeface', $typeface); $objWriter->endElement(); } } /** * Write colour scheme to XML format. */ private function writeColourScheme(XMLWriter $objWriter, SpreadsheetTheme $theme): void { $themeArray = $theme->getThemeColors(); // a:dk1 $objWriter->startElement('a:dk1'); $objWriter->startElement('a:sysClr'); $objWriter->writeAttribute('val', 'windowText'); $objWriter->writeAttribute('lastClr', $themeArray['dk1'] ?? '000000'); $objWriter->endElement(); // a:sysClr $objWriter->endElement(); // a:dk1 // a:lt1 $objWriter->startElement('a:lt1'); $objWriter->startElement('a:sysClr'); $objWriter->writeAttribute('val', 'window'); $objWriter->writeAttribute('lastClr', $themeArray['lt1'] ?? 'FFFFFF'); $objWriter->endElement(); // a:sysClr $objWriter->endElement(); // a:lt1 foreach ($themeArray as $colourName => $colourValue) { if ($colourName !== 'dk1' && $colourName !== 'lt1') { $objWriter->startElement('a:' . $colourName); $objWriter->startElement('a:srgbClr'); $objWriter->writeAttribute('val', $colourValue); $objWriter->endElement(); // a:srgbClr $objWriter->endElement(); // a:$colourName } } } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php 0000644 00000052451 15002227416 0017615 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; class Drawing extends WriterPart { /** * Write drawings to XML format. * * @param bool $includeCharts Flag indicating if we should include drawing details for charts * * @return string XML Output */ public function writeDrawings(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, $includeCharts = false) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // xdr:wsDr $objWriter->startElement('xdr:wsDr'); $objWriter->writeAttribute('xmlns:xdr', Namespaces::SPREADSHEET_DRAWING); $objWriter->writeAttribute('xmlns:a', Namespaces::DRAWINGML); // Loop through images and write drawings $i = 1; $iterator = $worksheet->getDrawingCollection()->getIterator(); while ($iterator->valid()) { /** @var BaseDrawing $pDrawing */ $pDrawing = $iterator->current(); $pRelationId = $i; $hlinkClickId = $pDrawing->getHyperlink() === null ? null : ++$i; $this->writeDrawing($objWriter, $pDrawing, $pRelationId, $hlinkClickId); $iterator->next(); ++$i; } if ($includeCharts) { $chartCount = $worksheet->getChartCount(); // Loop through charts and write the chart position if ($chartCount > 0) { for ($c = 0; $c < $chartCount; ++$c) { $chart = $worksheet->getChartByIndex((string) $c); if ($chart !== false) { $this->writeChart($objWriter, $chart, $c + $i); } } } } // unparsed AlternateContent $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingAlternateContents'])) { foreach ($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingAlternateContents'] as $drawingAlternateContent) { $objWriter->writeRaw($drawingAlternateContent); } } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write drawings to XML format. * * @param int $relationId */ public function writeChart(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Chart\Chart $chart, $relationId = -1): void { $tl = $chart->getTopLeftPosition(); $tlColRow = Coordinate::indexesFromString($tl['cell']); $br = $chart->getBottomRightPosition(); $isTwoCellAnchor = $br['cell'] !== ''; if ($isTwoCellAnchor) { $brColRow = Coordinate::indexesFromString($br['cell']); $objWriter->startElement('xdr:twoCellAnchor'); $objWriter->startElement('xdr:from'); $objWriter->writeElement('xdr:col', (string) ($tlColRow[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($tl['xOffset'])); $objWriter->writeElement('xdr:row', (string) ($tlColRow[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($tl['yOffset'])); $objWriter->endElement(); $objWriter->startElement('xdr:to'); $objWriter->writeElement('xdr:col', (string) ($brColRow[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($br['xOffset'])); $objWriter->writeElement('xdr:row', (string) ($brColRow[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($br['yOffset'])); $objWriter->endElement(); } elseif ($chart->getOneCellAnchor()) { $objWriter->startElement('xdr:oneCellAnchor'); $objWriter->startElement('xdr:from'); $objWriter->writeElement('xdr:col', (string) ($tlColRow[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($tl['xOffset'])); $objWriter->writeElement('xdr:row', (string) ($tlColRow[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($tl['yOffset'])); $objWriter->endElement(); $objWriter->startElement('xdr:ext'); $objWriter->writeAttribute('cx', self::stringEmu($br['xOffset'])); $objWriter->writeAttribute('cy', self::stringEmu($br['yOffset'])); $objWriter->endElement(); } else { $objWriter->startElement('xdr:absoluteAnchor'); $objWriter->startElement('xdr:pos'); $objWriter->writeAttribute('x', '0'); $objWriter->writeAttribute('y', '0'); $objWriter->endElement(); $objWriter->startElement('xdr:ext'); $objWriter->writeAttribute('cx', self::stringEmu($br['xOffset'])); $objWriter->writeAttribute('cy', self::stringEmu($br['yOffset'])); $objWriter->endElement(); } $objWriter->startElement('xdr:graphicFrame'); $objWriter->writeAttribute('macro', ''); $objWriter->startElement('xdr:nvGraphicFramePr'); $objWriter->startElement('xdr:cNvPr'); $objWriter->writeAttribute('name', 'Chart ' . $relationId); $objWriter->writeAttribute('id', (string) (1025 * $relationId)); $objWriter->endElement(); $objWriter->startElement('xdr:cNvGraphicFramePr'); $objWriter->startElement('a:graphicFrameLocks'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->startElement('xdr:xfrm'); $objWriter->startElement('a:off'); $objWriter->writeAttribute('x', '0'); $objWriter->writeAttribute('y', '0'); $objWriter->endElement(); $objWriter->startElement('a:ext'); $objWriter->writeAttribute('cx', '0'); $objWriter->writeAttribute('cy', '0'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->startElement('a:graphic'); $objWriter->startElement('a:graphicData'); $objWriter->writeAttribute('uri', Namespaces::CHART); $objWriter->startElement('c:chart'); $objWriter->writeAttribute('xmlns:c', Namespaces::CHART); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); $objWriter->writeAttribute('r:id', 'rId' . $relationId); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->startElement('xdr:clientData'); $objWriter->endElement(); $objWriter->endElement(); } /** * Write drawings to XML format. * * @param int $relationId * @param null|int $hlinkClickId */ public function writeDrawing(XMLWriter $objWriter, BaseDrawing $drawing, $relationId = -1, $hlinkClickId = null): void { if ($relationId >= 0) { $isTwoCellAnchor = $drawing->getCoordinates2() !== ''; if ($isTwoCellAnchor) { // xdr:twoCellAnchor $objWriter->startElement('xdr:twoCellAnchor'); if ($drawing->validEditAs()) { $objWriter->writeAttribute('editAs', $drawing->getEditAs()); } // Image location $aCoordinates = Coordinate::indexesFromString($drawing->getCoordinates()); $aCoordinates2 = Coordinate::indexesFromString($drawing->getCoordinates2()); // xdr:from $objWriter->startElement('xdr:from'); $objWriter->writeElement('xdr:col', (string) ($aCoordinates[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX())); $objWriter->writeElement('xdr:row', (string) ($aCoordinates[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY())); $objWriter->endElement(); // xdr:to $objWriter->startElement('xdr:to'); $objWriter->writeElement('xdr:col', (string) ($aCoordinates2[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX2())); $objWriter->writeElement('xdr:row', (string) ($aCoordinates2[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY2())); $objWriter->endElement(); } else { // xdr:oneCellAnchor $objWriter->startElement('xdr:oneCellAnchor'); // Image location $aCoordinates = Coordinate::indexesFromString($drawing->getCoordinates()); // xdr:from $objWriter->startElement('xdr:from'); $objWriter->writeElement('xdr:col', (string) ($aCoordinates[0] - 1)); $objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX())); $objWriter->writeElement('xdr:row', (string) ($aCoordinates[1] - 1)); $objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY())); $objWriter->endElement(); // xdr:ext $objWriter->startElement('xdr:ext'); $objWriter->writeAttribute('cx', self::stringEmu($drawing->getWidth())); $objWriter->writeAttribute('cy', self::stringEmu($drawing->getHeight())); $objWriter->endElement(); } // xdr:pic $objWriter->startElement('xdr:pic'); // xdr:nvPicPr $objWriter->startElement('xdr:nvPicPr'); // xdr:cNvPr $objWriter->startElement('xdr:cNvPr'); $objWriter->writeAttribute('id', (string) $relationId); $objWriter->writeAttribute('name', $drawing->getName()); $objWriter->writeAttribute('descr', $drawing->getDescription()); //a:hlinkClick $this->writeHyperLinkDrawing($objWriter, $hlinkClickId); $objWriter->endElement(); // xdr:cNvPicPr $objWriter->startElement('xdr:cNvPicPr'); // a:picLocks $objWriter->startElement('a:picLocks'); $objWriter->writeAttribute('noChangeAspect', '1'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // xdr:blipFill $objWriter->startElement('xdr:blipFill'); // a:blip $objWriter->startElement('a:blip'); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); $objWriter->writeAttribute('r:embed', 'rId' . $relationId); $objWriter->endElement(); // a:stretch $objWriter->startElement('a:stretch'); $objWriter->writeElement('a:fillRect', null); $objWriter->endElement(); $objWriter->endElement(); // xdr:spPr $objWriter->startElement('xdr:spPr'); // a:xfrm $objWriter->startElement('a:xfrm'); $objWriter->writeAttribute('rot', (string) SharedDrawing::degreesToAngle($drawing->getRotation())); if ($isTwoCellAnchor) { $objWriter->startElement('a:ext'); $objWriter->writeAttribute('cx', self::stringEmu($drawing->getWidth())); $objWriter->writeAttribute('cy', self::stringEmu($drawing->getHeight())); $objWriter->endElement(); } $objWriter->endElement(); // a:prstGeom $objWriter->startElement('a:prstGeom'); $objWriter->writeAttribute('prst', 'rect'); // a:avLst $objWriter->writeElement('a:avLst', null); $objWriter->endElement(); if ($drawing->getShadow()->getVisible()) { // a:effectLst $objWriter->startElement('a:effectLst'); // a:outerShdw $objWriter->startElement('a:outerShdw'); $objWriter->writeAttribute('blurRad', self::stringEmu($drawing->getShadow()->getBlurRadius())); $objWriter->writeAttribute('dist', self::stringEmu($drawing->getShadow()->getDistance())); $objWriter->writeAttribute('dir', (string) SharedDrawing::degreesToAngle($drawing->getShadow()->getDirection())); $objWriter->writeAttribute('algn', $drawing->getShadow()->getAlignment()); $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); $objWriter->writeAttribute('val', $drawing->getShadow()->getColor()->getRGB()); // a:alpha $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', (string) ($drawing->getShadow()->getAlpha() * 1000)); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); } $objWriter->endElement(); $objWriter->endElement(); // xdr:clientData $objWriter->writeElement('xdr:clientData', null); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); } } /** * Write VML header/footer images to XML format. * * @return string XML Output */ public function writeVMLHeaderFooterImages(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Header/footer images $images = $worksheet->getHeaderFooter()->getImages(); // xml $objWriter->startElement('xml'); $objWriter->writeAttribute('xmlns:v', Namespaces::URN_VML); $objWriter->writeAttribute('xmlns:o', Namespaces::URN_MSOFFICE); $objWriter->writeAttribute('xmlns:x', Namespaces::URN_EXCEL); // o:shapelayout $objWriter->startElement('o:shapelayout'); $objWriter->writeAttribute('v:ext', 'edit'); // o:idmap $objWriter->startElement('o:idmap'); $objWriter->writeAttribute('v:ext', 'edit'); $objWriter->writeAttribute('data', '1'); $objWriter->endElement(); $objWriter->endElement(); // v:shapetype $objWriter->startElement('v:shapetype'); $objWriter->writeAttribute('id', '_x0000_t75'); $objWriter->writeAttribute('coordsize', '21600,21600'); $objWriter->writeAttribute('o:spt', '75'); $objWriter->writeAttribute('o:preferrelative', 't'); $objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe'); $objWriter->writeAttribute('filled', 'f'); $objWriter->writeAttribute('stroked', 'f'); // v:stroke $objWriter->startElement('v:stroke'); $objWriter->writeAttribute('joinstyle', 'miter'); $objWriter->endElement(); // v:formulas $objWriter->startElement('v:formulas'); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'sum @0 1 0'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'sum 0 0 @1'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @2 1 2'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'sum @0 0 1'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @6 1 2'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'sum @8 21600 0'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight'); $objWriter->endElement(); // v:f $objWriter->startElement('v:f'); $objWriter->writeAttribute('eqn', 'sum @10 21600 0'); $objWriter->endElement(); $objWriter->endElement(); // v:path $objWriter->startElement('v:path'); $objWriter->writeAttribute('o:extrusionok', 'f'); $objWriter->writeAttribute('gradientshapeok', 't'); $objWriter->writeAttribute('o:connecttype', 'rect'); $objWriter->endElement(); // o:lock $objWriter->startElement('o:lock'); $objWriter->writeAttribute('v:ext', 'edit'); $objWriter->writeAttribute('aspectratio', 't'); $objWriter->endElement(); $objWriter->endElement(); // Loop through images foreach ($images as $key => $value) { $this->writeVMLHeaderFooterImage($objWriter, $key, $value); } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write VML comment to XML format. * * @param string $reference Reference */ private function writeVMLHeaderFooterImage(XMLWriter $objWriter, $reference, HeaderFooterDrawing $image): void { // Calculate object id preg_match('{(\d+)}', md5($reference), $m); $id = 1500 + ((int) substr($m[1], 0, 2) * 1); // Calculate offset $width = $image->getWidth(); $height = $image->getHeight(); $marginLeft = $image->getOffsetX(); $marginTop = $image->getOffsetY(); // v:shape $objWriter->startElement('v:shape'); $objWriter->writeAttribute('id', $reference); $objWriter->writeAttribute('o:spid', '_x0000_s' . $id); $objWriter->writeAttribute('type', '#_x0000_t75'); $objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1"); // v:imagedata $objWriter->startElement('v:imagedata'); $objWriter->writeAttribute('o:relid', 'rId' . $reference); $objWriter->writeAttribute('o:title', $image->getName()); $objWriter->endElement(); // o:lock $objWriter->startElement('o:lock'); $objWriter->writeAttribute('v:ext', 'edit'); $objWriter->writeAttribute('textRotation', 't'); $objWriter->endElement(); $objWriter->endElement(); } /** * Get an array of all drawings. * * @return BaseDrawing[] All drawings in PhpSpreadsheet */ public function allDrawings(Spreadsheet $spreadsheet) { // Get an array of all drawings $aDrawings = []; // Loop through PhpSpreadsheet $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { // Loop through images and add to array $iterator = $spreadsheet->getSheet($i)->getDrawingCollection()->getIterator(); while ($iterator->valid()) { $aDrawings[] = $iterator->current(); $iterator->next(); } } return $aDrawings; } /** * @param null|int $hlinkClickId */ private function writeHyperLinkDrawing(XMLWriter $objWriter, $hlinkClickId): void { if ($hlinkClickId === null) { return; } $objWriter->startElement('a:hlinkClick'); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); $objWriter->writeAttribute('r:id', 'rId' . $hlinkClickId); $objWriter->endElement(); } private static function stringEmu(int $pixelValue): string { return (string) SharedDrawing::pixelsToEMU($pixelValue); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Comments.php 0000644 00000017374 15002227416 0020014 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Comment; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; class Comments extends WriterPart { /** * Write comments to XML format. * * @return string XML Output */ public function writeComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Comments cache $comments = $worksheet->getComments(); // Authors cache $authors = []; $authorId = 0; foreach ($comments as $comment) { if (!isset($authors[$comment->getAuthor()])) { $authors[$comment->getAuthor()] = $authorId++; } } // comments $objWriter->startElement('comments'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); // Loop through authors $objWriter->startElement('authors'); foreach ($authors as $author => $index) { $objWriter->writeElement('author', $author); } $objWriter->endElement(); // Loop through comments $objWriter->startElement('commentList'); foreach ($comments as $key => $value) { $this->writeComment($objWriter, $key, $value, $authors); } $objWriter->endElement(); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write comment to XML format. * * @param string $cellReference Cell reference * @param Comment $comment Comment * @param array $authors Array of authors */ private function writeComment(XMLWriter $objWriter, $cellReference, Comment $comment, array $authors): void { // comment $objWriter->startElement('comment'); $objWriter->writeAttribute('ref', $cellReference); $objWriter->writeAttribute('authorId', $authors[$comment->getAuthor()]); // text $objWriter->startElement('text'); $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $comment->getText()); $objWriter->endElement(); $objWriter->endElement(); } /** * Write VML comments to XML format. * * @return string XML Output */ public function writeVMLComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Comments cache $comments = $worksheet->getComments(); // xml $objWriter->startElement('xml'); $objWriter->writeAttribute('xmlns:v', Namespaces::URN_VML); $objWriter->writeAttribute('xmlns:o', Namespaces::URN_MSOFFICE); $objWriter->writeAttribute('xmlns:x', Namespaces::URN_EXCEL); // o:shapelayout $objWriter->startElement('o:shapelayout'); $objWriter->writeAttribute('v:ext', 'edit'); // o:idmap $objWriter->startElement('o:idmap'); $objWriter->writeAttribute('v:ext', 'edit'); $objWriter->writeAttribute('data', '1'); $objWriter->endElement(); $objWriter->endElement(); // v:shapetype $objWriter->startElement('v:shapetype'); $objWriter->writeAttribute('id', '_x0000_t202'); $objWriter->writeAttribute('coordsize', '21600,21600'); $objWriter->writeAttribute('o:spt', '202'); $objWriter->writeAttribute('path', 'm,l,21600r21600,l21600,xe'); // v:stroke $objWriter->startElement('v:stroke'); $objWriter->writeAttribute('joinstyle', 'miter'); $objWriter->endElement(); // v:path $objWriter->startElement('v:path'); $objWriter->writeAttribute('gradientshapeok', 't'); $objWriter->writeAttribute('o:connecttype', 'rect'); $objWriter->endElement(); $objWriter->endElement(); // Loop through comments foreach ($comments as $key => $value) { $this->writeVMLComment($objWriter, $key, $value); } $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write VML comment to XML format. * * @param string $cellReference Cell reference, eg: 'A1' * @param Comment $comment Comment */ private function writeVMLComment(XMLWriter $objWriter, $cellReference, Comment $comment): void { // Metadata [$column, $row] = Coordinate::indexesFromString($cellReference); $id = 1024 + $column + $row; $id = substr("$id", 0, 4); // v:shape $objWriter->startElement('v:shape'); $objWriter->writeAttribute('id', '_x0000_s' . $id); $objWriter->writeAttribute('type', '#_x0000_t202'); $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $comment->getMarginLeft() . ';margin-top:' . $comment->getMarginTop() . ';width:' . $comment->getWidth() . ';height:' . $comment->getHeight() . ';z-index:1;visibility:' . ($comment->getVisible() ? 'visible' : 'hidden')); $objWriter->writeAttribute('fillcolor', '#' . $comment->getFillColor()->getRGB()); $objWriter->writeAttribute('o:insetmode', 'auto'); // v:fill $objWriter->startElement('v:fill'); $objWriter->writeAttribute('color2', '#' . $comment->getFillColor()->getRGB()); if ($comment->hasBackgroundImage()) { $bgImage = $comment->getBackgroundImage(); $objWriter->writeAttribute('o:relid', 'rId' . $bgImage->getImageIndex()); $objWriter->writeAttribute('o:title', $bgImage->getName()); $objWriter->writeAttribute('type', 'frame'); } $objWriter->endElement(); // v:shadow $objWriter->startElement('v:shadow'); $objWriter->writeAttribute('on', 't'); $objWriter->writeAttribute('color', 'black'); $objWriter->writeAttribute('obscured', 't'); $objWriter->endElement(); // v:path $objWriter->startElement('v:path'); $objWriter->writeAttribute('o:connecttype', 'none'); $objWriter->endElement(); // v:textbox $objWriter->startElement('v:textbox'); $objWriter->writeAttribute('style', 'mso-direction-alt:auto'); // div $objWriter->startElement('div'); $objWriter->writeAttribute('style', 'text-align:left'); $objWriter->endElement(); $objWriter->endElement(); // x:ClientData $objWriter->startElement('x:ClientData'); $objWriter->writeAttribute('ObjectType', 'Note'); // x:MoveWithCells $objWriter->writeElement('x:MoveWithCells', ''); // x:SizeWithCells $objWriter->writeElement('x:SizeWithCells', ''); // x:AutoFill $objWriter->writeElement('x:AutoFill', 'False'); // x:Row $objWriter->writeElement('x:Row', (string) ($row - 1)); // x:Column $objWriter->writeElement('x:Column', (string) ($column - 1)); $objWriter->endElement(); $objWriter->endElement(); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Rels.php 0000644 00000040367 15002227416 0017132 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; class Rels extends WriterPart { /** * Write relationships to XML format. * * @return string XML Output */ public function writeRelationships(Spreadsheet $spreadsheet) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); if (!empty($customPropertyList)) { // Relationship docProps/app.xml $this->writeRelationship( $objWriter, 4, Namespaces::RELATIONSHIPS_CUSTOM_PROPERTIES, 'docProps/custom.xml' ); } // Relationship docProps/app.xml $this->writeRelationship( $objWriter, 3, Namespaces::RELATIONSHIPS_EXTENDED_PROPERTIES, 'docProps/app.xml' ); // Relationship docProps/core.xml $this->writeRelationship( $objWriter, 2, Namespaces::CORE_PROPERTIES, 'docProps/core.xml' ); // Relationship xl/workbook.xml $this->writeRelationship( $objWriter, 1, Namespaces::OFFICE_DOCUMENT, 'xl/workbook.xml' ); // a custom UI in workbook ? $target = $spreadsheet->getRibbonXMLData('target'); if ($spreadsheet->hasRibbon()) { $this->writeRelationShip( $objWriter, 5, Namespaces::EXTENSIBILITY, is_string($target) ? $target : '' ); } $objWriter->endElement(); return $objWriter->getData(); } /** * Write workbook relationships to XML format. * * @return string XML Output */ public function writeWorkbookRelationships(Spreadsheet $spreadsheet) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); // Relationship styles.xml $this->writeRelationship( $objWriter, 1, Namespaces::STYLES, 'styles.xml' ); // Relationship theme/theme1.xml $this->writeRelationship( $objWriter, 2, Namespaces::THEME2, 'theme/theme1.xml' ); // Relationship sharedStrings.xml $this->writeRelationship( $objWriter, 3, Namespaces::SHARED_STRINGS, 'sharedStrings.xml' ); // Relationships with sheets $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { $this->writeRelationship( $objWriter, ($i + 1 + 3), Namespaces::WORKSHEET, 'worksheets/sheet' . ($i + 1) . '.xml' ); } // Relationships for vbaProject if needed // id : just after the last sheet if ($spreadsheet->hasMacros()) { $this->writeRelationShip( $objWriter, ($i + 1 + 3), Namespaces::VBA, 'vbaProject.bin' ); ++$i; //increment i if needed for an another relation } $objWriter->endElement(); return $objWriter->getData(); } /** * Write worksheet relationships to XML format. * * Numbering is as follows: * rId1 - Drawings * rId_hyperlink_x - Hyperlinks * * @param int $worksheetId * @param bool $includeCharts Flag indicating if we should write charts * @param int $tableRef Table ID * * @return string XML Output */ public function writeWorksheetRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, $worksheetId = 1, $includeCharts = false, $tableRef = 1) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); // Write drawing relationships? $drawingOriginalIds = []; $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) { $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']; } if ($includeCharts) { $charts = $worksheet->getChartCollection(); } else { $charts = []; } if (($worksheet->getDrawingCollection()->count() > 0) || (count($charts) > 0) || $drawingOriginalIds) { $rId = 1; // Use original $relPath to get original $rId. // Take first. In future can be overwritten. // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet::writeDrawings) reset($drawingOriginalIds); $relPath = key($drawingOriginalIds); if (isset($drawingOriginalIds[$relPath])) { $rId = (int) (substr($drawingOriginalIds[$relPath], 3)); } // Generate new $relPath to write drawing relationship $relPath = '../drawings/drawing' . $worksheetId . '.xml'; $this->writeRelationship( $objWriter, $rId, Namespaces::RELATIONSHIPS_DRAWING, $relPath ); } // Write hyperlink relationships? $i = 1; foreach ($worksheet->getHyperlinkCollection() as $hyperlink) { if (!$hyperlink->isInternal()) { $this->writeRelationship( $objWriter, '_hyperlink_' . $i, Namespaces::HYPERLINK, $hyperlink->getUrl(), 'External' ); ++$i; } } // Write comments relationship? $i = 1; if (count($worksheet->getComments()) > 0 || isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'])) { $this->writeRelationship( $objWriter, '_comments_vml' . $i, Namespaces::VML, '../drawings/vmlDrawing' . $worksheetId . '.vml' ); } if (count($worksheet->getComments()) > 0) { $this->writeRelationship( $objWriter, '_comments' . $i, Namespaces::COMMENTS, '../comments' . $worksheetId . '.xml' ); } // Write Table $tableCount = $worksheet->getTableCollection()->count(); for ($i = 1; $i <= $tableCount; ++$i) { $this->writeRelationship( $objWriter, '_table_' . $i, Namespaces::RELATIONSHIPS_TABLE, '../tables/table' . $tableRef++ . '.xml' ); } // Write header/footer relationship? $i = 1; if (count($worksheet->getHeaderFooter()->getImages()) > 0) { $this->writeRelationship( $objWriter, '_headerfooter_vml' . $i, Namespaces::VML, '../drawings/vmlDrawingHF' . $worksheetId . '.vml' ); } $this->writeUnparsedRelationship($worksheet, $objWriter, 'ctrlProps', Namespaces::RELATIONSHIPS_CTRLPROP); $this->writeUnparsedRelationship($worksheet, $objWriter, 'vmlDrawings', Namespaces::VML); $this->writeUnparsedRelationship($worksheet, $objWriter, 'printerSettings', Namespaces::RELATIONSHIPS_PRINTER_SETTINGS); $objWriter->endElement(); return $objWriter->getData(); } private function writeUnparsedRelationship(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, XMLWriter $objWriter, string $relationship, string $type): void { $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); if (!isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()][$relationship])) { return; } foreach ($unparsedLoadedData['sheets'][$worksheet->getCodeName()][$relationship] as $rId => $value) { if (substr($rId, 0, 17) !== '_headerfooter_vml') { $this->writeRelationship( $objWriter, $rId, $type, $value['relFilePath'] ); } } } /** * Write drawing relationships to XML format. * * @param int $chartRef Chart ID * @param bool $includeCharts Flag indicating if we should write charts * * @return string XML Output */ public function writeDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, &$chartRef, $includeCharts = false) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); // Loop through images and write relationships $i = 1; $iterator = $worksheet->getDrawingCollection()->getIterator(); while ($iterator->valid()) { $drawing = $iterator->current(); if ( $drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing || $drawing instanceof MemoryDrawing ) { // Write relationship for image drawing $this->writeRelationship( $objWriter, $i, Namespaces::IMAGE, '../media/' . $drawing->getIndexedFilename() ); $i = $this->writeDrawingHyperLink($objWriter, $drawing, $i); } $iterator->next(); ++$i; } if ($includeCharts) { // Loop through charts and write relationships $chartCount = $worksheet->getChartCount(); if ($chartCount > 0) { for ($c = 0; $c < $chartCount; ++$c) { $this->writeRelationship( $objWriter, $i++, Namespaces::RELATIONSHIPS_CHART, '../charts/chart' . ++$chartRef . '.xml' ); } } } $objWriter->endElement(); return $objWriter->getData(); } /** * Write header/footer drawing relationships to XML format. * * @return string XML Output */ public function writeHeaderFooterDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); // Loop through images and write relationships foreach ($worksheet->getHeaderFooter()->getImages() as $key => $value) { // Write relationship for image drawing $this->writeRelationship( $objWriter, $key, Namespaces::IMAGE, '../media/' . $value->getIndexedFilename() ); } $objWriter->endElement(); return $objWriter->getData(); } public function writeVMLDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): string { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); // Loop through images and write relationships foreach ($worksheet->getComments() as $comment) { if (!$comment->hasBackgroundImage()) { continue; } $bgImage = $comment->getBackgroundImage(); $this->writeRelationship( $objWriter, $bgImage->getImageIndex(), Namespaces::IMAGE, '../media/' . $bgImage->getMediaFilename() ); } $objWriter->endElement(); return $objWriter->getData(); } /** * Write Override content type. * * @param int|string $id Relationship ID. rId will be prepended! * @param string $type Relationship type * @param string $target Relationship target * @param string $targetMode Relationship target mode */ private function writeRelationship(XMLWriter $objWriter, $id, $type, $target, $targetMode = ''): void { if ($type != '' && $target != '') { // Write relationship $objWriter->startElement('Relationship'); $objWriter->writeAttribute('Id', 'rId' . $id); $objWriter->writeAttribute('Type', $type); $objWriter->writeAttribute('Target', $target); if ($targetMode != '') { $objWriter->writeAttribute('TargetMode', $targetMode); } $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); } } private function writeDrawingHyperLink(XMLWriter $objWriter, BaseDrawing $drawing, int $i): int { if ($drawing->getHyperlink() === null) { return $i; } ++$i; $this->writeRelationship( $objWriter, $i, Namespaces::HYPERLINK, $drawing->getHyperlink()->getUrl(), $drawing->getHyperlink()->getTypeHyperlink() ); return $i; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Table.php 0000644 00000011265 15002227416 0017247 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Worksheet\Table as WorksheetTable; class Table extends WriterPart { /** * Write Table to XML format. * * @param int $tableRef Table ID * * @return string XML Output */ public function writeTable(WorksheetTable $table, $tableRef): string { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Table $name = 'Table' . $tableRef; $range = $table->getRange(); $objWriter->startElement('table'); $objWriter->writeAttribute('xml:space', 'preserve'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); $objWriter->writeAttribute('id', (string) $tableRef); $objWriter->writeAttribute('name', $name); $objWriter->writeAttribute('displayName', $table->getName() ?: $name); $objWriter->writeAttribute('ref', $range); $objWriter->writeAttribute('headerRowCount', $table->getShowHeaderRow() ? '1' : '0'); $objWriter->writeAttribute('totalsRowCount', $table->getShowTotalsRow() ? '1' : '0'); // Table Boundaries [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($table->getRange()); // Table Auto Filter if ($table->getShowHeaderRow() && $table->getAllowFilter() === true) { $objWriter->startElement('autoFilter'); $objWriter->writeAttribute('ref', $range); $objWriter->endElement(); foreach (range($rangeStart[0], $rangeEnd[0]) as $offset => $columnIndex) { $column = $table->getColumnByOffset($offset); if (!$column->getShowFilterButton()) { $objWriter->startElement('filterColumn'); $objWriter->writeAttribute('colId', (string) $offset); $objWriter->writeAttribute('hiddenButton', '1'); $objWriter->endElement(); } else { $column = $table->getAutoFilter()->getColumnByOffset($offset); AutoFilter::writeAutoFilterColumn($objWriter, $column, $offset); } } } // Table Columns $objWriter->startElement('tableColumns'); $objWriter->writeAttribute('count', (string) ($rangeEnd[0] - $rangeStart[0] + 1)); foreach (range($rangeStart[0], $rangeEnd[0]) as $offset => $columnIndex) { $worksheet = $table->getWorksheet(); if (!$worksheet) { continue; } $column = $table->getColumnByOffset($offset); $cell = $worksheet->getCell([$columnIndex, $rangeStart[1]]); $objWriter->startElement('tableColumn'); $objWriter->writeAttribute('id', (string) ($offset + 1)); $objWriter->writeAttribute('name', $table->getShowHeaderRow() ? $cell->getValue() : 'Column' . ($offset + 1)); if ($table->getShowTotalsRow()) { if ($column->getTotalsRowLabel()) { $objWriter->writeAttribute('totalsRowLabel', $column->getTotalsRowLabel()); } if ($column->getTotalsRowFunction()) { $objWriter->writeAttribute('totalsRowFunction', $column->getTotalsRowFunction()); } } if ($column->getColumnFormula()) { $objWriter->writeElement('calculatedColumnFormula', $column->getColumnFormula()); } $objWriter->endElement(); } $objWriter->endElement(); // Table Styles $objWriter->startElement('tableStyleInfo'); $objWriter->writeAttribute('name', $table->getStyle()->getTheme()); $objWriter->writeAttribute('showFirstColumn', $table->getStyle()->getShowFirstColumn() ? '1' : '0'); $objWriter->writeAttribute('showLastColumn', $table->getStyle()->getShowLastColumn() ? '1' : '0'); $objWriter->writeAttribute('showRowStripes', $table->getStyle()->getShowRowStripes() ? '1' : '0'); $objWriter->writeAttribute('showColumnStripes', $table->getStyle()->getShowColumnStripes() ? '1' : '0'); $objWriter->endElement(); $objWriter->endElement(); // Return return $objWriter->getData(); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php 0000644 00000173667 15002227416 0020212 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension; use PhpOffice\PhpSpreadsheet\Worksheet\SheetView; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet; class Worksheet extends WriterPart { /** @var string */ private $numberStoredAsText = ''; /** @var string */ private $formula = ''; /** @var string */ private $twoDigitTextYear = ''; /** @var string */ private $evalError = ''; /** * Write worksheet to XML format. * * @param string[] $stringTable * @param bool $includeCharts Flag indicating if we should write charts * * @return string XML Output */ public function writeWorksheet(PhpspreadsheetWorksheet $worksheet, $stringTable = [], $includeCharts = false) { $this->numberStoredAsText = ''; $this->formula = ''; $this->twoDigitTextYear = ''; $this->evalError = ''; // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Worksheet $objWriter->startElement('worksheet'); $objWriter->writeAttribute('xml:space', 'preserve'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); $objWriter->writeAttribute('xmlns:xdr', Namespaces::SPREADSHEET_DRAWING); $objWriter->writeAttribute('xmlns:x14', Namespaces::DATA_VALIDATIONS1); $objWriter->writeAttribute('xmlns:xm', Namespaces::DATA_VALIDATIONS2); $objWriter->writeAttribute('xmlns:mc', Namespaces::COMPATIBILITY); $objWriter->writeAttribute('mc:Ignorable', 'x14ac'); $objWriter->writeAttribute('xmlns:x14ac', Namespaces::SPREADSHEETML_AC); // sheetPr $this->writeSheetPr($objWriter, $worksheet); // Dimension $this->writeDimension($objWriter, $worksheet); // sheetViews $this->writeSheetViews($objWriter, $worksheet); // sheetFormatPr $this->writeSheetFormatPr($objWriter, $worksheet); // cols $this->writeCols($objWriter, $worksheet); // sheetData $this->writeSheetData($objWriter, $worksheet, $stringTable); // sheetProtection $this->writeSheetProtection($objWriter, $worksheet); // protectedRanges $this->writeProtectedRanges($objWriter, $worksheet); // autoFilter $this->writeAutoFilter($objWriter, $worksheet); // mergeCells $this->writeMergeCells($objWriter, $worksheet); // conditionalFormatting $this->writeConditionalFormatting($objWriter, $worksheet); // dataValidations $this->writeDataValidations($objWriter, $worksheet); // hyperlinks $this->writeHyperlinks($objWriter, $worksheet); // Print options $this->writePrintOptions($objWriter, $worksheet); // Page margins $this->writePageMargins($objWriter, $worksheet); // Page setup $this->writePageSetup($objWriter, $worksheet); // Header / footer $this->writeHeaderFooter($objWriter, $worksheet); // Breaks $this->writeBreaks($objWriter, $worksheet); // Drawings and/or Charts $this->writeDrawings($objWriter, $worksheet, $includeCharts); // LegacyDrawing $this->writeLegacyDrawing($objWriter, $worksheet); // LegacyDrawingHF $this->writeLegacyDrawingHF($objWriter, $worksheet); // AlternateContent $this->writeAlternateContent($objWriter, $worksheet); // IgnoredErrors $this->writeIgnoredErrors($objWriter); // Table $this->writeTable($objWriter, $worksheet); // ConditionalFormattingRuleExtensionList // (Must be inserted last. Not insert last, an Excel parse error will occur) $this->writeExtLst($objWriter, $worksheet); $objWriter->endElement(); // Return return $objWriter->getData(); } private function writeIgnoredError(XMLWriter $objWriter, bool &$started, string $attr, string $cells): void { if ($cells !== '') { if (!$started) { $objWriter->startElement('ignoredErrors'); $started = true; } $objWriter->startElement('ignoredError'); $objWriter->writeAttribute('sqref', substr($cells, 1)); $objWriter->writeAttribute($attr, '1'); $objWriter->endElement(); } } private function writeIgnoredErrors(XMLWriter $objWriter): void { $started = false; $this->writeIgnoredError($objWriter, $started, 'numberStoredAsText', $this->numberStoredAsText); $this->writeIgnoredError($objWriter, $started, 'formula', $this->formula); $this->writeIgnoredError($objWriter, $started, 'twoDigitTextYear', $this->twoDigitTextYear); $this->writeIgnoredError($objWriter, $started, 'evalError', $this->evalError); if ($started) { $objWriter->endElement(); } } /** * Write SheetPr. */ private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetPr $objWriter->startElement('sheetPr'); if ($worksheet->getParentOrThrow()->hasMacros()) { //if the workbook have macros, we need to have codeName for the sheet if (!$worksheet->hasCodeName()) { $worksheet->setCodeName($worksheet->getTitle()); } self::writeAttributeNotNull($objWriter, 'codeName', $worksheet->getCodeName()); } $autoFilterRange = $worksheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { $objWriter->writeAttribute('filterMode', '1'); if (!$worksheet->getAutoFilter()->getEvaluated()) { $worksheet->getAutoFilter()->showHideRows(); } } $tables = $worksheet->getTableCollection(); if (count($tables)) { foreach ($tables as $table) { if (!$table->getAutoFilter()->getEvaluated()) { $table->getAutoFilter()->showHideRows(); } } } // tabColor if ($worksheet->isTabColorSet()) { $objWriter->startElement('tabColor'); $objWriter->writeAttribute('rgb', $worksheet->getTabColor()->getARGB() ?? ''); $objWriter->endElement(); } // outlinePr $objWriter->startElement('outlinePr'); $objWriter->writeAttribute('summaryBelow', ($worksheet->getShowSummaryBelow() ? '1' : '0')); $objWriter->writeAttribute('summaryRight', ($worksheet->getShowSummaryRight() ? '1' : '0')); $objWriter->endElement(); // pageSetUpPr if ($worksheet->getPageSetup()->getFitToPage()) { $objWriter->startElement('pageSetUpPr'); $objWriter->writeAttribute('fitToPage', '1'); $objWriter->endElement(); } $objWriter->endElement(); } /** * Write Dimension. */ private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // dimension $objWriter->startElement('dimension'); $objWriter->writeAttribute('ref', $worksheet->calculateWorksheetDimension()); $objWriter->endElement(); } /** * Write SheetViews. */ private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetViews $objWriter->startElement('sheetViews'); // Sheet selected? $sheetSelected = false; if ($this->getParentWriter()->getSpreadsheet()->getIndex($worksheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) { $sheetSelected = true; } // sheetView $objWriter->startElement('sheetView'); $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0'); $objWriter->writeAttribute('workbookViewId', '0'); // Zoom scales if ($worksheet->getSheetView()->getZoomScale() != 100) { $objWriter->writeAttribute('zoomScale', (string) $worksheet->getSheetView()->getZoomScale()); } if ($worksheet->getSheetView()->getZoomScaleNormal() != 100) { $objWriter->writeAttribute('zoomScaleNormal', (string) $worksheet->getSheetView()->getZoomScaleNormal()); } // Show zeros (Excel also writes this attribute only if set to false) if ($worksheet->getSheetView()->getShowZeros() === false) { $objWriter->writeAttribute('showZeros', '0'); } // View Layout Type if ($worksheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) { $objWriter->writeAttribute('view', $worksheet->getSheetView()->getView()); } // Gridlines if ($worksheet->getShowGridlines()) { $objWriter->writeAttribute('showGridLines', 'true'); } else { $objWriter->writeAttribute('showGridLines', 'false'); } // Row and column headers if ($worksheet->getShowRowColHeaders()) { $objWriter->writeAttribute('showRowColHeaders', '1'); } else { $objWriter->writeAttribute('showRowColHeaders', '0'); } // Right-to-left if ($worksheet->getRightToLeft()) { $objWriter->writeAttribute('rightToLeft', 'true'); } $topLeftCell = $worksheet->getTopLeftCell(); $activeCell = $worksheet->getActiveCell(); $sqref = $worksheet->getSelectedCells(); // Pane $pane = ''; if ($worksheet->getFreezePane()) { [$xSplit, $ySplit] = Coordinate::coordinateFromString($worksheet->getFreezePane()); $xSplit = Coordinate::columnIndexFromString($xSplit); --$xSplit; --$ySplit; // pane $pane = 'topRight'; $objWriter->startElement('pane'); if ($xSplit > 0) { $objWriter->writeAttribute('xSplit', "$xSplit"); } if ($ySplit > 0) { $objWriter->writeAttribute('ySplit', $ySplit); $pane = ($xSplit > 0) ? 'bottomRight' : 'bottomLeft'; } self::writeAttributeNotNull($objWriter, 'topLeftCell', $topLeftCell); $objWriter->writeAttribute('activePane', $pane); $objWriter->writeAttribute('state', 'frozen'); $objWriter->endElement(); if (($xSplit > 0) && ($ySplit > 0)) { // Write additional selections if more than two panes (ie both an X and a Y split) $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', 'topRight'); $objWriter->endElement(); $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', 'bottomLeft'); $objWriter->endElement(); } } else { self::writeAttributeNotNull($objWriter, 'topLeftCell', $topLeftCell); } // Selection // Only need to write selection element if we have a split pane // We cheat a little by over-riding the active cell selection, setting it to the split cell $objWriter->startElement('selection'); if ($pane != '') { $objWriter->writeAttribute('pane', $pane); } $objWriter->writeAttribute('activeCell', $activeCell); $objWriter->writeAttribute('sqref', $sqref); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); } /** * Write SheetFormatPr. */ private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetFormatPr $objWriter->startElement('sheetFormatPr'); // Default row height if ($worksheet->getDefaultRowDimension()->getRowHeight() >= 0) { $objWriter->writeAttribute('customHeight', 'true'); $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($worksheet->getDefaultRowDimension()->getRowHeight())); } else { $objWriter->writeAttribute('defaultRowHeight', '14.4'); } // Set Zero Height row if ($worksheet->getDefaultRowDimension()->getZeroHeight()) { $objWriter->writeAttribute('zeroHeight', '1'); } // Default column width if ($worksheet->getDefaultColumnDimension()->getWidth() >= 0) { $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($worksheet->getDefaultColumnDimension()->getWidth())); } // Outline level - row $outlineLevelRow = 0; foreach ($worksheet->getRowDimensions() as $dimension) { if ($dimension->getOutlineLevel() > $outlineLevelRow) { $outlineLevelRow = $dimension->getOutlineLevel(); } } $objWriter->writeAttribute('outlineLevelRow', (string) (int) $outlineLevelRow); // Outline level - column $outlineLevelCol = 0; foreach ($worksheet->getColumnDimensions() as $dimension) { if ($dimension->getOutlineLevel() > $outlineLevelCol) { $outlineLevelCol = $dimension->getOutlineLevel(); } } $objWriter->writeAttribute('outlineLevelCol', (string) (int) $outlineLevelCol); $objWriter->endElement(); } /** * Write Cols. */ private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // cols if (count($worksheet->getColumnDimensions()) > 0) { $objWriter->startElement('cols'); $worksheet->calculateColumnWidths(); // Loop through column dimensions foreach ($worksheet->getColumnDimensions() as $colDimension) { // col $objWriter->startElement('col'); $objWriter->writeAttribute('min', (string) Coordinate::columnIndexFromString($colDimension->getColumnIndex())); $objWriter->writeAttribute('max', (string) Coordinate::columnIndexFromString($colDimension->getColumnIndex())); if ($colDimension->getWidth() < 0) { // No width set, apply default of 10 $objWriter->writeAttribute('width', '9.10'); } else { // Width set $objWriter->writeAttribute('width', StringHelper::formatNumber($colDimension->getWidth())); } // Column visibility if ($colDimension->getVisible() === false) { $objWriter->writeAttribute('hidden', 'true'); } // Auto size? if ($colDimension->getAutoSize()) { $objWriter->writeAttribute('bestFit', 'true'); } // Custom width? if ($colDimension->getWidth() != $worksheet->getDefaultColumnDimension()->getWidth()) { $objWriter->writeAttribute('customWidth', 'true'); } // Collapsed if ($colDimension->getCollapsed() === true) { $objWriter->writeAttribute('collapsed', 'true'); } // Outline level if ($colDimension->getOutlineLevel() > 0) { $objWriter->writeAttribute('outlineLevel', (string) $colDimension->getOutlineLevel()); } // Style $objWriter->writeAttribute('style', (string) $colDimension->getXfIndex()); $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write SheetProtection. */ private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { $protection = $worksheet->getProtection(); if (!$protection->isProtectionEnabled()) { return; } // sheetProtection $objWriter->startElement('sheetProtection'); if ($protection->getAlgorithm()) { $objWriter->writeAttribute('algorithmName', $protection->getAlgorithm()); $objWriter->writeAttribute('hashValue', $protection->getPassword()); $objWriter->writeAttribute('saltValue', $protection->getSalt()); $objWriter->writeAttribute('spinCount', (string) $protection->getSpinCount()); } elseif ($protection->getPassword() !== '') { $objWriter->writeAttribute('password', $protection->getPassword()); } self::writeProtectionAttribute($objWriter, 'sheet', $protection->getSheet()); self::writeProtectionAttribute($objWriter, 'objects', $protection->getObjects()); self::writeProtectionAttribute($objWriter, 'scenarios', $protection->getScenarios()); self::writeProtectionAttribute($objWriter, 'formatCells', $protection->getFormatCells()); self::writeProtectionAttribute($objWriter, 'formatColumns', $protection->getFormatColumns()); self::writeProtectionAttribute($objWriter, 'formatRows', $protection->getFormatRows()); self::writeProtectionAttribute($objWriter, 'insertColumns', $protection->getInsertColumns()); self::writeProtectionAttribute($objWriter, 'insertRows', $protection->getInsertRows()); self::writeProtectionAttribute($objWriter, 'insertHyperlinks', $protection->getInsertHyperlinks()); self::writeProtectionAttribute($objWriter, 'deleteColumns', $protection->getDeleteColumns()); self::writeProtectionAttribute($objWriter, 'deleteRows', $protection->getDeleteRows()); self::writeProtectionAttribute($objWriter, 'sort', $protection->getSort()); self::writeProtectionAttribute($objWriter, 'autoFilter', $protection->getAutoFilter()); self::writeProtectionAttribute($objWriter, 'pivotTables', $protection->getPivotTables()); self::writeProtectionAttribute($objWriter, 'selectLockedCells', $protection->getSelectLockedCells()); self::writeProtectionAttribute($objWriter, 'selectUnlockedCells', $protection->getSelectUnlockedCells()); $objWriter->endElement(); } private static function writeProtectionAttribute(XMLWriter $objWriter, string $name, ?bool $value): void { if ($value === true) { $objWriter->writeAttribute($name, '1'); } elseif ($value === false) { $objWriter->writeAttribute($name, '0'); } } private static function writeAttributeIf(XMLWriter $objWriter, ?bool $condition, string $attr, string $val): void { if ($condition) { $objWriter->writeAttribute($attr, $val); } } private static function writeAttributeNotNull(XMLWriter $objWriter, string $attr, ?string $val): void { if ($val !== null) { $objWriter->writeAttribute($attr, $val); } } private static function writeElementIf(XMLWriter $objWriter, bool $condition, string $attr, string $val): void { if ($condition) { $objWriter->writeElement($attr, $val); } } private static function writeOtherCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void { $conditions = $conditional->getConditions(); if ( $conditional->getConditionType() == Conditional::CONDITION_CELLIS || $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION || !empty($conditions) ) { foreach ($conditions as $formula) { // Formula if (is_bool($formula)) { $formula = $formula ? 'TRUE' : 'FALSE'; } $objWriter->writeElement('formula', FunctionPrefix::addFunctionPrefix("$formula")); } } else { if ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSBLANKS) { // formula copied from ms xlsx xml source file $objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))=0'); } elseif ($conditional->getConditionType() == Conditional::CONDITION_NOTCONTAINSBLANKS) { // formula copied from ms xlsx xml source file $objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))>0'); } elseif ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSERRORS) { // formula copied from ms xlsx xml source file $objWriter->writeElement('formula', 'ISERROR(' . $cellCoordinate . ')'); } elseif ($conditional->getConditionType() == Conditional::CONDITION_NOTCONTAINSERRORS) { // formula copied from ms xlsx xml source file $objWriter->writeElement('formula', 'NOT(ISERROR(' . $cellCoordinate . '))'); } } } private static function writeTimePeriodCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void { $txt = $conditional->getText(); if (!empty($txt)) { $objWriter->writeAttribute('timePeriod', $txt); if (empty($conditional->getConditions())) { if ($conditional->getOperatorType() == Conditional::TIMEPERIOD_TODAY) { $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_TOMORROW) { $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()+1'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_YESTERDAY) { $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()-1'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_7_DAYS) { $objWriter->writeElement('formula', 'AND(TODAY()-FLOOR(' . $cellCoordinate . ',1)<=6,FLOOR(' . $cellCoordinate . ',1)<=TODAY())'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_WEEK) { $objWriter->writeElement('formula', 'AND(TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)<(WEEKDAY(TODAY())+7))'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_THIS_WEEK) { $objWriter->writeElement('formula', 'AND(TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()<=7-WEEKDAY(TODAY()))'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_NEXT_WEEK) { $objWriter->writeElement('formula', 'AND(ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()<(15-WEEKDAY(TODAY())))'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_MONTH) { $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(EDATE(TODAY(),0-1)),YEAR(' . $cellCoordinate . ')=YEAR(EDATE(TODAY(),0-1)))'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_THIS_MONTH) { $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(TODAY()),YEAR(' . $cellCoordinate . ')=YEAR(TODAY()))'); } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_NEXT_MONTH) { $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(EDATE(TODAY(),0+1)),YEAR(' . $cellCoordinate . ')=YEAR(EDATE(TODAY(),0+1)))'); } } else { $objWriter->writeElement('formula', (string) ($conditional->getConditions()[0])); } } } private static function writeTextCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void { $txt = $conditional->getText(); if (!empty($txt)) { $objWriter->writeAttribute('text', $txt); if (empty($conditional->getConditions())) { if ($conditional->getOperatorType() == Conditional::OPERATOR_CONTAINSTEXT) { $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $txt . '",' . $cellCoordinate . ')))'); } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_BEGINSWITH) { $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',LEN("' . $txt . '"))="' . $txt . '"'); } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_ENDSWITH) { $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',LEN("' . $txt . '"))="' . $txt . '"'); } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_NOTCONTAINS) { $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $txt . '",' . $cellCoordinate . '))'); } } else { $objWriter->writeElement('formula', (string) ($conditional->getConditions()[0])); } } } private static function writeExtConditionalFormattingElements(XMLWriter $objWriter, ConditionalFormattingRuleExtension $ruleExtension): void { $prefix = 'x14'; $objWriter->startElementNs($prefix, 'conditionalFormatting', null); $objWriter->startElementNs($prefix, 'cfRule', null); $objWriter->writeAttribute('type', $ruleExtension->getCfRule()); $objWriter->writeAttribute('id', $ruleExtension->getId()); $objWriter->startElementNs($prefix, 'dataBar', null); $dataBar = $ruleExtension->getDataBarExt(); foreach ($dataBar->getXmlAttributes() as $attrKey => $val) { $objWriter->writeAttribute($attrKey, $val); } $minCfvo = $dataBar->getMinimumConditionalFormatValueObject(); if ($minCfvo !== null) { $objWriter->startElementNs($prefix, 'cfvo', null); $objWriter->writeAttribute('type', $minCfvo->getType()); if ($minCfvo->getCellFormula()) { $objWriter->writeElement('xm:f', $minCfvo->getCellFormula()); } $objWriter->endElement(); //end cfvo } $maxCfvo = $dataBar->getMaximumConditionalFormatValueObject(); if ($maxCfvo !== null) { $objWriter->startElementNs($prefix, 'cfvo', null); $objWriter->writeAttribute('type', $maxCfvo->getType()); if ($maxCfvo->getCellFormula()) { $objWriter->writeElement('xm:f', $maxCfvo->getCellFormula()); } $objWriter->endElement(); //end cfvo } foreach ($dataBar->getXmlElements() as $elmKey => $elmAttr) { $objWriter->startElementNs($prefix, $elmKey, null); foreach ($elmAttr as $attrKey => $attrVal) { $objWriter->writeAttribute($attrKey, $attrVal); } $objWriter->endElement(); //end elmKey } $objWriter->endElement(); //end dataBar $objWriter->endElement(); //end cfRule $objWriter->writeElement('xm:sqref', $ruleExtension->getSqref()); $objWriter->endElement(); //end conditionalFormatting } private static function writeDataBarElements(XMLWriter $objWriter, ?ConditionalDataBar $dataBar): void { if ($dataBar) { $objWriter->startElement('dataBar'); self::writeAttributeIf($objWriter, null !== $dataBar->getShowValue(), 'showValue', $dataBar->getShowValue() ? '1' : '0'); $minCfvo = $dataBar->getMinimumConditionalFormatValueObject(); if ($minCfvo) { $objWriter->startElement('cfvo'); self::writeAttributeIf($objWriter, $minCfvo->getType(), 'type', (string) $minCfvo->getType()); self::writeAttributeIf($objWriter, $minCfvo->getValue(), 'val', (string) $minCfvo->getValue()); $objWriter->endElement(); } $maxCfvo = $dataBar->getMaximumConditionalFormatValueObject(); if ($maxCfvo) { $objWriter->startElement('cfvo'); self::writeAttributeIf($objWriter, $maxCfvo->getType(), 'type', (string) $maxCfvo->getType()); self::writeAttributeIf($objWriter, $maxCfvo->getValue(), 'val', (string) $maxCfvo->getValue()); $objWriter->endElement(); } if ($dataBar->getColor()) { $objWriter->startElement('color'); $objWriter->writeAttribute('rgb', $dataBar->getColor()); $objWriter->endElement(); } $objWriter->endElement(); // end dataBar if ($dataBar->getConditionalFormattingRuleExt()) { $objWriter->startElement('extLst'); $extension = $dataBar->getConditionalFormattingRuleExt(); $objWriter->startElement('ext'); $objWriter->writeAttribute('uri', '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}'); $objWriter->startElementNs('x14', 'id', null); $objWriter->text($extension->getId()); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); //end extLst } } } /** * Write ConditionalFormatting. */ private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Conditional id $id = 1; // Loop through styles in the current worksheet foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { $objWriter->startElement('conditionalFormatting'); $objWriter->writeAttribute('sqref', $cellCoordinate); foreach ($conditionalStyles as $conditional) { // WHY was this again? // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') { // continue; // } // cfRule $objWriter->startElement('cfRule'); $objWriter->writeAttribute('type', $conditional->getConditionType()); self::writeAttributeIf( $objWriter, ($conditional->getConditionType() !== Conditional::CONDITION_DATABAR && $conditional->getNoFormatSet() === false), 'dxfId', (string) $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) ); $objWriter->writeAttribute('priority', (string) $id++); self::writeAttributeif( $objWriter, ( $conditional->getConditionType() === Conditional::CONDITION_CELLIS || $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH ) && $conditional->getOperatorType() !== Conditional::OPERATOR_NONE, 'operator', $conditional->getOperatorType() ); self::writeAttributeIf($objWriter, $conditional->getStopIfTrue(), 'stopIfTrue', '1'); $cellRange = Coordinate::splitRange(str_replace('$', '', strtoupper($cellCoordinate))); [$topLeftCell] = $cellRange[0]; if ( $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH ) { self::writeTextCondElements($objWriter, $conditional, $topLeftCell); } elseif ($conditional->getConditionType() === Conditional::CONDITION_TIMEPERIOD) { self::writeTimePeriodCondElements($objWriter, $conditional, $topLeftCell); } else { self::writeOtherCondElements($objWriter, $conditional, $topLeftCell); } //<dataBar> self::writeDataBarElements($objWriter, $conditional->getDataBar()); $objWriter->endElement(); //end cfRule } $objWriter->endElement(); //end conditionalFormatting } } /** * Write DataValidations. */ private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Datavalidation collection $dataValidationCollection = $worksheet->getDataValidationCollection(); // Write data validations? if (!empty($dataValidationCollection)) { $dataValidationCollection = Coordinate::mergeRangesInCollection($dataValidationCollection); $objWriter->startElement('dataValidations'); $objWriter->writeAttribute('count', (string) count($dataValidationCollection)); foreach ($dataValidationCollection as $coordinate => $dv) { $objWriter->startElement('dataValidation'); if ($dv->getType() != '') { $objWriter->writeAttribute('type', $dv->getType()); } if ($dv->getErrorStyle() != '') { $objWriter->writeAttribute('errorStyle', $dv->getErrorStyle()); } if ($dv->getOperator() != '') { $objWriter->writeAttribute('operator', $dv->getOperator()); } $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0')); $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0')); $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0')); $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0')); if ($dv->getErrorTitle() !== '') { $objWriter->writeAttribute('errorTitle', $dv->getErrorTitle()); } if ($dv->getError() !== '') { $objWriter->writeAttribute('error', $dv->getError()); } if ($dv->getPromptTitle() !== '') { $objWriter->writeAttribute('promptTitle', $dv->getPromptTitle()); } if ($dv->getPrompt() !== '') { $objWriter->writeAttribute('prompt', $dv->getPrompt()); } $objWriter->writeAttribute('sqref', $dv->getSqref() ?? $coordinate); if ($dv->getFormula1() !== '') { $objWriter->writeElement('formula1', $dv->getFormula1()); } if ($dv->getFormula2() !== '') { $objWriter->writeElement('formula2', $dv->getFormula2()); } $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write Hyperlinks. */ private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Hyperlink collection $hyperlinkCollection = $worksheet->getHyperlinkCollection(); // Relation ID $relationId = 1; // Write hyperlinks? if (!empty($hyperlinkCollection)) { $objWriter->startElement('hyperlinks'); foreach ($hyperlinkCollection as $coordinate => $hyperlink) { $objWriter->startElement('hyperlink'); $objWriter->writeAttribute('ref', $coordinate); if (!$hyperlink->isInternal()) { $objWriter->writeAttribute('r:id', 'rId_hyperlink_' . $relationId); ++$relationId; } else { $objWriter->writeAttribute('location', str_replace('sheet://', '', $hyperlink->getUrl())); } if ($hyperlink->getTooltip() !== '') { $objWriter->writeAttribute('tooltip', $hyperlink->getTooltip()); $objWriter->writeAttribute('display', $hyperlink->getTooltip()); } $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write ProtectedRanges. */ private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { if (count($worksheet->getProtectedCells()) > 0) { // protectedRanges $objWriter->startElement('protectedRanges'); // Loop protectedRanges foreach ($worksheet->getProtectedCells() as $protectedCell => $passwordHash) { // protectedRange $objWriter->startElement('protectedRange'); $objWriter->writeAttribute('name', 'p' . md5($protectedCell)); $objWriter->writeAttribute('sqref', $protectedCell); if (!empty($passwordHash)) { $objWriter->writeAttribute('password', $passwordHash); } $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write MergeCells. */ private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { if (count($worksheet->getMergeCells()) > 0) { // mergeCells $objWriter->startElement('mergeCells'); // Loop mergeCells foreach ($worksheet->getMergeCells() as $mergeCell) { // mergeCell $objWriter->startElement('mergeCell'); $objWriter->writeAttribute('ref', $mergeCell); $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write PrintOptions. */ private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // printOptions $objWriter->startElement('printOptions'); $objWriter->writeAttribute('gridLines', ($worksheet->getPrintGridlines() ? 'true' : 'false')); $objWriter->writeAttribute('gridLinesSet', 'true'); if ($worksheet->getPageSetup()->getHorizontalCentered()) { $objWriter->writeAttribute('horizontalCentered', 'true'); } if ($worksheet->getPageSetup()->getVerticalCentered()) { $objWriter->writeAttribute('verticalCentered', 'true'); } $objWriter->endElement(); } /** * Write PageMargins. */ private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // pageMargins $objWriter->startElement('pageMargins'); $objWriter->writeAttribute('left', StringHelper::formatNumber($worksheet->getPageMargins()->getLeft())); $objWriter->writeAttribute('right', StringHelper::formatNumber($worksheet->getPageMargins()->getRight())); $objWriter->writeAttribute('top', StringHelper::formatNumber($worksheet->getPageMargins()->getTop())); $objWriter->writeAttribute('bottom', StringHelper::formatNumber($worksheet->getPageMargins()->getBottom())); $objWriter->writeAttribute('header', StringHelper::formatNumber($worksheet->getPageMargins()->getHeader())); $objWriter->writeAttribute('footer', StringHelper::formatNumber($worksheet->getPageMargins()->getFooter())); $objWriter->endElement(); } /** * Write AutoFilter. */ private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { AutoFilter::writeAutoFilter($objWriter, $worksheet); } /** * Write Table. */ private function writeTable(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { $tableCount = $worksheet->getTableCollection()->count(); $objWriter->startElement('tableParts'); $objWriter->writeAttribute('count', (string) $tableCount); for ($t = 1; $t <= $tableCount; ++$t) { $objWriter->startElement('tablePart'); $objWriter->writeAttribute('r:id', 'rId_table_' . $t); $objWriter->endElement(); } $objWriter->endElement(); } /** * Write PageSetup. */ private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // pageSetup $objWriter->startElement('pageSetup'); $objWriter->writeAttribute('paperSize', (string) $worksheet->getPageSetup()->getPaperSize()); $objWriter->writeAttribute('orientation', $worksheet->getPageSetup()->getOrientation()); if ($worksheet->getPageSetup()->getScale() !== null) { $objWriter->writeAttribute('scale', (string) $worksheet->getPageSetup()->getScale()); } if ($worksheet->getPageSetup()->getFitToHeight() !== null) { $objWriter->writeAttribute('fitToHeight', (string) $worksheet->getPageSetup()->getFitToHeight()); } else { $objWriter->writeAttribute('fitToHeight', '0'); } if ($worksheet->getPageSetup()->getFitToWidth() !== null) { $objWriter->writeAttribute('fitToWidth', (string) $worksheet->getPageSetup()->getFitToWidth()); } else { $objWriter->writeAttribute('fitToWidth', '0'); } if (!empty($worksheet->getPageSetup()->getFirstPageNumber())) { $objWriter->writeAttribute('firstPageNumber', (string) $worksheet->getPageSetup()->getFirstPageNumber()); $objWriter->writeAttribute('useFirstPageNumber', '1'); } $objWriter->writeAttribute('pageOrder', $worksheet->getPageSetup()->getPageOrder()); $getUnparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); if (isset($getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'])) { $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId']); } $objWriter->endElement(); } /** * Write Header / Footer. */ private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // headerFooter $objWriter->startElement('headerFooter'); $objWriter->writeAttribute('differentOddEven', ($worksheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false')); $objWriter->writeAttribute('differentFirst', ($worksheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false')); $objWriter->writeAttribute('scaleWithDoc', ($worksheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false')); $objWriter->writeAttribute('alignWithMargins', ($worksheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false')); $objWriter->writeElement('oddHeader', $worksheet->getHeaderFooter()->getOddHeader()); $objWriter->writeElement('oddFooter', $worksheet->getHeaderFooter()->getOddFooter()); $objWriter->writeElement('evenHeader', $worksheet->getHeaderFooter()->getEvenHeader()); $objWriter->writeElement('evenFooter', $worksheet->getHeaderFooter()->getEvenFooter()); $objWriter->writeElement('firstHeader', $worksheet->getHeaderFooter()->getFirstHeader()); $objWriter->writeElement('firstFooter', $worksheet->getHeaderFooter()->getFirstFooter()); $objWriter->endElement(); } /** * Write Breaks. */ private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Get row and column breaks $aRowBreaks = []; $aColumnBreaks = []; foreach ($worksheet->getRowBreaks() as $cell => $break) { $aRowBreaks[$cell] = $break; } foreach ($worksheet->getColumnBreaks() as $cell => $break) { $aColumnBreaks[$cell] = $break; } // rowBreaks if (!empty($aRowBreaks)) { $objWriter->startElement('rowBreaks'); $objWriter->writeAttribute('count', (string) count($aRowBreaks)); $objWriter->writeAttribute('manualBreakCount', (string) count($aRowBreaks)); foreach ($aRowBreaks as $cell => $break) { $coords = Coordinate::coordinateFromString($cell); $objWriter->startElement('brk'); $objWriter->writeAttribute('id', $coords[1]); $objWriter->writeAttribute('man', '1'); $rowBreakMax = $break->getMaxColOrRow(); if ($rowBreakMax >= 0) { $objWriter->writeAttribute('max', "$rowBreakMax"); } $objWriter->endElement(); } $objWriter->endElement(); } // Second, write column breaks if (!empty($aColumnBreaks)) { $objWriter->startElement('colBreaks'); $objWriter->writeAttribute('count', (string) count($aColumnBreaks)); $objWriter->writeAttribute('manualBreakCount', (string) count($aColumnBreaks)); foreach ($aColumnBreaks as $cell => $break) { $coords = Coordinate::coordinateFromString($cell); $objWriter->startElement('brk'); $objWriter->writeAttribute('id', (string) ((int) $coords[0] - 1)); $objWriter->writeAttribute('man', '1'); $objWriter->endElement(); } $objWriter->endElement(); } } /** * Write SheetData. * * @param string[] $stringTable String table */ private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, array $stringTable): void { // Flipped stringtable, for faster index searching $aFlippedStringTable = $this->getParentWriter()->getWriterPartstringtable()->flipStringTable($stringTable); // sheetData $objWriter->startElement('sheetData'); // Get column count $colCount = Coordinate::columnIndexFromString($worksheet->getHighestColumn()); // Highest row number $highestRow = $worksheet->getHighestRow(); // Loop through cells building a comma-separated list of the columns in each row // This is a trade-off between the memory usage that is required for a full array of columns, // and execution speed /** @var array<int, string> $cellsByRow */ $cellsByRow = []; foreach ($worksheet->getCoordinates() as $coordinate) { [$column, $row] = Coordinate::coordinateFromString($coordinate); $cellsByRow[$row] = $cellsByRow[$row] ?? ''; $cellsByRow[$row] .= "{$column},"; } $currentRow = 0; while ($currentRow++ < $highestRow) { $isRowSet = isset($cellsByRow[$currentRow]); if ($isRowSet || $worksheet->rowDimensionExists($currentRow)) { // Get row dimension $rowDimension = $worksheet->getRowDimension($currentRow); // Write current row? $writeCurrentRow = $isRowSet || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() === false || $rowDimension->getCollapsed() === true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null; if ($writeCurrentRow) { // Start a new row $objWriter->startElement('row'); $objWriter->writeAttribute('r', "$currentRow"); $objWriter->writeAttribute('spans', '1:' . $colCount); // Row dimensions if ($rowDimension->getRowHeight() >= 0) { $objWriter->writeAttribute('customHeight', '1'); $objWriter->writeAttribute('ht', StringHelper::formatNumber($rowDimension->getRowHeight())); } // Row visibility if (!$rowDimension->getVisible() === true) { $objWriter->writeAttribute('hidden', 'true'); } // Collapsed if ($rowDimension->getCollapsed() === true) { $objWriter->writeAttribute('collapsed', 'true'); } // Outline level if ($rowDimension->getOutlineLevel() > 0) { $objWriter->writeAttribute('outlineLevel', (string) $rowDimension->getOutlineLevel()); } // Style if ($rowDimension->getXfIndex() !== null) { $objWriter->writeAttribute('s', (string) $rowDimension->getXfIndex()); $objWriter->writeAttribute('customFormat', '1'); } // Write cells if (isset($cellsByRow[$currentRow])) { // We have a comma-separated list of column names (with a trailing entry); split to an array $columnsInRow = explode(',', $cellsByRow[$currentRow]); array_pop($columnsInRow); foreach ($columnsInRow as $column) { // Write cell $coord = "$column$currentRow"; if ($worksheet->getCell($coord)->getIgnoredErrors()->getNumberStoredAsText()) { $this->numberStoredAsText .= " $coord"; } if ($worksheet->getCell($coord)->getIgnoredErrors()->getFormula()) { $this->formula .= " $coord"; } if ($worksheet->getCell($coord)->getIgnoredErrors()->getTwoDigitTextYear()) { $this->twoDigitTextYear .= " $coord"; } if ($worksheet->getCell($coord)->getIgnoredErrors()->getEvalError()) { $this->evalError .= " $coord"; } $this->writeCell($objWriter, $worksheet, $coord, $aFlippedStringTable); } } // End row $objWriter->endElement(); } } } $objWriter->endElement(); } /** * @param RichText|string $cellValue */ private function writeCellInlineStr(XMLWriter $objWriter, string $mappedType, $cellValue): void { $objWriter->writeAttribute('t', $mappedType); if (!$cellValue instanceof RichText) { $objWriter->startElement('is'); $objWriter->writeElement( 't', StringHelper::controlCharacterPHP2OOXML(htmlspecialchars($cellValue, Settings::htmlEntityFlags())) ); $objWriter->endElement(); } else { $objWriter->startElement('is'); $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $cellValue); $objWriter->endElement(); } } /** * @param RichText|string $cellValue * @param string[] $flippedStringTable */ private function writeCellString(XMLWriter $objWriter, string $mappedType, $cellValue, array $flippedStringTable): void { $objWriter->writeAttribute('t', $mappedType); if (!$cellValue instanceof RichText) { self::writeElementIf($objWriter, isset($flippedStringTable[$cellValue]), 'v', $flippedStringTable[$cellValue] ?? ''); } else { $objWriter->writeElement('v', $flippedStringTable[$cellValue->getHashCode()]); } } /** * @param float|int $cellValue */ private function writeCellNumeric(XMLWriter $objWriter, $cellValue): void { //force a decimal to be written if the type is float if (is_float($cellValue)) { // force point as decimal separator in case current locale uses comma $cellValue = str_replace(',', '.', (string) $cellValue); if (strpos($cellValue, '.') === false) { $cellValue = $cellValue . '.0'; } } $objWriter->writeElement('v', "$cellValue"); } private function writeCellBoolean(XMLWriter $objWriter, string $mappedType, bool $cellValue): void { $objWriter->writeAttribute('t', $mappedType); $objWriter->writeElement('v', $cellValue ? '1' : '0'); } private function writeCellError(XMLWriter $objWriter, string $mappedType, string $cellValue, string $formulaerr = '#NULL!'): void { $objWriter->writeAttribute('t', $mappedType); $cellIsFormula = substr($cellValue, 0, 1) === '='; self::writeElementIf($objWriter, $cellIsFormula, 'f', FunctionPrefix::addFunctionPrefixStripEquals($cellValue)); $objWriter->writeElement('v', $cellIsFormula ? $formulaerr : $cellValue); } private function writeCellFormula(XMLWriter $objWriter, string $cellValue, Cell $cell): void { $calculatedValue = $this->getParentWriter()->getPreCalculateFormulas() ? $cell->getCalculatedValue() : $cellValue; if (is_string($calculatedValue)) { if (ErrorValue::isError($calculatedValue)) { $this->writeCellError($objWriter, 'e', $cellValue, $calculatedValue); return; } $objWriter->writeAttribute('t', 'str'); $calculatedValue = StringHelper::controlCharacterPHP2OOXML($calculatedValue); } elseif (is_bool($calculatedValue)) { $objWriter->writeAttribute('t', 'b'); $calculatedValue = (int) $calculatedValue; } $attributes = $cell->getFormulaAttributes(); if (($attributes['t'] ?? null) === 'array') { $objWriter->startElement('f'); $objWriter->writeAttribute('t', 'array'); $objWriter->writeAttribute('ref', $cell->getCoordinate()); $objWriter->writeAttribute('aca', '1'); $objWriter->writeAttribute('ca', '1'); $objWriter->text(FunctionPrefix::addFunctionPrefixStripEquals($cellValue)); $objWriter->endElement(); } else { $objWriter->writeElement('f', FunctionPrefix::addFunctionPrefixStripEquals($cellValue)); self::writeElementIf( $objWriter, $this->getParentWriter()->getOffice2003Compatibility() === false, 'v', ($this->getParentWriter()->getPreCalculateFormulas() && !is_array($calculatedValue) && substr($calculatedValue ?? '', 0, 1) !== '#') ? StringHelper::formatNumber($calculatedValue) : '0' ); } } /** * Write Cell. * * @param string $cellAddress Cell Address * @param string[] $flippedStringTable String table (flipped), for faster index searching */ private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, string $cellAddress, array $flippedStringTable): void { // Cell $pCell = $worksheet->getCell($cellAddress); $objWriter->startElement('c'); $objWriter->writeAttribute('r', $cellAddress); // Sheet styles $xfi = $pCell->getXfIndex(); self::writeAttributeIf($objWriter, (bool) $xfi, 's', "$xfi"); // If cell value is supplied, write cell value $cellValue = $pCell->getValue(); if (is_object($cellValue) || $cellValue !== '') { // Map type $mappedType = $pCell->getDataType(); // Write data depending on its type switch (strtolower($mappedType)) { case 'inlinestr': // Inline string $this->writeCellInlineStr($objWriter, $mappedType, $cellValue); break; case 's': // String $this->writeCellString($objWriter, $mappedType, $cellValue, $flippedStringTable); break; case 'f': // Formula $this->writeCellFormula($objWriter, $cellValue, $pCell); break; case 'n': // Numeric $this->writeCellNumeric($objWriter, $cellValue); break; case 'b': // Boolean $this->writeCellBoolean($objWriter, $mappedType, $cellValue); break; case 'e': // Error $this->writeCellError($objWriter, $mappedType, $cellValue); } } $objWriter->endElement(); } /** * Write Drawings. * * @param bool $includeCharts Flag indicating if we should include drawing details for charts */ private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, $includeCharts = false): void { $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']); $chartCount = ($includeCharts) ? $worksheet->getChartCollection()->count() : 0; if ($chartCount == 0 && $worksheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) { return; } // If sheet contains drawings, add the relationships $objWriter->startElement('drawing'); $rId = 'rId1'; if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) { $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']; // take first. In future can be overriten // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels::writeWorksheetRelationships) $rId = reset($drawingOriginalIds); } $objWriter->writeAttribute('r:id', $rId); $objWriter->endElement(); } /** * Write LegacyDrawing. */ private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // If sheet contains comments, add the relationships $unparsedLoadedData = $worksheet->getParentOrThrow()->getUnparsedLoadedData(); if (count($worksheet->getComments()) > 0 || isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['legacyDrawing'])) { $objWriter->startElement('legacyDrawing'); $objWriter->writeAttribute('r:id', 'rId_comments_vml1'); $objWriter->endElement(); } } /** * Write LegacyDrawingHF. */ private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // If sheet contains images, add the relationships if (count($worksheet->getHeaderFooter()->getImages()) > 0) { $objWriter->startElement('legacyDrawingHF'); $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1'); $objWriter->endElement(); } } private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { if (empty($worksheet->getParentOrThrow()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'])) { return; } foreach ($worksheet->getParentOrThrow()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'] as $alternateContent) { $objWriter->writeRaw($alternateContent); } } /** * write <ExtLst> * only implementation conditionalFormattings. * * @url https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627 */ private function writeExtLst(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { $conditionalFormattingRuleExtList = []; foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { /** @var Conditional $conditional */ foreach ($conditionalStyles as $conditional) { $dataBar = $conditional->getDataBar(); if ($dataBar && $dataBar->getConditionalFormattingRuleExt()) { $conditionalFormattingRuleExtList[] = $dataBar->getConditionalFormattingRuleExt(); } } } if (count($conditionalFormattingRuleExtList) > 0) { $conditionalFormattingRuleExtNsPrefix = 'x14'; $objWriter->startElement('extLst'); $objWriter->startElement('ext'); $objWriter->writeAttribute('uri', '{78C0D931-6437-407d-A8EE-F0AAD7539E65}'); $objWriter->startElementNs($conditionalFormattingRuleExtNsPrefix, 'conditionalFormattings', null); foreach ($conditionalFormattingRuleExtList as $extension) { self::writeExtConditionalFormattingElements($objWriter, $extension); } $objWriter->endElement(); //end conditionalFormattings $objWriter->endElement(); //end ext $objWriter->endElement(); //end extLst } } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Style.php 0000644 00000065233 15002227416 0017324 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Protection; class Style extends WriterPart { /** * Write styles to XML format. * * @return string XML Output */ public function writeStyles(Spreadsheet $spreadsheet) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // styleSheet $objWriter->startElement('styleSheet'); $objWriter->writeAttribute('xml:space', 'preserve'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); // numFmts $objWriter->startElement('numFmts'); $objWriter->writeAttribute('count', (string) $this->getParentWriter()->getNumFmtHashTable()->count()); // numFmt for ($i = 0; $i < $this->getParentWriter()->getNumFmtHashTable()->count(); ++$i) { $this->writeNumFmt($objWriter, $this->getParentWriter()->getNumFmtHashTable()->getByIndex($i), $i); } $objWriter->endElement(); // fonts $objWriter->startElement('fonts'); $objWriter->writeAttribute('count', (string) $this->getParentWriter()->getFontHashTable()->count()); // font for ($i = 0; $i < $this->getParentWriter()->getFontHashTable()->count(); ++$i) { $thisfont = $this->getParentWriter()->getFontHashTable()->getByIndex($i); if ($thisfont !== null) { $this->writeFont($objWriter, $thisfont); } } $objWriter->endElement(); // fills $objWriter->startElement('fills'); $objWriter->writeAttribute('count', (string) $this->getParentWriter()->getFillHashTable()->count()); // fill for ($i = 0; $i < $this->getParentWriter()->getFillHashTable()->count(); ++$i) { $thisfill = $this->getParentWriter()->getFillHashTable()->getByIndex($i); if ($thisfill !== null) { $this->writeFill($objWriter, $thisfill); } } $objWriter->endElement(); // borders $objWriter->startElement('borders'); $objWriter->writeAttribute('count', (string) $this->getParentWriter()->getBordersHashTable()->count()); // border for ($i = 0; $i < $this->getParentWriter()->getBordersHashTable()->count(); ++$i) { $thisborder = $this->getParentWriter()->getBordersHashTable()->getByIndex($i); if ($thisborder !== null) { $this->writeBorder($objWriter, $thisborder); } } $objWriter->endElement(); // cellStyleXfs $objWriter->startElement('cellStyleXfs'); $objWriter->writeAttribute('count', '1'); // xf $objWriter->startElement('xf'); $objWriter->writeAttribute('numFmtId', '0'); $objWriter->writeAttribute('fontId', '0'); $objWriter->writeAttribute('fillId', '0'); $objWriter->writeAttribute('borderId', '0'); $objWriter->endElement(); $objWriter->endElement(); // cellXfs $objWriter->startElement('cellXfs'); $objWriter->writeAttribute('count', (string) count($spreadsheet->getCellXfCollection())); // xf $alignment = new Alignment(); $defaultAlignHash = $alignment->getHashCode(); if ($defaultAlignHash !== $spreadsheet->getDefaultStyle()->getAlignment()->getHashCode()) { $defaultAlignHash = ''; } foreach ($spreadsheet->getCellXfCollection() as $cellXf) { $this->writeCellStyleXf($objWriter, $cellXf, $spreadsheet, $defaultAlignHash); } $objWriter->endElement(); // cellStyles $objWriter->startElement('cellStyles'); $objWriter->writeAttribute('count', '1'); // cellStyle $objWriter->startElement('cellStyle'); $objWriter->writeAttribute('name', 'Normal'); $objWriter->writeAttribute('xfId', '0'); $objWriter->writeAttribute('builtinId', '0'); $objWriter->endElement(); $objWriter->endElement(); // dxfs $objWriter->startElement('dxfs'); $objWriter->writeAttribute('count', (string) $this->getParentWriter()->getStylesConditionalHashTable()->count()); // dxf for ($i = 0; $i < $this->getParentWriter()->getStylesConditionalHashTable()->count(); ++$i) { $thisstyle = $this->getParentWriter()->getStylesConditionalHashTable()->getByIndex($i); if ($thisstyle !== null) { $this->writeCellStyleDxf($objWriter, $thisstyle->getStyle()); } } $objWriter->endElement(); // tableStyles $objWriter->startElement('tableStyles'); $objWriter->writeAttribute('defaultTableStyle', 'TableStyleMedium9'); $objWriter->writeAttribute('defaultPivotStyle', 'PivotTableStyle1'); $objWriter->endElement(); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write Fill. */ private function writeFill(XMLWriter $objWriter, Fill $fill): void { // Check if this is a pattern type or gradient type if ( $fill->getFillType() === Fill::FILL_GRADIENT_LINEAR || $fill->getFillType() === Fill::FILL_GRADIENT_PATH ) { // Gradient fill $this->writeGradientFill($objWriter, $fill); } elseif ($fill->getFillType() !== null) { // Pattern fill $this->writePatternFill($objWriter, $fill); } } /** * Write Gradient Fill. */ private function writeGradientFill(XMLWriter $objWriter, Fill $fill): void { // fill $objWriter->startElement('fill'); // gradientFill $objWriter->startElement('gradientFill'); $objWriter->writeAttribute('type', (string) $fill->getFillType()); $objWriter->writeAttribute('degree', (string) $fill->getRotation()); // stop $objWriter->startElement('stop'); $objWriter->writeAttribute('position', '0'); // color if ($fill->getStartColor()->getARGB() !== null) { $objWriter->startElement('color'); $objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB()); $objWriter->endElement(); } $objWriter->endElement(); // stop $objWriter->startElement('stop'); $objWriter->writeAttribute('position', '1'); // color if ($fill->getEndColor()->getARGB() !== null) { $objWriter->startElement('color'); $objWriter->writeAttribute('rgb', $fill->getEndColor()->getARGB()); $objWriter->endElement(); } $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); } private static function writePatternColors(Fill $fill): bool { if ($fill->getFillType() === Fill::FILL_NONE) { return false; } return $fill->getFillType() === Fill::FILL_SOLID || $fill->getColorsChanged(); } /** * Write Pattern Fill. */ private function writePatternFill(XMLWriter $objWriter, Fill $fill): void { // fill $objWriter->startElement('fill'); // patternFill $objWriter->startElement('patternFill'); $objWriter->writeAttribute('patternType', (string) $fill->getFillType()); if (self::writePatternColors($fill)) { // fgColor if ($fill->getStartColor()->getARGB()) { if (!$fill->getEndColor()->getARGB() && $fill->getFillType() === Fill::FILL_SOLID) { $objWriter->startElement('bgColor'); $objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB()); } else { $objWriter->startElement('fgColor'); $objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB()); } $objWriter->endElement(); } // bgColor if ($fill->getEndColor()->getARGB()) { $objWriter->startElement('bgColor'); $objWriter->writeAttribute('rgb', $fill->getEndColor()->getARGB()); $objWriter->endElement(); } } $objWriter->endElement(); $objWriter->endElement(); } private function startFont(XMLWriter $objWriter, bool &$fontStarted): void { if (!$fontStarted) { $fontStarted = true; $objWriter->startElement('font'); } } /** * Write Font. */ private function writeFont(XMLWriter $objWriter, Font $font): void { $fontStarted = false; // font // Weird! The order of these elements actually makes a difference when opening Xlsx // files in Excel2003 with the compatibility pack. It's not documented behaviour, // and makes for a real WTF! // Bold. We explicitly write this element also when false (like MS Office Excel 2007 does // for conditional formatting). Otherwise it will apparently not be picked up in conditional // formatting style dialog if ($font->getBold() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('b'); $objWriter->writeAttribute('val', $font->getBold() ? '1' : '0'); $objWriter->endElement(); } // Italic if ($font->getItalic() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('i'); $objWriter->writeAttribute('val', $font->getItalic() ? '1' : '0'); $objWriter->endElement(); } // Strikethrough if ($font->getStrikethrough() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('strike'); $objWriter->writeAttribute('val', $font->getStrikethrough() ? '1' : '0'); $objWriter->endElement(); } // Underline if ($font->getUnderline() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('u'); $objWriter->writeAttribute('val', $font->getUnderline()); $objWriter->endElement(); } // Superscript / subscript if ($font->getSuperscript() === true || $font->getSubscript() === true) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('vertAlign'); if ($font->getSuperscript() === true) { $objWriter->writeAttribute('val', 'superscript'); } elseif ($font->getSubscript() === true) { $objWriter->writeAttribute('val', 'subscript'); } $objWriter->endElement(); } // Size if ($font->getSize() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('sz'); $objWriter->writeAttribute('val', StringHelper::formatNumber($font->getSize())); $objWriter->endElement(); } // Foreground color if ($font->getColor()->getARGB() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('color'); $objWriter->writeAttribute('rgb', $font->getColor()->getARGB()); $objWriter->endElement(); } // Name if ($font->getName() !== null) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('name'); $objWriter->writeAttribute('val', $font->getName()); $objWriter->endElement(); } if (!empty($font->getScheme())) { $this->startFont($objWriter, $fontStarted); $objWriter->startElement('scheme'); $objWriter->writeAttribute('val', $font->getScheme()); $objWriter->endElement(); } if ($fontStarted) { $objWriter->endElement(); } } /** * Write Border. */ private function writeBorder(XMLWriter $objWriter, Borders $borders): void { // Write border $objWriter->startElement('border'); // Diagonal? switch ($borders->getDiagonalDirection()) { case Borders::DIAGONAL_UP: $objWriter->writeAttribute('diagonalUp', 'true'); $objWriter->writeAttribute('diagonalDown', 'false'); break; case Borders::DIAGONAL_DOWN: $objWriter->writeAttribute('diagonalUp', 'false'); $objWriter->writeAttribute('diagonalDown', 'true'); break; case Borders::DIAGONAL_BOTH: $objWriter->writeAttribute('diagonalUp', 'true'); $objWriter->writeAttribute('diagonalDown', 'true'); break; } // BorderPr $this->writeBorderPr($objWriter, 'left', $borders->getLeft()); $this->writeBorderPr($objWriter, 'right', $borders->getRight()); $this->writeBorderPr($objWriter, 'top', $borders->getTop()); $this->writeBorderPr($objWriter, 'bottom', $borders->getBottom()); $this->writeBorderPr($objWriter, 'diagonal', $borders->getDiagonal()); $objWriter->endElement(); } /** @var mixed */ private static $scrutinizerFalse = false; /** * Write Cell Style Xf. */ private function writeCellStyleXf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $style, Spreadsheet $spreadsheet, string $defaultAlignHash): void { // xf $objWriter->startElement('xf'); $objWriter->writeAttribute('xfId', '0'); $objWriter->writeAttribute('fontId', (string) (int) $this->getParentWriter()->getFontHashTable()->getIndexForHashCode($style->getFont()->getHashCode())); if ($style->getQuotePrefix()) { $objWriter->writeAttribute('quotePrefix', '1'); } if ($style->getNumberFormat()->getBuiltInFormatCode() === self::$scrutinizerFalse) { $objWriter->writeAttribute('numFmtId', (string) (int) ($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($style->getNumberFormat()->getHashCode()) + 164)); } else { $objWriter->writeAttribute('numFmtId', (string) (int) $style->getNumberFormat()->getBuiltInFormatCode()); } $objWriter->writeAttribute('fillId', (string) (int) $this->getParentWriter()->getFillHashTable()->getIndexForHashCode($style->getFill()->getHashCode())); $objWriter->writeAttribute('borderId', (string) (int) $this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($style->getBorders()->getHashCode())); // Apply styles? $objWriter->writeAttribute('applyFont', ($spreadsheet->getDefaultStyle()->getFont()->getHashCode() != $style->getFont()->getHashCode()) ? '1' : '0'); $objWriter->writeAttribute('applyNumberFormat', ($spreadsheet->getDefaultStyle()->getNumberFormat()->getHashCode() != $style->getNumberFormat()->getHashCode()) ? '1' : '0'); $objWriter->writeAttribute('applyFill', ($spreadsheet->getDefaultStyle()->getFill()->getHashCode() != $style->getFill()->getHashCode()) ? '1' : '0'); $objWriter->writeAttribute('applyBorder', ($spreadsheet->getDefaultStyle()->getBorders()->getHashCode() != $style->getBorders()->getHashCode()) ? '1' : '0'); if ($defaultAlignHash !== '' && $defaultAlignHash === $style->getAlignment()->getHashCode()) { $applyAlignment = '0'; } else { $applyAlignment = '1'; } $objWriter->writeAttribute('applyAlignment', $applyAlignment); if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { $objWriter->writeAttribute('applyProtection', 'true'); } // alignment if ($applyAlignment === '1') { $objWriter->startElement('alignment'); $vertical = Alignment::VERTICAL_ALIGNMENT_FOR_XLSX[$style->getAlignment()->getVertical()] ?? ''; $horizontal = Alignment::HORIZONTAL_ALIGNMENT_FOR_XLSX[$style->getAlignment()->getHorizontal()] ?? ''; if ($horizontal !== '') { $objWriter->writeAttribute('horizontal', $horizontal); } if ($vertical !== '') { $objWriter->writeAttribute('vertical', $vertical); } if ($style->getAlignment()->getTextRotation() >= 0) { $textRotation = $style->getAlignment()->getTextRotation(); } else { $textRotation = 90 - $style->getAlignment()->getTextRotation(); } $objWriter->writeAttribute('textRotation', (string) $textRotation); $objWriter->writeAttribute('wrapText', ($style->getAlignment()->getWrapText() ? 'true' : 'false')); $objWriter->writeAttribute('shrinkToFit', ($style->getAlignment()->getShrinkToFit() ? 'true' : 'false')); if ($style->getAlignment()->getIndent() > 0) { $objWriter->writeAttribute('indent', (string) $style->getAlignment()->getIndent()); } if ($style->getAlignment()->getReadOrder() > 0) { $objWriter->writeAttribute('readingOrder', (string) $style->getAlignment()->getReadOrder()); } $objWriter->endElement(); } // protection if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { $objWriter->startElement('protection'); if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT) { $objWriter->writeAttribute('locked', ($style->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } if ($style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { $objWriter->writeAttribute('hidden', ($style->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } $objWriter->endElement(); } $objWriter->endElement(); } /** * Write Cell Style Dxf. */ private function writeCellStyleDxf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $style): void { // dxf $objWriter->startElement('dxf'); // font $this->writeFont($objWriter, $style->getFont()); // numFmt $this->writeNumFmt($objWriter, $style->getNumberFormat()); // fill $this->writeFill($objWriter, $style->getFill()); // alignment $horizontal = Alignment::HORIZONTAL_ALIGNMENT_FOR_XLSX[$style->getAlignment()->getHorizontal()] ?? ''; $vertical = Alignment::VERTICAL_ALIGNMENT_FOR_XLSX[$style->getAlignment()->getVertical()] ?? ''; $rotation = $style->getAlignment()->getTextRotation(); if ($horizontal || $vertical || $rotation !== null) { $objWriter->startElement('alignment'); if ($horizontal) { $objWriter->writeAttribute('horizontal', $horizontal); } if ($vertical) { $objWriter->writeAttribute('vertical', $vertical); } if ($rotation !== null) { if ($rotation >= 0) { $textRotation = $rotation; } else { $textRotation = 90 - $rotation; } $objWriter->writeAttribute('textRotation', (string) $textRotation); } $objWriter->endElement(); } // border $this->writeBorder($objWriter, $style->getBorders()); // protection if ((!empty($style->getProtection()->getLocked())) || (!empty($style->getProtection()->getHidden()))) { if ( $style->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT ) { $objWriter->startElement('protection'); if ( ($style->getProtection()->getLocked() !== null) && ($style->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT) ) { $objWriter->writeAttribute('locked', ($style->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } if ( ($style->getProtection()->getHidden() !== null) && ($style->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT) ) { $objWriter->writeAttribute('hidden', ($style->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } $objWriter->endElement(); } } $objWriter->endElement(); } /** * Write BorderPr. * * @param string $name Element name */ private function writeBorderPr(XMLWriter $objWriter, $name, Border $border): void { // Write BorderPr if ($border->getBorderStyle() === Border::BORDER_OMIT) { return; } $objWriter->startElement($name); if ($border->getBorderStyle() !== Border::BORDER_NONE) { $objWriter->writeAttribute('style', $border->getBorderStyle()); // color if ($border->getColor()->getARGB() !== null) { $objWriter->startElement('color'); $objWriter->writeAttribute('rgb', $border->getColor()->getARGB()); $objWriter->endElement(); } } $objWriter->endElement(); } /** * Write NumberFormat. * * @param int $id Number Format identifier */ private function writeNumFmt(XMLWriter $objWriter, ?NumberFormat $numberFormat, $id = 0): void { // Translate formatcode $formatCode = ($numberFormat === null) ? null : $numberFormat->getFormatCode(); // numFmt if ($formatCode !== null) { $objWriter->startElement('numFmt'); $objWriter->writeAttribute('numFmtId', (string) ($id + 164)); $objWriter->writeAttribute('formatCode', $formatCode); $objWriter->endElement(); } } /** * Get an array of all styles. * * @return \PhpOffice\PhpSpreadsheet\Style\Style[] All styles in PhpSpreadsheet */ public function allStyles(Spreadsheet $spreadsheet) { return $spreadsheet->getCellXfCollection(); } /** * Get an array of all conditional styles. * * @return Conditional[] All conditional styles in PhpSpreadsheet */ public function allConditionalStyles(Spreadsheet $spreadsheet) { // Get an array of all styles $aStyles = []; $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { foreach ($spreadsheet->getSheet($i)->getConditionalStylesCollection() as $conditionalStyles) { foreach ($conditionalStyles as $conditionalStyle) { $aStyles[] = $conditionalStyle; } } } return $aStyles; } /** * Get an array of all fills. * * @return Fill[] All fills in PhpSpreadsheet */ public function allFills(Spreadsheet $spreadsheet) { // Get an array of unique fills $aFills = []; // Two first fills are predefined $fill0 = new Fill(); $fill0->setFillType(Fill::FILL_NONE); $aFills[] = $fill0; $fill1 = new Fill(); $fill1->setFillType(Fill::FILL_PATTERN_GRAY125); $aFills[] = $fill1; // The remaining fills $aStyles = $this->allStyles($spreadsheet); /** @var \PhpOffice\PhpSpreadsheet\Style\Style $style */ foreach ($aStyles as $style) { if (!isset($aFills[$style->getFill()->getHashCode()])) { $aFills[$style->getFill()->getHashCode()] = $style->getFill(); } } return $aFills; } /** * Get an array of all fonts. * * @return Font[] All fonts in PhpSpreadsheet */ public function allFonts(Spreadsheet $spreadsheet) { // Get an array of unique fonts $aFonts = []; $aStyles = $this->allStyles($spreadsheet); /** @var \PhpOffice\PhpSpreadsheet\Style\Style $style */ foreach ($aStyles as $style) { if (!isset($aFonts[$style->getFont()->getHashCode()])) { $aFonts[$style->getFont()->getHashCode()] = $style->getFont(); } } return $aFonts; } /** * Get an array of all borders. * * @return Borders[] All borders in PhpSpreadsheet */ public function allBorders(Spreadsheet $spreadsheet) { // Get an array of unique borders $aBorders = []; $aStyles = $this->allStyles($spreadsheet); /** @var \PhpOffice\PhpSpreadsheet\Style\Style $style */ foreach ($aStyles as $style) { if (!isset($aBorders[$style->getBorders()->getHashCode()])) { $aBorders[$style->getBorders()->getHashCode()] = $style->getBorders(); } } return $aBorders; } /** * Get an array of all number formats. * * @return NumberFormat[] All number formats in PhpSpreadsheet */ public function allNumberFormats(Spreadsheet $spreadsheet) { // Get an array of unique number formats $aNumFmts = []; $aStyles = $this->allStyles($spreadsheet); /** @var \PhpOffice\PhpSpreadsheet\Style\Style $style */ foreach ($aStyles as $style) { if ($style->getNumberFormat()->getBuiltInFormatCode() === false && !isset($aNumFmts[$style->getNumberFormat()->getHashCode()])) { $aNumFmts[$style->getNumberFormat()->getHashCode()] = $style->getNumberFormat(); } } return $aNumFmts; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/FunctionPrefix.php 0000644 00000011506 15002227416 0021161 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; class FunctionPrefix { const XLFNREGEXP = '/(?:_xlfn\.)?((?:_xlws\.)?\b(' // functions added with Excel 2010 . 'beta[.]dist' . '|beta[.]inv' . '|binom[.]dist' . '|binom[.]inv' . '|ceiling[.]precise' . '|chisq[.]dist' . '|chisq[.]dist[.]rt' . '|chisq[.]inv' . '|chisq[.]inv[.]rt' . '|chisq[.]test' . '|confidence[.]norm' . '|confidence[.]t' . '|covariance[.]p' . '|covariance[.]s' . '|erf[.]precise' . '|erfc[.]precise' . '|expon[.]dist' . '|f[.]dist' . '|f[.]dist[.]rt' . '|f[.]inv' . '|f[.]inv[.]rt' . '|f[.]test' . '|floor[.]precise' . '|gamma[.]dist' . '|gamma[.]inv' . '|gammaln[.]precise' . '|lognorm[.]dist' . '|lognorm[.]inv' . '|mode[.]mult' . '|mode[.]sngl' . '|negbinom[.]dist' . '|networkdays[.]intl' . '|norm[.]dist' . '|norm[.]inv' . '|norm[.]s[.]dist' . '|norm[.]s[.]inv' . '|percentile[.]exc' . '|percentile[.]inc' . '|percentrank[.]exc' . '|percentrank[.]inc' . '|poisson[.]dist' . '|quartile[.]exc' . '|quartile[.]inc' . '|rank[.]avg' . '|rank[.]eq' . '|stdev[.]p' . '|stdev[.]s' . '|t[.]dist' . '|t[.]dist[.]2t' . '|t[.]dist[.]rt' . '|t[.]inv' . '|t[.]inv[.]2t' . '|t[.]test' . '|var[.]p' . '|var[.]s' . '|weibull[.]dist' . '|z[.]test' // functions added with Excel 2013 . '|acot' . '|acoth' . '|arabic' . '|averageifs' . '|binom[.]dist[.]range' . '|bitand' . '|bitlshift' . '|bitor' . '|bitrshift' . '|bitxor' . '|ceiling[.]math' . '|combina' . '|cot' . '|coth' . '|csc' . '|csch' . '|days' . '|dbcs' . '|decimal' . '|encodeurl' . '|filterxml' . '|floor[.]math' . '|formulatext' . '|gamma' . '|gauss' . '|ifna' . '|imcosh' . '|imcot' . '|imcsc' . '|imcsch' . '|imsec' . '|imsech' . '|imsinh' . '|imtan' . '|isformula' . '|iso[.]ceiling' . '|isoweeknum' . '|munit' . '|numbervalue' . '|pduration' . '|permutationa' . '|phi' . '|rri' . '|sec' . '|sech' . '|sheet' . '|sheets' . '|skew[.]p' . '|unichar' . '|unicode' . '|webservice' . '|xor' // functions added with Excel 2016 . '|forecast[.]et2' . '|forecast[.]ets[.]confint' . '|forecast[.]ets[.]seasonality' . '|forecast[.]ets[.]stat' . '|forecast[.]linear' . '|switch' // functions added with Excel 2019 . '|concat' . '|countifs' . '|ifs' . '|maxifs' . '|minifs' . '|sumifs' . '|textjoin' // functions added with Excel 365 . '|filter' . '|randarray' . '|anchorarray' . '|sequence' . '|sort' . '|sortby' . '|unique' . '|xlookup' . '|xmatch' . '|arraytotext' . '|call' . '|let' . '|lambda' . '|single' . '|register[.]id' . '|textafter' . '|textbefore' . '|textsplit' . '|valuetotext' . '))\s*\(/Umui'; const XLWSREGEXP = '/(?<!_xlws\.)(' // functions added with Excel 365 . 'filter' . '|sort' . ')\s*\(/mui'; /** * Prefix function name in string with _xlfn. where required. */ protected static function addXlfnPrefix(string $functionString): string { return (string) preg_replace(self::XLFNREGEXP, '_xlfn.$1(', $functionString); } /** * Prefix function name in string with _xlws. where required. */ protected static function addXlwsPrefix(string $functionString): string { return (string) preg_replace(self::XLWSREGEXP, '_xlws.$1(', $functionString); } /** * Prefix function name in string with _xlfn. where required. */ public static function addFunctionPrefix(string $functionString): string { return self::addXlwsPrefix(self::addXlfnPrefix($functionString)); } /** * Prefix function name in string with _xlfn. where required. * Leading character, expected to be equals sign, is stripped. */ public static function addFunctionPrefixStripEquals(string $functionString): string { return self::addFunctionPrefix(substr($functionString, 1)); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php 0000644 00000021121 15002227416 0017741 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Document\Properties; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; class DocProps extends WriterPart { /** * Write docProps/app.xml to XML format. * * @return string XML Output */ public function writeDocPropsApp(Spreadsheet $spreadsheet) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Properties $objWriter->startElement('Properties'); $objWriter->writeAttribute('xmlns', Namespaces::EXTENDED_PROPERTIES); $objWriter->writeAttribute('xmlns:vt', Namespaces::PROPERTIES_VTYPES); // Application $objWriter->writeElement('Application', 'Microsoft Excel'); // DocSecurity $objWriter->writeElement('DocSecurity', '0'); // ScaleCrop $objWriter->writeElement('ScaleCrop', 'false'); // HeadingPairs $objWriter->startElement('HeadingPairs'); // Vector $objWriter->startElement('vt:vector'); $objWriter->writeAttribute('size', '2'); $objWriter->writeAttribute('baseType', 'variant'); // Variant $objWriter->startElement('vt:variant'); $objWriter->writeElement('vt:lpstr', 'Worksheets'); $objWriter->endElement(); // Variant $objWriter->startElement('vt:variant'); $objWriter->writeElement('vt:i4', (string) $spreadsheet->getSheetCount()); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); // TitlesOfParts $objWriter->startElement('TitlesOfParts'); // Vector $objWriter->startElement('vt:vector'); $objWriter->writeAttribute('size', (string) $spreadsheet->getSheetCount()); $objWriter->writeAttribute('baseType', 'lpstr'); $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { $objWriter->writeElement('vt:lpstr', $spreadsheet->getSheet($i)->getTitle()); } $objWriter->endElement(); $objWriter->endElement(); // Company $objWriter->writeElement('Company', $spreadsheet->getProperties()->getCompany()); // Company $objWriter->writeElement('Manager', $spreadsheet->getProperties()->getManager()); // LinksUpToDate $objWriter->writeElement('LinksUpToDate', 'false'); // SharedDoc $objWriter->writeElement('SharedDoc', 'false'); // HyperlinkBase $objWriter->writeElement('HyperlinkBase', $spreadsheet->getProperties()->getHyperlinkBase()); // HyperlinksChanged $objWriter->writeElement('HyperlinksChanged', 'false'); // AppVersion $objWriter->writeElement('AppVersion', '12.0000'); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write docProps/core.xml to XML format. * * @return string XML Output */ public function writeDocPropsCore(Spreadsheet $spreadsheet) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // cp:coreProperties $objWriter->startElement('cp:coreProperties'); $objWriter->writeAttribute('xmlns:cp', Namespaces::CORE_PROPERTIES2); $objWriter->writeAttribute('xmlns:dc', Namespaces::DC_ELEMENTS); $objWriter->writeAttribute('xmlns:dcterms', Namespaces::DC_TERMS); $objWriter->writeAttribute('xmlns:dcmitype', Namespaces::DC_DCMITYPE); $objWriter->writeAttribute('xmlns:xsi', Namespaces::SCHEMA_INSTANCE); // dc:creator $objWriter->writeElement('dc:creator', $spreadsheet->getProperties()->getCreator()); // cp:lastModifiedBy $objWriter->writeElement('cp:lastModifiedBy', $spreadsheet->getProperties()->getLastModifiedBy()); // dcterms:created $objWriter->startElement('dcterms:created'); $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); $created = $spreadsheet->getProperties()->getCreated(); $date = Date::dateTimeFromTimestamp("$created"); $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); // dcterms:modified $objWriter->startElement('dcterms:modified'); $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); $created = $spreadsheet->getProperties()->getModified(); $date = Date::dateTimeFromTimestamp("$created"); $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); // dc:title $objWriter->writeElement('dc:title', $spreadsheet->getProperties()->getTitle()); // dc:description $objWriter->writeElement('dc:description', $spreadsheet->getProperties()->getDescription()); // dc:subject $objWriter->writeElement('dc:subject', $spreadsheet->getProperties()->getSubject()); // cp:keywords $objWriter->writeElement('cp:keywords', $spreadsheet->getProperties()->getKeywords()); // cp:category $objWriter->writeElement('cp:category', $spreadsheet->getProperties()->getCategory()); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write docProps/custom.xml to XML format. * * @return null|string XML Output */ public function writeDocPropsCustom(Spreadsheet $spreadsheet) { $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); if (empty($customPropertyList)) { return null; } // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // cp:coreProperties $objWriter->startElement('Properties'); $objWriter->writeAttribute('xmlns', Namespaces::CUSTOM_PROPERTIES); $objWriter->writeAttribute('xmlns:vt', Namespaces::PROPERTIES_VTYPES); foreach ($customPropertyList as $key => $customProperty) { $propertyValue = $spreadsheet->getProperties()->getCustomPropertyValue($customProperty); $propertyType = $spreadsheet->getProperties()->getCustomPropertyType($customProperty); $objWriter->startElement('property'); $objWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}'); $objWriter->writeAttribute('pid', (string) ($key + 2)); $objWriter->writeAttribute('name', $customProperty); switch ($propertyType) { case Properties::PROPERTY_TYPE_INTEGER: $objWriter->writeElement('vt:i4', $propertyValue); break; case Properties::PROPERTY_TYPE_FLOAT: $objWriter->writeElement('vt:r8', sprintf('%F', $propertyValue)); break; case Properties::PROPERTY_TYPE_BOOLEAN: $objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false'); break; case Properties::PROPERTY_TYPE_DATE: $objWriter->startElement('vt:filetime'); $date = Date::dateTimeFromTimestamp("$propertyValue"); $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); break; default: $objWriter->writeElement('vt:lpwstr', $propertyValue); break; } $objWriter->endElement(); } $objWriter->endElement(); return $objWriter->getData(); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsRibbon.php 0000644 00000003022 15002227416 0020251 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; class RelsRibbon extends WriterPart { /** * Write relationships for additional objects of custom UI (ribbon). * * @return string XML Output */ public function writeRibbonRelationships(Spreadsheet $spreadsheet) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Relationships $objWriter->startElement('Relationships'); $objWriter->writeAttribute('xmlns', Namespaces::RELATIONSHIPS); $localRels = $spreadsheet->getRibbonBinObjects('names'); if (is_array($localRels)) { foreach ($localRels as $aId => $aTarget) { $objWriter->startElement('Relationship'); $objWriter->writeAttribute('Id', $aId); $objWriter->writeAttribute('Type', Namespaces::IMAGE); $objWriter->writeAttribute('Target', $aTarget); $objWriter->endElement(); } } $objWriter->endElement(); return $objWriter->getData(); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Chart.php 0000644 00000225345 15002227416 0017267 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Chart\Axis; use PhpOffice\PhpSpreadsheet\Chart\ChartColor; use PhpOffice\PhpSpreadsheet\Chart\DataSeries; use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues; use PhpOffice\PhpSpreadsheet\Chart\Layout; use PhpOffice\PhpSpreadsheet\Chart\Legend; use PhpOffice\PhpSpreadsheet\Chart\PlotArea; use PhpOffice\PhpSpreadsheet\Chart\Properties; use PhpOffice\PhpSpreadsheet\Chart\Title; use PhpOffice\PhpSpreadsheet\Chart\TrendLine; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; class Chart extends WriterPart { /** * @var int */ private $seriesIndex; /** * Write charts to XML format. * * @param mixed $calculateCellValues * * @return string XML Output */ public function writeChart(\PhpOffice\PhpSpreadsheet\Chart\Chart $chart, $calculateCellValues = true) { // Create XML writer $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // Ensure that data series values are up-to-date before we save if ($calculateCellValues) { $chart->refresh(); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // c:chartSpace $objWriter->startElement('c:chartSpace'); $objWriter->writeAttribute('xmlns:c', Namespaces::CHART); $objWriter->writeAttribute('xmlns:a', Namespaces::DRAWINGML); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); $objWriter->startElement('c:date1904'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); $objWriter->startElement('c:lang'); $objWriter->writeAttribute('val', 'en-GB'); $objWriter->endElement(); $objWriter->startElement('c:roundedCorners'); $objWriter->writeAttribute('val', $chart->getRoundedCorners() ? '1' : '0'); $objWriter->endElement(); $this->writeAlternateContent($objWriter); $objWriter->startElement('c:chart'); $this->writeTitle($objWriter, $chart->getTitle()); $objWriter->startElement('c:autoTitleDeleted'); $objWriter->writeAttribute('val', (string) (int) $chart->getAutoTitleDeleted()); $objWriter->endElement(); $objWriter->startElement('c:view3D'); $surface2D = false; $plotArea = $chart->getPlotArea(); if ($plotArea !== null) { $seriesArray = $plotArea->getPlotGroup(); foreach ($seriesArray as $series) { if ($series->getPlotType() === DataSeries::TYPE_SURFACECHART) { $surface2D = true; break; } } } $this->writeView3D($objWriter, $chart->getRotX(), 'c:rotX', $surface2D, 90); $this->writeView3D($objWriter, $chart->getRotY(), 'c:rotY', $surface2D); $this->writeView3D($objWriter, $chart->getRAngAx(), 'c:rAngAx', $surface2D); $this->writeView3D($objWriter, $chart->getPerspective(), 'c:perspective', $surface2D); $objWriter->endElement(); // view3D $this->writePlotArea($objWriter, $chart->getPlotArea(), $chart->getXAxisLabel(), $chart->getYAxisLabel(), $chart->getChartAxisX(), $chart->getChartAxisY()); $this->writeLegend($objWriter, $chart->getLegend()); $objWriter->startElement('c:plotVisOnly'); $objWriter->writeAttribute('val', (string) (int) $chart->getPlotVisibleOnly()); $objWriter->endElement(); $objWriter->startElement('c:dispBlanksAs'); $objWriter->writeAttribute('val', $chart->getDisplayBlanksAs()); $objWriter->endElement(); $objWriter->startElement('c:showDLblsOverMax'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); $objWriter->endElement(); // c:chart $objWriter->startElement('c:spPr'); if ($chart->getNoFill()) { $objWriter->startElement('a:noFill'); $objWriter->endElement(); // a:noFill } $fillColor = $chart->getFillColor(); if ($fillColor->isUsable()) { $this->writeColor($objWriter, $fillColor); } $borderLines = $chart->getBorderLines(); $this->writeLineStyles($objWriter, $borderLines); $this->writeEffects($objWriter, $borderLines); $objWriter->endElement(); // c:spPr $this->writePrintSettings($objWriter); $objWriter->endElement(); // c:chartSpace // Return return $objWriter->getData(); } private function writeView3D(XMLWriter $objWriter, ?int $value, string $tag, bool $surface2D, int $default = 0): void { if ($value === null && $surface2D) { $value = $default; } if ($value !== null) { $objWriter->startElement($tag); $objWriter->writeAttribute('val', "$value"); $objWriter->endElement(); } } /** * Write Chart Title. */ private function writeTitle(XMLWriter $objWriter, ?Title $title = null): void { if ($title === null) { return; } $objWriter->startElement('c:title'); $objWriter->startElement('c:tx'); $objWriter->startElement('c:rich'); $objWriter->startElement('a:bodyPr'); $objWriter->endElement(); $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); $objWriter->startElement('a:p'); $objWriter->startElement('a:pPr'); $objWriter->startElement('a:defRPr'); $objWriter->endElement(); $objWriter->endElement(); $caption = $title->getCaption(); if ((is_array($caption)) && (count($caption) > 0)) { $caption = $caption[0]; } $this->getParentWriter()->getWriterPartstringtable()->writeRichTextForCharts($objWriter, $caption, 'a'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $this->writeLayout($objWriter, $title->getLayout()); $objWriter->startElement('c:overlay'); $objWriter->writeAttribute('val', ($title->getOverlay()) ? '1' : '0'); $objWriter->endElement(); $objWriter->endElement(); } /** * Write Chart Legend. */ private function writeLegend(XMLWriter $objWriter, ?Legend $legend = null): void { if ($legend === null) { return; } $objWriter->startElement('c:legend'); $objWriter->startElement('c:legendPos'); $objWriter->writeAttribute('val', $legend->getPosition()); $objWriter->endElement(); $this->writeLayout($objWriter, $legend->getLayout()); $objWriter->startElement('c:overlay'); $objWriter->writeAttribute('val', ($legend->getOverlay()) ? '1' : '0'); $objWriter->endElement(); $objWriter->startElement('c:spPr'); $fillColor = $legend->getFillColor(); if ($fillColor->isUsable()) { $this->writeColor($objWriter, $fillColor); } $borderLines = $legend->getBorderLines(); $this->writeLineStyles($objWriter, $borderLines); $this->writeEffects($objWriter, $borderLines); $objWriter->endElement(); // c:spPr $legendText = $legend->getLegendText(); $objWriter->startElement('c:txPr'); $objWriter->startElement('a:bodyPr'); $objWriter->endElement(); $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); $objWriter->startElement('a:p'); $objWriter->startElement('a:pPr'); $objWriter->writeAttribute('rtl', '0'); $objWriter->startElement('a:defRPr'); if ($legendText !== null) { $this->writeColor($objWriter, $legendText->getFillColorObject()); $this->writeEffects($objWriter, $legendText); } $objWriter->endElement(); // a:defRpr $objWriter->endElement(); // a:pPr $objWriter->startElement('a:endParaRPr'); $objWriter->writeAttribute('lang', 'en-US'); $objWriter->endElement(); // a:endParaRPr $objWriter->endElement(); // a:p $objWriter->endElement(); // c:txPr $objWriter->endElement(); // c:legend } /** * Write Chart Plot Area. */ private function writePlotArea(XMLWriter $objWriter, ?PlotArea $plotArea, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null): void { if ($plotArea === null) { return; } $id1 = $id2 = $id3 = '0'; $this->seriesIndex = 0; $objWriter->startElement('c:plotArea'); $layout = $plotArea->getLayout(); $this->writeLayout($objWriter, $layout); $chartTypes = self::getChartType($plotArea); $catIsMultiLevelSeries = $valIsMultiLevelSeries = false; $plotGroupingType = ''; $chartType = null; foreach ($chartTypes as $chartType) { $objWriter->startElement('c:' . $chartType); $groupCount = $plotArea->getPlotGroupCount(); $plotGroup = null; for ($i = 0; $i < $groupCount; ++$i) { $plotGroup = $plotArea->getPlotGroupByIndex($i); $groupType = $plotGroup->getPlotType(); if ($groupType == $chartType) { $plotStyle = $plotGroup->getPlotStyle(); if (!empty($plotStyle) && $groupType === DataSeries::TYPE_RADARCHART) { $objWriter->startElement('c:radarStyle'); $objWriter->writeAttribute('val', $plotStyle); $objWriter->endElement(); } elseif (!empty($plotStyle) && $groupType === DataSeries::TYPE_SCATTERCHART) { $objWriter->startElement('c:scatterStyle'); $objWriter->writeAttribute('val', $plotStyle); $objWriter->endElement(); } elseif ($groupType === DataSeries::TYPE_SURFACECHART_3D || $groupType === DataSeries::TYPE_SURFACECHART) { $objWriter->startElement('c:wireframe'); $objWriter->writeAttribute('val', $plotStyle ? '1' : '0'); $objWriter->endElement(); } $this->writePlotGroup($plotGroup, $chartType, $objWriter, $catIsMultiLevelSeries, $valIsMultiLevelSeries, $plotGroupingType); } } $this->writeDataLabels($objWriter, $layout); if ($chartType === DataSeries::TYPE_LINECHART && $plotGroup) { // Line only, Line3D can't be smoothed $objWriter->startElement('c:smooth'); $objWriter->writeAttribute('val', (string) (int) $plotGroup->getSmoothLine()); $objWriter->endElement(); } elseif (($chartType === DataSeries::TYPE_BARCHART) || ($chartType === DataSeries::TYPE_BARCHART_3D)) { $objWriter->startElement('c:gapWidth'); $objWriter->writeAttribute('val', '150'); $objWriter->endElement(); if ($plotGroupingType == 'percentStacked' || $plotGroupingType == 'stacked') { $objWriter->startElement('c:overlap'); $objWriter->writeAttribute('val', '100'); $objWriter->endElement(); } } elseif ($chartType === DataSeries::TYPE_BUBBLECHART) { $scale = ($plotGroup === null) ? '' : (string) $plotGroup->getPlotStyle(); if ($scale !== '') { $objWriter->startElement('c:bubbleScale'); $objWriter->writeAttribute('val', $scale); $objWriter->endElement(); } $objWriter->startElement('c:showNegBubbles'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); } elseif ($chartType === DataSeries::TYPE_STOCKCHART) { $objWriter->startElement('c:hiLowLines'); $objWriter->endElement(); $gapWidth = $plotArea->getGapWidth(); $upBars = $plotArea->getUseUpBars(); $downBars = $plotArea->getUseDownBars(); if ($gapWidth !== null || $upBars || $downBars) { $objWriter->startElement('c:upDownBars'); if ($gapWidth !== null) { $objWriter->startElement('c:gapWidth'); $objWriter->writeAttribute('val', "$gapWidth"); $objWriter->endElement(); } if ($upBars) { $objWriter->startElement('c:upBars'); $objWriter->endElement(); } if ($downBars) { $objWriter->startElement('c:downBars'); $objWriter->endElement(); } $objWriter->endElement(); // c:upDownBars } } // Generate 3 unique numbers to use for axId values $id1 = '110438656'; $id2 = '110444544'; $id3 = '110365312'; // used in Surface Chart if (($chartType !== DataSeries::TYPE_PIECHART) && ($chartType !== DataSeries::TYPE_PIECHART_3D) && ($chartType !== DataSeries::TYPE_DONUTCHART)) { $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id1); $objWriter->endElement(); $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id2); $objWriter->endElement(); if ($chartType === DataSeries::TYPE_SURFACECHART_3D || $chartType === DataSeries::TYPE_SURFACECHART) { $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id3); $objWriter->endElement(); } } else { $objWriter->startElement('c:firstSliceAng'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); if ($chartType === DataSeries::TYPE_DONUTCHART) { $objWriter->startElement('c:holeSize'); $objWriter->writeAttribute('val', '50'); $objWriter->endElement(); } } $objWriter->endElement(); } if (($chartType !== DataSeries::TYPE_PIECHART) && ($chartType !== DataSeries::TYPE_PIECHART_3D) && ($chartType !== DataSeries::TYPE_DONUTCHART)) { if ($chartType === DataSeries::TYPE_BUBBLECHART) { $this->writeValueAxis($objWriter, $xAxisLabel, $chartType, $id2, $id1, $catIsMultiLevelSeries, $xAxis ?? new Axis()); } else { $this->writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $catIsMultiLevelSeries, $xAxis ?? new Axis()); } $this->writeValueAxis($objWriter, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $yAxis ?? new Axis()); if ($chartType === DataSeries::TYPE_SURFACECHART_3D || $chartType === DataSeries::TYPE_SURFACECHART) { $this->writeSerAxis($objWriter, $id2, $id3); } } $stops = $plotArea->getGradientFillStops(); if ($plotArea->getNoFill() || !empty($stops)) { $objWriter->startElement('c:spPr'); if ($plotArea->getNoFill()) { $objWriter->startElement('a:noFill'); $objWriter->endElement(); // a:noFill } if (!empty($stops)) { $objWriter->startElement('a:gradFill'); $objWriter->startElement('a:gsLst'); foreach ($stops as $stop) { $objWriter->startElement('a:gs'); $objWriter->writeAttribute('pos', (string) (Properties::PERCENTAGE_MULTIPLIER * (float) $stop[0])); $this->writeColor($objWriter, $stop[1], false); $objWriter->endElement(); // a:gs } $objWriter->endElement(); // a:gsLst $angle = $plotArea->getGradientFillAngle(); if ($angle !== null) { $objWriter->startElement('a:lin'); $objWriter->writeAttribute('ang', Properties::angleToXml($angle)); $objWriter->endElement(); // a:lin } $objWriter->endElement(); // a:gradFill } $objWriter->endElement(); // c:spPr } $objWriter->endElement(); // c:plotArea } private function writeDataLabelsBool(XMLWriter $objWriter, string $name, ?bool $value): void { if ($value !== null) { $objWriter->startElement("c:$name"); $objWriter->writeAttribute('val', $value ? '1' : '0'); $objWriter->endElement(); } } /** * Write Data Labels. */ private function writeDataLabels(XMLWriter $objWriter, ?Layout $chartLayout = null): void { if (!isset($chartLayout)) { return; } $objWriter->startElement('c:dLbls'); $fillColor = $chartLayout->getLabelFillColor(); $borderColor = $chartLayout->getLabelBorderColor(); if ($fillColor && $fillColor->isUsable()) { $objWriter->startElement('c:spPr'); $this->writeColor($objWriter, $fillColor); if ($borderColor && $borderColor->isUsable()) { $objWriter->startElement('a:ln'); $this->writeColor($objWriter, $borderColor); $objWriter->endElement(); // a:ln } $objWriter->endElement(); // c:spPr } $labelFont = $chartLayout->getLabelFont(); if ($labelFont !== null) { $objWriter->startElement('c:txPr'); $objWriter->startElement('a:bodyPr'); $objWriter->writeAttribute('wrap', 'square'); $objWriter->writeAttribute('lIns', '38100'); $objWriter->writeAttribute('tIns', '19050'); $objWriter->writeAttribute('rIns', '38100'); $objWriter->writeAttribute('bIns', '19050'); $objWriter->writeAttribute('anchor', 'ctr'); $objWriter->startElement('a:spAutoFit'); $objWriter->endElement(); // a:spAutoFit $objWriter->endElement(); // a:bodyPr $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); // a:lstStyle $this->writeLabelFont($objWriter, $labelFont, $chartLayout->getLabelEffects()); $objWriter->endElement(); // c:txPr } if ($chartLayout->getNumFmtCode() !== '') { $objWriter->startElement('c:numFmt'); $objWriter->writeAttribute('formatCode', $chartLayout->getnumFmtCode()); $objWriter->writeAttribute('sourceLinked', (string) (int) $chartLayout->getnumFmtLinked()); $objWriter->endElement(); // c:numFmt } if ($chartLayout->getDLblPos() !== '') { $objWriter->startElement('c:dLblPos'); $objWriter->writeAttribute('val', $chartLayout->getDLblPos()); $objWriter->endElement(); // c:dLblPos } $this->writeDataLabelsBool($objWriter, 'showLegendKey', $chartLayout->getShowLegendKey()); $this->writeDataLabelsBool($objWriter, 'showVal', $chartLayout->getShowVal()); $this->writeDataLabelsBool($objWriter, 'showCatName', $chartLayout->getShowCatName()); $this->writeDataLabelsBool($objWriter, 'showSerName', $chartLayout->getShowSerName()); $this->writeDataLabelsBool($objWriter, 'showPercent', $chartLayout->getShowPercent()); $this->writeDataLabelsBool($objWriter, 'showBubbleSize', $chartLayout->getShowBubbleSize()); $this->writeDataLabelsBool($objWriter, 'showLeaderLines', $chartLayout->getShowLeaderLines()); $objWriter->endElement(); // c:dLbls } /** * Write Category Axis. * * @param string $id1 * @param string $id2 * @param bool $isMultiLevelSeries */ private function writeCategoryAxis(XMLWriter $objWriter, ?Title $xAxisLabel, $id1, $id2, $isMultiLevelSeries, Axis $yAxis): void { // N.B. writeCategoryAxis may be invoked with the last parameter($yAxis) using $xAxis for ScatterChart, etc // In that case, xAxis may contain values like the yAxis, or it may be a date axis (LINECHART). $axisType = $yAxis->getAxisType(); if ($axisType !== '') { $objWriter->startElement("c:$axisType"); } elseif ($yAxis->getAxisIsNumericFormat()) { $objWriter->startElement('c:' . Axis::AXIS_TYPE_VALUE); } else { $objWriter->startElement('c:' . Axis::AXIS_TYPE_CATEGORY); } $majorGridlines = $yAxis->getMajorGridlines(); $minorGridlines = $yAxis->getMinorGridlines(); if ($id1 !== '0') { $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id1); $objWriter->endElement(); } $objWriter->startElement('c:scaling'); if ($yAxis->getAxisOptionsProperty('maximum') !== null) { $objWriter->startElement('c:max'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('maximum')); $objWriter->endElement(); } if ($yAxis->getAxisOptionsProperty('minimum') !== null) { $objWriter->startElement('c:min'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minimum')); $objWriter->endElement(); } if (!empty($yAxis->getAxisOptionsProperty('orientation'))) { $objWriter->startElement('c:orientation'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('orientation')); $objWriter->endElement(); } $objWriter->endElement(); // c:scaling $objWriter->startElement('c:delete'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('hidden') ?? '0'); $objWriter->endElement(); $objWriter->startElement('c:axPos'); $objWriter->writeAttribute('val', 'b'); $objWriter->endElement(); if ($majorGridlines !== null) { $objWriter->startElement('c:majorGridlines'); $objWriter->startElement('c:spPr'); $this->writeLineStyles($objWriter, $majorGridlines); $this->writeEffects($objWriter, $majorGridlines); $objWriter->endElement(); //end spPr $objWriter->endElement(); //end majorGridLines } if ($minorGridlines !== null && $minorGridlines->getObjectState()) { $objWriter->startElement('c:minorGridlines'); $objWriter->startElement('c:spPr'); $this->writeLineStyles($objWriter, $minorGridlines); $this->writeEffects($objWriter, $minorGridlines); $objWriter->endElement(); //end spPr $objWriter->endElement(); //end minorGridLines } if ($xAxisLabel !== null) { $objWriter->startElement('c:title'); $objWriter->startElement('c:tx'); $objWriter->startElement('c:rich'); $objWriter->startElement('a:bodyPr'); $objWriter->endElement(); $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); $objWriter->startElement('a:p'); $caption = $xAxisLabel->getCaption(); if (is_array($caption)) { $caption = $caption[0]; } $this->getParentWriter()->getWriterPartstringtable()->writeRichTextForCharts($objWriter, $caption, 'a'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); $layout = $xAxisLabel->getLayout(); $this->writeLayout($objWriter, $layout); $objWriter->startElement('c:overlay'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); $objWriter->endElement(); } $objWriter->startElement('c:numFmt'); $objWriter->writeAttribute('formatCode', $yAxis->getAxisNumberFormat()); $objWriter->writeAttribute('sourceLinked', $yAxis->getAxisNumberSourceLinked()); $objWriter->endElement(); if (!empty($yAxis->getAxisOptionsProperty('major_tick_mark'))) { $objWriter->startElement('c:majorTickMark'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('major_tick_mark')); $objWriter->endElement(); } if (!empty($yAxis->getAxisOptionsProperty('minor_tick_mark'))) { $objWriter->startElement('c:minorTickMark'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minor_tick_mark')); $objWriter->endElement(); } if (!empty($yAxis->getAxisOptionsProperty('axis_labels'))) { $objWriter->startElement('c:tickLblPos'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('axis_labels')); $objWriter->endElement(); } $textRotation = $yAxis->getAxisOptionsProperty('textRotation'); $axisText = $yAxis->getAxisText(); if ($axisText !== null || is_numeric($textRotation)) { $objWriter->startElement('c:txPr'); $objWriter->startElement('a:bodyPr'); if (is_numeric($textRotation)) { $objWriter->writeAttribute('rot', Properties::angleToXml((float) $textRotation)); } $objWriter->endElement(); // a:bodyPr $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); // a:lstStyle $this->writeLabelFont($objWriter, ($axisText === null) ? null : $axisText->getFont(), $axisText); $objWriter->endElement(); // c:txPr } $objWriter->startElement('c:spPr'); $this->writeColor($objWriter, $yAxis->getFillColorObject()); $this->writeLineStyles($objWriter, $yAxis, $yAxis->getNoFill()); $this->writeEffects($objWriter, $yAxis); $objWriter->endElement(); // spPr if ($yAxis->getAxisOptionsProperty('major_unit') !== null) { $objWriter->startElement('c:majorUnit'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('major_unit')); $objWriter->endElement(); } if ($yAxis->getAxisOptionsProperty('minor_unit') !== null) { $objWriter->startElement('c:minorUnit'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minor_unit')); $objWriter->endElement(); } if ($id2 !== '0') { $objWriter->startElement('c:crossAx'); $objWriter->writeAttribute('val', $id2); $objWriter->endElement(); if (!empty($yAxis->getAxisOptionsProperty('horizontal_crosses'))) { $objWriter->startElement('c:crosses'); $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('horizontal_crosses')); $objWriter->endElement(); } } $objWriter->startElement('c:auto'); // LineChart with dateAx wants '0' $objWriter->writeAttribute('val', ($axisType === Axis::AXIS_TYPE_DATE) ? '0' : '1'); $objWriter->endElement(); $objWriter->startElement('c:lblAlgn'); $objWriter->writeAttribute('val', 'ctr'); $objWriter->endElement(); $objWriter->startElement('c:lblOffset'); $objWriter->writeAttribute('val', '100'); $objWriter->endElement(); if ($axisType === Axis::AXIS_TYPE_DATE) { $property = 'baseTimeUnit'; $propertyVal = $yAxis->getAxisOptionsProperty($property); if (!empty($propertyVal)) { $objWriter->startElement("c:$property"); $objWriter->writeAttribute('val', $propertyVal); $objWriter->endElement(); } $property = 'majorTimeUnit'; $propertyVal = $yAxis->getAxisOptionsProperty($property); if (!empty($propertyVal)) { $objWriter->startElement("c:$property"); $objWriter->writeAttribute('val', $propertyVal); $objWriter->endElement(); } $property = 'minorTimeUnit'; $propertyVal = $yAxis->getAxisOptionsProperty($property); if (!empty($propertyVal)) { $objWriter->startElement("c:$property"); $objWriter->writeAttribute('val', $propertyVal); $objWriter->endElement(); } } if ($isMultiLevelSeries) { $objWriter->startElement('c:noMultiLvlLbl'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); } $objWriter->endElement(); } /** * Write Value Axis. * * @param null|string $groupType Chart type * @param string $id1 * @param string $id2 * @param bool $isMultiLevelSeries */ private function writeValueAxis(XMLWriter $objWriter, ?Title $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, Axis $xAxis): void { $objWriter->startElement('c:' . Axis::AXIS_TYPE_VALUE); $majorGridlines = $xAxis->getMajorGridlines(); $minorGridlines = $xAxis->getMinorGridlines(); if ($id2 !== '0') { $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id2); $objWriter->endElement(); } $objWriter->startElement('c:scaling'); if ($xAxis->getAxisOptionsProperty('maximum') !== null) { $objWriter->startElement('c:max'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('maximum')); $objWriter->endElement(); } if ($xAxis->getAxisOptionsProperty('minimum') !== null) { $objWriter->startElement('c:min'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minimum')); $objWriter->endElement(); } if (!empty($xAxis->getAxisOptionsProperty('orientation'))) { $objWriter->startElement('c:orientation'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('orientation')); $objWriter->endElement(); } $objWriter->endElement(); // c:scaling $objWriter->startElement('c:delete'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('hidden') ?? '0'); $objWriter->endElement(); $objWriter->startElement('c:axPos'); $objWriter->writeAttribute('val', 'l'); $objWriter->endElement(); if ($majorGridlines !== null) { $objWriter->startElement('c:majorGridlines'); $objWriter->startElement('c:spPr'); $this->writeLineStyles($objWriter, $majorGridlines); $this->writeEffects($objWriter, $majorGridlines); $objWriter->endElement(); //end spPr $objWriter->endElement(); //end majorGridLines } if ($minorGridlines !== null && $minorGridlines->getObjectState()) { $objWriter->startElement('c:minorGridlines'); $objWriter->startElement('c:spPr'); $this->writeLineStyles($objWriter, $minorGridlines); $this->writeEffects($objWriter, $minorGridlines); $objWriter->endElement(); //end spPr $objWriter->endElement(); //end minorGridLines } if ($yAxisLabel !== null) { $objWriter->startElement('c:title'); $objWriter->startElement('c:tx'); $objWriter->startElement('c:rich'); $objWriter->startElement('a:bodyPr'); $objWriter->endElement(); $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); $objWriter->startElement('a:p'); $caption = $yAxisLabel->getCaption(); if (is_array($caption)) { $caption = $caption[0]; } $this->getParentWriter()->getWriterPartstringtable()->writeRichTextForCharts($objWriter, $caption, 'a'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); if ($groupType !== DataSeries::TYPE_BUBBLECHART) { $layout = $yAxisLabel->getLayout(); $this->writeLayout($objWriter, $layout); } $objWriter->startElement('c:overlay'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); $objWriter->endElement(); } $objWriter->startElement('c:numFmt'); $objWriter->writeAttribute('formatCode', $xAxis->getAxisNumberFormat()); $objWriter->writeAttribute('sourceLinked', $xAxis->getAxisNumberSourceLinked()); $objWriter->endElement(); if (!empty($xAxis->getAxisOptionsProperty('major_tick_mark'))) { $objWriter->startElement('c:majorTickMark'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('major_tick_mark')); $objWriter->endElement(); } if (!empty($xAxis->getAxisOptionsProperty('minor_tick_mark'))) { $objWriter->startElement('c:minorTickMark'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minor_tick_mark')); $objWriter->endElement(); } if (!empty($xAxis->getAxisOptionsProperty('axis_labels'))) { $objWriter->startElement('c:tickLblPos'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('axis_labels')); $objWriter->endElement(); } $textRotation = $xAxis->getAxisOptionsProperty('textRotation'); $axisText = $xAxis->getAxisText(); if ($axisText !== null || is_numeric($textRotation)) { $objWriter->startElement('c:txPr'); $objWriter->startElement('a:bodyPr'); if (is_numeric($textRotation)) { $objWriter->writeAttribute('rot', Properties::angleToXml((float) $textRotation)); } $objWriter->endElement(); // a:bodyPr $objWriter->startElement('a:lstStyle'); $objWriter->endElement(); // a:lstStyle $this->writeLabelFont($objWriter, ($axisText === null) ? null : $axisText->getFont(), $axisText); $objWriter->endElement(); // c:txPr } $objWriter->startElement('c:spPr'); $this->writeColor($objWriter, $xAxis->getFillColorObject()); $this->writeLineStyles($objWriter, $xAxis, $xAxis->getNoFill()); $this->writeEffects($objWriter, $xAxis); $objWriter->endElement(); //end spPr if ($id1 !== '0') { $objWriter->startElement('c:crossAx'); $objWriter->writeAttribute('val', $id1); $objWriter->endElement(); if ($xAxis->getAxisOptionsProperty('horizontal_crosses_value') !== null) { $objWriter->startElement('c:crossesAt'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('horizontal_crosses_value')); $objWriter->endElement(); } else { $crosses = $xAxis->getAxisOptionsProperty('horizontal_crosses'); if ($crosses) { $objWriter->startElement('c:crosses'); $objWriter->writeAttribute('val', $crosses); $objWriter->endElement(); } } $crossBetween = $xAxis->getCrossBetween(); if ($crossBetween !== '') { $objWriter->startElement('c:crossBetween'); $objWriter->writeAttribute('val', $crossBetween); $objWriter->endElement(); } if ($xAxis->getAxisOptionsProperty('major_unit') !== null) { $objWriter->startElement('c:majorUnit'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('major_unit')); $objWriter->endElement(); } if ($xAxis->getAxisOptionsProperty('minor_unit') !== null) { $objWriter->startElement('c:minorUnit'); $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minor_unit')); $objWriter->endElement(); } } if ($isMultiLevelSeries) { if ($groupType !== DataSeries::TYPE_BUBBLECHART) { $objWriter->startElement('c:noMultiLvlLbl'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); } } $objWriter->endElement(); } /** * Write Ser Axis, for Surface chart. */ private function writeSerAxis(XMLWriter $objWriter, string $id2, string $id3): void { $objWriter->startElement('c:serAx'); $objWriter->startElement('c:axId'); $objWriter->writeAttribute('val', $id3); $objWriter->endElement(); // axId $objWriter->startElement('c:scaling'); $objWriter->startElement('c:orientation'); $objWriter->writeAttribute('val', 'minMax'); $objWriter->endElement(); // orientation $objWriter->endElement(); // scaling $objWriter->startElement('c:delete'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); // delete $objWriter->startElement('c:axPos'); $objWriter->writeAttribute('val', 'b'); $objWriter->endElement(); // axPos $objWriter->startElement('c:majorTickMark'); $objWriter->writeAttribute('val', 'out'); $objWriter->endElement(); // majorTickMark $objWriter->startElement('c:minorTickMark'); $objWriter->writeAttribute('val', 'none'); $objWriter->endElement(); // minorTickMark $objWriter->startElement('c:tickLblPos'); $objWriter->writeAttribute('val', 'nextTo'); $objWriter->endElement(); // tickLblPos $objWriter->startElement('c:crossAx'); $objWriter->writeAttribute('val', $id2); $objWriter->endElement(); // crossAx $objWriter->startElement('c:crosses'); $objWriter->writeAttribute('val', 'autoZero'); $objWriter->endElement(); // crosses $objWriter->endElement(); //serAx } /** * Get the data series type(s) for a chart plot series. * * @return string[] */ private static function getChartType(PlotArea $plotArea): array { $groupCount = $plotArea->getPlotGroupCount(); if ($groupCount == 1) { $chartType = [$plotArea->getPlotGroupByIndex(0)->getPlotType()]; } else { $chartTypes = []; for ($i = 0; $i < $groupCount; ++$i) { $chartTypes[] = $plotArea->getPlotGroupByIndex($i)->getPlotType(); } $chartType = array_unique($chartTypes); if (count($chartTypes) == 0) { throw new WriterException('Chart is not yet implemented'); } } return $chartType; } /** * Method writing plot series values. */ private function writePlotSeriesValuesElement(XMLWriter $objWriter, int $val, ?ChartColor $fillColor): void { if ($fillColor === null || !$fillColor->isUsable()) { return; } $objWriter->startElement('c:dPt'); $objWriter->startElement('c:idx'); $objWriter->writeAttribute('val', "$val"); $objWriter->endElement(); // c:idx $objWriter->startElement('c:spPr'); $this->writeColor($objWriter, $fillColor); $objWriter->endElement(); // c:spPr $objWriter->endElement(); // c:dPt } /** * Write Plot Group (series of related plots). * * @param string $groupType Type of plot for dataseries * @param bool $catIsMultiLevelSeries Is category a multi-series category * @param bool $valIsMultiLevelSeries Is value set a multi-series set * @param string $plotGroupingType Type of grouping for multi-series values */ private function writePlotGroup(?DataSeries $plotGroup, string $groupType, XMLWriter $objWriter, &$catIsMultiLevelSeries, &$valIsMultiLevelSeries, &$plotGroupingType): void { if ($plotGroup === null) { return; } if (($groupType == DataSeries::TYPE_BARCHART) || ($groupType == DataSeries::TYPE_BARCHART_3D)) { $objWriter->startElement('c:barDir'); $objWriter->writeAttribute('val', $plotGroup->getPlotDirection()); $objWriter->endElement(); } $plotGroupingType = $plotGroup->getPlotGrouping(); if ($plotGroupingType !== null && $groupType !== DataSeries::TYPE_SURFACECHART && $groupType !== DataSeries::TYPE_SURFACECHART_3D) { $objWriter->startElement('c:grouping'); $objWriter->writeAttribute('val', $plotGroupingType); $objWriter->endElement(); } // Get these details before the loop, because we can use the count to check for varyColors $plotSeriesOrder = $plotGroup->getPlotOrder(); $plotSeriesCount = count($plotSeriesOrder); if (($groupType !== DataSeries::TYPE_RADARCHART) && ($groupType !== DataSeries::TYPE_STOCKCHART)) { if ($groupType !== DataSeries::TYPE_LINECHART) { if (($groupType == DataSeries::TYPE_PIECHART) || ($groupType == DataSeries::TYPE_PIECHART_3D) || ($groupType == DataSeries::TYPE_DONUTCHART) || ($plotSeriesCount > 1)) { $objWriter->startElement('c:varyColors'); $objWriter->writeAttribute('val', '1'); $objWriter->endElement(); } else { $objWriter->startElement('c:varyColors'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); } } } $plotSeriesIdx = 0; foreach ($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) { $objWriter->startElement('c:ser'); $objWriter->startElement('c:idx'); $adder = array_key_exists(0, $plotSeriesOrder) ? $this->seriesIndex : 0; $objWriter->writeAttribute('val', (string) ($adder + $plotSeriesIdx)); $objWriter->endElement(); $objWriter->startElement('c:order'); $objWriter->writeAttribute('val', (string) ($adder + $plotSeriesRef)); $objWriter->endElement(); $plotLabel = $plotGroup->getPlotLabelByIndex($plotSeriesIdx); $labelFill = null; if ($plotLabel && $groupType === DataSeries::TYPE_LINECHART) { $labelFill = $plotLabel->getFillColorObject(); $labelFill = ($labelFill instanceof ChartColor) ? $labelFill : null; } // Values $plotSeriesValues = $plotGroup->getPlotValuesByIndex($plotSeriesIdx); if ($plotSeriesValues !== false && in_array($groupType, self::CUSTOM_COLOR_TYPES, true)) { $fillColorValues = $plotSeriesValues->getFillColorObject(); if ($fillColorValues !== null && is_array($fillColorValues)) { foreach ($plotSeriesValues->getDataValues() as $dataKey => $dataValue) { $this->writePlotSeriesValuesElement($objWriter, $dataKey, $fillColorValues[$dataKey] ?? null); } } } if ($plotSeriesValues !== false && $plotSeriesValues->getLabelLayout()) { $this->writeDataLabels($objWriter, $plotSeriesValues->getLabelLayout()); } // Labels $plotSeriesLabel = $plotGroup->getPlotLabelByIndex($plotSeriesIdx); if ($plotSeriesLabel && ($plotSeriesLabel->getPointCount() > 0)) { $objWriter->startElement('c:tx'); $objWriter->startElement('c:strRef'); $this->writePlotSeriesLabel($plotSeriesLabel, $objWriter); $objWriter->endElement(); $objWriter->endElement(); } // Formatting for the points if ( $plotSeriesValues !== false ) { $objWriter->startElement('c:spPr'); if ($plotLabel && $groupType !== DataSeries::TYPE_LINECHART) { $fillColor = $plotLabel->getFillColorObject(); if ($fillColor !== null && !is_array($fillColor) && $fillColor->isUsable()) { $this->writeColor($objWriter, $fillColor); } } $fillObject = $labelFill ?? $plotSeriesValues->getFillColorObject(); $callLineStyles = true; if ($fillObject instanceof ChartColor && $fillObject->isUsable()) { if ($groupType === DataSeries::TYPE_LINECHART) { $objWriter->startElement('a:ln'); $callLineStyles = false; } $this->writeColor($objWriter, $fillObject); if (!$callLineStyles) { $objWriter->endElement(); // a:ln } } $nofill = $groupType === DataSeries::TYPE_STOCKCHART || (($groupType === DataSeries::TYPE_SCATTERCHART || $groupType === DataSeries::TYPE_LINECHART) && !$plotSeriesValues->getScatterLines()); if ($callLineStyles) { $this->writeLineStyles($objWriter, $plotSeriesValues, $nofill); $this->writeEffects($objWriter, $plotSeriesValues); } $objWriter->endElement(); // c:spPr } if ($plotSeriesValues) { $plotSeriesMarker = $plotSeriesValues->getPointMarker(); $markerFillColor = $plotSeriesValues->getMarkerFillColor(); $fillUsed = $markerFillColor->IsUsable(); $markerBorderColor = $plotSeriesValues->getMarkerBorderColor(); $borderUsed = $markerBorderColor->isUsable(); if ($plotSeriesMarker || $fillUsed || $borderUsed) { $objWriter->startElement('c:marker'); $objWriter->startElement('c:symbol'); if ($plotSeriesMarker) { $objWriter->writeAttribute('val', $plotSeriesMarker); } $objWriter->endElement(); if ($plotSeriesMarker !== 'none') { $objWriter->startElement('c:size'); $objWriter->writeAttribute('val', (string) $plotSeriesValues->getPointSize()); $objWriter->endElement(); // c:size $objWriter->startElement('c:spPr'); $this->writeColor($objWriter, $markerFillColor); if ($borderUsed) { $objWriter->startElement('a:ln'); $this->writeColor($objWriter, $markerBorderColor); $objWriter->endElement(); // a:ln } $objWriter->endElement(); // spPr } $objWriter->endElement(); } } if (($groupType === DataSeries::TYPE_BARCHART) || ($groupType === DataSeries::TYPE_BARCHART_3D) || ($groupType === DataSeries::TYPE_BUBBLECHART)) { $objWriter->startElement('c:invertIfNegative'); $objWriter->writeAttribute('val', '0'); $objWriter->endElement(); } // Trendlines if ($plotSeriesValues !== false) { foreach ($plotSeriesValues->getTrendLines() as $trendLine) { $trendLineType = $trendLine->getTrendLineType(); $order = $trendLine->getOrder(); $period = $trendLine->getPeriod(); $dispRSqr = $trendLine->getDispRSqr(); $dispEq = $trendLine->getDispEq(); $forward = $trendLine->getForward(); $backward = $trendLine->getBackward(); $intercept = $trendLine->getIntercept(); $name = $trendLine->getName(); $trendLineColor = $trendLine->getLineColor(); // ChartColor $objWriter->startElement('c:trendline'); // N.B. lowercase 'ell' if ($name !== '') { $objWriter->startElement('c:name'); $objWriter->writeRawData($name); $objWriter->endElement(); // c:name } $objWriter->startElement('c:spPr'); if (!$trendLineColor->isUsable()) { // use dataSeriesValues line color as a backup if $trendLineColor is null $dsvLineColor = $plotSeriesValues->getLineColor(); if ($dsvLineColor->isUsable()) { $trendLine ->getLineColor() ->setColorProperties($dsvLineColor->getValue(), $dsvLineColor->getAlpha(), $dsvLineColor->getType()); } } // otherwise, hope Excel does the right thing $this->writeLineStyles($objWriter, $trendLine, false); // suppress noFill $objWriter->endElement(); // spPr $objWriter->startElement('c:trendlineType'); // N.B lowercase 'ell' $objWriter->writeAttribute('val', $trendLineType); $objWriter->endElement(); // trendlineType if ($backward !== 0.0) { $objWriter->startElement('c:backward'); $objWriter->writeAttribute('val', "$backward"); $objWriter->endElement(); // c:backward } if ($forward !== 0.0) { $objWriter->startElement('c:forward'); $objWriter->writeAttribute('val', "$forward"); $objWriter->endElement(); // c:forward } if ($intercept !== 0.0) { $objWriter->startElement('c:intercept'); $objWriter->writeAttribute('val', "$intercept"); $objWriter->endElement(); // c:intercept } if ($trendLineType == TrendLine::TRENDLINE_POLYNOMIAL) { $objWriter->startElement('c:order'); $objWriter->writeAttribute('val', $order); $objWriter->endElement(); // order } if ($trendLineType == TrendLine::TRENDLINE_MOVING_AVG) { $objWriter->startElement('c:period'); $objWriter->writeAttribute('val', $period); $objWriter->endElement(); // period } $objWriter->startElement('c:dispRSqr'); $objWriter->writeAttribute('val', $dispRSqr ? '1' : '0'); $objWriter->endElement(); $objWriter->startElement('c:dispEq'); $objWriter->writeAttribute('val', $dispEq ? '1' : '0'); $objWriter->endElement(); if ($groupType === DataSeries::TYPE_SCATTERCHART || $groupType === DataSeries::TYPE_LINECHART) { $objWriter->startElement('c:trendlineLbl'); $objWriter->startElement('c:numFmt'); $objWriter->writeAttribute('formatCode', 'General'); $objWriter->writeAttribute('sourceLinked', '0'); $objWriter->endElement(); // numFmt $objWriter->endElement(); // trendlineLbl } $objWriter->endElement(); // trendline } } // Category Labels $plotSeriesCategory = $plotGroup->getPlotCategoryByIndex($plotSeriesIdx); if ($plotSeriesCategory && ($plotSeriesCategory->getPointCount() > 0)) { $catIsMultiLevelSeries = $catIsMultiLevelSeries || $plotSeriesCategory->isMultiLevelSeries(); if (($groupType == DataSeries::TYPE_PIECHART) || ($groupType == DataSeries::TYPE_PIECHART_3D) || ($groupType == DataSeries::TYPE_DONUTCHART)) { $plotStyle = $plotGroup->getPlotStyle(); if (is_numeric($plotStyle)) { $objWriter->startElement('c:explosion'); $objWriter->writeAttribute('val', $plotStyle); $objWriter->endElement(); } } if (($groupType === DataSeries::TYPE_BUBBLECHART) || ($groupType === DataSeries::TYPE_SCATTERCHART)) { $objWriter->startElement('c:xVal'); } else { $objWriter->startElement('c:cat'); } // xVals (Categories) are not always 'str' // Test X-axis Label's Datatype to decide 'str' vs 'num' $CategoryDatatype = $plotSeriesCategory->getDataType(); if ($CategoryDatatype == DataSeriesValues::DATASERIES_TYPE_NUMBER) { $this->writePlotSeriesValues($plotSeriesCategory, $objWriter, $groupType, 'num'); } else { $this->writePlotSeriesValues($plotSeriesCategory, $objWriter, $groupType, 'str'); } $objWriter->endElement(); } // Values if ($plotSeriesValues) { $valIsMultiLevelSeries = $valIsMultiLevelSeries || $plotSeriesValues->isMultiLevelSeries(); if (($groupType === DataSeries::TYPE_BUBBLECHART) || ($groupType === DataSeries::TYPE_SCATTERCHART)) { $objWriter->startElement('c:yVal'); } else { $objWriter->startElement('c:val'); } $this->writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, 'num'); $objWriter->endElement(); if ($groupType === DataSeries::TYPE_SCATTERCHART && $plotGroup->getPlotStyle() === 'smoothMarker') { $objWriter->startElement('c:smooth'); $objWriter->writeAttribute('val', $plotSeriesValues->getSmoothLine() ? '1' : '0'); $objWriter->endElement(); } } if ($groupType === DataSeries::TYPE_BUBBLECHART) { if (!empty($plotGroup->getPlotBubbleSizes()[$plotSeriesIdx])) { $objWriter->startElement('c:bubbleSize'); $this->writePlotSeriesValues( $plotGroup->getPlotBubbleSizes()[$plotSeriesIdx], $objWriter, $groupType, 'num' ); $objWriter->endElement(); if ($plotSeriesValues !== false) { $objWriter->startElement('c:bubble3D'); $objWriter->writeAttribute('val', $plotSeriesValues->getBubble3D() ? '1' : '0'); $objWriter->endElement(); } } elseif ($plotSeriesValues !== false) { $this->writeBubbles($plotSeriesValues, $objWriter); } } $objWriter->endElement(); } $this->seriesIndex += $plotSeriesIdx + 1; } /** * Write Plot Series Label. */ private function writePlotSeriesLabel(?DataSeriesValues $plotSeriesLabel, XMLWriter $objWriter): void { if ($plotSeriesLabel === null) { return; } $objWriter->startElement('c:f'); $objWriter->writeRawData($plotSeriesLabel->getDataSource()); $objWriter->endElement(); $objWriter->startElement('c:strCache'); $objWriter->startElement('c:ptCount'); $objWriter->writeAttribute('val', (string) $plotSeriesLabel->getPointCount()); $objWriter->endElement(); foreach ($plotSeriesLabel->getDataValues() as $plotLabelKey => $plotLabelValue) { $objWriter->startElement('c:pt'); $objWriter->writeAttribute('idx', $plotLabelKey); $objWriter->startElement('c:v'); $objWriter->writeRawData($plotLabelValue); $objWriter->endElement(); $objWriter->endElement(); } $objWriter->endElement(); } /** * Write Plot Series Values. * * @param string $groupType Type of plot for dataseries * @param string $dataType Datatype of series values */ private function writePlotSeriesValues(?DataSeriesValues $plotSeriesValues, XMLWriter $objWriter, $groupType, $dataType = 'str'): void { if ($plotSeriesValues === null) { return; } if ($plotSeriesValues->isMultiLevelSeries()) { $levelCount = $plotSeriesValues->multiLevelCount(); $objWriter->startElement('c:multiLvlStrRef'); $objWriter->startElement('c:f'); $objWriter->writeRawData($plotSeriesValues->getDataSource()); $objWriter->endElement(); $objWriter->startElement('c:multiLvlStrCache'); $objWriter->startElement('c:ptCount'); $objWriter->writeAttribute('val', (string) $plotSeriesValues->getPointCount()); $objWriter->endElement(); for ($level = 0; $level < $levelCount; ++$level) { $objWriter->startElement('c:lvl'); foreach ($plotSeriesValues->getDataValues() as $plotSeriesKey => $plotSeriesValue) { if (isset($plotSeriesValue[$level])) { $objWriter->startElement('c:pt'); $objWriter->writeAttribute('idx', $plotSeriesKey); $objWriter->startElement('c:v'); $objWriter->writeRawData($plotSeriesValue[$level]); $objWriter->endElement(); $objWriter->endElement(); } } $objWriter->endElement(); } $objWriter->endElement(); $objWriter->endElement(); } else { $objWriter->startElement('c:' . $dataType . 'Ref'); $objWriter->startElement('c:f'); $objWriter->writeRawData($plotSeriesValues->getDataSource()); $objWriter->endElement(); $count = $plotSeriesValues->getPointCount(); $source = $plotSeriesValues->getDataSource(); $values = $plotSeriesValues->getDataValues(); if ($count > 1 || ($count === 1 && array_key_exists(0, $values) && "=$source" !== (string) $values[0])) { $objWriter->startElement('c:' . $dataType . 'Cache'); if (($groupType != DataSeries::TYPE_PIECHART) && ($groupType != DataSeries::TYPE_PIECHART_3D) && ($groupType != DataSeries::TYPE_DONUTCHART)) { if (($plotSeriesValues->getFormatCode() !== null) && ($plotSeriesValues->getFormatCode() !== '')) { $objWriter->startElement('c:formatCode'); $objWriter->writeRawData($plotSeriesValues->getFormatCode()); $objWriter->endElement(); } } $objWriter->startElement('c:ptCount'); $objWriter->writeAttribute('val', (string) $plotSeriesValues->getPointCount()); $objWriter->endElement(); $dataValues = $plotSeriesValues->getDataValues(); if (!empty($dataValues)) { foreach ($dataValues as $plotSeriesKey => $plotSeriesValue) { $objWriter->startElement('c:pt'); $objWriter->writeAttribute('idx', $plotSeriesKey); $objWriter->startElement('c:v'); $objWriter->writeRawData($plotSeriesValue); $objWriter->endElement(); $objWriter->endElement(); } } $objWriter->endElement(); // *Cache } $objWriter->endElement(); // *Ref } } private const CUSTOM_COLOR_TYPES = [ DataSeries::TYPE_BARCHART, DataSeries::TYPE_BARCHART_3D, DataSeries::TYPE_PIECHART, DataSeries::TYPE_PIECHART_3D, DataSeries::TYPE_DONUTCHART, ]; /** * Write Bubble Chart Details. */ private function writeBubbles(?DataSeriesValues $plotSeriesValues, XMLWriter $objWriter): void { if ($plotSeriesValues === null) { return; } $objWriter->startElement('c:bubbleSize'); $objWriter->startElement('c:numLit'); $objWriter->startElement('c:formatCode'); $objWriter->writeRawData('General'); $objWriter->endElement(); $objWriter->startElement('c:ptCount'); $objWriter->writeAttribute('val', (string) $plotSeriesValues->getPointCount()); $objWriter->endElement(); $dataValues = $plotSeriesValues->getDataValues(); if (!empty($dataValues)) { foreach ($dataValues as $plotSeriesKey => $plotSeriesValue) { $objWriter->startElement('c:pt'); $objWriter->writeAttribute('idx', $plotSeriesKey); $objWriter->startElement('c:v'); $objWriter->writeRawData('1'); $objWriter->endElement(); $objWriter->endElement(); } } $objWriter->endElement(); $objWriter->endElement(); $objWriter->startElement('c:bubble3D'); $objWriter->writeAttribute('val', $plotSeriesValues->getBubble3D() ? '1' : '0'); $objWriter->endElement(); } /** * Write Layout. */ private function writeLayout(XMLWriter $objWriter, ?Layout $layout = null): void { $objWriter->startElement('c:layout'); if ($layout !== null) { $objWriter->startElement('c:manualLayout'); $layoutTarget = $layout->getLayoutTarget(); if ($layoutTarget !== null) { $objWriter->startElement('c:layoutTarget'); $objWriter->writeAttribute('val', $layoutTarget); $objWriter->endElement(); } $xMode = $layout->getXMode(); if ($xMode !== null) { $objWriter->startElement('c:xMode'); $objWriter->writeAttribute('val', $xMode); $objWriter->endElement(); } $yMode = $layout->getYMode(); if ($yMode !== null) { $objWriter->startElement('c:yMode'); $objWriter->writeAttribute('val', $yMode); $objWriter->endElement(); } $x = $layout->getXPosition(); if ($x !== null) { $objWriter->startElement('c:x'); $objWriter->writeAttribute('val', "$x"); $objWriter->endElement(); } $y = $layout->getYPosition(); if ($y !== null) { $objWriter->startElement('c:y'); $objWriter->writeAttribute('val', "$y"); $objWriter->endElement(); } $w = $layout->getWidth(); if ($w !== null) { $objWriter->startElement('c:w'); $objWriter->writeAttribute('val', "$w"); $objWriter->endElement(); } $h = $layout->getHeight(); if ($h !== null) { $objWriter->startElement('c:h'); $objWriter->writeAttribute('val', "$h"); $objWriter->endElement(); } $objWriter->endElement(); } $objWriter->endElement(); } /** * Write Alternate Content block. */ private function writeAlternateContent(XMLWriter $objWriter): void { $objWriter->startElement('mc:AlternateContent'); $objWriter->writeAttribute('xmlns:mc', Namespaces::COMPATIBILITY); $objWriter->startElement('mc:Choice'); $objWriter->writeAttribute('Requires', 'c14'); $objWriter->writeAttribute('xmlns:c14', Namespaces::CHART_ALTERNATE); $objWriter->startElement('c14:style'); $objWriter->writeAttribute('val', '102'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->startElement('mc:Fallback'); $objWriter->startElement('c:style'); $objWriter->writeAttribute('val', '2'); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); } /** * Write Printer Settings. */ private function writePrintSettings(XMLWriter $objWriter): void { $objWriter->startElement('c:printSettings'); $objWriter->startElement('c:headerFooter'); $objWriter->endElement(); $objWriter->startElement('c:pageMargins'); $objWriter->writeAttribute('footer', '0.3'); $objWriter->writeAttribute('header', '0.3'); $objWriter->writeAttribute('r', '0.7'); $objWriter->writeAttribute('l', '0.7'); $objWriter->writeAttribute('t', '0.75'); $objWriter->writeAttribute('b', '0.75'); $objWriter->endElement(); $objWriter->startElement('c:pageSetup'); $objWriter->writeAttribute('orientation', 'portrait'); $objWriter->endElement(); $objWriter->endElement(); } private function writeEffects(XMLWriter $objWriter, Properties $yAxis): void { if ( !empty($yAxis->getSoftEdgesSize()) || !empty($yAxis->getShadowProperty('effect')) || !empty($yAxis->getGlowProperty('size')) ) { $objWriter->startElement('a:effectLst'); $this->writeGlow($objWriter, $yAxis); $this->writeShadow($objWriter, $yAxis); $this->writeSoftEdge($objWriter, $yAxis); $objWriter->endElement(); // effectLst } } private function writeShadow(XMLWriter $objWriter, Properties $xAxis): void { if (empty($xAxis->getShadowProperty('effect'))) { return; } /** @var string */ $effect = $xAxis->getShadowProperty('effect'); $objWriter->startElement("a:$effect"); if (is_numeric($xAxis->getShadowProperty('blur'))) { $objWriter->writeAttribute('blurRad', Properties::pointsToXml((float) $xAxis->getShadowProperty('blur'))); } if (is_numeric($xAxis->getShadowProperty('distance'))) { $objWriter->writeAttribute('dist', Properties::pointsToXml((float) $xAxis->getShadowProperty('distance'))); } if (is_numeric($xAxis->getShadowProperty('direction'))) { $objWriter->writeAttribute('dir', Properties::angleToXml((float) $xAxis->getShadowProperty('direction'))); } $algn = $xAxis->getShadowProperty('algn'); if (is_string($algn) && $algn !== '') { $objWriter->writeAttribute('algn', $algn); } foreach (['sx', 'sy'] as $sizeType) { $sizeValue = $xAxis->getShadowProperty(['size', $sizeType]); if (is_numeric($sizeValue)) { $objWriter->writeAttribute($sizeType, Properties::tenthOfPercentToXml((float) $sizeValue)); } } foreach (['kx', 'ky'] as $sizeType) { $sizeValue = $xAxis->getShadowProperty(['size', $sizeType]); if (is_numeric($sizeValue)) { $objWriter->writeAttribute($sizeType, Properties::angleToXml((float) $sizeValue)); } } $rotWithShape = $xAxis->getShadowProperty('rotWithShape'); if (is_numeric($rotWithShape)) { $objWriter->writeAttribute('rotWithShape', (string) (int) $rotWithShape); } $this->writeColor($objWriter, $xAxis->getShadowColorObject(), false); $objWriter->endElement(); } private function writeGlow(XMLWriter $objWriter, Properties $yAxis): void { $size = $yAxis->getGlowProperty('size'); if (empty($size)) { return; } $objWriter->startElement('a:glow'); $objWriter->writeAttribute('rad', Properties::pointsToXml((float) $size)); $this->writeColor($objWriter, $yAxis->getGlowColorObject(), false); $objWriter->endElement(); // glow } private function writeSoftEdge(XMLWriter $objWriter, Properties $yAxis): void { $softEdgeSize = $yAxis->getSoftEdgesSize(); if (empty($softEdgeSize)) { return; } $objWriter->startElement('a:softEdge'); $objWriter->writeAttribute('rad', Properties::pointsToXml((float) $softEdgeSize)); $objWriter->endElement(); //end softEdge } private function writeLineStyles(XMLWriter $objWriter, Properties $gridlines, bool $noFill = false): void { $objWriter->startElement('a:ln'); $widthTemp = $gridlines->getLineStyleProperty('width'); if (is_numeric($widthTemp)) { $objWriter->writeAttribute('w', Properties::pointsToXml((float) $widthTemp)); } $this->writeNotEmpty($objWriter, 'cap', $gridlines->getLineStyleProperty('cap')); $this->writeNotEmpty($objWriter, 'cmpd', $gridlines->getLineStyleProperty('compound')); if ($noFill) { $objWriter->startElement('a:noFill'); $objWriter->endElement(); } else { $this->writeColor($objWriter, $gridlines->getLineColor()); } $dash = $gridlines->getLineStyleProperty('dash'); if (!empty($dash)) { $objWriter->startElement('a:prstDash'); $this->writeNotEmpty($objWriter, 'val', $dash); $objWriter->endElement(); } if ($gridlines->getLineStyleProperty('join') === 'miter') { $objWriter->startElement('a:miter'); $objWriter->writeAttribute('lim', '800000'); $objWriter->endElement(); } elseif ($gridlines->getLineStyleProperty('join') === 'bevel') { $objWriter->startElement('a:bevel'); $objWriter->endElement(); } if ($gridlines->getLineStyleProperty(['arrow', 'head', 'type'])) { $objWriter->startElement('a:headEnd'); $objWriter->writeAttribute('type', $gridlines->getLineStyleProperty(['arrow', 'head', 'type'])); $this->writeNotEmpty($objWriter, 'w', $gridlines->getLineStyleArrowWidth('head')); $this->writeNotEmpty($objWriter, 'len', $gridlines->getLineStyleArrowLength('head')); $objWriter->endElement(); } if ($gridlines->getLineStyleProperty(['arrow', 'end', 'type'])) { $objWriter->startElement('a:tailEnd'); $objWriter->writeAttribute('type', $gridlines->getLineStyleProperty(['arrow', 'end', 'type'])); $this->writeNotEmpty($objWriter, 'w', $gridlines->getLineStyleArrowWidth('end')); $this->writeNotEmpty($objWriter, 'len', $gridlines->getLineStyleArrowLength('end')); $objWriter->endElement(); } $objWriter->endElement(); //end ln } private function writeNotEmpty(XMLWriter $objWriter, string $name, ?string $value): void { if ($value !== null && $value !== '') { $objWriter->writeAttribute($name, $value); } } private function writeColor(XMLWriter $objWriter, ChartColor $chartColor, bool $solidFill = true): void { $type = $chartColor->getType(); $value = $chartColor->getValue(); if (!empty($type) && !empty($value)) { if ($solidFill) { $objWriter->startElement('a:solidFill'); } $objWriter->startElement("a:$type"); $objWriter->writeAttribute('val', $value); $alpha = $chartColor->getAlpha(); if (is_numeric($alpha)) { $objWriter->startElement('a:alpha'); $objWriter->writeAttribute('val', ChartColor::alphaToXml((int) $alpha)); $objWriter->endElement(); // a:alpha } $brightness = $chartColor->getBrightness(); if (is_numeric($brightness)) { $brightness = (int) $brightness; $lumOff = 100 - $brightness; $objWriter->startElement('a:lumMod'); $objWriter->writeAttribute('val', ChartColor::alphaToXml($brightness)); $objWriter->endElement(); // a:lumMod $objWriter->startElement('a:lumOff'); $objWriter->writeAttribute('val', ChartColor::alphaToXml($lumOff)); $objWriter->endElement(); // a:lumOff } $objWriter->endElement(); //a:srgbClr/schemeClr/prstClr if ($solidFill) { $objWriter->endElement(); //a:solidFill } } } private function writeLabelFont(XMLWriter $objWriter, ?Font $labelFont, ?Properties $axisText): void { $objWriter->startElement('a:p'); $objWriter->startElement('a:pPr'); $objWriter->startElement('a:defRPr'); if ($labelFont !== null) { $fontSize = $labelFont->getSize(); if (is_numeric($fontSize)) { $fontSize *= (($fontSize < 100) ? 100 : 1); $objWriter->writeAttribute('sz', (string) $fontSize); } if ($labelFont->getBold() === true) { $objWriter->writeAttribute('b', '1'); } if ($labelFont->getItalic() === true) { $objWriter->writeAttribute('i', '1'); } $fontColor = $labelFont->getChartColor(); if ($fontColor !== null) { $this->writeColor($objWriter, $fontColor); } } if ($axisText !== null) { $this->writeEffects($objWriter, $axisText); } if ($labelFont !== null) { if (!empty($labelFont->getLatin())) { $objWriter->startElement('a:latin'); $objWriter->writeAttribute('typeface', $labelFont->getLatin()); $objWriter->endElement(); } if (!empty($labelFont->getEastAsian())) { $objWriter->startElement('a:eastAsian'); $objWriter->writeAttribute('typeface', $labelFont->getEastAsian()); $objWriter->endElement(); } if (!empty($labelFont->getComplexScript())) { $objWriter->startElement('a:complexScript'); $objWriter->writeAttribute('typeface', $labelFont->getComplexScript()); $objWriter->endElement(); } } $objWriter->endElement(); // a:defRPr $objWriter->endElement(); // a:pPr $objWriter->endElement(); // a:p } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php 0000644 00000017465 15002227416 0020025 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\DefinedNames as DefinedNamesWriter; class Workbook extends WriterPart { /** * Write workbook to XML format. * * @param bool $recalcRequired Indicate whether formulas should be recalculated before writing * * @return string XML Output */ public function writeWorkbook(Spreadsheet $spreadsheet, $recalcRequired = false) { // Create XML writer if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // workbook $objWriter->startElement('workbook'); $objWriter->writeAttribute('xml:space', 'preserve'); $objWriter->writeAttribute('xmlns', Namespaces::MAIN); $objWriter->writeAttribute('xmlns:r', Namespaces::SCHEMA_OFFICE_DOCUMENT); // fileVersion $this->writeFileVersion($objWriter); // workbookPr $this->writeWorkbookPr($objWriter); // workbookProtection $this->writeWorkbookProtection($objWriter, $spreadsheet); // bookViews if ($this->getParentWriter()->getOffice2003Compatibility() === false) { $this->writeBookViews($objWriter, $spreadsheet); } // sheets $this->writeSheets($objWriter, $spreadsheet); // definedNames (new DefinedNamesWriter($objWriter, $spreadsheet))->write(); // calcPr $this->writeCalcPr($objWriter, $recalcRequired); $objWriter->endElement(); // Return return $objWriter->getData(); } /** * Write file version. */ private function writeFileVersion(XMLWriter $objWriter): void { $objWriter->startElement('fileVersion'); $objWriter->writeAttribute('appName', 'xl'); $objWriter->writeAttribute('lastEdited', '4'); $objWriter->writeAttribute('lowestEdited', '4'); $objWriter->writeAttribute('rupBuild', '4505'); $objWriter->endElement(); } /** * Write WorkbookPr. */ private function writeWorkbookPr(XMLWriter $objWriter): void { $objWriter->startElement('workbookPr'); if (Date::getExcelCalendar() === Date::CALENDAR_MAC_1904) { $objWriter->writeAttribute('date1904', '1'); } $objWriter->writeAttribute('codeName', 'ThisWorkbook'); $objWriter->endElement(); } /** * Write BookViews. */ private function writeBookViews(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { // bookViews $objWriter->startElement('bookViews'); // workbookView $objWriter->startElement('workbookView'); $objWriter->writeAttribute('activeTab', (string) $spreadsheet->getActiveSheetIndex()); $objWriter->writeAttribute('autoFilterDateGrouping', ($spreadsheet->getAutoFilterDateGrouping() ? 'true' : 'false')); $objWriter->writeAttribute('firstSheet', (string) $spreadsheet->getFirstSheetIndex()); $objWriter->writeAttribute('minimized', ($spreadsheet->getMinimized() ? 'true' : 'false')); $objWriter->writeAttribute('showHorizontalScroll', ($spreadsheet->getShowHorizontalScroll() ? 'true' : 'false')); $objWriter->writeAttribute('showSheetTabs', ($spreadsheet->getShowSheetTabs() ? 'true' : 'false')); $objWriter->writeAttribute('showVerticalScroll', ($spreadsheet->getShowVerticalScroll() ? 'true' : 'false')); $objWriter->writeAttribute('tabRatio', (string) $spreadsheet->getTabRatio()); $objWriter->writeAttribute('visibility', $spreadsheet->getVisibility()); $objWriter->endElement(); $objWriter->endElement(); } /** * Write WorkbookProtection. */ private function writeWorkbookProtection(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { if ($spreadsheet->getSecurity()->isSecurityEnabled()) { $objWriter->startElement('workbookProtection'); $objWriter->writeAttribute('lockRevision', ($spreadsheet->getSecurity()->getLockRevision() ? 'true' : 'false')); $objWriter->writeAttribute('lockStructure', ($spreadsheet->getSecurity()->getLockStructure() ? 'true' : 'false')); $objWriter->writeAttribute('lockWindows', ($spreadsheet->getSecurity()->getLockWindows() ? 'true' : 'false')); if ($spreadsheet->getSecurity()->getRevisionsPassword() != '') { $objWriter->writeAttribute('revisionsPassword', $spreadsheet->getSecurity()->getRevisionsPassword()); } if ($spreadsheet->getSecurity()->getWorkbookPassword() != '') { $objWriter->writeAttribute('workbookPassword', $spreadsheet->getSecurity()->getWorkbookPassword()); } $objWriter->endElement(); } } /** * Write calcPr. * * @param bool $recalcRequired Indicate whether formulas should be recalculated before writing */ private function writeCalcPr(XMLWriter $objWriter, $recalcRequired = true): void { $objWriter->startElement('calcPr'); // Set the calcid to a higher value than Excel itself will use, otherwise Excel will always recalc // If MS Excel does do a recalc, then users opening a file in MS Excel will be prompted to save on exit // because the file has changed $objWriter->writeAttribute('calcId', '999999'); $objWriter->writeAttribute('calcMode', 'auto'); // fullCalcOnLoad isn't needed if we've recalculating for the save $objWriter->writeAttribute('calcCompleted', ($recalcRequired) ? '1' : '0'); $objWriter->writeAttribute('fullCalcOnLoad', ($recalcRequired) ? '0' : '1'); $objWriter->writeAttribute('forceFullCalc', ($recalcRequired) ? '0' : '1'); $objWriter->endElement(); } /** * Write sheets. */ private function writeSheets(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { // Write sheets $objWriter->startElement('sheets'); $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { // sheet $this->writeSheet( $objWriter, $spreadsheet->getSheet($i)->getTitle(), ($i + 1), ($i + 1 + 3), $spreadsheet->getSheet($i)->getSheetState() ); } $objWriter->endElement(); } /** * Write sheet. * * @param string $worksheetName Sheet name * @param int $worksheetId Sheet id * @param int $relId Relationship ID * @param string $sheetState Sheet state (visible, hidden, veryHidden) */ private function writeSheet(XMLWriter $objWriter, $worksheetName, $worksheetId = 1, $relId = 1, $sheetState = 'visible'): void { if ($worksheetName != '') { // Write sheet $objWriter->startElement('sheet'); $objWriter->writeAttribute('name', $worksheetName); $objWriter->writeAttribute('sheetId', (string) $worksheetId); if ($sheetState !== 'visible' && $sheetState != '') { $objWriter->writeAttribute('state', $sheetState); } $objWriter->writeAttribute('r:id', 'rId' . $relId); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); } } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php 0000644 00000001021 15002227416 0020310 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; abstract class WriterPart { /** * Parent Xlsx object. * * @var Xlsx */ private $parentWriter; /** * Get parent Xlsx object. * * @return Xlsx */ public function getParentWriter() { return $this->parentWriter; } /** * Set parent Xlsx object. */ public function __construct(Xlsx $writer) { $this->parentWriter = $writer; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php 0000644 00000062402 15002227416 0016217 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\HashTable; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing as WorksheetDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Chart; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Comments; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\ContentTypes; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\DocProps; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Drawing; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsRibbon; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsVBA; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\StringTable; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Style; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Table; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Theme; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Workbook; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet; use ZipArchive; use ZipStream\Exception\OverflowException; use ZipStream\ZipStream; class Xlsx extends BaseWriter { /** * Office2003 compatibility. * * @var bool */ private $office2003compatibility = false; /** * Private Spreadsheet. * * @var Spreadsheet */ private $spreadSheet; /** * Private string table. * * @var string[] */ private $stringTable = []; /** * Private unique Conditional HashTable. * * @var HashTable<Conditional> */ private $stylesConditionalHashTable; /** * Private unique Style HashTable. * * @var HashTable<\PhpOffice\PhpSpreadsheet\Style\Style> */ private $styleHashTable; /** * Private unique Fill HashTable. * * @var HashTable<Fill> */ private $fillHashTable; /** * Private unique \PhpOffice\PhpSpreadsheet\Style\Font HashTable. * * @var HashTable<Font> */ private $fontHashTable; /** * Private unique Borders HashTable. * * @var HashTable<Borders> */ private $bordersHashTable; /** * Private unique NumberFormat HashTable. * * @var HashTable<NumberFormat> */ private $numFmtHashTable; /** * Private unique \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable. * * @var HashTable<BaseDrawing> */ private $drawingHashTable; /** * Private handle for zip stream. * * @var ZipStream */ private $zip; /** * @var Chart */ private $writerPartChart; /** * @var Comments */ private $writerPartComments; /** * @var ContentTypes */ private $writerPartContentTypes; /** * @var DocProps */ private $writerPartDocProps; /** * @var Drawing */ private $writerPartDrawing; /** * @var Rels */ private $writerPartRels; /** * @var RelsRibbon */ private $writerPartRelsRibbon; /** * @var RelsVBA */ private $writerPartRelsVBA; /** * @var StringTable */ private $writerPartStringTable; /** * @var Style */ private $writerPartStyle; /** * @var Theme */ private $writerPartTheme; /** * @var Table */ private $writerPartTable; /** * @var Workbook */ private $writerPartWorkbook; /** * @var Worksheet */ private $writerPartWorksheet; /** * Create a new Xlsx Writer. */ public function __construct(Spreadsheet $spreadsheet) { // Assign PhpSpreadsheet $this->setSpreadsheet($spreadsheet); $this->writerPartChart = new Chart($this); $this->writerPartComments = new Comments($this); $this->writerPartContentTypes = new ContentTypes($this); $this->writerPartDocProps = new DocProps($this); $this->writerPartDrawing = new Drawing($this); $this->writerPartRels = new Rels($this); $this->writerPartRelsRibbon = new RelsRibbon($this); $this->writerPartRelsVBA = new RelsVBA($this); $this->writerPartStringTable = new StringTable($this); $this->writerPartStyle = new Style($this); $this->writerPartTheme = new Theme($this); $this->writerPartTable = new Table($this); $this->writerPartWorkbook = new Workbook($this); $this->writerPartWorksheet = new Worksheet($this); // Set HashTable variables // @phpstan-ignore-next-line $this->bordersHashTable = new HashTable(); // @phpstan-ignore-next-line $this->drawingHashTable = new HashTable(); // @phpstan-ignore-next-line $this->fillHashTable = new HashTable(); // @phpstan-ignore-next-line $this->fontHashTable = new HashTable(); // @phpstan-ignore-next-line $this->numFmtHashTable = new HashTable(); // @phpstan-ignore-next-line $this->styleHashTable = new HashTable(); // @phpstan-ignore-next-line $this->stylesConditionalHashTable = new HashTable(); } public function getWriterPartChart(): Chart { return $this->writerPartChart; } public function getWriterPartComments(): Comments { return $this->writerPartComments; } public function getWriterPartContentTypes(): ContentTypes { return $this->writerPartContentTypes; } public function getWriterPartDocProps(): DocProps { return $this->writerPartDocProps; } public function getWriterPartDrawing(): Drawing { return $this->writerPartDrawing; } public function getWriterPartRels(): Rels { return $this->writerPartRels; } public function getWriterPartRelsRibbon(): RelsRibbon { return $this->writerPartRelsRibbon; } public function getWriterPartRelsVBA(): RelsVBA { return $this->writerPartRelsVBA; } public function getWriterPartStringTable(): StringTable { return $this->writerPartStringTable; } public function getWriterPartStyle(): Style { return $this->writerPartStyle; } public function getWriterPartTheme(): Theme { return $this->writerPartTheme; } public function getWriterPartTable(): Table { return $this->writerPartTable; } public function getWriterPartWorkbook(): Workbook { return $this->writerPartWorkbook; } public function getWriterPartWorksheet(): Worksheet { return $this->writerPartWorksheet; } /** * Save PhpSpreadsheet to file. * * @param resource|string $filename */ public function save($filename, int $flags = 0): void { $this->processFlags($flags); // garbage collect $this->pathNames = []; $this->spreadSheet->garbageCollect(); $saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog(); Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false); $saveDateReturnType = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); // Create string lookup table $this->stringTable = []; for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { $this->stringTable = $this->getWriterPartStringTable()->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable); } // Create styles dictionaries $this->styleHashTable->addFromSource($this->getWriterPartStyle()->allStyles($this->spreadSheet)); $this->stylesConditionalHashTable->addFromSource($this->getWriterPartStyle()->allConditionalStyles($this->spreadSheet)); $this->fillHashTable->addFromSource($this->getWriterPartStyle()->allFills($this->spreadSheet)); $this->fontHashTable->addFromSource($this->getWriterPartStyle()->allFonts($this->spreadSheet)); $this->bordersHashTable->addFromSource($this->getWriterPartStyle()->allBorders($this->spreadSheet)); $this->numFmtHashTable->addFromSource($this->getWriterPartStyle()->allNumberFormats($this->spreadSheet)); // Create drawing dictionary $this->drawingHashTable->addFromSource($this->getWriterPartDrawing()->allDrawings($this->spreadSheet)); $zipContent = []; // Add [Content_Types].xml to ZIP file $zipContent['[Content_Types].xml'] = $this->getWriterPartContentTypes()->writeContentTypes($this->spreadSheet, $this->includeCharts); //if hasMacros, add the vbaProject.bin file, Certificate file(if exists) if ($this->spreadSheet->hasMacros()) { $macrosCode = $this->spreadSheet->getMacrosCode(); if ($macrosCode !== null) { // we have the code ? $zipContent['xl/vbaProject.bin'] = $macrosCode; //allways in 'xl', allways named vbaProject.bin if ($this->spreadSheet->hasMacrosCertificate()) { //signed macros ? // Yes : add the certificate file and the related rels file $zipContent['xl/vbaProjectSignature.bin'] = $this->spreadSheet->getMacrosCertificate(); $zipContent['xl/_rels/vbaProject.bin.rels'] = $this->getWriterPartRelsVBA()->writeVBARelationships(); } } } //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels) if ($this->spreadSheet->hasRibbon()) { $tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target'); $tmpRibbonTarget = is_string($tmpRibbonTarget) ? $tmpRibbonTarget : ''; $zipContent[$tmpRibbonTarget] = $this->spreadSheet->getRibbonXMLData('data'); if ($this->spreadSheet->hasRibbonBinObjects()) { $tmpRootPath = dirname($tmpRibbonTarget) . '/'; $ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write if (is_array($ribbonBinObjects)) { foreach ($ribbonBinObjects as $aPath => $aContent) { $zipContent[$tmpRootPath . $aPath] = $aContent; } } //the rels for files $zipContent[$tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels'] = $this->getWriterPartRelsRibbon()->writeRibbonRelationships($this->spreadSheet); } } // Add relationships to ZIP file $zipContent['_rels/.rels'] = $this->getWriterPartRels()->writeRelationships($this->spreadSheet); $zipContent['xl/_rels/workbook.xml.rels'] = $this->getWriterPartRels()->writeWorkbookRelationships($this->spreadSheet); // Add document properties to ZIP file $zipContent['docProps/app.xml'] = $this->getWriterPartDocProps()->writeDocPropsApp($this->spreadSheet); $zipContent['docProps/core.xml'] = $this->getWriterPartDocProps()->writeDocPropsCore($this->spreadSheet); $customPropertiesPart = $this->getWriterPartDocProps()->writeDocPropsCustom($this->spreadSheet); if ($customPropertiesPart !== null) { $zipContent['docProps/custom.xml'] = $customPropertiesPart; } // Add theme to ZIP file $zipContent['xl/theme/theme1.xml'] = $this->getWriterPartTheme()->writeTheme($this->spreadSheet); // Add string table to ZIP file $zipContent['xl/sharedStrings.xml'] = $this->getWriterPartStringTable()->writeStringTable($this->stringTable); // Add styles to ZIP file $zipContent['xl/styles.xml'] = $this->getWriterPartStyle()->writeStyles($this->spreadSheet); // Add workbook to ZIP file $zipContent['xl/workbook.xml'] = $this->getWriterPartWorkbook()->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas); $chartCount = 0; // Add worksheets for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { $zipContent['xl/worksheets/sheet' . ($i + 1) . '.xml'] = $this->getWriterPartWorksheet()->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts); if ($this->includeCharts) { $charts = $this->spreadSheet->getSheet($i)->getChartCollection(); if (count($charts) > 0) { foreach ($charts as $chart) { $zipContent['xl/charts/chart' . ($chartCount + 1) . '.xml'] = $this->getWriterPartChart()->writeChart($chart, $this->preCalculateFormulas); ++$chartCount; } } } } $chartRef1 = 0; $tableRef1 = 1; // Add worksheet relationships (drawings, ...) for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { // Add relationships $zipContent['xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts, $tableRef1); // Add unparsedLoadedData $sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName(); $unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData(); if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) { $zipContent[$ctrlProp['filePath']] = $ctrlProp['content']; } } if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) { $zipContent[$ctrlProp['filePath']] = $ctrlProp['content']; } } $drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection(); $drawingCount = count($drawings); if ($this->includeCharts) { $chartCount = $this->spreadSheet->getSheet($i)->getChartCount(); } // Add drawing and image relationship parts if (($drawingCount > 0) || ($chartCount > 0)) { // Drawing relationships $zipContent['xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts); // Drawings $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts); } elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) { // Drawings $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts); } // Add unparsed drawings if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['Drawings'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['Drawings'] as $relId => $drawingXml) { $drawingFile = array_search($relId, $unparsedLoadedData['sheets'][$sheetCodeName]['drawingOriginalIds']); if ($drawingFile !== false) { //$drawingFile = ltrim($drawingFile, '.'); //$zipContent['xl' . $drawingFile] = $drawingXml; $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $drawingXml; } } } // Add comment relationship parts $legacy = $unparsedLoadedData['sheets'][$this->spreadSheet->getSheet($i)->getCodeName()]['legacyDrawing'] ?? null; if (count($this->spreadSheet->getSheet($i)->getComments()) > 0 || $legacy !== null) { // VML Comments relationships $zipContent['xl/drawings/_rels/vmlDrawing' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeVMLDrawingRelationships($this->spreadSheet->getSheet($i)); // VML Comments $zipContent['xl/drawings/vmlDrawing' . ($i + 1) . '.vml'] = $legacy ?? $this->getWriterPartComments()->writeVMLComments($this->spreadSheet->getSheet($i)); } // Comments if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) { $zipContent['xl/comments' . ($i + 1) . '.xml'] = $this->getWriterPartComments()->writeComments($this->spreadSheet->getSheet($i)); // Media foreach ($this->spreadSheet->getSheet($i)->getComments() as $comment) { if ($comment->hasBackgroundImage()) { $image = $comment->getBackgroundImage(); $zipContent['xl/media/' . $image->getMediaFilename()] = $this->processDrawing($image); } } } // Add unparsed relationship parts if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'])) { foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'] as $vmlDrawing) { if (!isset($zipContent[$vmlDrawing['filePath']])) { $zipContent[$vmlDrawing['filePath']] = $vmlDrawing['content']; } } } // Add header/footer relationship parts if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { // VML Drawings $zipContent['xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml'] = $this->getWriterPartDrawing()->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i)); // VML Drawing relationships $zipContent['xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i)); // Media foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { $zipContent['xl/media/' . $image->getIndexedFilename()] = file_get_contents($image->getPath()); } } // Add Table parts $tables = $this->spreadSheet->getSheet($i)->getTableCollection(); foreach ($tables as $table) { $zipContent['xl/tables/table' . $tableRef1 . '.xml'] = $this->getWriterPartTable()->writeTable($table, $tableRef1++); } } // Add media for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) { if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) { $imageContents = null; $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath(); if (strpos($imagePath, 'zip://') !== false) { $imagePath = substr($imagePath, 6); $imagePathSplitted = explode('#', $imagePath); $imageZip = new ZipArchive(); $imageZip->open($imagePathSplitted[0]); $imageContents = $imageZip->getFromName($imagePathSplitted[1]); $imageZip->close(); unset($imageZip); } else { $imageContents = file_get_contents($imagePath); } $zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents; } elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) { ob_start(); /** @var callable */ $callable = $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(); call_user_func( $callable, $this->getDrawingHashTable()->getByIndex($i)->getImageResource() ); $imageContents = ob_get_contents(); ob_end_clean(); $zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents; } } Functions::setReturnDateType($saveDateReturnType); Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); $this->openFileHandle($filename); $this->zip = ZipStream0::newZipStream($this->fileHandle); $this->addZipFiles($zipContent); // Close file try { $this->zip->finish(); } catch (OverflowException $e) { throw new WriterException('Could not close resource.'); } $this->maybeCloseFileHandle(); } /** * Get Spreadsheet object. * * @return Spreadsheet */ public function getSpreadsheet() { return $this->spreadSheet; } /** * Set Spreadsheet object. * * @param Spreadsheet $spreadsheet PhpSpreadsheet object * * @return $this */ public function setSpreadsheet(Spreadsheet $spreadsheet) { $this->spreadSheet = $spreadsheet; return $this; } /** * Get string table. * * @return string[] */ public function getStringTable() { return $this->stringTable; } /** * Get Style HashTable. * * @return HashTable<\PhpOffice\PhpSpreadsheet\Style\Style> */ public function getStyleHashTable() { return $this->styleHashTable; } /** * Get Conditional HashTable. * * @return HashTable<Conditional> */ public function getStylesConditionalHashTable() { return $this->stylesConditionalHashTable; } /** * Get Fill HashTable. * * @return HashTable<Fill> */ public function getFillHashTable() { return $this->fillHashTable; } /** * Get \PhpOffice\PhpSpreadsheet\Style\Font HashTable. * * @return HashTable<Font> */ public function getFontHashTable() { return $this->fontHashTable; } /** * Get Borders HashTable. * * @return HashTable<Borders> */ public function getBordersHashTable() { return $this->bordersHashTable; } /** * Get NumberFormat HashTable. * * @return HashTable<NumberFormat> */ public function getNumFmtHashTable() { return $this->numFmtHashTable; } /** * Get \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable. * * @return HashTable<BaseDrawing> */ public function getDrawingHashTable() { return $this->drawingHashTable; } /** * Get Office2003 compatibility. * * @return bool */ public function getOffice2003Compatibility() { return $this->office2003compatibility; } /** * Set Office2003 compatibility. * * @param bool $office2003compatibility Office2003 compatibility? * * @return $this */ public function setOffice2003Compatibility($office2003compatibility) { $this->office2003compatibility = $office2003compatibility; return $this; } /** @var array */ private $pathNames = []; private function addZipFile(string $path, string $content): void { if (!in_array($path, $this->pathNames)) { $this->pathNames[] = $path; $this->zip->addFile($path, $content); } } private function addZipFiles(array $zipContent): void { foreach ($zipContent as $path => $content) { $this->addZipFile($path, $content); } } /** * @return mixed */ private function processDrawing(WorksheetDrawing $drawing) { $data = null; $filename = $drawing->getPath(); $imageData = getimagesize($filename); if (!empty($imageData)) { switch ($imageData[2]) { case 1: // GIF, not supported by BIFF8, we convert to PNG $image = imagecreatefromgif($filename); if ($image !== false) { ob_start(); imagepng($image); $data = ob_get_contents(); ob_end_clean(); } break; case 2: // JPEG $data = file_get_contents($filename); break; case 3: // PNG $data = file_get_contents($filename); break; case 6: // Windows DIB (BMP), we convert to PNG $image = imagecreatefrombmp($filename); if ($image !== false) { ob_start(); imagepng($image); $data = ob_get_contents(); ob_end_clean(); } break; } } return $data; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods.php 0000644 00000010707 15002227416 0016007 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; use PhpOffice\PhpSpreadsheet\Writer\Ods\Content; use PhpOffice\PhpSpreadsheet\Writer\Ods\Meta; use PhpOffice\PhpSpreadsheet\Writer\Ods\MetaInf; use PhpOffice\PhpSpreadsheet\Writer\Ods\Mimetype; use PhpOffice\PhpSpreadsheet\Writer\Ods\Settings; use PhpOffice\PhpSpreadsheet\Writer\Ods\Styles; use PhpOffice\PhpSpreadsheet\Writer\Ods\Thumbnails; use ZipStream\Exception\OverflowException; use ZipStream\ZipStream; class Ods extends BaseWriter { /** * Private PhpSpreadsheet. * * @var Spreadsheet */ private $spreadSheet; /** * @var Content */ private $writerPartContent; /** * @var Meta */ private $writerPartMeta; /** * @var MetaInf */ private $writerPartMetaInf; /** * @var Mimetype */ private $writerPartMimetype; /** * @var Settings */ private $writerPartSettings; /** * @var Styles */ private $writerPartStyles; /** * @var Thumbnails */ private $writerPartThumbnails; /** * Create a new Ods. */ public function __construct(Spreadsheet $spreadsheet) { $this->setSpreadsheet($spreadsheet); $this->writerPartContent = new Content($this); $this->writerPartMeta = new Meta($this); $this->writerPartMetaInf = new MetaInf($this); $this->writerPartMimetype = new Mimetype($this); $this->writerPartSettings = new Settings($this); $this->writerPartStyles = new Styles($this); $this->writerPartThumbnails = new Thumbnails($this); } public function getWriterPartContent(): Content { return $this->writerPartContent; } public function getWriterPartMeta(): Meta { return $this->writerPartMeta; } public function getWriterPartMetaInf(): MetaInf { return $this->writerPartMetaInf; } public function getWriterPartMimetype(): Mimetype { return $this->writerPartMimetype; } public function getWriterPartSettings(): Settings { return $this->writerPartSettings; } public function getWriterPartStyles(): Styles { return $this->writerPartStyles; } public function getWriterPartThumbnails(): Thumbnails { return $this->writerPartThumbnails; } /** * Save PhpSpreadsheet to file. * * @param resource|string $filename */ public function save($filename, int $flags = 0): void { $this->processFlags($flags); // garbage collect $this->spreadSheet->garbageCollect(); $this->openFileHandle($filename); $zip = $this->createZip(); $zip->addFile('META-INF/manifest.xml', $this->getWriterPartMetaInf()->write()); $zip->addFile('Thumbnails/thumbnail.png', $this->getWriterPartthumbnails()->write()); // Settings always need to be written before Content; Styles after Content $zip->addFile('settings.xml', $this->getWriterPartsettings()->write()); $zip->addFile('content.xml', $this->getWriterPartcontent()->write()); $zip->addFile('meta.xml', $this->getWriterPartmeta()->write()); $zip->addFile('mimetype', $this->getWriterPartmimetype()->write()); $zip->addFile('styles.xml', $this->getWriterPartstyles()->write()); // Close file try { $zip->finish(); } catch (OverflowException $e) { throw new WriterException('Could not close resource.'); } $this->maybeCloseFileHandle(); } /** * Create zip object. * * @return ZipStream */ private function createZip() { // Try opening the ZIP file if (!is_resource($this->fileHandle)) { throw new WriterException('Could not open resource for writing.'); } // Create new ZIP stream return ZipStream0::newZipStream($this->fileHandle); } /** * Get Spreadsheet object. * * @return Spreadsheet */ public function getSpreadsheet() { return $this->spreadSheet; } /** * Set Spreadsheet object. * * @param Spreadsheet $spreadsheet PhpSpreadsheet object * * @return $this */ public function setSpreadsheet(Spreadsheet $spreadsheet) { $this->spreadSheet = $spreadsheet; return $this; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf.php 0000644 00000022076 15002227416 0015775 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; abstract class Pdf extends Html { /** * Temporary storage directory. * * @var string */ protected $tempDir = ''; /** * Font. * * @var string */ protected $font = 'freesans'; /** * Orientation (Over-ride). * * @var ?string */ protected $orientation; /** * Paper size (Over-ride). * * @var ?int */ protected $paperSize; /** * Paper Sizes xRef List. * * @var array */ protected static $paperSizes = [ PageSetup::PAPERSIZE_LETTER => 'LETTER', // (8.5 in. by 11 in.) PageSetup::PAPERSIZE_LETTER_SMALL => 'LETTER', // (8.5 in. by 11 in.) PageSetup::PAPERSIZE_TABLOID => [792.00, 1224.00], // (11 in. by 17 in.) PageSetup::PAPERSIZE_LEDGER => [1224.00, 792.00], // (17 in. by 11 in.) PageSetup::PAPERSIZE_LEGAL => 'LEGAL', // (8.5 in. by 14 in.) PageSetup::PAPERSIZE_STATEMENT => [396.00, 612.00], // (5.5 in. by 8.5 in.) PageSetup::PAPERSIZE_EXECUTIVE => 'EXECUTIVE', // (7.25 in. by 10.5 in.) PageSetup::PAPERSIZE_A3 => 'A3', // (297 mm by 420 mm) PageSetup::PAPERSIZE_A4 => 'A4', // (210 mm by 297 mm) PageSetup::PAPERSIZE_A4_SMALL => 'A4', // (210 mm by 297 mm) PageSetup::PAPERSIZE_A5 => 'A5', // (148 mm by 210 mm) PageSetup::PAPERSIZE_B4 => 'B4', // (250 mm by 353 mm) PageSetup::PAPERSIZE_B5 => 'B5', // (176 mm by 250 mm) PageSetup::PAPERSIZE_FOLIO => 'FOLIO', // (8.5 in. by 13 in.) PageSetup::PAPERSIZE_QUARTO => [609.45, 779.53], // (215 mm by 275 mm) PageSetup::PAPERSIZE_STANDARD_1 => [720.00, 1008.00], // (10 in. by 14 in.) PageSetup::PAPERSIZE_STANDARD_2 => [792.00, 1224.00], // (11 in. by 17 in.) PageSetup::PAPERSIZE_NOTE => 'LETTER', // (8.5 in. by 11 in.) PageSetup::PAPERSIZE_NO9_ENVELOPE => [279.00, 639.00], // (3.875 in. by 8.875 in.) PageSetup::PAPERSIZE_NO10_ENVELOPE => [297.00, 684.00], // (4.125 in. by 9.5 in.) PageSetup::PAPERSIZE_NO11_ENVELOPE => [324.00, 747.00], // (4.5 in. by 10.375 in.) PageSetup::PAPERSIZE_NO12_ENVELOPE => [342.00, 792.00], // (4.75 in. by 11 in.) PageSetup::PAPERSIZE_NO14_ENVELOPE => [360.00, 828.00], // (5 in. by 11.5 in.) PageSetup::PAPERSIZE_C => [1224.00, 1584.00], // (17 in. by 22 in.) PageSetup::PAPERSIZE_D => [1584.00, 2448.00], // (22 in. by 34 in.) PageSetup::PAPERSIZE_E => [2448.00, 3168.00], // (34 in. by 44 in.) PageSetup::PAPERSIZE_DL_ENVELOPE => [311.81, 623.62], // (110 mm by 220 mm) PageSetup::PAPERSIZE_C5_ENVELOPE => 'C5', // (162 mm by 229 mm) PageSetup::PAPERSIZE_C3_ENVELOPE => 'C3', // (324 mm by 458 mm) PageSetup::PAPERSIZE_C4_ENVELOPE => 'C4', // (229 mm by 324 mm) PageSetup::PAPERSIZE_C6_ENVELOPE => 'C6', // (114 mm by 162 mm) PageSetup::PAPERSIZE_C65_ENVELOPE => [323.15, 649.13], // (114 mm by 229 mm) PageSetup::PAPERSIZE_B4_ENVELOPE => 'B4', // (250 mm by 353 mm) PageSetup::PAPERSIZE_B5_ENVELOPE => 'B5', // (176 mm by 250 mm) PageSetup::PAPERSIZE_B6_ENVELOPE => [498.90, 354.33], // (176 mm by 125 mm) PageSetup::PAPERSIZE_ITALY_ENVELOPE => [311.81, 651.97], // (110 mm by 230 mm) PageSetup::PAPERSIZE_MONARCH_ENVELOPE => [279.00, 540.00], // (3.875 in. by 7.5 in.) PageSetup::PAPERSIZE_6_3_4_ENVELOPE => [261.00, 468.00], // (3.625 in. by 6.5 in.) PageSetup::PAPERSIZE_US_STANDARD_FANFOLD => [1071.00, 792.00], // (14.875 in. by 11 in.) PageSetup::PAPERSIZE_GERMAN_STANDARD_FANFOLD => [612.00, 864.00], // (8.5 in. by 12 in.) PageSetup::PAPERSIZE_GERMAN_LEGAL_FANFOLD => 'FOLIO', // (8.5 in. by 13 in.) PageSetup::PAPERSIZE_ISO_B4 => 'B4', // (250 mm by 353 mm) PageSetup::PAPERSIZE_JAPANESE_DOUBLE_POSTCARD => [566.93, 419.53], // (200 mm by 148 mm) PageSetup::PAPERSIZE_STANDARD_PAPER_1 => [648.00, 792.00], // (9 in. by 11 in.) PageSetup::PAPERSIZE_STANDARD_PAPER_2 => [720.00, 792.00], // (10 in. by 11 in.) PageSetup::PAPERSIZE_STANDARD_PAPER_3 => [1080.00, 792.00], // (15 in. by 11 in.) PageSetup::PAPERSIZE_INVITE_ENVELOPE => [623.62, 623.62], // (220 mm by 220 mm) PageSetup::PAPERSIZE_LETTER_EXTRA_PAPER => [667.80, 864.00], // (9.275 in. by 12 in.) PageSetup::PAPERSIZE_LEGAL_EXTRA_PAPER => [667.80, 1080.00], // (9.275 in. by 15 in.) PageSetup::PAPERSIZE_TABLOID_EXTRA_PAPER => [841.68, 1296.00], // (11.69 in. by 18 in.) PageSetup::PAPERSIZE_A4_EXTRA_PAPER => [668.98, 912.76], // (236 mm by 322 mm) PageSetup::PAPERSIZE_LETTER_TRANSVERSE_PAPER => [595.80, 792.00], // (8.275 in. by 11 in.) PageSetup::PAPERSIZE_A4_TRANSVERSE_PAPER => 'A4', // (210 mm by 297 mm) PageSetup::PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER => [667.80, 864.00], // (9.275 in. by 12 in.) PageSetup::PAPERSIZE_SUPERA_SUPERA_A4_PAPER => [643.46, 1009.13], // (227 mm by 356 mm) PageSetup::PAPERSIZE_SUPERB_SUPERB_A3_PAPER => [864.57, 1380.47], // (305 mm by 487 mm) PageSetup::PAPERSIZE_LETTER_PLUS_PAPER => [612.00, 913.68], // (8.5 in. by 12.69 in.) PageSetup::PAPERSIZE_A4_PLUS_PAPER => [595.28, 935.43], // (210 mm by 330 mm) PageSetup::PAPERSIZE_A5_TRANSVERSE_PAPER => 'A5', // (148 mm by 210 mm) PageSetup::PAPERSIZE_JIS_B5_TRANSVERSE_PAPER => [515.91, 728.50], // (182 mm by 257 mm) PageSetup::PAPERSIZE_A3_EXTRA_PAPER => [912.76, 1261.42], // (322 mm by 445 mm) PageSetup::PAPERSIZE_A5_EXTRA_PAPER => [493.23, 666.14], // (174 mm by 235 mm) PageSetup::PAPERSIZE_ISO_B5_EXTRA_PAPER => [569.76, 782.36], // (201 mm by 276 mm) PageSetup::PAPERSIZE_A2_PAPER => 'A2', // (420 mm by 594 mm) PageSetup::PAPERSIZE_A3_TRANSVERSE_PAPER => 'A3', // (297 mm by 420 mm) PageSetup::PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER => [912.76, 1261.42], // (322 mm by 445 mm) ]; /** * Create a new PDF Writer instance. * * @param Spreadsheet $spreadsheet Spreadsheet object */ public function __construct(Spreadsheet $spreadsheet) { parent::__construct($spreadsheet); //$this->setUseInlineCss(true); $this->tempDir = File::sysGetTempDir() . '/phpsppdf'; $this->isPdf = true; } /** * Get Font. * * @return string */ public function getFont() { return $this->font; } /** * Set font. Examples: * 'arialunicid0-chinese-simplified' * 'arialunicid0-chinese-traditional' * 'arialunicid0-korean' * 'arialunicid0-japanese'. * * @param string $fontName * * @return $this */ public function setFont($fontName) { $this->font = $fontName; return $this; } /** * Get Paper Size. * * @return ?int */ public function getPaperSize() { return $this->paperSize; } /** * Set Paper Size. * * @param int $paperSize Paper size see PageSetup::PAPERSIZE_* * * @return self */ public function setPaperSize($paperSize) { $this->paperSize = $paperSize; return $this; } /** * Get Orientation. */ public function getOrientation(): ?string { return $this->orientation; } /** * Set Orientation. * * @param string $orientation Page orientation see PageSetup::ORIENTATION_* * * @return self */ public function setOrientation($orientation) { $this->orientation = $orientation; return $this; } /** * Get temporary storage directory. * * @return string */ public function getTempDir() { return $this->tempDir; } /** * Set temporary storage directory. * * @param string $temporaryDirectory Temporary storage directory * * @return self */ public function setTempDir($temporaryDirectory) { if (is_dir($temporaryDirectory)) { $this->tempDir = $temporaryDirectory; } else { throw new WriterException("Directory does not exist: $temporaryDirectory"); } return $this; } /** * Save Spreadsheet to PDF file, pre-save. * * @param string $filename Name of the file to save as * * @return resource */ protected function prepareForSave($filename) { // Open file $this->openFileHandle($filename); return $this->fileHandle; } /** * Save PhpSpreadsheet to PDF file, post-save. */ protected function restoreStateAfterSave(): void { $this->maybeCloseFileHandle(); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Html.php 0000644 00000200314 15002227416 0016161 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; use HTMLPurifier; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\Document\Properties; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\Font as SharedFont; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Html extends BaseWriter { /** * Spreadsheet object. * * @var Spreadsheet */ protected $spreadsheet; /** * Sheet index to write. * * @var null|int */ private $sheetIndex = 0; /** * Images root. * * @var string */ private $imagesRoot = ''; /** * embed images, or link to images. * * @var bool */ protected $embedImages = false; /** * Use inline CSS? * * @var bool */ private $useInlineCss = false; /** * Use embedded CSS? * * @var bool */ private $useEmbeddedCSS = true; /** * Array of CSS styles. * * @var array */ private $cssStyles; /** * Array of column widths in points. * * @var array */ private $columnWidths; /** * Default font. * * @var Font */ private $defaultFont; /** * Flag whether spans have been calculated. * * @var bool */ private $spansAreCalculated = false; /** * Excel cells that should not be written as HTML cells. * * @var array */ private $isSpannedCell = []; /** * Excel cells that are upper-left corner in a cell merge. * * @var array */ private $isBaseCell = []; /** * Excel rows that should not be written as HTML rows. * * @var array */ private $isSpannedRow = []; /** * Is the current writer creating PDF? * * @var bool */ protected $isPdf = false; /** * Is the current writer creating mPDF? * * @var bool */ protected $isMPdf = false; /** * Generate the Navigation block. * * @var bool */ private $generateSheetNavigationBlock = true; /** * Callback for editing generated html. * * @var null|callable */ private $editHtmlCallback; /** * Create a new HTML. */ public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; $this->defaultFont = $this->spreadsheet->getDefaultStyle()->getFont(); } /** * Save Spreadsheet to file. * * @param resource|string $filename */ public function save($filename, int $flags = 0): void { $this->processFlags($flags); // Open file $this->openFileHandle($filename); // Write html fwrite($this->fileHandle, $this->generateHTMLAll()); // Close file $this->maybeCloseFileHandle(); } /** * Save Spreadsheet as html to variable. * * @return string */ public function generateHtmlAll() { // garbage collect $this->spreadsheet->garbageCollect(); $saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog(); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false); $saveArrayReturnType = Calculation::getArrayReturnType(); Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE); // Build CSS $this->buildCSS(!$this->useInlineCss); $html = ''; // Write headers $html .= $this->generateHTMLHeader(!$this->useInlineCss); // Write navigation (tabs) if ((!$this->isPdf) && ($this->generateSheetNavigationBlock)) { $html .= $this->generateNavigation(); } // Write data $html .= $this->generateSheetData(); // Write footer $html .= $this->generateHTMLFooter(); $callback = $this->editHtmlCallback; if ($callback) { $html = $callback($html); } Calculation::setArrayReturnType($saveArrayReturnType); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); return $html; } /** * Set a callback to edit the entire HTML. * * The callback must accept the HTML as string as first parameter, * and it must return the edited HTML as string. */ public function setEditHtmlCallback(?callable $callback): void { $this->editHtmlCallback = $callback; } /** * Map VAlign. * * @param string $vAlign Vertical alignment * * @return string */ private function mapVAlign($vAlign) { return Alignment::VERTICAL_ALIGNMENT_FOR_HTML[$vAlign] ?? ''; } /** * Map HAlign. * * @param string $hAlign Horizontal alignment * * @return string */ private function mapHAlign($hAlign) { return Alignment::HORIZONTAL_ALIGNMENT_FOR_HTML[$hAlign] ?? ''; } const BORDER_ARR = [ Border::BORDER_NONE => 'none', Border::BORDER_DASHDOT => '1px dashed', Border::BORDER_DASHDOTDOT => '1px dotted', Border::BORDER_DASHED => '1px dashed', Border::BORDER_DOTTED => '1px dotted', Border::BORDER_DOUBLE => '3px double', Border::BORDER_HAIR => '1px solid', Border::BORDER_MEDIUM => '2px solid', Border::BORDER_MEDIUMDASHDOT => '2px dashed', Border::BORDER_MEDIUMDASHDOTDOT => '2px dotted', Border::BORDER_SLANTDASHDOT => '2px dashed', Border::BORDER_THICK => '3px solid', ]; /** * Map border style. * * @param int|string $borderStyle Sheet index * * @return string */ private function mapBorderStyle($borderStyle) { return array_key_exists($borderStyle, self::BORDER_ARR) ? self::BORDER_ARR[$borderStyle] : '1px solid'; } /** * Get sheet index. */ public function getSheetIndex(): ?int { return $this->sheetIndex; } /** * Set sheet index. * * @param int $sheetIndex Sheet index * * @return $this */ public function setSheetIndex($sheetIndex) { $this->sheetIndex = $sheetIndex; return $this; } /** * Get sheet index. * * @return bool */ public function getGenerateSheetNavigationBlock() { return $this->generateSheetNavigationBlock; } /** * Set sheet index. * * @param bool $generateSheetNavigationBlock Flag indicating whether the sheet navigation block should be generated or not * * @return $this */ public function setGenerateSheetNavigationBlock($generateSheetNavigationBlock) { $this->generateSheetNavigationBlock = (bool) $generateSheetNavigationBlock; return $this; } /** * Write all sheets (resets sheetIndex to NULL). * * @return $this */ public function writeAllSheets() { $this->sheetIndex = null; return $this; } private static function generateMeta(?string $val, string $desc): string { return ($val || $val === '0') ? (' <meta name="' . $desc . '" content="' . htmlspecialchars($val, Settings::htmlEntityFlags()) . '" />' . PHP_EOL) : ''; } public const BODY_LINE = ' <body>' . PHP_EOL; private const CUSTOM_TO_META = [ Properties::PROPERTY_TYPE_BOOLEAN => 'bool', Properties::PROPERTY_TYPE_DATE => 'date', Properties::PROPERTY_TYPE_FLOAT => 'float', Properties::PROPERTY_TYPE_INTEGER => 'int', Properties::PROPERTY_TYPE_STRING => 'string', ]; /** * Generate HTML header. * * @param bool $includeStyles Include styles? * * @return string */ public function generateHTMLHeader($includeStyles = false) { // Construct HTML $properties = $this->spreadsheet->getProperties(); $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . PHP_EOL; $html .= '<html xmlns="http://www.w3.org/1999/xhtml">' . PHP_EOL; $html .= ' <head>' . PHP_EOL; $html .= ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . PHP_EOL; $html .= ' <meta name="generator" content="PhpSpreadsheet, https://github.com/PHPOffice/PhpSpreadsheet" />' . PHP_EOL; $html .= ' <title>' . htmlspecialchars($properties->getTitle(), Settings::htmlEntityFlags()) . '</title>' . PHP_EOL; $html .= self::generateMeta($properties->getCreator(), 'author'); $html .= self::generateMeta($properties->getTitle(), 'title'); $html .= self::generateMeta($properties->getDescription(), 'description'); $html .= self::generateMeta($properties->getSubject(), 'subject'); $html .= self::generateMeta($properties->getKeywords(), 'keywords'); $html .= self::generateMeta($properties->getCategory(), 'category'); $html .= self::generateMeta($properties->getCompany(), 'company'); $html .= self::generateMeta($properties->getManager(), 'manager'); $html .= self::generateMeta($properties->getLastModifiedBy(), 'lastModifiedBy'); $date = Date::dateTimeFromTimestamp((string) $properties->getCreated()); $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); $html .= self::generateMeta($date->format(DATE_W3C), 'created'); $date = Date::dateTimeFromTimestamp((string) $properties->getModified()); $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); $html .= self::generateMeta($date->format(DATE_W3C), 'modified'); $customProperties = $properties->getCustomProperties(); foreach ($customProperties as $customProperty) { $propertyValue = $properties->getCustomPropertyValue($customProperty); $propertyType = $properties->getCustomPropertyType($customProperty); $propertyQualifier = self::CUSTOM_TO_META[$propertyType] ?? null; if ($propertyQualifier !== null) { if ($propertyType === Properties::PROPERTY_TYPE_BOOLEAN) { $propertyValue = $propertyValue ? '1' : '0'; } elseif ($propertyType === Properties::PROPERTY_TYPE_DATE) { $date = Date::dateTimeFromTimestamp((string) $propertyValue); $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); $propertyValue = $date->format(DATE_W3C); } else { $propertyValue = (string) $propertyValue; } $html .= self::generateMeta($propertyValue, "custom.$propertyQualifier.$customProperty"); } } if (!empty($properties->getHyperlinkBase())) { $html .= ' <base href="' . $properties->getHyperlinkBase() . '" />' . PHP_EOL; } $html .= $includeStyles ? $this->generateStyles(true) : $this->generatePageDeclarations(true); $html .= ' </head>' . PHP_EOL; $html .= '' . PHP_EOL; $html .= self::BODY_LINE; return $html; } private function generateSheetPrep(): array { // Ensure that Spans have been calculated? $this->calculateSpans(); // Fetch sheets if ($this->sheetIndex === null) { $sheets = $this->spreadsheet->getAllSheets(); } else { $sheets = [$this->spreadsheet->getSheet($this->sheetIndex)]; } return $sheets; } private function generateSheetStarts(Worksheet $sheet, int $rowMin): array { // calculate start of <tbody>, <thead> $tbodyStart = $rowMin; $theadStart = $theadEnd = 0; // default: no <thead> no </thead> if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) { $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop(); // we can only support repeating rows that start at top row if ($rowsToRepeatAtTop[0] == 1) { $theadStart = $rowsToRepeatAtTop[0]; $theadEnd = $rowsToRepeatAtTop[1]; $tbodyStart = $rowsToRepeatAtTop[1] + 1; } } return [$theadStart, $theadEnd, $tbodyStart]; } private function generateSheetTags(int $row, int $theadStart, int $theadEnd, int $tbodyStart): array { // <thead> ? $startTag = ($row == $theadStart) ? (' <thead>' . PHP_EOL) : ''; if (!$startTag) { $startTag = ($row == $tbodyStart) ? (' <tbody>' . PHP_EOL) : ''; } $endTag = ($row == $theadEnd) ? (' </thead>' . PHP_EOL) : ''; $cellType = ($row >= $tbodyStart) ? 'td' : 'th'; return [$cellType, $startTag, $endTag]; } /** * Generate sheet data. * * @return string */ public function generateSheetData() { $sheets = $this->generateSheetPrep(); // Construct HTML $html = ''; // Loop all sheets $sheetId = 0; foreach ($sheets as $sheet) { // Write table header $html .= $this->generateTableHeader($sheet); // Get worksheet dimension [$min, $max] = explode(':', $sheet->calculateWorksheetDataDimension()); [$minCol, $minRow] = Coordinate::indexesFromString($min); [$maxCol, $maxRow] = Coordinate::indexesFromString($max); [$theadStart, $theadEnd, $tbodyStart] = $this->generateSheetStarts($sheet, $minRow); // Loop through cells $row = $minRow - 1; while ($row++ < $maxRow) { [$cellType, $startTag, $endTag] = $this->generateSheetTags($row, $theadStart, $theadEnd, $tbodyStart); $html .= $startTag; // Write row if there are HTML table cells in it if (!isset($this->isSpannedRow[$sheet->getParent()->getIndex($sheet)][$row])) { // Start a new rowData $rowData = []; // Loop through columns $column = $minCol; while ($column <= $maxCol) { // Cell exists? $cellAddress = Coordinate::stringFromColumnIndex($column) . $row; $rowData[$column++] = ($sheet->getCellCollection()->has($cellAddress)) ? $cellAddress : ''; } $html .= $this->generateRow($sheet, $rowData, $row - 1, $cellType); } $html .= $endTag; } --$row; $html .= $this->extendRowsForChartsAndImages($sheet, $row); // Write table footer $html .= $this->generateTableFooter(); // Writing PDF? if ($this->isPdf && $this->useInlineCss) { if ($this->sheetIndex === null && $sheetId + 1 < $this->spreadsheet->getSheetCount()) { $html .= '<div style="page-break-before:always" ></div>'; } } // Next sheet ++$sheetId; } return $html; } /** * Generate sheet tabs. * * @return string */ public function generateNavigation() { // Fetch sheets $sheets = []; if ($this->sheetIndex === null) { $sheets = $this->spreadsheet->getAllSheets(); } else { $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex); } // Construct HTML $html = ''; // Only if there are more than 1 sheets if (count($sheets) > 1) { // Loop all sheets $sheetId = 0; $html .= '<ul class="navigation">' . PHP_EOL; foreach ($sheets as $sheet) { $html .= ' <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . $sheet->getTitle() . '</a></li>' . PHP_EOL; ++$sheetId; } $html .= '</ul>' . PHP_EOL; } return $html; } /** * Extend Row if chart is placed after nominal end of row. * This code should be exercised by sample: * Chart/32_Chart_read_write_PDF.php. * * @param int $row Row to check for charts * * @return array */ private function extendRowsForCharts(Worksheet $worksheet, int $row) { $rowMax = $row; $colMax = 'A'; $anyfound = false; if ($this->includeCharts) { foreach ($worksheet->getChartCollection() as $chart) { if ($chart instanceof Chart) { $anyfound = true; $chartCoordinates = $chart->getTopLeftPosition(); $chartTL = Coordinate::coordinateFromString($chartCoordinates['cell']); $chartCol = Coordinate::columnIndexFromString($chartTL[0]); if ($chartTL[1] > $rowMax) { $rowMax = $chartTL[1]; if ($chartCol > Coordinate::columnIndexFromString($colMax)) { $colMax = $chartTL[0]; } } } } } return [$rowMax, $colMax, $anyfound]; } private function extendRowsForChartsAndImages(Worksheet $worksheet, int $row): string { [$rowMax, $colMax, $anyfound] = $this->extendRowsForCharts($worksheet, $row); foreach ($worksheet->getDrawingCollection() as $drawing) { $anyfound = true; $imageTL = Coordinate::coordinateFromString($drawing->getCoordinates()); $imageCol = Coordinate::columnIndexFromString($imageTL[0]); if ($imageTL[1] > $rowMax) { $rowMax = $imageTL[1]; if ($imageCol > Coordinate::columnIndexFromString($colMax)) { $colMax = $imageTL[0]; } } } // Don't extend rows if not needed if ($row === $rowMax || !$anyfound) { return ''; } $html = ''; ++$colMax; ++$row; while ($row <= $rowMax) { $html .= '<tr>'; for ($col = 'A'; $col != $colMax; ++$col) { $htmlx = $this->writeImageInCell($worksheet, $col . $row); $htmlx .= $this->includeCharts ? $this->writeChartInCell($worksheet, $col . $row) : ''; if ($htmlx) { $html .= "<td class='style0' style='position: relative;'>$htmlx</td>"; } else { $html .= "<td class='style0'></td>"; } } ++$row; $html .= '</tr>' . PHP_EOL; } return $html; } /** * Convert Windows file name to file protocol URL. * * @param string $filename file name on local system * * @return string */ public static function winFileToUrl($filename, bool $mpdf = false) { // Windows filename if (substr($filename, 1, 2) === ':\\') { $protocol = $mpdf ? '' : 'file:///'; $filename = $protocol . str_replace('\\', '/', $filename); } return $filename; } /** * Generate image tag in cell. * * @param Worksheet $worksheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet * @param string $coordinates Cell coordinates * * @return string */ private function writeImageInCell(Worksheet $worksheet, $coordinates) { // Construct HTML $html = ''; // Write images foreach ($worksheet->getDrawingCollection() as $drawing) { if ($drawing->getCoordinates() != $coordinates) { continue; } $filedesc = $drawing->getDescription(); $filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded image'; if ($drawing instanceof Drawing) { $filename = $drawing->getPath(); // Strip off eventual '.' $filename = (string) preg_replace('/^[.]/', '', $filename); // Prepend images root $filename = $this->getImagesRoot() . $filename; // Strip off eventual '.' if followed by non-/ $filename = (string) preg_replace('@^[.]([^/])@', '$1', $filename); // Convert UTF8 data to PCDATA $filename = htmlspecialchars($filename, Settings::htmlEntityFlags()); $html .= PHP_EOL; $imageData = self::winFileToUrl($filename, $this->isMPdf); if ($this->embedImages || substr($imageData, 0, 6) === 'zip://') { $picture = @file_get_contents($filename); if ($picture !== false) { $imageDetails = getimagesize($filename) ?: []; // base64 encode the binary data $base64 = base64_encode($picture); $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64; } } $html .= '<img style="position: absolute; z-index: 1; left: ' . $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: ' . $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="' . $imageData . '" alt="' . $filedesc . '" />'; } elseif ($drawing instanceof MemoryDrawing) { $imageResource = $drawing->getImageResource(); if ($imageResource) { ob_start(); // Let's start output buffering. imagepng($imageResource); // This will normally output the image, but because of ob_start(), it won't. $contents = (string) ob_get_contents(); // Instead, output above is saved to $contents ob_end_clean(); // End the output buffer. $dataUri = 'data:image/png;base64,' . base64_encode($contents); // Because of the nature of tables, width is more important than height. // max-width: 100% ensures that image doesnt overflow containing cell // width: X sets width of supplied image. // As a result, images bigger than cell will be contained and images smaller will not get stretched $html .= '<img alt="' . $filedesc . '" src="' . $dataUri . '" style="max-width:100%;width:' . $drawing->getWidth() . 'px;left: ' . $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px;position: absolute; z-index: 1;" />'; } } } return $html; } /** * Generate chart tag in cell. * This code should be exercised by sample: * Chart/32_Chart_read_write_PDF.php. */ private function writeChartInCell(Worksheet $worksheet, string $coordinates): string { // Construct HTML $html = ''; // Write charts foreach ($worksheet->getChartCollection() as $chart) { if ($chart instanceof Chart) { $chartCoordinates = $chart->getTopLeftPosition(); if ($chartCoordinates['cell'] == $coordinates) { $chartFileName = File::sysGetTempDir() . '/' . uniqid('', true) . '.png'; if (!$chart->render($chartFileName)) { return ''; } $html .= PHP_EOL; $imageDetails = getimagesize($chartFileName) ?: []; $filedesc = $chart->getTitle(); $filedesc = $filedesc ? $filedesc->getCaptionText() : ''; $filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded chart'; $picture = file_get_contents($chartFileName); if ($picture !== false) { $base64 = base64_encode($picture); $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64; $html .= '<img style="position: absolute; z-index: 1; left: ' . $chartCoordinates['xOffset'] . 'px; top: ' . $chartCoordinates['yOffset'] . 'px; width: ' . $imageDetails[0] . 'px; height: ' . $imageDetails[1] . 'px;" src="' . $imageData . '" alt="' . $filedesc . '" />' . PHP_EOL; } unlink($chartFileName); } } } // Return return $html; } /** * Generate CSS styles. * * @param bool $generateSurroundingHTML Generate surrounding HTML tags? (<style> and </style>) * * @return string */ public function generateStyles($generateSurroundingHTML = true) { // Build CSS $css = $this->buildCSS($generateSurroundingHTML); // Construct HTML $html = ''; // Start styles if ($generateSurroundingHTML) { $html .= ' <style type="text/css">' . PHP_EOL; $html .= (array_key_exists('html', $css)) ? (' html { ' . $this->assembleCSS($css['html']) . ' }' . PHP_EOL) : ''; } // Write all other styles foreach ($css as $styleName => $styleDefinition) { if ($styleName != 'html') { $html .= ' ' . $styleName . ' { ' . $this->assembleCSS($styleDefinition) . ' }' . PHP_EOL; } } $html .= $this->generatePageDeclarations(false); // End styles if ($generateSurroundingHTML) { $html .= ' </style>' . PHP_EOL; } // Return return $html; } private function buildCssRowHeights(Worksheet $sheet, array &$css, int $sheetIndex): void { // Calculate row heights foreach ($sheet->getRowDimensions() as $rowDimension) { $row = $rowDimension->getRowIndex() - 1; // table.sheetN tr.rowYYYYYY { } $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = []; if ($rowDimension->getRowHeight() != -1) { $pt_height = $rowDimension->getRowHeight(); $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'] = $pt_height . 'pt'; } if ($rowDimension->getVisible() === false) { $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['display'] = 'none'; $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['visibility'] = 'hidden'; } } } private function buildCssPerSheet(Worksheet $sheet, array &$css): void { // Calculate hash code $sheetIndex = $sheet->getParentOrThrow()->getIndex($sheet); $setup = $sheet->getPageSetup(); if ($setup->getFitToPage() && $setup->getFitToHeight() === 1) { $css["table.sheet$sheetIndex"]['page-break-inside'] = 'avoid'; $css["table.sheet$sheetIndex"]['break-inside'] = 'avoid'; } // Build styles // Calculate column widths $sheet->calculateColumnWidths(); // col elements, initialize $highestColumnIndex = Coordinate::columnIndexFromString($sheet->getHighestColumn()) - 1; $column = -1; while ($column++ < $highestColumnIndex) { $this->columnWidths[$sheetIndex][$column] = 42; // approximation $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = '42pt'; } // col elements, loop through columnDimensions and set width foreach ($sheet->getColumnDimensions() as $columnDimension) { $column = Coordinate::columnIndexFromString($columnDimension->getColumnIndex()) - 1; $width = SharedDrawing::cellDimensionToPixels($columnDimension->getWidth(), $this->defaultFont); $width = SharedDrawing::pixelsToPoints($width); if ($columnDimension->getVisible() === false) { $css['table.sheet' . $sheetIndex . ' .column' . $column]['display'] = 'none'; } if ($width >= 0) { $this->columnWidths[$sheetIndex][$column] = $width; $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = $width . 'pt'; } } // Default row height $rowDimension = $sheet->getDefaultRowDimension(); // table.sheetN tr { } $css['table.sheet' . $sheetIndex . ' tr'] = []; if ($rowDimension->getRowHeight() == -1) { $pt_height = SharedFont::getDefaultRowHeightByFont($this->spreadsheet->getDefaultStyle()->getFont()); } else { $pt_height = $rowDimension->getRowHeight(); } $css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt'; if ($rowDimension->getVisible() === false) { $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none'; $css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden'; } $this->buildCssRowHeights($sheet, $css, $sheetIndex); } /** * Build CSS styles. * * @param bool $generateSurroundingHTML Generate surrounding HTML style? (html { }) * * @return array */ public function buildCSS($generateSurroundingHTML = true) { // Cached? if ($this->cssStyles !== null) { return $this->cssStyles; } // Ensure that spans have been calculated $this->calculateSpans(); // Construct CSS $css = []; // Start styles if ($generateSurroundingHTML) { // html { } $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif'; $css['html']['font-size'] = '11pt'; $css['html']['background-color'] = 'white'; } // CSS for comments as found in LibreOffice $css['a.comment-indicator:hover + div.comment'] = [ 'background' => '#ffd', 'position' => 'absolute', 'display' => 'block', 'border' => '1px solid black', 'padding' => '0.5em', ]; $css['a.comment-indicator'] = [ 'background' => 'red', 'display' => 'inline-block', 'border' => '1px solid black', 'width' => '0.5em', 'height' => '0.5em', ]; $css['div.comment']['display'] = 'none'; // table { } $css['table']['border-collapse'] = 'collapse'; // .b {} $css['.b']['text-align'] = 'center'; // BOOL // .e {} $css['.e']['text-align'] = 'center'; // ERROR // .f {} $css['.f']['text-align'] = 'right'; // FORMULA // .inlineStr {} $css['.inlineStr']['text-align'] = 'left'; // INLINE // .n {} $css['.n']['text-align'] = 'right'; // NUMERIC // .s {} $css['.s']['text-align'] = 'left'; // STRING // Calculate cell style hashes foreach ($this->spreadsheet->getCellXfCollection() as $index => $style) { $css['td.style' . $index . ', th.style' . $index] = $this->createCSSStyle($style); //$css['th.style' . $index] = $this->createCSSStyle($style); } // Fetch sheets $sheets = []; if ($this->sheetIndex === null) { $sheets = $this->spreadsheet->getAllSheets(); } else { $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex); } // Build styles per sheet foreach ($sheets as $sheet) { $this->buildCssPerSheet($sheet, $css); } // Cache if ($this->cssStyles === null) { $this->cssStyles = $css; } // Return return $css; } /** * Create CSS style. * * @return array */ private function createCSSStyle(Style $style) { // Create CSS return array_merge( $this->createCSSStyleAlignment($style->getAlignment()), $this->createCSSStyleBorders($style->getBorders()), $this->createCSSStyleFont($style->getFont()), $this->createCSSStyleFill($style->getFill()) ); } /** * Create CSS style. * * @return array */ private function createCSSStyleAlignment(Alignment $alignment) { // Construct CSS $css = []; // Create CSS $verticalAlign = $this->mapVAlign($alignment->getVertical() ?? ''); if ($verticalAlign) { $css['vertical-align'] = $verticalAlign; } $textAlign = $this->mapHAlign($alignment->getHorizontal() ?? ''); if ($textAlign) { $css['text-align'] = $textAlign; if (in_array($textAlign, ['left', 'right'])) { $css['padding-' . $textAlign] = (string) ((int) $alignment->getIndent() * 9) . 'px'; } } $rotation = $alignment->getTextRotation(); if ($rotation !== 0 && $rotation !== Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) { if ($this->isMPdf) { $css['text-rotate'] = "$rotation"; } else { $css['transform'] = "rotate({$rotation}deg)"; } } return $css; } /** * Create CSS style. * * @return array */ private function createCSSStyleFont(Font $font) { // Construct CSS $css = []; // Create CSS if ($font->getBold()) { $css['font-weight'] = 'bold'; } if ($font->getUnderline() != Font::UNDERLINE_NONE && $font->getStrikethrough()) { $css['text-decoration'] = 'underline line-through'; } elseif ($font->getUnderline() != Font::UNDERLINE_NONE) { $css['text-decoration'] = 'underline'; } elseif ($font->getStrikethrough()) { $css['text-decoration'] = 'line-through'; } if ($font->getItalic()) { $css['font-style'] = 'italic'; } $css['color'] = '#' . $font->getColor()->getRGB(); $css['font-family'] = '\'' . $font->getName() . '\''; $css['font-size'] = $font->getSize() . 'pt'; return $css; } /** * Create CSS style. * * @param Borders $borders Borders * * @return array */ private function createCSSStyleBorders(Borders $borders) { // Construct CSS $css = []; // Create CSS $css['border-bottom'] = $this->createCSSStyleBorder($borders->getBottom()); $css['border-top'] = $this->createCSSStyleBorder($borders->getTop()); $css['border-left'] = $this->createCSSStyleBorder($borders->getLeft()); $css['border-right'] = $this->createCSSStyleBorder($borders->getRight()); return $css; } /** * Create CSS style. * * @param Border $border Border */ private function createCSSStyleBorder(Border $border): string { // Create CSS - add !important to non-none border styles for merged cells $borderStyle = $this->mapBorderStyle($border->getBorderStyle()); return $borderStyle . ' #' . $border->getColor()->getRGB() . (($borderStyle == 'none') ? '' : ' !important'); } /** * Create CSS style (Fill). * * @param Fill $fill Fill * * @return array */ private function createCSSStyleFill(Fill $fill) { // Construct HTML $css = []; // Create CSS if ($fill->getFillType() !== Fill::FILL_NONE) { $value = $fill->getFillType() == Fill::FILL_NONE ? 'white' : '#' . $fill->getStartColor()->getRGB(); $css['background-color'] = $value; } return $css; } /** * Generate HTML footer. */ public function generateHTMLFooter(): string { // Construct HTML $html = ''; $html .= ' </body>' . PHP_EOL; $html .= '</html>' . PHP_EOL; return $html; } private function generateTableTagInline(Worksheet $worksheet, string $id): string { $style = isset($this->cssStyles['table']) ? $this->assembleCSS($this->cssStyles['table']) : ''; $prntgrid = $worksheet->getPrintGridlines(); $viewgrid = $this->isPdf ? $prntgrid : $worksheet->getShowGridlines(); if ($viewgrid && $prntgrid) { $html = " <table border='1' cellpadding='1' $id cellspacing='1' style='$style' class='gridlines gridlinesp'>" . PHP_EOL; } elseif ($viewgrid) { $html = " <table border='0' cellpadding='0' $id cellspacing='0' style='$style' class='gridlines'>" . PHP_EOL; } elseif ($prntgrid) { $html = " <table border='0' cellpadding='0' $id cellspacing='0' style='$style' class='gridlinesp'>" . PHP_EOL; } else { $html = " <table border='0' cellpadding='1' $id cellspacing='0' style='$style'>" . PHP_EOL; } return $html; } private function generateTableTag(Worksheet $worksheet, string $id, string &$html, int $sheetIndex): void { if (!$this->useInlineCss) { $gridlines = $worksheet->getShowGridlines() ? ' gridlines' : ''; $gridlinesp = $worksheet->getPrintGridlines() ? ' gridlinesp' : ''; $html .= " <table border='0' cellpadding='0' cellspacing='0' $id class='sheet$sheetIndex$gridlines$gridlinesp'>" . PHP_EOL; } else { $html .= $this->generateTableTagInline($worksheet, $id); } } /** * Generate table header. * * @param Worksheet $worksheet The worksheet for the table we are writing * @param bool $showid whether or not to add id to table tag * * @return string */ private function generateTableHeader(Worksheet $worksheet, $showid = true) { $sheetIndex = $worksheet->getParentOrThrow()->getIndex($worksheet); // Construct HTML $html = ''; $id = $showid ? "id='sheet$sheetIndex'" : ''; if ($showid) { $html .= "<div style='page: page$sheetIndex'>" . PHP_EOL; } else { $html .= "<div style='page: page$sheetIndex' class='scrpgbrk'>" . PHP_EOL; } $this->generateTableTag($worksheet, $id, $html, $sheetIndex); // Write <col> elements $highestColumnIndex = Coordinate::columnIndexFromString($worksheet->getHighestColumn()) - 1; $i = -1; while ($i++ < $highestColumnIndex) { if (!$this->useInlineCss) { $html .= ' <col class="col' . $i . '" />' . PHP_EOL; } else { $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : ''; $html .= ' <col style="' . $style . '" />' . PHP_EOL; } } return $html; } /** * Generate table footer. */ private function generateTableFooter(): string { return ' </tbody></table>' . PHP_EOL . '</div>' . PHP_EOL; } /** * Generate row start. * * @param int $sheetIndex Sheet index (0-based) * @param int $row row number * * @return string */ private function generateRowStart(Worksheet $worksheet, $sheetIndex, $row) { $html = ''; if (count($worksheet->getBreaks()) > 0) { $breaks = $worksheet->getRowBreaks(); // check if a break is needed before this row if (isset($breaks['A' . $row])) { // close table: </table> $html .= $this->generateTableFooter(); if ($this->isPdf && $this->useInlineCss) { $html .= '<div style="page-break-before:always" />'; } // open table again: <table> + <col> etc. $html .= $this->generateTableHeader($worksheet, false); $html .= '<tbody>' . PHP_EOL; } } // Write row start if (!$this->useInlineCss) { $html .= ' <tr class="row' . $row . '">' . PHP_EOL; } else { $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]) ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]) : ''; $html .= ' <tr style="' . $style . '">' . PHP_EOL; } return $html; } private function generateRowCellCss(Worksheet $worksheet, string $cellAddress, int $row, int $columnNumber): array { $cell = ($cellAddress > '') ? $worksheet->getCellCollection()->get($cellAddress) : ''; $coordinate = Coordinate::stringFromColumnIndex($columnNumber + 1) . ($row + 1); if (!$this->useInlineCss) { $cssClass = 'column' . $columnNumber; } else { $cssClass = []; // The statements below do nothing. // Commenting out the code rather than deleting it // in case someone can figure out what their intent was. //if ($cellType == 'th') { // if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum])) { // $this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum]; // } //} else { // if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) { // $this->cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum]; // } //} // End of mystery statements. } return [$cell, $cssClass, $coordinate]; } private function generateRowCellDataValueRich(Cell $cell, string &$cellData): void { // Loop through rich text elements $elements = $cell->getValue()->getRichTextElements(); foreach ($elements as $element) { // Rich text start? if ($element instanceof Run) { $cellEnd = ''; if ($element->getFont() !== null) { $cellData .= '<span style="' . $this->assembleCSS($this->createCSSStyleFont($element->getFont())) . '">'; if ($element->getFont()->getSuperscript()) { $cellData .= '<sup>'; $cellEnd = '</sup>'; } elseif ($element->getFont()->getSubscript()) { $cellData .= '<sub>'; $cellEnd = '</sub>'; } } // Convert UTF8 data to PCDATA $cellText = $element->getText(); $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags()); $cellData .= $cellEnd; $cellData .= '</span>'; } else { // Convert UTF8 data to PCDATA $cellText = $element->getText(); $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags()); } } } private function generateRowCellDataValue(Worksheet $worksheet, Cell $cell, string &$cellData): void { if ($cell->getValue() instanceof RichText) { $this->generateRowCellDataValueRich($cell, $cellData); } else { $origData = $this->preCalculateFormulas ? $cell->getCalculatedValue() : $cell->getValue(); $formatCode = $worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(); $cellData = NumberFormat::toFormattedString( $origData ?? '', $formatCode ?? NumberFormat::FORMAT_GENERAL, [$this, 'formatColor'] ); if ($cellData === $origData) { $cellData = htmlspecialchars($cellData, Settings::htmlEntityFlags()); } if ($worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) { $cellData = '<sup>' . $cellData . '</sup>'; } elseif ($worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) { $cellData = '<sub>' . $cellData . '</sub>'; } } } /** * @param null|Cell|string $cell * @param array|string $cssClass */ private function generateRowCellData(Worksheet $worksheet, $cell, &$cssClass, string $cellType): string { $cellData = ' '; if ($cell instanceof Cell) { $cellData = ''; // Don't know what this does, and no test cases. //if ($cell->getParent() === null) { // $cell->attach($worksheet); //} // Value $this->generateRowCellDataValue($worksheet, $cell, $cellData); // Converts the cell content so that spaces occuring at beginning of each new line are replaced by // Example: " Hello\n to the world" is converted to " Hello\n to the world" $cellData = (string) preg_replace('/(?m)(?:^|\\G) /', ' ', $cellData); // convert newline "\n" to '<br>' $cellData = nl2br($cellData); // Extend CSS class? if (!$this->useInlineCss && is_string($cssClass)) { $cssClass .= ' style' . $cell->getXfIndex(); $cssClass .= ' ' . $cell->getDataType(); } elseif (is_array($cssClass)) { if ($cellType == 'th') { if (isset($this->cssStyles['th.style' . $cell->getXfIndex()])) { $cssClass = array_merge($cssClass, $this->cssStyles['th.style' . $cell->getXfIndex()]); } } else { if (isset($this->cssStyles['td.style' . $cell->getXfIndex()])) { $cssClass = array_merge($cssClass, $this->cssStyles['td.style' . $cell->getXfIndex()]); } } // General horizontal alignment: Actual horizontal alignment depends on dataType $sharedStyle = $worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex()); if ( $sharedStyle->getAlignment()->getHorizontal() == Alignment::HORIZONTAL_GENERAL && isset($this->cssStyles['.' . $cell->getDataType()]['text-align']) ) { $cssClass['text-align'] = $this->cssStyles['.' . $cell->getDataType()]['text-align']; } } } else { // Use default borders for empty cell if (is_string($cssClass)) { $cssClass .= ' style0'; } } return $cellData; } private function generateRowIncludeCharts(Worksheet $worksheet, string $coordinate): string { return $this->includeCharts ? $this->writeChartInCell($worksheet, $coordinate) : ''; } private function generateRowSpans(string $html, int $rowSpan, int $colSpan): string { $html .= ($colSpan > 1) ? (' colspan="' . $colSpan . '"') : ''; $html .= ($rowSpan > 1) ? (' rowspan="' . $rowSpan . '"') : ''; return $html; } /** * @param array|string $cssClass */ private function generateRowWriteCell(string &$html, Worksheet $worksheet, string $coordinate, string $cellType, string $cellData, int $colSpan, int $rowSpan, $cssClass, int $colNum, int $sheetIndex, int $row): void { // Image? $htmlx = $this->writeImageInCell($worksheet, $coordinate); // Chart? $htmlx .= $this->generateRowIncludeCharts($worksheet, $coordinate); // Column start $html .= ' <' . $cellType; if (!$this->useInlineCss && !$this->isPdf && is_string($cssClass)) { $html .= ' class="' . $cssClass . '"'; if ($htmlx) { $html .= " style='position: relative;'"; } } else { //** Necessary redundant code for the sake of \PhpOffice\PhpSpreadsheet\Writer\Pdf ** // We must explicitly write the width of the <td> element because TCPDF // does not recognize e.g. <col style="width:42pt"> if ($this->useInlineCss) { $xcssClass = is_array($cssClass) ? $cssClass : []; } else { if (is_string($cssClass)) { $html .= ' class="' . $cssClass . '"'; } $xcssClass = []; } $width = 0; $i = $colNum - 1; $e = $colNum + $colSpan - 1; while ($i++ < $e) { if (isset($this->columnWidths[$sheetIndex][$i])) { $width += $this->columnWidths[$sheetIndex][$i]; } } $xcssClass['width'] = (string) $width . 'pt'; // We must also explicitly write the height of the <td> element because TCPDF // does not recognize e.g. <tr style="height:50pt"> if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'])) { $height = $this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]['height']; $xcssClass['height'] = $height; } //** end of redundant code ** if ($htmlx) { $xcssClass['position'] = 'relative'; } $html .= ' style="' . $this->assembleCSS($xcssClass) . '"'; } $html = $this->generateRowSpans($html, $rowSpan, $colSpan); $html .= '>'; $html .= $htmlx; $html .= $this->writeComment($worksheet, $coordinate); // Cell data $html .= $cellData; // Column end $html .= '</' . $cellType . '>' . PHP_EOL; } /** * Generate row. * * @param array $values Array containing cells in a row * @param int $row Row number (0-based) * @param string $cellType eg: 'td' * * @return string */ private function generateRow(Worksheet $worksheet, array $values, $row, $cellType) { // Sheet index $sheetIndex = $worksheet->getParentOrThrow()->getIndex($worksheet); $html = $this->generateRowStart($worksheet, $sheetIndex, $row); $generateDiv = $this->isMPdf && $worksheet->getRowDimension($row + 1)->getVisible() === false; if ($generateDiv) { $html .= '<div style="visibility:hidden; display:none;">' . PHP_EOL; } // Write cells $colNum = 0; foreach ($values as $cellAddress) { [$cell, $cssClass, $coordinate] = $this->generateRowCellCss($worksheet, $cellAddress, $row, $colNum); // Cell Data $cellData = $this->generateRowCellData($worksheet, $cell, $cssClass, $cellType); // Hyperlink? if ($worksheet->hyperlinkExists($coordinate) && !$worksheet->getHyperlink($coordinate)->isInternal()) { $cellData = '<a href="' . htmlspecialchars($worksheet->getHyperlink($coordinate)->getUrl(), Settings::htmlEntityFlags()) . '" title="' . htmlspecialchars($worksheet->getHyperlink($coordinate)->getTooltip(), Settings::htmlEntityFlags()) . '">' . $cellData . '</a>'; } // Should the cell be written or is it swallowed by a rowspan or colspan? $writeCell = !(isset($this->isSpannedCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum]) && $this->isSpannedCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum]); // Colspan and Rowspan $colSpan = 1; $rowSpan = 1; if (isset($this->isBaseCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum])) { $spans = $this->isBaseCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum]; $rowSpan = $spans['rowspan']; $colSpan = $spans['colspan']; // Also apply style from last cell in merge to fix borders - // relies on !important for non-none border declarations in createCSSStyleBorder $endCellCoord = Coordinate::stringFromColumnIndex($colNum + $colSpan) . ($row + $rowSpan); if (!$this->useInlineCss) { $cssClass .= ' style' . $worksheet->getCell($endCellCoord)->getXfIndex(); } } // Write if ($writeCell) { $this->generateRowWriteCell($html, $worksheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $row); } // Next column ++$colNum; } // Write row end if ($generateDiv) { $html .= '</div>' . PHP_EOL; } $html .= ' </tr>' . PHP_EOL; // Return return $html; } /** * Takes array where of CSS properties / values and converts to CSS string. * * @return string */ private function assembleCSS(array $values = []) { $pairs = []; foreach ($values as $property => $value) { $pairs[] = $property . ':' . $value; } $string = implode('; ', $pairs); return $string; } /** * Get images root. * * @return string */ public function getImagesRoot() { return $this->imagesRoot; } /** * Set images root. * * @param string $imagesRoot * * @return $this */ public function setImagesRoot($imagesRoot) { $this->imagesRoot = $imagesRoot; return $this; } /** * Get embed images. * * @return bool */ public function getEmbedImages() { return $this->embedImages; } /** * Set embed images. * * @param bool $embedImages * * @return $this */ public function setEmbedImages($embedImages) { $this->embedImages = $embedImages; return $this; } /** * Get use inline CSS? * * @return bool */ public function getUseInlineCss() { return $this->useInlineCss; } /** * Set use inline CSS? * * @param bool $useInlineCss * * @return $this */ public function setUseInlineCss($useInlineCss) { $this->useInlineCss = $useInlineCss; return $this; } /** * Get use embedded CSS? * * @return bool * * @codeCoverageIgnore * * @deprecated no longer used */ public function getUseEmbeddedCSS() { return $this->useEmbeddedCSS; } /** * Set use embedded CSS? * * @param bool $useEmbeddedCSS * * @return $this * * @codeCoverageIgnore * * @deprecated no longer used */ public function setUseEmbeddedCSS($useEmbeddedCSS) { $this->useEmbeddedCSS = $useEmbeddedCSS; return $this; } /** * Add color to formatted string as inline style. * * @param string $value Plain formatted value without color * @param string $format Format code * * @return string */ public function formatColor($value, $format) { // Color information, e.g. [Red] is always at the beginning $color = null; // initialize $matches = []; $color_regex = '/^\\[[a-zA-Z]+\\]/'; if (preg_match($color_regex, $format, $matches)) { $color = str_replace(['[', ']'], '', $matches[0]); $color = strtolower($color); } // convert to PCDATA $result = htmlspecialchars($value, Settings::htmlEntityFlags()); // color span tag if ($color !== null) { $result = '<span style="color:' . $color . '">' . $result . '</span>'; } return $result; } /** * Calculate information about HTML colspan and rowspan which is not always the same as Excel's. */ private function calculateSpans(): void { if ($this->spansAreCalculated) { return; } // Identify all cells that should be omitted in HTML due to cell merge. // In HTML only the upper-left cell should be written and it should have // appropriate rowspan / colspan attribute $sheetIndexes = $this->sheetIndex !== null ? [$this->sheetIndex] : range(0, $this->spreadsheet->getSheetCount() - 1); foreach ($sheetIndexes as $sheetIndex) { $sheet = $this->spreadsheet->getSheet($sheetIndex); $candidateSpannedRow = []; // loop through all Excel merged cells foreach ($sheet->getMergeCells() as $cells) { [$cells] = Coordinate::splitRange($cells); $first = $cells[0]; $last = $cells[1]; [$fc, $fr] = Coordinate::indexesFromString($first); $fc = $fc - 1; [$lc, $lr] = Coordinate::indexesFromString($last); $lc = $lc - 1; // loop through the individual cells in the individual merge $r = $fr - 1; while ($r++ < $lr) { // also, flag this row as a HTML row that is candidate to be omitted $candidateSpannedRow[$r] = $r; $c = $fc - 1; while ($c++ < $lc) { if (!($c == $fc && $r == $fr)) { // not the upper-left cell (should not be written in HTML) $this->isSpannedCell[$sheetIndex][$r][$c] = [ 'baseCell' => [$fr, $fc], ]; } else { // upper-left is the base cell that should hold the colspan/rowspan attribute $this->isBaseCell[$sheetIndex][$r][$c] = [ 'xlrowspan' => $lr - $fr + 1, // Excel rowspan 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change 'xlcolspan' => $lc - $fc + 1, // Excel colspan 'colspan' => $lc - $fc + 1, // HTML colspan, value may change ]; } } } } $this->calculateSpansOmitRows($sheet, $sheetIndex, $candidateSpannedRow); // TODO: Same for columns } // We have calculated the spans $this->spansAreCalculated = true; } private function calculateSpansOmitRows(Worksheet $sheet, int $sheetIndex, array $candidateSpannedRow): void { // Identify which rows should be omitted in HTML. These are the rows where all the cells // participate in a merge and the where base cells are somewhere above. $countColumns = Coordinate::columnIndexFromString($sheet->getHighestColumn()); foreach ($candidateSpannedRow as $rowIndex) { if (isset($this->isSpannedCell[$sheetIndex][$rowIndex])) { if (count($this->isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) { $this->isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex; } } } // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1 if (isset($this->isSpannedRow[$sheetIndex])) { foreach ($this->isSpannedRow[$sheetIndex] as $rowIndex) { $adjustedBaseCells = []; $c = -1; $e = $countColumns - 1; while ($c++ < $e) { $baseCell = $this->isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell']; if (!in_array($baseCell, $adjustedBaseCells, true)) { // subtract rowspan by 1 --$this->isBaseCell[$sheetIndex][$baseCell[0]][$baseCell[1]]['rowspan']; $adjustedBaseCells[] = $baseCell; } } } } } /** * Write a comment in the same format as LibreOffice. * * @see https://github.com/LibreOffice/core/blob/9fc9bf3240f8c62ad7859947ab8a033ac1fe93fa/sc/source/filter/html/htmlexp.cxx#L1073-L1092 * * @param string $coordinate * * @return string */ private function writeComment(Worksheet $worksheet, $coordinate) { $result = ''; if (!$this->isPdf && isset($worksheet->getComments()[$coordinate])) { $sanitizer = new HTMLPurifier(); $cachePath = File::sysGetTempDir() . '/phpsppur'; if (is_dir($cachePath) || mkdir($cachePath)) { $sanitizer->config->set('Cache.SerializerPath', $cachePath); } $sanitizedString = $sanitizer->purify($worksheet->getComment($coordinate)->getText()->getPlainText()); if ($sanitizedString !== '') { $result .= '<a class="comment-indicator"></a>'; $result .= '<div class="comment">' . nl2br($sanitizedString) . '</div>'; $result .= PHP_EOL; } } return $result; } public function getOrientation(): ?string { // Expect Pdf classes to override this method. return $this->isPdf ? PageSetup::ORIENTATION_PORTRAIT : null; } /** * Generate @page declarations. * * @param bool $generateSurroundingHTML * * @return string */ private function generatePageDeclarations($generateSurroundingHTML) { // Ensure that Spans have been calculated? $this->calculateSpans(); // Fetch sheets $sheets = []; if ($this->sheetIndex === null) { $sheets = $this->spreadsheet->getAllSheets(); } else { $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex); } // Construct HTML $htmlPage = $generateSurroundingHTML ? ('<style type="text/css">' . PHP_EOL) : ''; // Loop all sheets $sheetId = 0; foreach ($sheets as $worksheet) { $htmlPage .= "@page page$sheetId { "; $left = StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()) . 'in; '; $htmlPage .= 'margin-left: ' . $left; $right = StringHelper::FormatNumber($worksheet->getPageMargins()->getRight()) . 'in; '; $htmlPage .= 'margin-right: ' . $right; $top = StringHelper::FormatNumber($worksheet->getPageMargins()->getTop()) . 'in; '; $htmlPage .= 'margin-top: ' . $top; $bottom = StringHelper::FormatNumber($worksheet->getPageMargins()->getBottom()) . 'in; '; $htmlPage .= 'margin-bottom: ' . $bottom; $orientation = $this->getOrientation() ?? $worksheet->getPageSetup()->getOrientation(); if ($orientation === PageSetup::ORIENTATION_LANDSCAPE) { $htmlPage .= 'size: landscape; '; } elseif ($orientation === PageSetup::ORIENTATION_PORTRAIT) { $htmlPage .= 'size: portrait; '; } $htmlPage .= '}' . PHP_EOL; ++$sheetId; } $htmlPage .= implode(PHP_EOL, [ '.navigation {page-break-after: always;}', '.scrpgbrk, div + div {page-break-before: always;}', '@media screen {', ' .gridlines td {border: 1px solid black;}', ' .gridlines th {border: 1px solid black;}', ' body>div {margin-top: 5px;}', ' body>div:first-child {margin-top: 0;}', ' .scrpgbrk {margin-top: 1px;}', '}', '@media print {', ' .gridlinesp td {border: 1px solid black;}', ' .gridlinesp th {border: 1px solid black;}', ' .navigation {display: none;}', '}', '', ]); $htmlPage .= $generateSurroundingHTML ? ('</style>' . PHP_EOL) : ''; return $htmlPage; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Mimetype.php 0000644 00000000462 15002227416 0017575 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; class Mimetype extends WriterPart { /** * Write mimetype to plain text format. * * @return string XML Output */ public function write(): string { return 'application/vnd.oasis.opendocument.spreadsheet'; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php 0000644 00000000417 15002227416 0020112 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; class Thumbnails extends WriterPart { /** * Write Thumbnails/thumbnail.png to PNG format. * * @return string XML Output */ public function write(): string { return ''; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Content.php 0000644 00000036425 15002227416 0017426 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Row; use PhpOffice\PhpSpreadsheet\Worksheet\RowCellIterator; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use PhpOffice\PhpSpreadsheet\Writer\Exception; use PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Comment; use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Style; /** * @author Alexander Pervakov <frost-nzcr4@jagmort.com> */ class Content extends WriterPart { const NUMBER_COLS_REPEATED_MAX = 1024; const NUMBER_ROWS_REPEATED_MAX = 1048576; /** @var Formula */ private $formulaConvertor; /** * Set parent Ods writer. */ public function __construct(Ods $writer) { parent::__construct($writer); $this->formulaConvertor = new Formula($this->getParentWriter()->getSpreadsheet()->getDefinedNames()); } /** * Write content.xml to XML format. * * @return string XML Output */ public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8'); // Content $objWriter->startElement('office:document-content'); $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'); $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'); $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'); $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'); $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'); $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'); $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'); $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'); $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0'); $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'); $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML'); $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'); $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0'); $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer'); $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc'); $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events'); $objWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms'); $objWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'); $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report'); $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2'); $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml'); $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table'); $objWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0'); $objWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0'); $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/'); $objWriter->writeAttribute('office:version', '1.2'); $objWriter->writeElement('office:scripts'); $objWriter->writeElement('office:font-face-decls'); // Styles XF $objWriter->startElement('office:automatic-styles'); $this->writeXfStyles($objWriter, $this->getParentWriter()->getSpreadsheet()); $objWriter->endElement(); $objWriter->startElement('office:body'); $objWriter->startElement('office:spreadsheet'); $objWriter->writeElement('table:calculation-settings'); $this->writeSheets($objWriter); (new AutoFilters($objWriter, $this->getParentWriter()->getSpreadsheet()))->write(); // Defined names (ranges and formulae) (new NamedExpressions($objWriter, $this->getParentWriter()->getSpreadsheet(), $this->formulaConvertor))->write(); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); } /** * Write sheets. */ private function writeSheets(XMLWriter $objWriter): void { $spreadsheet = $this->getParentWriter()->getSpreadsheet(); /** @var Spreadsheet $spreadsheet */ $sheetCount = $spreadsheet->getSheetCount(); for ($sheetIndex = 0; $sheetIndex < $sheetCount; ++$sheetIndex) { $objWriter->startElement('table:table'); $objWriter->writeAttribute('table:name', $spreadsheet->getSheet($sheetIndex)->getTitle()); $objWriter->writeAttribute('table:style-name', Style::TABLE_STYLE_PREFIX . (string) ($sheetIndex + 1)); $objWriter->writeElement('office:forms'); $lastColumn = 0; foreach ($spreadsheet->getSheet($sheetIndex)->getColumnDimensions() as $columnDimension) { $thisColumn = $columnDimension->getColumnNumeric(); $emptyColumns = $thisColumn - $lastColumn - 1; if ($emptyColumns > 0) { $objWriter->startElement('table:table-column'); $objWriter->writeAttribute('table:number-columns-repeated', (string) $emptyColumns); $objWriter->endElement(); } $lastColumn = $thisColumn; $objWriter->startElement('table:table-column'); $objWriter->writeAttribute( 'table:style-name', sprintf('%s_%d_%d', Style::COLUMN_STYLE_PREFIX, $sheetIndex, $columnDimension->getColumnNumeric()) ); $objWriter->writeAttribute('table:default-cell-style-name', 'ce0'); // $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX); $objWriter->endElement(); } $this->writeRows($objWriter, $spreadsheet->getSheet($sheetIndex), $sheetIndex); $objWriter->endElement(); } } /** * Write rows of the specified sheet. */ private function writeRows(XMLWriter $objWriter, Worksheet $sheet, int $sheetIndex): void { $numberRowsRepeated = self::NUMBER_ROWS_REPEATED_MAX; $span_row = 0; $rows = $sheet->getRowIterator(); foreach ($rows as $row) { $cellIterator = $row->getCellIterator(); --$numberRowsRepeated; if ($cellIterator->valid()) { $objWriter->startElement('table:table-row'); if ($span_row) { if ($span_row > 1) { $objWriter->writeAttribute('table:number-rows-repeated', (string) $span_row); } $objWriter->startElement('table:table-cell'); $objWriter->writeAttribute('table:number-columns-repeated', (string) self::NUMBER_COLS_REPEATED_MAX); $objWriter->endElement(); $span_row = 0; } else { if ($sheet->getRowDimension($row->getRowIndex())->getRowHeight() > 0) { $objWriter->writeAttribute( 'table:style-name', sprintf('%s_%d_%d', Style::ROW_STYLE_PREFIX, $sheetIndex, $row->getRowIndex()) ); } $this->writeCells($objWriter, $cellIterator); } $objWriter->endElement(); } else { ++$span_row; } } } /** * Write cells of the specified row. */ private function writeCells(XMLWriter $objWriter, RowCellIterator $cells): void { $numberColsRepeated = self::NUMBER_COLS_REPEATED_MAX; $prevColumn = -1; foreach ($cells as $cell) { /** @var \PhpOffice\PhpSpreadsheet\Cell\Cell $cell */ $column = Coordinate::columnIndexFromString($cell->getColumn()) - 1; $this->writeCellSpan($objWriter, $column, $prevColumn); $objWriter->startElement('table:table-cell'); $this->writeCellMerge($objWriter, $cell); // Style XF $style = $cell->getXfIndex(); if ($style !== null) { $objWriter->writeAttribute('table:style-name', Style::CELL_STYLE_PREFIX . $style); } switch ($cell->getDataType()) { case DataType::TYPE_BOOL: $objWriter->writeAttribute('office:value-type', 'boolean'); $objWriter->writeAttribute('office:value', $cell->getValue()); $objWriter->writeElement('text:p', $cell->getValue()); break; case DataType::TYPE_ERROR: $objWriter->writeAttribute('table:formula', 'of:=#NULL!'); $objWriter->writeAttribute('office:value-type', 'string'); $objWriter->writeAttribute('office:string-value', ''); $objWriter->writeElement('text:p', '#NULL!'); break; case DataType::TYPE_FORMULA: $formulaValue = $cell->getValue(); if ($this->getParentWriter()->getPreCalculateFormulas()) { try { $formulaValue = $cell->getCalculatedValue(); } catch (Exception $e) { // don't do anything } } $objWriter->writeAttribute('table:formula', $this->formulaConvertor->convertFormula($cell->getValue())); if (is_numeric($formulaValue)) { $objWriter->writeAttribute('office:value-type', 'float'); } else { $objWriter->writeAttribute('office:value-type', 'string'); } $objWriter->writeAttribute('office:value', $formulaValue); $objWriter->writeElement('text:p', $formulaValue); break; case DataType::TYPE_NUMERIC: $objWriter->writeAttribute('office:value-type', 'float'); $objWriter->writeAttribute('office:value', $cell->getValue()); $objWriter->writeElement('text:p', $cell->getValue()); break; case DataType::TYPE_INLINE: // break intentionally omitted case DataType::TYPE_STRING: $objWriter->writeAttribute('office:value-type', 'string'); $objWriter->writeElement('text:p', $cell->getValue()); break; } Comment::write($objWriter, $cell); $objWriter->endElement(); $prevColumn = $column; } $numberColsRepeated = $numberColsRepeated - $prevColumn - 1; if ($numberColsRepeated > 0) { if ($numberColsRepeated > 1) { $objWriter->startElement('table:table-cell'); $objWriter->writeAttribute('table:number-columns-repeated', (string) $numberColsRepeated); $objWriter->endElement(); } else { $objWriter->writeElement('table:table-cell'); } } } /** * Write span. * * @param int $curColumn * @param int $prevColumn */ private function writeCellSpan(XMLWriter $objWriter, $curColumn, $prevColumn): void { $diff = $curColumn - $prevColumn - 1; if (1 === $diff) { $objWriter->writeElement('table:table-cell'); } elseif ($diff > 1) { $objWriter->startElement('table:table-cell'); $objWriter->writeAttribute('table:number-columns-repeated', (string) $diff); $objWriter->endElement(); } } /** * Write XF cell styles. */ private function writeXfStyles(XMLWriter $writer, Spreadsheet $spreadsheet): void { $styleWriter = new Style($writer); $sheetCount = $spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { $worksheet = $spreadsheet->getSheet($i); $styleWriter->writeTableStyle($worksheet, $i + 1); $worksheet->calculateColumnWidths(); foreach ($worksheet->getColumnDimensions() as $columnDimension) { if ($columnDimension->getWidth() !== -1.0) { $styleWriter->writeColumnStyles($columnDimension, $i); } } } for ($i = 0; $i < $sheetCount; ++$i) { $worksheet = $spreadsheet->getSheet($i); foreach ($worksheet->getRowDimensions() as $rowDimension) { if ($rowDimension->getRowHeight() > 0.0) { $styleWriter->writeRowStyles($rowDimension, $i); } } } foreach ($spreadsheet->getCellXfCollection() as $style) { $styleWriter->write($style); } } /** * Write attributes for merged cell. */ private function writeCellMerge(XMLWriter $objWriter, Cell $cell): void { if (!$cell->isMergeRangeValueCell()) { return; } $mergeRange = Coordinate::splitRange((string) $cell->getMergeRange()); [$startCell, $endCell] = $mergeRange[0]; $start = Coordinate::coordinateFromString($startCell); $end = Coordinate::coordinateFromString($endCell); $columnSpan = Coordinate::columnIndexFromString($end[0]) - Coordinate::columnIndexFromString($start[0]) + 1; $rowSpan = ((int) $end[1]) - ((int) $start[1]) + 1; $objWriter->writeAttribute('table:number-columns-spanned', (string) $columnSpan); $objWriter->writeAttribute('table:number-rows-spanned', (string) $rowSpan); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Settings.php 0000644 00000014774 15002227416 0017617 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Cell\CellAddress; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Settings extends WriterPart { /** * Write settings.xml to XML format. * * @return string XML Output */ public function write(): string { if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8'); // Settings $objWriter->startElement('office:document-settings'); $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); $objWriter->writeAttribute('xmlns:config', 'urn:oasis:names:tc:opendocument:xmlns:config:1.0'); $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); $objWriter->writeAttribute('office:version', '1.2'); $objWriter->startElement('office:settings'); $objWriter->startElement('config:config-item-set'); $objWriter->writeAttribute('config:name', 'ooo:view-settings'); $objWriter->startElement('config:config-item-map-indexed'); $objWriter->writeAttribute('config:name', 'Views'); $objWriter->startElement('config:config-item-map-entry'); $spreadsheet = $this->getParentWriter()->getSpreadsheet(); $objWriter->startElement('config:config-item'); $objWriter->writeAttribute('config:name', 'ViewId'); $objWriter->writeAttribute('config:type', 'string'); $objWriter->text('view1'); $objWriter->endElement(); // ViewId $objWriter->startElement('config:config-item-map-named'); $this->writeAllWorksheetSettings($objWriter, $spreadsheet); $wstitle = $spreadsheet->getActiveSheet()->getTitle(); $objWriter->startElement('config:config-item'); $objWriter->writeAttribute('config:name', 'ActiveTable'); $objWriter->writeAttribute('config:type', 'string'); $objWriter->text($wstitle); $objWriter->endElement(); // config:config-item ActiveTable $objWriter->endElement(); // config:config-item-map-entry $objWriter->endElement(); // config:config-item-map-indexed Views $objWriter->endElement(); // config:config-item-set ooo:view-settings $objWriter->startElement('config:config-item-set'); $objWriter->writeAttribute('config:name', 'ooo:configuration-settings'); $objWriter->endElement(); // config:config-item-set ooo:configuration-settings $objWriter->endElement(); // office:settings $objWriter->endElement(); // office:document-settings return $objWriter->getData(); } private function writeAllWorksheetSettings(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { $objWriter->writeAttribute('config:name', 'Tables'); foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { $this->writeWorksheetSettings($objWriter, $worksheet); } $objWriter->endElement(); // config:config-item-map-entry Tables } private function writeWorksheetSettings(XMLWriter $objWriter, Worksheet $worksheet): void { $objWriter->startElement('config:config-item-map-entry'); $objWriter->writeAttribute('config:name', $worksheet->getTitle()); $this->writeSelectedCells($objWriter, $worksheet); if ($worksheet->getFreezePane() !== null) { $this->writeFreezePane($objWriter, $worksheet); } $objWriter->endElement(); // config:config-item-map-entry Worksheet } private function writeSelectedCells(XMLWriter $objWriter, Worksheet $worksheet): void { $selected = $worksheet->getSelectedCells(); if (preg_match('/^([a-z]+)([0-9]+)/i', $selected, $matches) === 1) { $colSel = Coordinate::columnIndexFromString($matches[1]) - 1; $rowSel = (int) $matches[2] - 1; $objWriter->startElement('config:config-item'); $objWriter->writeAttribute('config:name', 'CursorPositionX'); $objWriter->writeAttribute('config:type', 'int'); $objWriter->text((string) $colSel); $objWriter->endElement(); $objWriter->startElement('config:config-item'); $objWriter->writeAttribute('config:name', 'CursorPositionY'); $objWriter->writeAttribute('config:type', 'int'); $objWriter->text((string) $rowSel); $objWriter->endElement(); } } private function writeSplitValue(XMLWriter $objWriter, string $splitMode, string $type, string $value): void { $objWriter->startElement('config:config-item'); $objWriter->writeAttribute('config:name', $splitMode); $objWriter->writeAttribute('config:type', $type); $objWriter->text($value); $objWriter->endElement(); } private function writeFreezePane(XMLWriter $objWriter, Worksheet $worksheet): void { $freezePane = CellAddress::fromCellAddress($worksheet->getFreezePane()); if ($freezePane->cellAddress() === 'A1') { return; } $columnId = $freezePane->columnId(); $columnName = $freezePane->columnName(); $row = $freezePane->rowId(); $this->writeSplitValue($objWriter, 'HorizontalSplitMode', 'short', '2'); $this->writeSplitValue($objWriter, 'HorizontalSplitPosition', 'int', (string) ($columnId - 1)); $this->writeSplitValue($objWriter, 'PositionLeft', 'short', '0'); $this->writeSplitValue($objWriter, 'PositionRight', 'short', (string) ($columnId - 1)); for ($column = 'A'; $column !== $columnName; ++$column) { $worksheet->getColumnDimension($column)->setAutoSize(true); } $this->writeSplitValue($objWriter, 'VerticalSplitMode', 'short', '2'); $this->writeSplitValue($objWriter, 'VerticalSplitPosition', 'int', (string) ($row - 1)); $this->writeSplitValue($objWriter, 'PositionTop', 'short', '0'); $this->writeSplitValue($objWriter, 'PositionBottom', 'short', (string) ($row - 1)); $this->writeSplitValue($objWriter, 'ActiveSplitRange', 'short', '3'); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php 0000644 00000011123 15002227416 0021267 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class NamedExpressions { /** @var XMLWriter */ private $objWriter; /** @var Spreadsheet */ private $spreadsheet; /** @var Formula */ private $formulaConvertor; public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet, Formula $formulaConvertor) { $this->objWriter = $objWriter; $this->spreadsheet = $spreadsheet; $this->formulaConvertor = $formulaConvertor; } public function write(): string { $this->objWriter->startElement('table:named-expressions'); $this->writeExpressions(); $this->objWriter->endElement(); return ''; } private function writeExpressions(): void { $definedNames = $this->spreadsheet->getDefinedNames(); foreach ($definedNames as $definedName) { if ($definedName->isFormula()) { $this->objWriter->startElement('table:named-expression'); $this->writeNamedFormula($definedName, $this->spreadsheet->getActiveSheet()); } else { $this->objWriter->startElement('table:named-range'); $this->writeNamedRange($definedName); } $this->objWriter->endElement(); } } private function writeNamedFormula(DefinedName $definedName, Worksheet $defaultWorksheet): void { $title = ($definedName->getWorksheet() !== null) ? $definedName->getWorksheet()->getTitle() : $defaultWorksheet->getTitle(); $this->objWriter->writeAttribute('table:name', $definedName->getName()); $this->objWriter->writeAttribute( 'table:expression', $this->formulaConvertor->convertFormula($definedName->getValue(), $title) ); $this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress( $definedName, "'" . $title . "'!\$A\$1" )); } private function writeNamedRange(DefinedName $definedName): void { $baseCell = '$A$1'; $ws = $definedName->getWorksheet(); if ($ws !== null) { $baseCell = "'" . $ws->getTitle() . "'!$baseCell"; } $this->objWriter->writeAttribute('table:name', $definedName->getName()); $this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress( $definedName, $baseCell )); $this->objWriter->writeAttribute('table:cell-range-address', $this->convertAddress($definedName, $definedName->getValue())); } private function convertAddress(DefinedName $definedName, string $address): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', $address, $splitRanges, PREG_OFFSET_CAPTURE ); $lengths = array_map('strlen', array_column($splitRanges[0], 0)); $offsets = array_column($splitRanges[0], 1); $worksheets = $splitRanges[2]; $columns = $splitRanges[6]; $rows = $splitRanges[7]; while ($splitCount > 0) { --$splitCount; $length = $lengths[$splitCount]; $offset = $offsets[$splitCount]; $worksheet = $worksheets[$splitCount][0]; $column = $columns[$splitCount][0]; $row = $rows[$splitCount][0]; $newRange = ''; if (empty($worksheet)) { if (($offset === 0) || ($address[$offset - 1] !== ':')) { // We need a worksheet $ws = $definedName->getWorksheet(); if ($ws !== null) { $worksheet = $ws->getTitle(); } } } else { $worksheet = str_replace("''", "'", trim($worksheet, "'")); } if (!empty($worksheet)) { $newRange = "'" . str_replace("'", "''", $worksheet) . "'."; } if (!empty($column)) { $newRange .= $column; } if (!empty($row)) { $newRange .= $row; } $address = substr($address, 0, $offset) . $newRange . substr($address, $offset + $length); } if (substr($address, 0, 1) === '=') { $address = substr($address, 1); } return $address; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Styles.php 0000644 00000007153 15002227416 0017273 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; class Styles extends WriterPart { /** * Write styles.xml to XML format. * * @return string XML Output */ public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8'); // Content $objWriter->startElement('office:document-styles'); $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'); $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'); $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'); $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'); $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'); $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'); $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'); $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'); $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0'); $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'); $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML'); $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'); $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0'); $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer'); $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc'); $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events'); $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report'); $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2'); $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml'); $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table'); $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/'); $objWriter->writeAttribute('office:version', '1.2'); $objWriter->writeElement('office:font-face-decls'); $objWriter->writeElement('office:styles'); $objWriter->writeElement('office:automatic-styles'); $objWriter->writeElement('office:master-styles'); $objWriter->endElement(); return $objWriter->getData(); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Meta.php 0000644 00000012372 15002227416 0016675 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Document\Properties; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; class Meta extends WriterPart { /** * Write meta.xml to XML format. * * @return string XML Output */ public function write(): string { $spreadsheet = $this->getParentWriter()->getSpreadsheet(); $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8'); // Meta $objWriter->startElement('office:document-meta'); $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); $objWriter->writeAttribute('office:version', '1.2'); $objWriter->startElement('office:meta'); $objWriter->writeElement('meta:initial-creator', $spreadsheet->getProperties()->getCreator()); $objWriter->writeElement('dc:creator', $spreadsheet->getProperties()->getCreator()); $created = $spreadsheet->getProperties()->getCreated(); $date = Date::dateTimeFromTimestamp("$created"); $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); $objWriter->writeElement('meta:creation-date', $date->format(DATE_W3C)); $created = $spreadsheet->getProperties()->getModified(); $date = Date::dateTimeFromTimestamp("$created"); $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); $objWriter->writeElement('dc:date', $date->format(DATE_W3C)); $objWriter->writeElement('dc:title', $spreadsheet->getProperties()->getTitle()); $objWriter->writeElement('dc:description', $spreadsheet->getProperties()->getDescription()); $objWriter->writeElement('dc:subject', $spreadsheet->getProperties()->getSubject()); $objWriter->writeElement('meta:keyword', $spreadsheet->getProperties()->getKeywords()); // Don't know if this changed over time, but the keywords are all // in a single declaration now. //$keywords = explode(' ', $spreadsheet->getProperties()->getKeywords()); //foreach ($keywords as $keyword) { // $objWriter->writeElement('meta:keyword', $keyword); //} //<meta:document-statistic meta:table-count="XXX" meta:cell-count="XXX" meta:object-count="XXX"/> $objWriter->startElement('meta:user-defined'); $objWriter->writeAttribute('meta:name', 'Company'); $objWriter->writeRaw($spreadsheet->getProperties()->getCompany()); $objWriter->endElement(); $objWriter->startElement('meta:user-defined'); $objWriter->writeAttribute('meta:name', 'category'); $objWriter->writeRaw($spreadsheet->getProperties()->getCategory()); $objWriter->endElement(); self::writeDocPropsCustom($objWriter, $spreadsheet); $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); } private static function writeDocPropsCustom(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); foreach ($customPropertyList as $key => $customProperty) { $propertyValue = $spreadsheet->getProperties()->getCustomPropertyValue($customProperty); $propertyType = $spreadsheet->getProperties()->getCustomPropertyType($customProperty); $objWriter->startElement('meta:user-defined'); $objWriter->writeAttribute('meta:name', $customProperty); switch ($propertyType) { case Properties::PROPERTY_TYPE_INTEGER: case Properties::PROPERTY_TYPE_FLOAT: $objWriter->writeAttribute('meta:value-type', 'float'); $objWriter->writeRawData($propertyValue); break; case Properties::PROPERTY_TYPE_BOOLEAN: $objWriter->writeAttribute('meta:value-type', 'boolean'); $objWriter->writeRawData($propertyValue ? 'true' : 'false'); break; case Properties::PROPERTY_TYPE_DATE: $objWriter->writeAttribute('meta:value-type', 'date'); $dtobj = Date::dateTimeFromTimestamp($propertyValue ?? 0); $objWriter->writeRawData($dtobj->format(DATE_W3C)); break; default: $objWriter->writeRawData($propertyValue); break; } $objWriter->endElement(); } } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php 0000644 00000003767 15002227416 0020260 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class AutoFilters { /** * @var XMLWriter */ private $objWriter; /** * @var Spreadsheet */ private $spreadsheet; public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet) { $this->objWriter = $objWriter; $this->spreadsheet = $spreadsheet; } /** @var mixed */ private static $scrutinizerFalse = false; public function write(): void { $wrapperWritten = self::$scrutinizerFalse; $sheetCount = $this->spreadsheet->getSheetCount(); for ($i = 0; $i < $sheetCount; ++$i) { $worksheet = $this->spreadsheet->getSheet($i); $autofilter = $worksheet->getAutoFilter(); if ($autofilter !== null && !empty($autofilter->getRange())) { if ($wrapperWritten === false) { $this->objWriter->startElement('table:database-ranges'); $wrapperWritten = true; } $this->objWriter->startElement('table:database-range'); $this->objWriter->writeAttribute('table:orientation', 'column'); $this->objWriter->writeAttribute('table:display-filter-buttons', 'true'); $this->objWriter->writeAttribute( 'table:target-range-address', $this->formatRange($worksheet, $autofilter) ); $this->objWriter->endElement(); } } if ($wrapperWritten === true) { $this->objWriter->endElement(); } } protected function formatRange(Worksheet $worksheet, Autofilter $autofilter): string { $title = $worksheet->getTitle(); $range = $autofilter->getRange(); return "'{$title}'.{$range}"; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Formula.php 0000644 00000007570 15002227416 0017420 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\DefinedName; class Formula { /** @var array */ private $definedNames = []; /** * @param DefinedName[] $definedNames */ public function __construct(array $definedNames) { foreach ($definedNames as $definedName) { $this->definedNames[] = $definedName->getName(); } } public function convertFormula(string $formula, string $worksheetName = ''): string { $formula = $this->convertCellReferences($formula, $worksheetName); $formula = $this->convertDefinedNames($formula); if (substr($formula, 0, 1) !== '=') { $formula = '=' . $formula; } return 'of:' . $formula; } private function convertDefinedNames(string $formula): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $lengths = array_map('strlen', array_column($splitRanges[0], 0)); $offsets = array_column($splitRanges[0], 1); $values = array_column($splitRanges[0], 0); while ($splitCount > 0) { --$splitCount; $length = $lengths[$splitCount]; $offset = $offsets[$splitCount]; $value = $values[$splitCount]; if (in_array($value, $this->definedNames, true)) { $formula = substr($formula, 0, $offset) . '$$' . $value . substr($formula, $offset + $length); } } return $formula; } private function convertCellReferences(string $formula, string $worksheetName): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $lengths = array_map('strlen', array_column($splitRanges[0], 0)); $offsets = array_column($splitRanges[0], 1); $worksheets = $splitRanges[2]; $columns = $splitRanges[6]; $rows = $splitRanges[7]; // Replace any commas in the formula with semi-colons for Ods // If by chance there are commas in worksheet names, then they will be "fixed" again in the loop // because we've already extracted worksheet names with our preg_match_all() $formula = str_replace(',', ';', $formula); while ($splitCount > 0) { --$splitCount; $length = $lengths[$splitCount]; $offset = $offsets[$splitCount]; $worksheet = $worksheets[$splitCount][0]; $column = $columns[$splitCount][0]; $row = $rows[$splitCount][0]; $newRange = ''; if (empty($worksheet)) { if (($offset === 0) || ($formula[$offset - 1] !== ':')) { // We need a worksheet $worksheet = $worksheetName; } } else { $worksheet = str_replace("''", "'", trim($worksheet, "'")); } if (!empty($worksheet)) { $newRange = "['" . str_replace("'", "''", $worksheet) . "'"; } elseif (substr($formula, $offset - 1, 1) !== ':') { $newRange = '['; } $newRange .= '.'; if (!empty($column)) { $newRange .= $column; } if (!empty($row)) { $newRange .= $row; } // close the wrapping [] unless this is the first part of a range $newRange .= substr($formula, $offset + $length, 1) !== ':' ? ']' : ''; $formula = substr($formula, 0, $offset) . $newRange . substr($formula, $offset + $length); } return $formula; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Comment.php 0000644 00000002027 15002227416 0020264 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods\Cell; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; /** * @author Alexander Pervakov <frost-nzcr4@jagmort.com> */ class Comment { public static function write(XMLWriter $objWriter, Cell $cell): void { $comments = $cell->getWorksheet()->getComments(); if (!isset($comments[$cell->getCoordinate()])) { return; } $comment = $comments[$cell->getCoordinate()]; $objWriter->startElement('office:annotation'); $objWriter->writeAttribute('svg:width', $comment->getWidth()); $objWriter->writeAttribute('svg:height', $comment->getHeight()); $objWriter->writeAttribute('svg:x', $comment->getMarginLeft()); $objWriter->writeAttribute('svg:y', $comment->getMarginTop()); $objWriter->writeElement('dc:creator', $comment->getAuthor()); $objWriter->writeElement('text:p', $comment->getText()->getPlainText()); $objWriter->endElement(); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php 0000644 00000021254 15002227416 0017765 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods\Cell; use PhpOffice\PhpSpreadsheet\Helper\Dimension; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\Style as CellStyle; use PhpOffice\PhpSpreadsheet\Worksheet\ColumnDimension; use PhpOffice\PhpSpreadsheet\Worksheet\RowDimension; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Style { public const CELL_STYLE_PREFIX = 'ce'; public const COLUMN_STYLE_PREFIX = 'co'; public const ROW_STYLE_PREFIX = 'ro'; public const TABLE_STYLE_PREFIX = 'ta'; /** @var XMLWriter */ private $writer; public function __construct(XMLWriter $writer) { $this->writer = $writer; } private function mapHorizontalAlignment(string $horizontalAlignment): string { switch ($horizontalAlignment) { case Alignment::HORIZONTAL_CENTER: case Alignment::HORIZONTAL_CENTER_CONTINUOUS: case Alignment::HORIZONTAL_DISTRIBUTED: return 'center'; case Alignment::HORIZONTAL_RIGHT: return 'end'; case Alignment::HORIZONTAL_FILL: case Alignment::HORIZONTAL_JUSTIFY: return 'justify'; } return 'start'; } private function mapVerticalAlignment(string $verticalAlignment): string { switch ($verticalAlignment) { case Alignment::VERTICAL_TOP: return 'top'; case Alignment::VERTICAL_CENTER: return 'middle'; case Alignment::VERTICAL_DISTRIBUTED: case Alignment::VERTICAL_JUSTIFY: return 'automatic'; } return 'bottom'; } private function writeFillStyle(Fill $fill): void { switch ($fill->getFillType()) { case Fill::FILL_SOLID: $this->writer->writeAttribute('fo:background-color', sprintf( '#%s', strtolower($fill->getStartColor()->getRGB()) )); break; case Fill::FILL_GRADIENT_LINEAR: case Fill::FILL_GRADIENT_PATH: /// TODO :: To be implemented break; case Fill::FILL_NONE: default: } } private function writeCellProperties(CellStyle $style): void { // Align $hAlign = $style->getAlignment()->getHorizontal(); $vAlign = $style->getAlignment()->getVertical(); $wrap = $style->getAlignment()->getWrapText(); $this->writer->startElement('style:table-cell-properties'); if (!empty($vAlign) || $wrap) { if (!empty($vAlign)) { $vAlign = $this->mapVerticalAlignment($vAlign); $this->writer->writeAttribute('style:vertical-align', $vAlign); } if ($wrap) { $this->writer->writeAttribute('fo:wrap-option', 'wrap'); } } $this->writer->writeAttribute('style:rotation-align', 'none'); // Fill $this->writeFillStyle($style->getFill()); $this->writer->endElement(); if (!empty($hAlign)) { $hAlign = $this->mapHorizontalAlignment($hAlign); $this->writer->startElement('style:paragraph-properties'); $this->writer->writeAttribute('fo:text-align', $hAlign); $this->writer->endElement(); } } protected function mapUnderlineStyle(Font $font): string { switch ($font->getUnderline()) { case Font::UNDERLINE_DOUBLE: case Font::UNDERLINE_DOUBLEACCOUNTING: return'double'; case Font::UNDERLINE_SINGLE: case Font::UNDERLINE_SINGLEACCOUNTING: return'single'; } return 'none'; } protected function writeTextProperties(CellStyle $style): void { // Font $this->writer->startElement('style:text-properties'); $font = $style->getFont(); if ($font->getBold()) { $this->writer->writeAttribute('fo:font-weight', 'bold'); $this->writer->writeAttribute('style:font-weight-complex', 'bold'); $this->writer->writeAttribute('style:font-weight-asian', 'bold'); } if ($font->getItalic()) { $this->writer->writeAttribute('fo:font-style', 'italic'); } $this->writer->writeAttribute('fo:color', sprintf('#%s', $font->getColor()->getRGB())); if ($family = $font->getName()) { $this->writer->writeAttribute('fo:font-family', $family); } if ($size = $font->getSize()) { $this->writer->writeAttribute('fo:font-size', sprintf('%.1Fpt', $size)); } if ($font->getUnderline() && $font->getUnderline() !== Font::UNDERLINE_NONE) { $this->writer->writeAttribute('style:text-underline-style', 'solid'); $this->writer->writeAttribute('style:text-underline-width', 'auto'); $this->writer->writeAttribute('style:text-underline-color', 'font-color'); $underline = $this->mapUnderlineStyle($font); $this->writer->writeAttribute('style:text-underline-type', $underline); } $this->writer->endElement(); // Close style:text-properties } protected function writeColumnProperties(ColumnDimension $columnDimension): void { $this->writer->startElement('style:table-column-properties'); $this->writer->writeAttribute( 'style:column-width', round($columnDimension->getWidth(Dimension::UOM_CENTIMETERS), 3) . 'cm' ); $this->writer->writeAttribute('fo:break-before', 'auto'); // End $this->writer->endElement(); // Close style:table-column-properties } public function writeColumnStyles(ColumnDimension $columnDimension, int $sheetId): void { $this->writer->startElement('style:style'); $this->writer->writeAttribute('style:family', 'table-column'); $this->writer->writeAttribute( 'style:name', sprintf('%s_%d_%d', self::COLUMN_STYLE_PREFIX, $sheetId, $columnDimension->getColumnNumeric()) ); $this->writeColumnProperties($columnDimension); // End $this->writer->endElement(); // Close style:style } protected function writeRowProperties(RowDimension $rowDimension): void { $this->writer->startElement('style:table-row-properties'); $this->writer->writeAttribute( 'style:row-height', round($rowDimension->getRowHeight(Dimension::UOM_CENTIMETERS), 3) . 'cm' ); $this->writer->writeAttribute('style:use-optimal-row-height', 'false'); $this->writer->writeAttribute('fo:break-before', 'auto'); // End $this->writer->endElement(); // Close style:table-row-properties } public function writeRowStyles(RowDimension $rowDimension, int $sheetId): void { $this->writer->startElement('style:style'); $this->writer->writeAttribute('style:family', 'table-row'); $this->writer->writeAttribute( 'style:name', sprintf('%s_%d_%d', self::ROW_STYLE_PREFIX, $sheetId, $rowDimension->getRowIndex()) ); $this->writeRowProperties($rowDimension); // End $this->writer->endElement(); // Close style:style } public function writeTableStyle(Worksheet $worksheet, int $sheetId): void { $this->writer->startElement('style:style'); $this->writer->writeAttribute('style:family', 'table'); $this->writer->writeAttribute( 'style:name', sprintf('%s%d', self::TABLE_STYLE_PREFIX, $sheetId) ); $this->writer->startElement('style:table-properties'); $this->writer->writeAttribute( 'table:display', $worksheet->getSheetState() === Worksheet::SHEETSTATE_VISIBLE ? 'true' : 'false' ); $this->writer->endElement(); // Close style:table-properties $this->writer->endElement(); // Close style:style } public function write(CellStyle $style): void { $this->writer->startElement('style:style'); $this->writer->writeAttribute('style:name', self::CELL_STYLE_PREFIX . $style->getIndex()); $this->writer->writeAttribute('style:family', 'table-cell'); $this->writer->writeAttribute('style:parent-style-name', 'Default'); // Alignment, fill colour, etc $this->writeCellProperties($style); // style:text-properties $this->writeTextProperties($style); // End $this->writer->endElement(); // Close style:style } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/MetaInf.php 0000644 00000004705 15002227416 0017333 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; class MetaInf extends WriterPart { /** * Write META-INF/manifest.xml to XML format. * * @return string XML Output */ public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); } // XML header $objWriter->startDocument('1.0', 'UTF-8'); // Manifest $objWriter->startElement('manifest:manifest'); $objWriter->writeAttribute('xmlns:manifest', 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0'); $objWriter->writeAttribute('manifest:version', '1.2'); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', '/'); $objWriter->writeAttribute('manifest:version', '1.2'); $objWriter->writeAttribute('manifest:media-type', 'application/vnd.oasis.opendocument.spreadsheet'); $objWriter->endElement(); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', 'meta.xml'); $objWriter->writeAttribute('manifest:media-type', 'text/xml'); $objWriter->endElement(); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', 'settings.xml'); $objWriter->writeAttribute('manifest:media-type', 'text/xml'); $objWriter->endElement(); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', 'content.xml'); $objWriter->writeAttribute('manifest:media-type', 'text/xml'); $objWriter->endElement(); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', 'Thumbnails/thumbnail.png'); $objWriter->writeAttribute('manifest:media-type', 'image/png'); $objWriter->endElement(); $objWriter->startElement('manifest:file-entry'); $objWriter->writeAttribute('manifest:full-path', 'styles.xml'); $objWriter->writeAttribute('manifest:media-type', 'text/xml'); $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); } } phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/WriterPart.php 0000644 00000001061 15002227416 0020103 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Writer\Ods; abstract class WriterPart { /** * Parent Ods object. * * @var Ods */ private $parentWriter; /** * Get Ods writer. * * @return Ods */ public function getParentWriter() { return $this->parentWriter; } /** * Set parent Ods writer. */ public function __construct(Ods $writer) { $this->parentWriter = $writer; } abstract public function write(): string; } phpspreadsheet/src/PhpSpreadsheet/Writer/ZipStream0.php 0000644 00000000574 15002227416 0017261 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; use ZipStream\Option\Archive; use ZipStream\ZipStream; class ZipStream0 { /** * @param resource $fileHandle */ public static function newZipStream($fileHandle): ZipStream { return class_exists(Archive::class) ? ZipStream2::newZipStream($fileHandle) : ZipStream3::newZipStream($fileHandle); } } phpspreadsheet/src/PhpSpreadsheet/Writer/IWriter.php 0000644 00000006147 15002227416 0016652 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Spreadsheet; interface IWriter { public const SAVE_WITH_CHARTS = 1; public const DISABLE_PRECALCULATE_FORMULAE = 2; /** * IWriter constructor. * * @param Spreadsheet $spreadsheet The spreadsheet that we want to save using this Writer */ public function __construct(Spreadsheet $spreadsheet); /** * Write charts in workbook? * If this is true, then the Writer will write definitions for any charts that exist in the PhpSpreadsheet object. * If false (the default) it will ignore any charts defined in the PhpSpreadsheet object. * * @return bool */ public function getIncludeCharts(); /** * Set write charts in workbook * Set to true, to advise the Writer to include any charts that exist in the PhpSpreadsheet object. * Set to false (the default) to ignore charts. * * @param bool $includeCharts * * @return IWriter */ public function setIncludeCharts($includeCharts); /** * Get Pre-Calculate Formulas flag * If this is true (the default), then the writer will recalculate all formulae in a workbook when saving, * so that the pre-calculated values are immediately available to MS Excel or other office spreadsheet * viewer when opening the file * If false, then formulae are not calculated on save. This is faster for saving in PhpSpreadsheet, but slower * when opening the resulting file in MS Excel, because Excel has to recalculate the formulae itself. * * @return bool */ public function getPreCalculateFormulas(); /** * Set Pre-Calculate Formulas * Set to true (the default) to advise the Writer to calculate all formulae on save * Set to false to prevent precalculation of formulae on save. * * @param bool $precalculateFormulas Pre-Calculate Formulas? * * @return IWriter */ public function setPreCalculateFormulas($precalculateFormulas); /** * Save PhpSpreadsheet to file. * * @param resource|string $filename Name of the file to save * @param int $flags Flags that can change the behaviour of the Writer: * self::SAVE_WITH_CHARTS Save any charts that are defined (if the Writer supports Charts) * self::DISABLE_PRECALCULATE_FORMULAE Don't Precalculate formulae before saving the file * * @throws Exception */ public function save($filename, int $flags = 0): void; /** * Get use disk caching where possible? * * @return bool */ public function getUseDiskCaching(); /** * Set use disk caching where possible? * * @param bool $useDiskCache * @param string $cacheDirectory Disk caching directory * * @return IWriter */ public function setUseDiskCaching($useDiskCache, $cacheDirectory = null); /** * Get disk caching directory. * * @return string */ public function getDiskCachingDirectory(); } phpspreadsheet/src/PhpSpreadsheet/Writer/Exception.php 0000644 00000000253 15002227416 0017213 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Exception extends PhpSpreadsheetException { } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/ErrorCode.php 0000644 00000001064 15002227416 0017710 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; class ErrorCode { /** * @var array<string, int> */ protected static $errorCodeMap = [ '#NULL!' => 0x00, '#DIV/0!' => 0x07, '#VALUE!' => 0x0F, '#REF!' => 0x17, '#NAME?' => 0x1D, '#NUM!' => 0x24, '#N/A' => 0x2A, ]; public static function error(string $errorCode): int { if (array_key_exists($errorCode, self::$errorCodeMap)) { return self::$errorCodeMap[$errorCode]; } return 0; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/ConditionalHelper.php 0000644 00000003346 15002227416 0021434 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; class ConditionalHelper { /** * Formula parser. * * @var Parser */ protected $parser; /** * @var mixed */ protected $condition; /** * @var string */ protected $cellRange; /** * @var null|string */ protected $tokens; /** * @var int */ protected $size; public function __construct(Parser $parser) { $this->parser = $parser; } /** * @param mixed $condition */ public function processCondition($condition, string $cellRange): void { $this->condition = $condition; $this->cellRange = $cellRange; if (is_int($condition) || is_float($condition)) { $this->size = ($condition <= 65535 ? 3 : 0x0000); $this->tokens = pack('Cv', 0x1E, $condition); } else { try { $formula = Wizard\WizardAbstract::reverseAdjustCellRef((string) $condition, $cellRange); $this->parser->parse($formula); $this->tokens = $this->parser->toReversePolish(); $this->size = strlen($this->tokens ?? ''); } catch (PhpSpreadsheetException $e) { // In the event of a parser error with a formula value, we set the expression to ptgInt + 0 $this->tokens = pack('Cv', 0x1E, 0); $this->size = 3; } } } public function tokens(): ?string { return $this->tokens; } public function size(): int { return $this->size; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Worksheet.php 0000644 00000343033 15002227416 0020004 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use GdImage; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\Xls; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Worksheet\SheetView; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; // Original file header of PEAR::Spreadsheet_Excel_Writer_Worksheet (used as the base for this class): // ----------------------------------------------------------------------------------------- // /* // * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> // * // * The majority of this is _NOT_ my code. I simply ported it from the // * PERL Spreadsheet::WriteExcel module. // * // * The author of the Spreadsheet::WriteExcel module is John McNamara // * <jmcnamara@cpan.org> // * // * I _DO_ maintain this code, and John McNamara has nothing to do with the // * porting of this code to PHP. Any questions directly related to this // * class library should be directed to me. // * // * License Information: // * // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com // * // * This library is free software; you can redistribute it and/or // * modify it under the terms of the GNU Lesser General Public // * License as published by the Free Software Foundation; either // * version 2.1 of the License, or (at your option) any later version. // * // * This library is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // * Lesser General Public License for more details. // * // * You should have received a copy of the GNU Lesser General Public // * License along with this library; if not, write to the Free Software // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // */ class Worksheet extends BIFFwriter { /** @var int */ private static $always0 = 0; /** @var int */ private static $always1 = 1; /** * Formula parser. * * @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Parser */ private $parser; /** * Array containing format information for columns. * * @var array */ private $columnInfo; /** * The active pane for the worksheet. * * @var int */ private $activePane; /** * Whether to use outline. * * @var bool */ private $outlineOn; /** * Auto outline styles. * * @var bool */ private $outlineStyle; /** * Whether to have outline summary below. * Not currently used. * * @var bool */ private $outlineBelow; //* @phpstan-ignore-line /** * Whether to have outline summary at the right. * Not currently used. * * @var bool */ private $outlineRight; //* @phpstan-ignore-line /** * Reference to the total number of strings in the workbook. * * @var int */ private $stringTotal; /** * Reference to the number of unique strings in the workbook. * * @var int */ private $stringUnique; /** * Reference to the array containing all the unique strings in the workbook. * * @var array */ private $stringTable; /** * Color cache. * * @var array */ private $colors; /** * Index of first used row (at least 0). * * @var int */ private $firstRowIndex; /** * Index of last used row. (no used rows means -1). * * @var int */ private $lastRowIndex; /** * Index of first used column (at least 0). * * @var int */ private $firstColumnIndex; /** * Index of last used column (no used columns means -1). * * @var int */ private $lastColumnIndex; /** * Sheet object. * * @var \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet */ public $phpSheet; /** * Escher object corresponding to MSODRAWING. * * @var null|\PhpOffice\PhpSpreadsheet\Shared\Escher */ private $escher; /** * Array of font hashes associated to FONT records index. * * @var array */ public $fontHashIndex; /** * @var bool */ private $preCalculateFormulas; /** * @var int */ private $printHeaders; /** * Constructor. * * @param int $str_total Total number of strings * @param int $str_unique Total number of unique strings * @param array $str_table String Table * @param array $colors Colour Table * @param Parser $parser The formula parser created for the Workbook * @param bool $preCalculateFormulas Flag indicating whether formulas should be calculated or just written * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet The worksheet to write */ public function __construct(&$str_total, &$str_unique, &$str_table, &$colors, Parser $parser, $preCalculateFormulas, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet) { // It needs to call its parent's constructor explicitly parent::__construct(); $this->preCalculateFormulas = $preCalculateFormulas; $this->stringTotal = &$str_total; $this->stringUnique = &$str_unique; $this->stringTable = &$str_table; $this->colors = &$colors; $this->parser = $parser; $this->phpSheet = $phpSheet; $this->columnInfo = []; $this->activePane = 3; $this->printHeaders = 0; $this->outlineStyle = false; $this->outlineBelow = true; $this->outlineRight = true; $this->outlineOn = true; $this->fontHashIndex = []; // calculate values for DIMENSIONS record $minR = 1; $minC = 'A'; $maxR = $this->phpSheet->getHighestRow(); $maxC = $this->phpSheet->getHighestColumn(); // Determine lowest and highest column and row $this->firstRowIndex = $minR; $this->lastRowIndex = ($maxR > 65535) ? 65535 : $maxR; $this->firstColumnIndex = Coordinate::columnIndexFromString($minC); $this->lastColumnIndex = Coordinate::columnIndexFromString($maxC); if ($this->lastColumnIndex > 255) { $this->lastColumnIndex = 255; } } /** * Add data to the beginning of the workbook (note the reverse order) * and to the end of the workbook. * * @see \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook::storeWorkbook() */ public function close(): void { $phpSheet = $this->phpSheet; // Storing selected cells and active sheet because it changes while parsing cells with formulas. $selectedCells = $this->phpSheet->getSelectedCells(); $activeSheetIndex = $this->phpSheet->getParentOrThrow()->getActiveSheetIndex(); // Write BOF record $this->storeBof(0x0010); // Write PRINTHEADERS $this->writePrintHeaders(); // Write PRINTGRIDLINES $this->writePrintGridlines(); // Write GRIDSET $this->writeGridset(); // Calculate column widths $phpSheet->calculateColumnWidths(); // Column dimensions if (($defaultWidth = $phpSheet->getDefaultColumnDimension()->getWidth()) < 0) { $defaultWidth = \PhpOffice\PhpSpreadsheet\Shared\Font::getDefaultColumnWidthByFont($phpSheet->getParentOrThrow()->getDefaultStyle()->getFont()); } $columnDimensions = $phpSheet->getColumnDimensions(); $maxCol = $this->lastColumnIndex - 1; for ($i = 0; $i <= $maxCol; ++$i) { $hidden = 0; $level = 0; $xfIndex = 15; // there are 15 cell style Xfs $width = $defaultWidth; $columnLetter = Coordinate::stringFromColumnIndex($i + 1); if (isset($columnDimensions[$columnLetter])) { $columnDimension = $columnDimensions[$columnLetter]; if ($columnDimension->getWidth() >= 0) { $width = $columnDimension->getWidth(); } $hidden = $columnDimension->getVisible() ? 0 : 1; $level = $columnDimension->getOutlineLevel(); $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs } // Components of columnInfo: // $firstcol first column on the range // $lastcol last column on the range // $width width to set // $xfIndex The optional cell style Xf index to apply to the columns // $hidden The optional hidden atribute // $level The optional outline level $this->columnInfo[] = [$i, $i, $width, $xfIndex, $hidden, $level]; } // Write GUTS $this->writeGuts(); // Write DEFAULTROWHEIGHT $this->writeDefaultRowHeight(); // Write WSBOOL $this->writeWsbool(); // Write horizontal and vertical page breaks $this->writeBreaks(); // Write page header $this->writeHeader(); // Write page footer $this->writeFooter(); // Write page horizontal centering $this->writeHcenter(); // Write page vertical centering $this->writeVcenter(); // Write left margin $this->writeMarginLeft(); // Write right margin $this->writeMarginRight(); // Write top margin $this->writeMarginTop(); // Write bottom margin $this->writeMarginBottom(); // Write page setup $this->writeSetup(); // Write sheet protection $this->writeProtect(); // Write SCENPROTECT $this->writeScenProtect(); // Write OBJECTPROTECT $this->writeObjectProtect(); // Write sheet password $this->writePassword(); // Write DEFCOLWIDTH record $this->writeDefcol(); // Write the COLINFO records if they exist if (!empty($this->columnInfo)) { $colcount = count($this->columnInfo); for ($i = 0; $i < $colcount; ++$i) { $this->writeColinfo($this->columnInfo[$i]); } } $autoFilterRange = $phpSheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { // Write AUTOFILTERINFO $this->writeAutoFilterInfo(); } // Write sheet dimensions $this->writeDimensions(); // Row dimensions foreach ($phpSheet->getRowDimensions() as $rowDimension) { $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs $this->writeRow( $rowDimension->getRowIndex() - 1, (int) $rowDimension->getRowHeight(), $xfIndex, !$rowDimension->getVisible(), $rowDimension->getOutlineLevel() ); } // Write Cells foreach ($phpSheet->getCellCollection()->getSortedCoordinates() as $coordinate) { /** @var Cell $cell */ $cell = $phpSheet->getCellCollection()->get($coordinate); $row = $cell->getRow() - 1; $column = Coordinate::columnIndexFromString($cell->getColumn()) - 1; // Don't break Excel break the code! if ($row > 65535 || $column > 255) { throw new WriterException('Rows or columns overflow! Excel5 has limit to 65535 rows and 255 columns. Use XLSX instead.'); } // Write cell value $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs $cVal = $cell->getValue(); if ($cVal instanceof RichText) { $arrcRun = []; $str_pos = 0; $elements = $cVal->getRichTextElements(); foreach ($elements as $element) { // FONT Index $str_fontidx = 0; if ($element instanceof Run) { $getFont = $element->getFont(); if ($getFont !== null) { $str_fontidx = $this->fontHashIndex[$getFont->getHashCode()]; } } $arrcRun[] = ['strlen' => $str_pos, 'fontidx' => $str_fontidx]; // Position FROM $str_pos += StringHelper::countCharacters($element->getText(), 'UTF-8'); } $this->writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun); } else { switch ($cell->getDatatype()) { case DataType::TYPE_STRING: case DataType::TYPE_INLINE: case DataType::TYPE_NULL: if ($cVal === '' || $cVal === null) { $this->writeBlank($row, $column, $xfIndex); } else { $this->writeString($row, $column, $cVal, $xfIndex); } break; case DataType::TYPE_NUMERIC: $this->writeNumber($row, $column, $cVal, $xfIndex); break; case DataType::TYPE_FORMULA: $calculatedValue = $this->preCalculateFormulas ? $cell->getCalculatedValue() : null; if (self::WRITE_FORMULA_EXCEPTION == $this->writeFormula($row, $column, $cVal, $xfIndex, $calculatedValue)) { if ($calculatedValue === null) { $calculatedValue = $cell->getCalculatedValue(); } $calctype = gettype($calculatedValue); switch ($calctype) { case 'integer': case 'double': $this->writeNumber($row, $column, (float) $calculatedValue, $xfIndex); break; case 'string': $this->writeString($row, $column, $calculatedValue, $xfIndex); break; case 'boolean': $this->writeBoolErr($row, $column, (int) $calculatedValue, 0, $xfIndex); break; default: $this->writeString($row, $column, $cVal, $xfIndex); } } break; case DataType::TYPE_BOOL: $this->writeBoolErr($row, $column, $cVal, 0, $xfIndex); break; case DataType::TYPE_ERROR: $this->writeBoolErr($row, $column, ErrorCode::error($cVal), 1, $xfIndex); break; } } } // Append $this->writeMsoDrawing(); // Restoring active sheet. $this->phpSheet->getParentOrThrow()->setActiveSheetIndex($activeSheetIndex); // Write WINDOW2 record $this->writeWindow2(); // Write PLV record $this->writePageLayoutView(); // Write ZOOM record $this->writeZoom(); if ($phpSheet->getFreezePane()) { $this->writePanes(); } // Restoring selected cells. $this->phpSheet->setSelectedCells($selectedCells); // Write SELECTION record $this->writeSelection(); // Write MergedCellsTable Record $this->writeMergedCells(); // Hyperlinks $phpParent = $phpSheet->getParent(); $hyperlinkbase = ($phpParent === null) ? '' : $phpParent->getProperties()->getHyperlinkBase(); foreach ($phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) { [$column, $row] = Coordinate::indexesFromString($coordinate); $url = $hyperlink->getUrl(); if (strpos($url, 'sheet://') !== false) { // internal to current workbook $url = str_replace('sheet://', 'internal:', $url); } elseif (preg_match('/^(http:|https:|ftp:|mailto:)/', $url)) { // URL } elseif (!empty($hyperlinkbase) && preg_match('~^([A-Za-z]:)?[/\\\\]~', $url) !== 1) { $url = "$hyperlinkbase$url"; if (preg_match('/^(http:|https:|ftp:|mailto:)/', $url) !== 1) { $url = 'external:' . $url; } } else { // external (local file) $url = 'external:' . $url; } $this->writeUrl($row - 1, $column - 1, $url); } $this->writeDataValidity(); $this->writeSheetLayout(); // Write SHEETPROTECTION record $this->writeSheetProtection(); $this->writeRangeProtection(); // Write Conditional Formatting Rules and Styles $this->writeConditionalFormatting(); $this->storeEof(); } private function writeConditionalFormatting(): void { $conditionalFormulaHelper = new ConditionalHelper($this->parser); $arrConditionalStyles = $this->phpSheet->getConditionalStylesCollection(); if (!empty($arrConditionalStyles)) { $arrConditional = []; // Write ConditionalFormattingTable records foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) { $cfHeaderWritten = false; foreach ($conditionalStyles as $conditional) { /** @var Conditional $conditional */ if ( $conditional->getConditionType() === Conditional::CONDITION_EXPRESSION || $conditional->getConditionType() === Conditional::CONDITION_CELLIS ) { // Write CFHEADER record (only if there are Conditional Styles that we are able to write) if ($cfHeaderWritten === false) { $cfHeaderWritten = $this->writeCFHeader($cellCoordinate, $conditionalStyles); } if ($cfHeaderWritten === true && !isset($arrConditional[$conditional->getHashCode()])) { // This hash code has been handled $arrConditional[$conditional->getHashCode()] = true; // Write CFRULE record $this->writeCFRule($conditionalFormulaHelper, $conditional, $cellCoordinate); } } } } } } /** * Write a cell range address in BIFF8 * always fixed range * See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format. * * @param string $range E.g. 'A1' or 'A1:B6' * * @return string Binary data */ private function writeBIFF8CellRangeAddressFixed($range) { $explodes = explode(':', $range); // extract first cell, e.g. 'A1' $firstCell = $explodes[0]; // extract last cell, e.g. 'B6' if (count($explodes) == 1) { $lastCell = $firstCell; } else { $lastCell = $explodes[1]; } $firstCellCoordinates = Coordinate::indexesFromString($firstCell); // e.g. [0, 1] $lastCellCoordinates = Coordinate::indexesFromString($lastCell); // e.g. [1, 6] return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, $firstCellCoordinates[0] - 1, $lastCellCoordinates[0] - 1); } /** * Retrieves data from memory in one chunk, or from disk * sized chunks. * * @return string The data */ public function getData() { // Return data stored in memory if (isset($this->_data)) { $tmp = $this->_data; $this->_data = null; return $tmp; } // No data to return return ''; } /** * Set the option to print the row and column headers on the printed page. * * @param int $print Whether to print the headers or not. Defaults to 1 (print). */ public function printRowColHeaders($print = 1): void { $this->printHeaders = $print; } /** * This method sets the properties for outlining and grouping. The defaults * correspond to Excel's defaults. * * @param bool $visible * @param bool $symbols_below * @param bool $symbols_right * @param bool $auto_style */ public function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false): void { $this->outlineOn = $visible; $this->outlineBelow = $symbols_below; $this->outlineRight = $symbols_right; $this->outlineStyle = $auto_style; } /** * Write a double to the specified row and column (zero indexed). * An integer can be written as a double. Excel will display an * integer. $format is optional. * * Returns 0 : normal termination * -2 : row or column out of range * * @param int $row Zero indexed row * @param int $col Zero indexed column * @param float $num The number to write * @param mixed $xfIndex The optional XF format * * @return int */ private function writeNumber($row, $col, $num, $xfIndex) { $record = 0x0203; // Record identifier $length = 0x000E; // Number of bytes to follow $header = pack('vv', $record, $length); $data = pack('vvv', $row, $col, $xfIndex); $xl_double = pack('d', $num); if (self::getByteOrder()) { // if it's Big Endian $xl_double = strrev($xl_double); } $this->append($header . $data . $xl_double); return 0; } /** * Write a LABELSST record or a LABEL record. Which one depends on BIFF version. * * @param int $row Row index (0-based) * @param int $col Column index (0-based) * @param string $str The string * @param int $xfIndex Index to XF record */ private function writeString($row, $col, $str, $xfIndex): void { $this->writeLabelSst($row, $col, $str, $xfIndex); } /** * Write a LABELSST record or a LABEL record. Which one depends on BIFF version * It differs from writeString by the writing of rich text strings. * * @param int $row Row index (0-based) * @param int $col Column index (0-based) * @param string $str The string * @param int $xfIndex The XF format index for the cell * @param array $arrcRun Index to Font record and characters beginning */ private function writeRichTextString($row, $col, $str, $xfIndex, $arrcRun): void { $record = 0x00FD; // Record identifier $length = 0x000A; // Bytes to follow $str = StringHelper::UTF8toBIFF8UnicodeShort($str, $arrcRun); // check if string is already present if (!isset($this->stringTable[$str])) { $this->stringTable[$str] = $this->stringUnique++; } ++$this->stringTotal; $header = pack('vv', $record, $length); $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]); $this->append($header . $data); } /** * Write a string to the specified row and column (zero indexed). * This is the BIFF8 version (no 255 chars limit). * $format is optional. * * @param int $row Zero indexed row * @param int $col Zero indexed column * @param string $str The string to write * @param mixed $xfIndex The XF format index for the cell */ private function writeLabelSst($row, $col, $str, $xfIndex): void { $record = 0x00FD; // Record identifier $length = 0x000A; // Bytes to follow $str = StringHelper::UTF8toBIFF8UnicodeLong($str); // check if string is already present if (!isset($this->stringTable[$str])) { $this->stringTable[$str] = $this->stringUnique++; } ++$this->stringTotal; $header = pack('vv', $record, $length); $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]); $this->append($header . $data); } /** * Write a blank cell to the specified row and column (zero indexed). * A blank cell is used to specify formatting without adding a string * or a number. * * A blank cell without a format serves no purpose. Therefore, we don't write * a BLANK record unless a format is specified. * * Returns 0 : normal termination (including no format) * -1 : insufficient number of arguments * -2 : row or column out of range * * @param int $row Zero indexed row * @param int $col Zero indexed column * @param mixed $xfIndex The XF format index * * @return int */ public function writeBlank($row, $col, $xfIndex) { $record = 0x0201; // Record identifier $length = 0x0006; // Number of bytes to follow $header = pack('vv', $record, $length); $data = pack('vvv', $row, $col, $xfIndex); $this->append($header . $data); return 0; } /** * Write a boolean or an error type to the specified row and column (zero indexed). * * @param int $row Row index (0-based) * @param int $col Column index (0-based) * @param int $value * @param int $isError Error or Boolean? * @param int $xfIndex * * @return int */ private function writeBoolErr($row, $col, $value, $isError, $xfIndex) { $record = 0x0205; $length = 8; $header = pack('vv', $record, $length); $data = pack('vvvCC', $row, $col, $xfIndex, $value, $isError); $this->append($header . $data); return 0; } const WRITE_FORMULA_NORMAL = 0; const WRITE_FORMULA_ERRORS = -1; const WRITE_FORMULA_RANGE = -2; const WRITE_FORMULA_EXCEPTION = -3; /** @var bool */ private static $allowThrow = false; public static function setAllowThrow(bool $allowThrow): void { self::$allowThrow = $allowThrow; } public static function getAllowThrow(): bool { return self::$allowThrow; } /** * Write a formula to the specified row and column (zero indexed). * The textual representation of the formula is passed to the parser in * Parser.php which returns a packed binary string. * * Returns 0 : WRITE_FORMULA_NORMAL normal termination * -1 : WRITE_FORMULA_ERRORS formula errors (bad formula) * -2 : WRITE_FORMULA_RANGE row or column out of range * -3 : WRITE_FORMULA_EXCEPTION parse raised exception, probably due to definedname * * @param int $row Zero indexed row * @param int $col Zero indexed column * @param string $formula The formula text string * @param mixed $xfIndex The XF format index * @param mixed $calculatedValue Calculated value * * @return int */ private function writeFormula($row, $col, $formula, $xfIndex, $calculatedValue) { $record = 0x0006; // Record identifier // Initialize possible additional value for STRING record that should be written after the FORMULA record? $stringValue = null; // calculated value if (isset($calculatedValue)) { // Since we can't yet get the data type of the calculated value, // we use best effort to determine data type if (is_bool($calculatedValue)) { // Boolean value $num = pack('CCCvCv', 0x01, 0x00, (int) $calculatedValue, 0x00, 0x00, 0xFFFF); } elseif (is_int($calculatedValue) || is_float($calculatedValue)) { // Numeric value $num = pack('d', $calculatedValue); } elseif (is_string($calculatedValue)) { $errorCodes = DataType::getErrorCodes(); if (isset($errorCodes[$calculatedValue])) { // Error value $num = pack('CCCvCv', 0x02, 0x00, ErrorCode::error($calculatedValue), 0x00, 0x00, 0xFFFF); } elseif ($calculatedValue === '') { // Empty string (and BIFF8) $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF); } else { // Non-empty string value (or empty string BIFF5) $stringValue = $calculatedValue; $num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF); } } else { // We are really not supposed to reach here $num = pack('d', 0x00); } } else { $num = pack('d', 0x00); } $grbit = 0x03; // Option flags $unknown = 0x0000; // Must be zero // Strip the '=' or '@' sign at the beginning of the formula string if ($formula[0] == '=') { $formula = substr($formula, 1); } else { // Error handling $this->writeString($row, $col, 'Unrecognised character for formula', 0); return self::WRITE_FORMULA_ERRORS; } // Parse the formula using the parser in Parser.php try { $this->parser->parse($formula); $formula = $this->parser->toReversePolish(); $formlen = strlen($formula); // Length of the binary string $length = 0x16 + $formlen; // Length of the record data $header = pack('vv', $record, $length); $data = pack('vvv', $row, $col, $xfIndex) . $num . pack('vVv', $grbit, $unknown, $formlen); $this->append($header . $data . $formula); // Append also a STRING record if necessary if ($stringValue !== null) { $this->writeStringRecord($stringValue); } return self::WRITE_FORMULA_NORMAL; } catch (PhpSpreadsheetException $e) { if (self::$allowThrow) { throw $e; } return self::WRITE_FORMULA_EXCEPTION; } } /** * Write a STRING record. This. * * @param string $stringValue */ private function writeStringRecord($stringValue): void { $record = 0x0207; // Record identifier $data = StringHelper::UTF8toBIFF8UnicodeLong($stringValue); $length = strlen($data); $header = pack('vv', $record, $length); $this->append($header . $data); } /** * Write a hyperlink. * This is comprised of two elements: the visible label and * the invisible link. The visible label is the same as the link unless an * alternative string is specified. The label is written using the * writeString() method. Therefore the 255 characters string limit applies. * $string and $format are optional. * * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external * directory url. * * @param int $row Row * @param int $col Column * @param string $url URL string */ private function writeUrl($row, $col, $url): void { // Add start row and col to arg list $this->writeUrlRange($row, $col, $row, $col, $url); } /** * This is the more general form of writeUrl(). It allows a hyperlink to be * written to a range of cells. This function also decides the type of hyperlink * to be written. These are either, Web (http, ftp, mailto), Internal * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1'). * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * * @see writeUrl() */ private function writeUrlRange($row1, $col1, $row2, $col2, $url): void { // Check for internal/external sheet links or default to web link if (preg_match('[^internal:]', $url)) { $this->writeUrlInternal($row1, $col1, $row2, $col2, $url); } if (preg_match('[^external:]', $url)) { $this->writeUrlExternal($row1, $col1, $row2, $col2, $url); } $this->writeUrlWeb($row1, $col1, $row2, $col2, $url); } /** * Used to write http, ftp and mailto hyperlinks. * The link type ($options) is 0x03 is the same as absolute dir ref without * sheet. However it is differentiated by the $unknown2 data stream. * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * * @see writeUrl() */ public function writeUrlWeb($row1, $col1, $row2, $col2, $url): void { $record = 0x01B8; // Record identifier // Pack the undocumented parts of the hyperlink stream $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); $unknown2 = pack('H*', 'E0C9EA79F9BACE118C8200AA004BA90B'); // Pack the option flags $options = pack('V', 0x03); // Convert URL to a null terminated wchar string /** @phpstan-ignore-next-line */ $url = implode("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY)); $url = $url . "\0\0\0"; // Pack the length of the URL $url_len = pack('V', strlen($url)); // Calculate the data length $length = 0x34 + strlen($url); // Pack the header data $header = pack('vv', $record, $length); $data = pack('vvvv', $row1, $row2, $col1, $col2); // Write the packed data $this->append($header . $data . $unknown1 . $options . $unknown2 . $url_len . $url); } /** * Used to write internal reference hyperlinks such as "Sheet1!A1". * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * * @see writeUrl() */ private function writeUrlInternal($row1, $col1, $row2, $col2, $url): void { $record = 0x01B8; // Record identifier // Strip URL type $url = (string) preg_replace('/^internal:/', '', $url); // Pack the undocumented parts of the hyperlink stream $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); // Pack the option flags $options = pack('V', 0x08); // Convert the URL type and to a null terminated wchar string $url .= "\0"; // character count $url_len = StringHelper::countCharacters($url); $url_len = pack('V', $url_len); $url = StringHelper::convertEncoding($url, 'UTF-16LE', 'UTF-8'); // Calculate the data length $length = 0x24 + strlen($url); // Pack the header data $header = pack('vv', $record, $length); $data = pack('vvvv', $row1, $row2, $col1, $col2); // Write the packed data $this->append($header . $data . $unknown1 . $options . $url_len . $url); } /** * Write links to external directory names such as 'c:\foo.xls', * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'. * * Note: Excel writes some relative links with the $dir_long string. We ignore * these cases for the sake of simpler code. * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * * @see writeUrl() */ private function writeUrlExternal($row1, $col1, $row2, $col2, $url): void { // Network drives are different. We will handle them separately // MS/Novell network drives and shares start with \\ if (preg_match('[^external:\\\\]', $url)) { return; } $record = 0x01B8; // Record identifier // Strip URL type and change Unix dir separator to Dos style (if needed) // $url = (string) preg_replace(['/^external:/', '/\//'], ['', '\\'], $url); // Determine if the link is relative or absolute: // relative if link contains no dir separator, "somefile.xls" // relative if link starts with up-dir, "..\..\somefile.xls" // otherwise, absolute $absolute = 0x00; // relative path if (preg_match('/^[A-Z]:/', $url)) { $absolute = 0x02; // absolute path on Windows, e.g. C:\... } $link_type = 0x01 | $absolute; // Determine if the link contains a sheet reference and change some of the // parameters accordingly. // Split the dir name and sheet name (if it exists) $dir_long = $url; if (preg_match('/\\#/', $url)) { $link_type |= 0x08; } // Pack the link type $link_type = pack('V', $link_type); // Calculate the up-level dir count e.g.. (..\..\..\ == 3) $up_count = preg_match_all('/\\.\\.\\\\/', $dir_long, $useless); $up_count = pack('v', $up_count); // Store the short dos dir name (null terminated) $dir_short = (string) preg_replace('/\\.\\.\\\\/', '', $dir_long) . "\0"; // Store the long dir name as a wchar string (non-null terminated) //$dir_long = $dir_long . "\0"; // Pack the lengths of the dir strings $dir_short_len = pack('V', strlen($dir_short)); //$dir_long_len = pack('V', strlen($dir_long)); $stream_len = pack('V', 0); //strlen($dir_long) + 0x06); // Pack the undocumented parts of the hyperlink stream $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); $unknown2 = pack('H*', '0303000000000000C000000000000046'); $unknown3 = pack('H*', 'FFFFADDE000000000000000000000000000000000000000'); //$unknown4 = pack('v', 0x03); // Pack the main data stream $data = pack('vvvv', $row1, $row2, $col1, $col2) . $unknown1 . $link_type . $unknown2 . $up_count . $dir_short_len . $dir_short . $unknown3 . $stream_len; /*. $dir_long_len . $unknown4 . $dir_long . $sheet_len . $sheet ;*/ // Pack the header data $length = strlen($data); $header = pack('vv', $record, $length); // Write the packed data $this->append($header . $data); } /** * This method is used to set the height and format for a row. * * @param int $row The row to set * @param int $height Height we are giving to the row. * Use null to set XF without setting height * @param int $xfIndex The optional cell style Xf index to apply to the columns * @param bool $hidden The optional hidden attribute * @param int $level The optional outline level for row, in range [0,7] */ private function writeRow($row, $height, $xfIndex, $hidden = false, $level = 0): void { $record = 0x0208; // Record identifier $length = 0x0010; // Number of bytes to follow $colMic = 0x0000; // First defined column $colMac = 0x0000; // Last defined column $irwMac = 0x0000; // Used by Excel to optimise loading $reserved = 0x0000; // Reserved $grbit = 0x0000; // Option flags $ixfe = $xfIndex; if ($height < 0) { $height = null; } // Use writeRow($row, null, $XF) to set XF format without setting height if ($height !== null) { $miyRw = $height * 20; // row height } else { $miyRw = 0xff; // default row height is 256 } // Set the options flags. fUnsynced is used to show that the font and row // heights are not compatible. This is usually the case for WriteExcel. // The collapsed flag 0x10 doesn't seem to be used to indicate that a row // is collapsed. Instead it is used to indicate that the previous row is // collapsed. The zero height flag, 0x20, is used to collapse a row. $grbit |= $level; if ($hidden === true) { $grbit |= 0x0030; } if ($height !== null) { $grbit |= 0x0040; // fUnsynced } if ($xfIndex !== 0xF) { $grbit |= 0x0080; } $grbit |= 0x0100; $header = pack('vv', $record, $length); $data = pack('vvvvvvvv', $row, $colMic, $colMac, $miyRw, $irwMac, $reserved, $grbit, $ixfe); $this->append($header . $data); } /** * Writes Excel DIMENSIONS to define the area in which there is data. */ private function writeDimensions(): void { $record = 0x0200; // Record identifier $length = 0x000E; $data = pack('VVvvv', $this->firstRowIndex, $this->lastRowIndex + 1, $this->firstColumnIndex, $this->lastColumnIndex + 1, 0x0000); // reserved $header = pack('vv', $record, $length); $this->append($header . $data); } /** * Write BIFF record Window2. */ private function writeWindow2(): void { $record = 0x023E; // Record identifier $length = 0x0012; $rwTop = 0x0000; // Top row visible in window $colLeft = 0x0000; // Leftmost column visible in window // The options flags that comprise $grbit $fDspFmla = 0; // 0 - bit $fDspGrid = $this->phpSheet->getShowGridlines() ? 1 : 0; // 1 $fDspRwCol = $this->phpSheet->getShowRowColHeaders() ? 1 : 0; // 2 $fFrozen = $this->phpSheet->getFreezePane() ? 1 : 0; // 3 $fDspZeros = 1; // 4 $fDefaultHdr = 1; // 5 $fArabic = $this->phpSheet->getRightToLeft() ? 1 : 0; // 6 $fDspGuts = $this->outlineOn; // 7 $fFrozenNoSplit = 0; // 0 - bit // no support in PhpSpreadsheet for selected sheet, therefore sheet is only selected if it is the active sheet $fSelected = ($this->phpSheet === $this->phpSheet->getParentOrThrow()->getActiveSheet()) ? 1 : 0; $fPageBreakPreview = $this->phpSheet->getSheetView()->getView() === SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW; $grbit = $fDspFmla; $grbit |= $fDspGrid << 1; $grbit |= $fDspRwCol << 2; $grbit |= $fFrozen << 3; $grbit |= $fDspZeros << 4; $grbit |= $fDefaultHdr << 5; $grbit |= $fArabic << 6; $grbit |= $fDspGuts << 7; $grbit |= $fFrozenNoSplit << 8; $grbit |= $fSelected << 9; // Selected sheets. $grbit |= $fSelected << 10; // Active sheet. $grbit |= $fPageBreakPreview << 11; $header = pack('vv', $record, $length); $data = pack('vvv', $grbit, $rwTop, $colLeft); // FIXME !!! $rgbHdr = 0x0040; // Row/column heading and gridline color index $zoom_factor_page_break = ($fPageBreakPreview ? $this->phpSheet->getSheetView()->getZoomScale() : 0x0000); $zoom_factor_normal = $this->phpSheet->getSheetView()->getZoomScaleNormal(); $data .= pack('vvvvV', $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000); $this->append($header . $data); } /** * Write BIFF record DEFAULTROWHEIGHT. */ private function writeDefaultRowHeight(): void { $defaultRowHeight = $this->phpSheet->getDefaultRowDimension()->getRowHeight(); if ($defaultRowHeight < 0) { return; } // convert to twips $defaultRowHeight = (int) 20 * $defaultRowHeight; $record = 0x0225; // Record identifier $length = 0x0004; // Number of bytes to follow $header = pack('vv', $record, $length); $data = pack('vv', 1, $defaultRowHeight); $this->append($header . $data); } /** * Write BIFF record DEFCOLWIDTH if COLINFO records are in use. */ private function writeDefcol(): void { $defaultColWidth = 8; $record = 0x0055; // Record identifier $length = 0x0002; // Number of bytes to follow $header = pack('vv', $record, $length); $data = pack('v', $defaultColWidth); $this->append($header . $data); } /** * Write BIFF record COLINFO to define column widths. * * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C * length record. * * @param array $col_array This is the only parameter received and is composed of the following: * 0 => First formatted column, * 1 => Last formatted column, * 2 => Col width (8.43 is Excel default), * 3 => The optional XF format of the column, * 4 => Option flags. * 5 => Optional outline level */ private function writeColinfo($col_array): void { $colFirst = $col_array[0] ?? null; $colLast = $col_array[1] ?? null; $coldx = $col_array[2] ?? 8.43; $xfIndex = $col_array[3] ?? 15; $grbit = $col_array[4] ?? 0; $level = $col_array[5] ?? 0; $record = 0x007D; // Record identifier $length = 0x000C; // Number of bytes to follow $coldx *= 256; // Convert to units of 1/256 of a char $ixfe = $xfIndex; $reserved = 0x0000; // Reserved $level = max(0, min($level, 7)); $grbit |= $level << 8; $header = pack('vv', $record, $length); $data = pack('vvvvvv', $colFirst, $colLast, $coldx, $ixfe, $grbit, $reserved); $this->append($header . $data); } /** * Write BIFF record SELECTION. */ private function writeSelection(): void { // look up the selected cell range $selectedCells = Coordinate::splitRange($this->phpSheet->getSelectedCells()); $selectedCells = $selectedCells[0]; if (count($selectedCells) == 2) { [$first, $last] = $selectedCells; } else { $first = $selectedCells[0]; $last = $selectedCells[0]; } [$colFirst, $rwFirst] = Coordinate::coordinateFromString($first); $colFirst = Coordinate::columnIndexFromString($colFirst) - 1; // base 0 column index --$rwFirst; // base 0 row index [$colLast, $rwLast] = Coordinate::coordinateFromString($last); $colLast = Coordinate::columnIndexFromString($colLast) - 1; // base 0 column index --$rwLast; // base 0 row index // make sure we are not out of bounds $colFirst = min($colFirst, 255); $colLast = min($colLast, 255); $rwFirst = min($rwFirst, 65535); $rwLast = min($rwLast, 65535); $record = 0x001D; // Record identifier $length = 0x000F; // Number of bytes to follow $pnn = $this->activePane; // Pane position $rwAct = $rwFirst; // Active row $colAct = $colFirst; // Active column $irefAct = 0; // Active cell ref $cref = 1; // Number of refs // Swap last row/col for first row/col as necessary if ($rwFirst > $rwLast) { [$rwFirst, $rwLast] = [$rwLast, $rwFirst]; } if ($colFirst > $colLast) { [$colFirst, $colLast] = [$colLast, $colFirst]; } $header = pack('vv', $record, $length); $data = pack('CvvvvvvCC', $pnn, $rwAct, $colAct, $irefAct, $cref, $rwFirst, $rwLast, $colFirst, $colLast); $this->append($header . $data); } /** * Store the MERGEDCELLS records for all ranges of merged cells. */ private function writeMergedCells(): void { $mergeCells = $this->phpSheet->getMergeCells(); $countMergeCells = count($mergeCells); if ($countMergeCells == 0) { return; } // maximum allowed number of merged cells per record $maxCountMergeCellsPerRecord = 1027; // record identifier $record = 0x00E5; // counter for total number of merged cells treated so far by the writer $i = 0; // counter for number of merged cells written in record currently being written $j = 0; // initialize record data $recordData = ''; // loop through the merged cells foreach ($mergeCells as $mergeCell) { ++$i; ++$j; // extract the row and column indexes $range = Coordinate::splitRange($mergeCell); [$first, $last] = $range[0]; [$firstColumn, $firstRow] = Coordinate::indexesFromString($first); [$lastColumn, $lastRow] = Coordinate::indexesFromString($last); $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, $firstColumn - 1, $lastColumn - 1); // flush record if we have reached limit for number of merged cells, or reached final merged cell if ($j == $maxCountMergeCellsPerRecord || $i == $countMergeCells) { $recordData = pack('v', $j) . $recordData; $length = strlen($recordData); $header = pack('vv', $record, $length); $this->append($header . $recordData); // initialize for next record, if any $recordData = ''; $j = 0; } } } /** * Write SHEETLAYOUT record. */ private function writeSheetLayout(): void { if (!$this->phpSheet->isTabColorSet()) { return; } $recordData = pack( 'vvVVVvv', 0x0862, 0x0000, // unused 0x00000000, // unused 0x00000000, // unused 0x00000014, // size of record data $this->colors[$this->phpSheet->getTabColor()->getRGB()], // color index 0x0000 // unused ); $length = strlen($recordData); $record = 0x0862; // Record identifier $header = pack('vv', $record, $length); $this->append($header . $recordData); } private static function protectionBitsDefaultFalse(?bool $value, int $shift): int { if ($value === false) { return 1 << $shift; } return 0; } private static function protectionBitsDefaultTrue(?bool $value, int $shift): int { if ($value !== false) { return 1 << $shift; } return 0; } /** * Write SHEETPROTECTION. */ private function writeSheetProtection(): void { // record identifier $record = 0x0867; // prepare options $protection = $this->phpSheet->getProtection(); $options = self::protectionBitsDefaultTrue($protection->getObjects(), 0) | self::protectionBitsDefaultTrue($protection->getScenarios(), 1) | self::protectionBitsDefaultFalse($protection->getFormatCells(), 2) | self::protectionBitsDefaultFalse($protection->getFormatColumns(), 3) | self::protectionBitsDefaultFalse($protection->getFormatRows(), 4) | self::protectionBitsDefaultFalse($protection->getInsertColumns(), 5) | self::protectionBitsDefaultFalse($protection->getInsertRows(), 6) | self::protectionBitsDefaultFalse($protection->getInsertHyperlinks(), 7) | self::protectionBitsDefaultFalse($protection->getDeleteColumns(), 8) | self::protectionBitsDefaultFalse($protection->getDeleteRows(), 9) | self::protectionBitsDefaultTrue($protection->getSelectLockedCells(), 10) | self::protectionBitsDefaultFalse($protection->getSort(), 11) | self::protectionBitsDefaultFalse($protection->getAutoFilter(), 12) | self::protectionBitsDefaultFalse($protection->getPivotTables(), 13) | self::protectionBitsDefaultTrue($protection->getSelectUnlockedCells(), 14); // record data $recordData = pack( 'vVVCVVvv', 0x0867, // repeated record identifier 0x0000, // not used 0x0000, // not used 0x00, // not used 0x01000200, // unknown data 0xFFFFFFFF, // unknown data $options, // options 0x0000 // not used ); $length = strlen($recordData); $header = pack('vv', $record, $length); $this->append($header . $recordData); } /** * Write BIFF record RANGEPROTECTION. * * Openoffice.org's Documentation of the Microsoft Excel File Format uses term RANGEPROTECTION for these records * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records */ private function writeRangeProtection(): void { foreach ($this->phpSheet->getProtectedCells() as $range => $password) { // number of ranges, e.g. 'A1:B3 C20:D25' $cellRanges = explode(' ', $range); $cref = count($cellRanges); $recordData = pack( 'vvVVvCVvVv', 0x0868, 0x00, 0x0000, 0x0000, 0x02, 0x0, 0x0000, $cref, 0x0000, 0x00 ); foreach ($cellRanges as $cellRange) { $recordData .= $this->writeBIFF8CellRangeAddressFixed($cellRange); } // the rgbFeat structure $recordData .= pack( 'VV', 0x0000, hexdec($password) ); $recordData .= StringHelper::UTF8toBIFF8UnicodeLong('p' . md5($recordData)); $length = strlen($recordData); $record = 0x0868; // Record identifier $header = pack('vv', $record, $length); $this->append($header . $recordData); } } /** * Writes the Excel BIFF PANE record. * The panes can either be frozen or thawed (unfrozen). * Frozen panes are specified in terms of an integer number of rows and columns. * Thawed panes are specified in terms of Excel's units for rows and columns. */ private function writePanes(): void { if (!$this->phpSheet->getFreezePane()) { // thaw panes return; } [$column, $row] = Coordinate::indexesFromString($this->phpSheet->getFreezePane()); $x = $column - 1; $y = $row - 1; [$leftMostColumn, $topRow] = Coordinate::indexesFromString($this->phpSheet->getTopLeftCell() ?? ''); //Coordinates are zero-based in xls files $rwTop = $topRow - 1; $colLeft = $leftMostColumn - 1; $record = 0x0041; // Record identifier $length = 0x000A; // Number of bytes to follow // Determine which pane should be active. There is also the undocumented // option to override this should it be necessary: may be removed later. $pnnAct = 0; if ($x != 0 && $y != 0) { $pnnAct = 0; // Bottom right } if ($x != 0 && $y == 0) { $pnnAct = 1; // Top right } if ($x == 0 && $y != 0) { $pnnAct = 2; // Bottom left } if ($x == 0 && $y == 0) { $pnnAct = 3; // Top left } $this->activePane = $pnnAct; // Used in writeSelection $header = pack('vv', $record, $length); $data = pack('vvvvv', $x, $y, $rwTop, $colLeft, $pnnAct); $this->append($header . $data); } /** * Store the page setup SETUP BIFF record. */ private function writeSetup(): void { $record = 0x00A1; // Record identifier $length = 0x0022; // Number of bytes to follow $iPaperSize = $this->phpSheet->getPageSetup()->getPaperSize(); // Paper size $iScale = $this->phpSheet->getPageSetup()->getScale() ?: 100; // Print scaling factor $iPageStart = 0x01; // Starting page number $iFitWidth = (int) $this->phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide $iFitHeight = (int) $this->phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high $iRes = 0x0258; // Print resolution $iVRes = 0x0258; // Vertical print resolution $numHdr = $this->phpSheet->getPageMargins()->getHeader(); // Header Margin $numFtr = $this->phpSheet->getPageMargins()->getFooter(); // Footer Margin $iCopies = 0x01; // Number of copies // Order of printing pages $fLeftToRight = $this->phpSheet->getPageSetup()->getPageOrder() === PageSetup::PAGEORDER_DOWN_THEN_OVER ? 0x0 : 0x1; // Page orientation $fLandscape = ($this->phpSheet->getPageSetup()->getOrientation() == PageSetup::ORIENTATION_LANDSCAPE) ? 0x0 : 0x1; $fNoPls = 0x0; // Setup not read from printer $fNoColor = 0x0; // Print black and white $fDraft = 0x0; // Print draft quality $fNotes = 0x0; // Print notes $fNoOrient = 0x0; // Orientation not set $fUsePage = 0x0; // Use custom starting page $grbit = $fLeftToRight; $grbit |= $fLandscape << 1; $grbit |= $fNoPls << 2; $grbit |= $fNoColor << 3; $grbit |= $fDraft << 4; $grbit |= $fNotes << 5; $grbit |= $fNoOrient << 6; $grbit |= $fUsePage << 7; $numHdr = pack('d', $numHdr); $numFtr = pack('d', $numFtr); if (self::getByteOrder()) { // if it's Big Endian $numHdr = strrev($numHdr); $numFtr = strrev($numFtr); } $header = pack('vv', $record, $length); $data1 = pack('vvvvvvvv', $iPaperSize, $iScale, $iPageStart, $iFitWidth, $iFitHeight, $grbit, $iRes, $iVRes); $data2 = $numHdr . $numFtr; $data3 = pack('v', $iCopies); $this->append($header . $data1 . $data2 . $data3); } /** * Store the header caption BIFF record. */ private function writeHeader(): void { $record = 0x0014; // Record identifier /* removing for now // need to fix character count (multibyte!) if (strlen($this->phpSheet->getHeaderFooter()->getOddHeader()) <= 255) { $str = $this->phpSheet->getHeaderFooter()->getOddHeader(); // header string } else { $str = ''; } */ $recordData = StringHelper::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddHeader()); $length = strlen($recordData); $header = pack('vv', $record, $length); $this->append($header . $recordData); } /** * Store the footer caption BIFF record. */ private function writeFooter(): void { $record = 0x0015; // Record identifier /* removing for now // need to fix character count (multibyte!) if (strlen($this->phpSheet->getHeaderFooter()->getOddFooter()) <= 255) { $str = $this->phpSheet->getHeaderFooter()->getOddFooter(); } else { $str = ''; } */ $recordData = StringHelper::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddFooter()); $length = strlen($recordData); $header = pack('vv', $record, $length); $this->append($header . $recordData); } /** * Store the horizontal centering HCENTER BIFF record. */ private function writeHcenter(): void { $record = 0x0083; // Record identifier $length = 0x0002; // Bytes to follow $fHCenter = $this->phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering $header = pack('vv', $record, $length); $data = pack('v', $fHCenter); $this->append($header . $data); } /** * Store the vertical centering VCENTER BIFF record. */ private function writeVcenter(): void { $record = 0x0084; // Record identifier $length = 0x0002; // Bytes to follow $fVCenter = $this->phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering $header = pack('vv', $record, $length); $data = pack('v', $fVCenter); $this->append($header . $data); } /** * Store the LEFTMARGIN BIFF record. */ private function writeMarginLeft(): void { $record = 0x0026; // Record identifier $length = 0x0008; // Bytes to follow $margin = $this->phpSheet->getPageMargins()->getLeft(); // Margin in inches $header = pack('vv', $record, $length); $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } $this->append($header . $data); } /** * Store the RIGHTMARGIN BIFF record. */ private function writeMarginRight(): void { $record = 0x0027; // Record identifier $length = 0x0008; // Bytes to follow $margin = $this->phpSheet->getPageMargins()->getRight(); // Margin in inches $header = pack('vv', $record, $length); $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } $this->append($header . $data); } /** * Store the TOPMARGIN BIFF record. */ private function writeMarginTop(): void { $record = 0x0028; // Record identifier $length = 0x0008; // Bytes to follow $margin = $this->phpSheet->getPageMargins()->getTop(); // Margin in inches $header = pack('vv', $record, $length); $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } $this->append($header . $data); } /** * Store the BOTTOMMARGIN BIFF record. */ private function writeMarginBottom(): void { $record = 0x0029; // Record identifier $length = 0x0008; // Bytes to follow $margin = $this->phpSheet->getPageMargins()->getBottom(); // Margin in inches $header = pack('vv', $record, $length); $data = pack('d', $margin); if (self::getByteOrder()) { // if it's Big Endian $data = strrev($data); } $this->append($header . $data); } /** * Write the PRINTHEADERS BIFF record. */ private function writePrintHeaders(): void { $record = 0x002a; // Record identifier $length = 0x0002; // Bytes to follow $fPrintRwCol = $this->printHeaders; // Boolean flag $header = pack('vv', $record, $length); $data = pack('v', $fPrintRwCol); $this->append($header . $data); } /** * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the * GRIDSET record. */ private function writePrintGridlines(): void { $record = 0x002b; // Record identifier $length = 0x0002; // Bytes to follow $fPrintGrid = $this->phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag $header = pack('vv', $record, $length); $data = pack('v', $fPrintGrid); $this->append($header . $data); } /** * Write the GRIDSET BIFF record. Must be used in conjunction with the * PRINTGRIDLINES record. */ private function writeGridset(): void { $record = 0x0082; // Record identifier $length = 0x0002; // Bytes to follow $fGridSet = !$this->phpSheet->getPrintGridlines(); // Boolean flag $header = pack('vv', $record, $length); $data = pack('v', $fGridSet); $this->append($header . $data); } /** * Write the AUTOFILTERINFO BIFF record. This is used to configure the number of autofilter select used in the sheet. */ private function writeAutoFilterInfo(): void { $record = 0x009D; // Record identifier $length = 0x0002; // Bytes to follow $rangeBounds = Coordinate::rangeBoundaries($this->phpSheet->getAutoFilter()->getRange()); $iNumFilters = 1 + $rangeBounds[1][0] - $rangeBounds[0][0]; $header = pack('vv', $record, $length); $data = pack('v', $iNumFilters); $this->append($header . $data); } /** * Write the GUTS BIFF record. This is used to configure the gutter margins * where Excel outline symbols are displayed. The visibility of the gutters is * controlled by a flag in WSBOOL. * * @see writeWsbool() */ private function writeGuts(): void { $record = 0x0080; // Record identifier $length = 0x0008; // Bytes to follow $dxRwGut = 0x0000; // Size of row gutter $dxColGut = 0x0000; // Size of col gutter // determine maximum row outline level $maxRowOutlineLevel = 0; foreach ($this->phpSheet->getRowDimensions() as $rowDimension) { $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel()); } $col_level = 0; // Calculate the maximum column outline level. The equivalent calculation // for the row outline level is carried out in writeRow(). $colcount = count($this->columnInfo); for ($i = 0; $i < $colcount; ++$i) { $col_level = max($this->columnInfo[$i][5], $col_level); } // Set the limits for the outline levels (0 <= x <= 7). $col_level = max(0, min($col_level, 7)); // The displayed level is one greater than the max outline levels if ($maxRowOutlineLevel) { ++$maxRowOutlineLevel; } if ($col_level) { ++$col_level; } $header = pack('vv', $record, $length); $data = pack('vvvv', $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level); $this->append($header . $data); } /** * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction * with the SETUP record. */ private function writeWsbool(): void { $record = 0x0081; // Record identifier $length = 0x0002; // Bytes to follow $grbit = 0x0000; // The only option that is of interest is the flag for fit to page. So we // set all the options in one go. // // Set the option flags $grbit |= 0x0001; // Auto page breaks visible if ($this->outlineStyle) { $grbit |= 0x0020; // Auto outline styles } if ($this->phpSheet->getShowSummaryBelow()) { $grbit |= 0x0040; // Outline summary below } if ($this->phpSheet->getShowSummaryRight()) { $grbit |= 0x0080; // Outline summary right } if ($this->phpSheet->getPageSetup()->getFitToPage()) { $grbit |= 0x0100; // Page setup fit to page } if ($this->outlineOn) { $grbit |= 0x0400; // Outline symbols displayed } $header = pack('vv', $record, $length); $data = pack('v', $grbit); $this->append($header . $data); } /** * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records. */ private function writeBreaks(): void { // initialize $vbreaks = []; $hbreaks = []; foreach ($this->phpSheet->getRowBreaks() as $cell => $break) { // Fetch coordinates $coordinates = Coordinate::coordinateFromString($cell); $hbreaks[] = $coordinates[1]; } foreach ($this->phpSheet->getColumnBreaks() as $cell => $break) { // Fetch coordinates $coordinates = Coordinate::indexesFromString($cell); $vbreaks[] = $coordinates[0] - 1; } //horizontal page breaks if (!empty($hbreaks)) { // Sort and filter array of page breaks sort($hbreaks, SORT_NUMERIC); if ($hbreaks[0] == 0) { // don't use first break if it's 0 array_shift($hbreaks); } $record = 0x001b; // Record identifier $cbrk = count($hbreaks); // Number of page breaks $length = 2 + 6 * $cbrk; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('v', $cbrk); // Append each page break foreach ($hbreaks as $hbreak) { $data .= pack('vvv', $hbreak, 0x0000, 0x00ff); } $this->append($header . $data); } // vertical page breaks if (!empty($vbreaks)) { // 1000 vertical pagebreaks appears to be an internal Excel 5 limit. // It is slightly higher in Excel 97/200, approx. 1026 $vbreaks = array_slice($vbreaks, 0, 1000); // Sort and filter array of page breaks sort($vbreaks, SORT_NUMERIC); if ($vbreaks[0] == 0) { // don't use first break if it's 0 array_shift($vbreaks); } $record = 0x001a; // Record identifier $cbrk = count($vbreaks); // Number of page breaks $length = 2 + 6 * $cbrk; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('v', $cbrk); // Append each page break foreach ($vbreaks as $vbreak) { $data .= pack('vvv', $vbreak, 0x0000, 0xffff); } $this->append($header . $data); } } /** * Set the Biff PROTECT record to indicate that the worksheet is protected. */ private function writeProtect(): void { // Exit unless sheet protection has been specified if ($this->phpSheet->getProtection()->getSheet() !== true) { return; } $record = 0x0012; // Record identifier $length = 0x0002; // Bytes to follow $fLock = 1; // Worksheet is protected $header = pack('vv', $record, $length); $data = pack('v', $fLock); $this->append($header . $data); } /** * Write SCENPROTECT. */ private function writeScenProtect(): void { // Exit if sheet protection is not active if ($this->phpSheet->getProtection()->getSheet() !== true) { return; } // Exit if scenarios are not protected if ($this->phpSheet->getProtection()->getScenarios() !== true) { return; } $record = 0x00DD; // Record identifier $length = 0x0002; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('v', 1); $this->append($header . $data); } /** * Write OBJECTPROTECT. */ private function writeObjectProtect(): void { // Exit if sheet protection is not active if ($this->phpSheet->getProtection()->getSheet() !== true) { return; } // Exit if objects are not protected if ($this->phpSheet->getProtection()->getObjects() !== true) { return; } $record = 0x0063; // Record identifier $length = 0x0002; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('v', 1); $this->append($header . $data); } /** * Write the worksheet PASSWORD record. */ private function writePassword(): void { // Exit unless sheet protection and password have been specified if ($this->phpSheet->getProtection()->getSheet() !== true || !$this->phpSheet->getProtection()->getPassword() || $this->phpSheet->getProtection()->getAlgorithm() !== '') { return; } $record = 0x0013; // Record identifier $length = 0x0002; // Bytes to follow $wPassword = hexdec($this->phpSheet->getProtection()->getPassword()); // Encoded password $header = pack('vv', $record, $length); $data = pack('v', $wPassword); $this->append($header . $data); } /** * Insert a 24bit bitmap image in a worksheet. * * @param int $row The row we are going to insert the bitmap into * @param int $col The column we are going to insert the bitmap into * @param mixed $bitmap The bitmap filename or GD-image resource * @param int $x the horizontal position (offset) of the image inside the cell * @param int $y the vertical position (offset) of the image inside the cell * @param float $scale_x The horizontal scale * @param float $scale_y The vertical scale */ public function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1): void { $bitmap_array = (is_resource($bitmap) || $bitmap instanceof GdImage ? $this->processBitmapGd($bitmap) : $this->processBitmap($bitmap)); [$width, $height, $size, $data] = $bitmap_array; // Scale the frame of the image. $width *= $scale_x; $height *= $scale_y; // Calculate the vertices of the image and write the OBJ record $this->positionImage($col, $row, $x, $y, (int) $width, (int) $height); // Write the IMDATA record to store the bitmap data $record = 0x007f; $length = 8 + $size; $cf = 0x09; $env = 0x01; $lcb = $size; $header = pack('vvvvV', $record, $length, $cf, $env, $lcb); $this->append($header . $data); } /** * Calculate the vertices that define the position of the image as required by * the OBJ record. * * +------------+------------+ * | A | B | * +-----+------------+------------+ * | |(x1,y1) | | * | 1 |(A1)._______|______ | * | | | | | * | | | | | * +-----+----| BITMAP |-----+ * | | | | | * | 2 | |______________. | * | | | (B2)| * | | | (x2,y2)| * +---- +------------+------------+ * * Example of a bitmap that covers some of the area from cell A1 to cell B2. * * Based on the width and height of the bitmap we need to calculate 8 vars: * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2. * The width and height of the cells are also variable and have to be taken into * account. * The values of $col_start and $row_start are passed in from the calling * function. The values of $col_end and $row_end are calculated by subtracting * the width and height of the bitmap from the width and height of the * underlying cells. * The vertices are expressed as a percentage of the underlying cell width as * follows (rhs values are in pixels): * * x1 = X / W *1024 * y1 = Y / H *256 * x2 = (X-1) / W *1024 * y2 = (Y-1) / H *256 * * Where: X is distance from the left side of the underlying cell * Y is distance from the top of the underlying cell * W is the width of the cell * H is the height of the cell * The SDK incorrectly states that the height should be expressed as a * percentage of 1024. * * @param int $col_start Col containing upper left corner of object * @param int $row_start Row containing top left corner of object * @param int $x1 Distance to left side of object * @param int $y1 Distance to top of object * @param int $width Width of image frame * @param int $height Height of image frame */ public function positionImage($col_start, $row_start, $x1, $y1, $width, $height): void { // Initialise end cell to the same as the start cell $col_end = $col_start; // Col containing lower right corner of object $row_end = $row_start; // Row containing bottom right corner of object // Zero the specified offset if greater than the cell dimensions if ($x1 >= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1))) { $x1 = 0; } if ($y1 >= Xls::sizeRow($this->phpSheet, $row_start + 1)) { $y1 = 0; } $width = $width + $x1 - 1; $height = $height + $y1 - 1; // Subtract the underlying cell widths to find the end cell of the image while ($width >= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1))) { $width -= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1)); ++$col_end; } // Subtract the underlying cell heights to find the end cell of the image while ($height >= Xls::sizeRow($this->phpSheet, $row_end + 1)) { $height -= Xls::sizeRow($this->phpSheet, $row_end + 1); ++$row_end; } // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell // with zero eight or width. // if (Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1)) == 0) { return; } if (Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1)) == 0) { return; } if (Xls::sizeRow($this->phpSheet, $row_start + 1) == 0) { return; } if (Xls::sizeRow($this->phpSheet, $row_end + 1) == 0) { return; } // Convert the pixel values to the percentage value expected by Excel $x1 = $x1 / Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1)) * 1024; $y1 = $y1 / Xls::sizeRow($this->phpSheet, $row_start + 1) * 256; $x2 = $width / Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1)) * 1024; // Distance to right side of object $y2 = $height / Xls::sizeRow($this->phpSheet, $row_end + 1) * 256; // Distance to bottom of object $this->writeObjPicture($col_start, $x1, $row_start, $y1, $col_end, $x2, $row_end, $y2); } /** * Store the OBJ record that precedes an IMDATA record. This could be generalise * to support other Excel objects. * * @param int $colL Column containing upper left corner of object * @param int $dxL Distance from left side of cell * @param int $rwT Row containing top left corner of object * @param int $dyT Distance from top of cell * @param int $colR Column containing lower right corner of object * @param int $dxR Distance from right of cell * @param int $rwB Row containing bottom right corner of object * @param int $dyB Distance from bottom of cell */ private function writeObjPicture($colL, $dxL, $rwT, $dyT, $colR, $dxR, $rwB, $dyB): void { $record = 0x005d; // Record identifier $length = 0x003c; // Bytes to follow $cObj = 0x0001; // Count of objects in file (set to 1) $OT = 0x0008; // Object type. 8 = Picture $id = 0x0001; // Object ID $grbit = 0x0614; // Option flags $cbMacro = 0x0000; // Length of FMLA structure $Reserved1 = 0x0000; // Reserved $Reserved2 = 0x0000; // Reserved $icvBack = 0x09; // Background colour $icvFore = 0x09; // Foreground colour $fls = 0x00; // Fill pattern $fAuto = 0x00; // Automatic fill $icv = 0x08; // Line colour $lns = 0xff; // Line style $lnw = 0x01; // Line weight $fAutoB = 0x00; // Automatic border $frs = 0x0000; // Frame style $cf = 0x0009; // Image format, 9 = bitmap $Reserved3 = 0x0000; // Reserved $cbPictFmla = 0x0000; // Length of FMLA structure $Reserved4 = 0x0000; // Reserved $grbit2 = 0x0001; // Option flags $Reserved5 = 0x0000; // Reserved $header = pack('vv', $record, $length); $data = pack('V', $cObj); $data .= pack('v', $OT); $data .= pack('v', $id); $data .= pack('v', $grbit); $data .= pack('v', $colL); $data .= pack('v', $dxL); $data .= pack('v', $rwT); $data .= pack('v', $dyT); $data .= pack('v', $colR); $data .= pack('v', $dxR); $data .= pack('v', $rwB); $data .= pack('v', $dyB); $data .= pack('v', $cbMacro); $data .= pack('V', $Reserved1); $data .= pack('v', $Reserved2); $data .= pack('C', $icvBack); $data .= pack('C', $icvFore); $data .= pack('C', $fls); $data .= pack('C', $fAuto); $data .= pack('C', $icv); $data .= pack('C', $lns); $data .= pack('C', $lnw); $data .= pack('C', $fAutoB); $data .= pack('v', $frs); $data .= pack('V', $cf); $data .= pack('v', $Reserved3); $data .= pack('v', $cbPictFmla); $data .= pack('v', $Reserved4); $data .= pack('v', $grbit2); $data .= pack('V', $Reserved5); $this->append($header . $data); } /** * Convert a GD-image into the internal format. * * @param GdImage|resource $image The image to process * * @return array Array with data and properties of the bitmap */ public function processBitmapGd($image) { $width = imagesx($image); $height = imagesy($image); $data = pack('Vvvvv', 0x000c, $width, $height, 0x01, 0x18); for ($j = $height; --$j;) { for ($i = 0; $i < $width; ++$i) { /** @phpstan-ignore-next-line */ $color = imagecolorsforindex($image, imagecolorat($image, $i, $j)); if ($color !== false) { foreach (['red', 'green', 'blue'] as $key) { $color[$key] = $color[$key] + (int) round((255 - $color[$key]) * $color['alpha'] / 127); } $data .= chr($color['blue']) . chr($color['green']) . chr($color['red']); } } if (3 * $width % 4) { $data .= str_repeat("\x00", 4 - 3 * $width % 4); } } return [$width, $height, strlen($data), $data]; } /** * Convert a 24 bit bitmap into the modified internal format used by Windows. * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the * MSDN library. * * @param string $bitmap The bitmap to process * * @return array Array with data and properties of the bitmap */ public function processBitmap($bitmap) { // Open file. $bmp_fd = @fopen($bitmap, 'rb'); if ($bmp_fd === false) { throw new WriterException("Couldn't import $bitmap"); } // Slurp the file into a string. $data = (string) fread($bmp_fd, (int) filesize($bitmap)); // Check that the file is big enough to be a bitmap. if (strlen($data) <= 0x36) { throw new WriterException("$bitmap doesn't contain enough data.\n"); } // The first 2 bytes are used to identify the bitmap. $identity = unpack('A2ident', $data); if ($identity === false || $identity['ident'] != 'BM') { throw new WriterException("$bitmap doesn't appear to be a valid bitmap image.\n"); } // Remove bitmap data: ID. $data = substr($data, 2); // Read and remove the bitmap size. This is more reliable than reading // the data size at offset 0x22. // $size_array = unpack('Vsa', substr($data, 0, 4)) ?: []; $size = $size_array['sa']; $data = substr($data, 4); $size -= 0x36; // Subtract size of bitmap header. $size += 0x0C; // Add size of BIFF header. // Remove bitmap data: reserved, offset, header length. $data = substr($data, 12); // Read and remove the bitmap width and height. Verify the sizes. $width_and_height = unpack('V2', substr($data, 0, 8)) ?: []; $width = $width_and_height[1]; $height = $width_and_height[2]; $data = substr($data, 8); if ($width > 0xFFFF) { throw new WriterException("$bitmap: largest image width supported is 65k.\n"); } if ($height > 0xFFFF) { throw new WriterException("$bitmap: largest image height supported is 65k.\n"); } // Read and remove the bitmap planes and bpp data. Verify them. $planes_and_bitcount = unpack('v2', substr($data, 0, 4)); $data = substr($data, 4); if ($planes_and_bitcount === false || $planes_and_bitcount[2] != 24) { // Bitcount throw new WriterException("$bitmap isn't a 24bit true color bitmap.\n"); } if ($planes_and_bitcount[1] != 1) { throw new WriterException("$bitmap: only 1 plane supported in bitmap image.\n"); } // Read and remove the bitmap compression. Verify compression. $compression = unpack('Vcomp', substr($data, 0, 4)); $data = substr($data, 4); if ($compression === false || $compression['comp'] != 0) { throw new WriterException("$bitmap: compression not supported in bitmap image.\n"); } // Remove bitmap data: data size, hres, vres, colours, imp. colours. $data = substr($data, 20); // Add the BITMAPCOREHEADER data $header = pack('Vvvvv', 0x000c, $width, $height, 0x01, 0x18); $data = $header . $data; return [$width, $height, $size, $data]; } /** * Store the window zoom factor. This should be a reduced fraction but for * simplicity we will store all fractions with a numerator of 100. */ private function writeZoom(): void { // If scale is 100 we don't need to write a record if ($this->phpSheet->getSheetView()->getZoomScale() == 100) { return; } $record = 0x00A0; // Record identifier $length = 0x0004; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('vv', $this->phpSheet->getSheetView()->getZoomScale(), 100); $this->append($header . $data); } /** * Get Escher object. */ public function getEscher(): ?\PhpOffice\PhpSpreadsheet\Shared\Escher { return $this->escher; } /** * Set Escher object. */ public function setEscher(?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher): void { $this->escher = $escher; } /** * Write MSODRAWING record. */ private function writeMsoDrawing(): void { // write the Escher stream if necessary if (isset($this->escher)) { $writer = new Escher($this->escher); $data = $writer->close(); $spOffsets = $writer->getSpOffsets(); $spTypes = $writer->getSpTypes(); // write the neccesary MSODRAWING, OBJ records // split the Escher stream $spOffsets[0] = 0; $nm = count($spOffsets) - 1; // number of shapes excluding first shape for ($i = 1; $i <= $nm; ++$i) { // MSODRAWING record $record = 0x00EC; // Record identifier // chunk of Escher stream for one shape $dataChunk = substr($data, $spOffsets[$i - 1], $spOffsets[$i] - $spOffsets[$i - 1]); $length = strlen($dataChunk); $header = pack('vv', $record, $length); $this->append($header . $dataChunk); // OBJ record $record = 0x005D; // record identifier $objData = ''; // ftCmo if ($spTypes[$i] == 0x00C9) { // Add ftCmo (common object data) subobject $objData .= pack( 'vvvvvVVV', 0x0015, // 0x0015 = ftCmo 0x0012, // length of ftCmo data 0x0014, // object type, 0x0014 = filter $i, // object id number, Excel seems to use 1-based index, local for the sheet 0x2101, // option flags, 0x2001 is what OpenOffice.org uses 0, // reserved 0, // reserved 0 // reserved ); // Add ftSbs Scroll bar subobject $objData .= pack('vv', 0x00C, 0x0014); $objData .= pack('H*', '0000000000000000640001000A00000010000100'); // Add ftLbsData (List box data) subobject $objData .= pack('vv', 0x0013, 0x1FEE); $objData .= pack('H*', '00000000010001030000020008005700'); } else { // Add ftCmo (common object data) subobject $objData .= pack( 'vvvvvVVV', 0x0015, // 0x0015 = ftCmo 0x0012, // length of ftCmo data 0x0008, // object type, 0x0008 = picture $i, // object id number, Excel seems to use 1-based index, local for the sheet 0x6011, // option flags, 0x6011 is what OpenOffice.org uses 0, // reserved 0, // reserved 0 // reserved ); } // ftEnd $objData .= pack( 'vv', 0x0000, // 0x0000 = ftEnd 0x0000 // length of ftEnd data ); $length = strlen($objData); $header = pack('vv', $record, $length); $this->append($header . $objData); } } } /** * Store the DATAVALIDATIONS and DATAVALIDATION records. */ private function writeDataValidity(): void { // Datavalidation collection $dataValidationCollection = $this->phpSheet->getDataValidationCollection(); // Write data validations? if (!empty($dataValidationCollection)) { // DATAVALIDATIONS record $record = 0x01B2; // Record identifier $length = 0x0012; // Bytes to follow $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position $verPos = 0x00000000; // Vertical position of prompt box, if fixed position $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible $header = pack('vv', $record, $length); $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId, count($dataValidationCollection)); $this->append($header . $data); // DATAVALIDATION records $record = 0x01BE; // Record identifier foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) { // options $options = 0x00000000; // data type $type = CellDataValidation::type($dataValidation); $options |= $type << 0; // error style $errorStyle = CellDataValidation::errorStyle($dataValidation); $options |= $errorStyle << 4; // explicit formula? if ($type == 0x03 && preg_match('/^\".*\"$/', $dataValidation->getFormula1())) { $options |= 0x01 << 7; } // empty cells allowed $options |= $dataValidation->getAllowBlank() << 8; // show drop down $options |= (!$dataValidation->getShowDropDown()) << 9; // show input message $options |= $dataValidation->getShowInputMessage() << 18; // show error message $options |= $dataValidation->getShowErrorMessage() << 19; // condition operator $operator = CellDataValidation::operator($dataValidation); $options |= $operator << 20; $data = pack('V', $options); // prompt title $promptTitle = $dataValidation->getPromptTitle() !== '' ? $dataValidation->getPromptTitle() : chr(0); $data .= StringHelper::UTF8toBIFF8UnicodeLong($promptTitle); // error title $errorTitle = $dataValidation->getErrorTitle() !== '' ? $dataValidation->getErrorTitle() : chr(0); $data .= StringHelper::UTF8toBIFF8UnicodeLong($errorTitle); // prompt text $prompt = $dataValidation->getPrompt() !== '' ? $dataValidation->getPrompt() : chr(0); $data .= StringHelper::UTF8toBIFF8UnicodeLong($prompt); // error text $error = $dataValidation->getError() !== '' ? $dataValidation->getError() : chr(0); $data .= StringHelper::UTF8toBIFF8UnicodeLong($error); // formula 1 try { $formula1 = $dataValidation->getFormula1(); if ($type == 0x03) { // list type $formula1 = str_replace(',', chr(0), $formula1); } $this->parser->parse($formula1); $formula1 = $this->parser->toReversePolish(); $sz1 = strlen($formula1); } catch (PhpSpreadsheetException $e) { $sz1 = 0; $formula1 = ''; } $data .= pack('vv', $sz1, 0x0000); $data .= $formula1; // formula 2 try { $formula2 = $dataValidation->getFormula2(); if ($formula2 === '') { throw new WriterException('No formula2'); } $this->parser->parse($formula2); $formula2 = $this->parser->toReversePolish(); $sz2 = strlen($formula2); } catch (PhpSpreadsheetException $e) { $sz2 = 0; $formula2 = ''; } $data .= pack('vv', $sz2, 0x0000); $data .= $formula2; // cell range address list $data .= pack('v', 0x0001); $data .= $this->writeBIFF8CellRangeAddressFixed($cellCoordinate); $length = strlen($data); $header = pack('vv', $record, $length); $this->append($header . $data); } } } /** * Write PLV Record. */ private function writePageLayoutView(): void { $record = 0x088B; // Record identifier $length = 0x0010; // Bytes to follow $rt = 0x088B; // 2 $grbitFrt = 0x0000; // 2 //$reserved = 0x0000000000000000; // 8 $wScalvePLV = $this->phpSheet->getSheetView()->getZoomScale(); // 2 // The options flags that comprise $grbit if ($this->phpSheet->getSheetView()->getView() == SheetView::SHEETVIEW_PAGE_LAYOUT) { $fPageLayoutView = 1; } else { $fPageLayoutView = 0; } $fRulerVisible = 0; $fWhitespaceHidden = 0; $grbit = $fPageLayoutView; // 2 $grbit |= $fRulerVisible << 1; $grbit |= $fWhitespaceHidden << 3; $header = pack('vv', $record, $length); $data = pack('vvVVvv', $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit); $this->append($header . $data); } /** * Write CFRule Record. */ private function writeCFRule( ConditionalHelper $conditionalFormulaHelper, Conditional $conditional, string $cellRange ): void { $record = 0x01B1; // Record identifier $type = null; // Type of the CF $operatorType = null; // Comparison operator if ($conditional->getConditionType() == Conditional::CONDITION_EXPRESSION) { $type = 0x02; $operatorType = 0x00; } elseif ($conditional->getConditionType() == Conditional::CONDITION_CELLIS) { $type = 0x01; switch ($conditional->getOperatorType()) { case Conditional::OPERATOR_NONE: $operatorType = 0x00; break; case Conditional::OPERATOR_EQUAL: $operatorType = 0x03; break; case Conditional::OPERATOR_GREATERTHAN: $operatorType = 0x05; break; case Conditional::OPERATOR_GREATERTHANOREQUAL: $operatorType = 0x07; break; case Conditional::OPERATOR_LESSTHAN: $operatorType = 0x06; break; case Conditional::OPERATOR_LESSTHANOREQUAL: $operatorType = 0x08; break; case Conditional::OPERATOR_NOTEQUAL: $operatorType = 0x04; break; case Conditional::OPERATOR_BETWEEN: $operatorType = 0x01; break; // not OPERATOR_NOTBETWEEN 0x02 } } // $szValue1 : size of the formula data for first value or formula // $szValue2 : size of the formula data for second value or formula $arrConditions = $conditional->getConditions(); $numConditions = count($arrConditions); $szValue1 = 0x0000; $szValue2 = 0x0000; $operand1 = null; $operand2 = null; if ($numConditions === 1) { $conditionalFormulaHelper->processCondition($arrConditions[0], $cellRange); $szValue1 = $conditionalFormulaHelper->size(); $operand1 = $conditionalFormulaHelper->tokens(); } elseif ($numConditions === 2 && ($conditional->getOperatorType() === Conditional::OPERATOR_BETWEEN)) { $conditionalFormulaHelper->processCondition($arrConditions[0], $cellRange); $szValue1 = $conditionalFormulaHelper->size(); $operand1 = $conditionalFormulaHelper->tokens(); $conditionalFormulaHelper->processCondition($arrConditions[1], $cellRange); $szValue2 = $conditionalFormulaHelper->size(); $operand2 = $conditionalFormulaHelper->tokens(); } // $flags : Option flags // Alignment $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() === null ? 1 : 0); $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() === null ? 1 : 0); $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() === false ? 1 : 0); $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() === null ? 1 : 0); $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() === 0 ? 1 : 0); $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() === false ? 1 : 0); if ($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0) { $bFormatAlign = 1; } else { $bFormatAlign = 0; } // Protection $bProtLocked = ($conditional->getStyle()->getProtection()->getLocked() == null ? 1 : 0); $bProtHidden = ($conditional->getStyle()->getProtection()->getHidden() == null ? 1 : 0); if ($bProtLocked == 0 || $bProtHidden == 0) { $bFormatProt = 1; } else { $bFormatProt = 0; } // Border $bBorderLeft = ($conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() !== Border::BORDER_OMIT) ? 1 : 0; $bBorderRight = ($conditional->getStyle()->getBorders()->getRight()->getBorderStyle() !== Border::BORDER_OMIT) ? 1 : 0; $bBorderTop = ($conditional->getStyle()->getBorders()->getTop()->getBorderStyle() !== Border::BORDER_OMIT) ? 1 : 0; $bBorderBottom = ($conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() !== Border::BORDER_OMIT) ? 1 : 0; if ($bBorderLeft === 1 || $bBorderRight === 1 || $bBorderTop === 1 || $bBorderBottom === 1) { $bFormatBorder = 1; } else { $bFormatBorder = 0; } // Pattern $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() === null ? 0 : 1); $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() === null ? 0 : 1); $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() === null ? 0 : 1); if ($bFillStyle == 1 || $bFillColor == 1 || $bFillColorBg == 1) { $bFormatFill = 1; } else { $bFormatFill = 0; } // Font if ( $conditional->getStyle()->getFont()->getName() !== null || $conditional->getStyle()->getFont()->getSize() !== null || $conditional->getStyle()->getFont()->getBold() !== null || $conditional->getStyle()->getFont()->getItalic() !== null || $conditional->getStyle()->getFont()->getSuperscript() !== null || $conditional->getStyle()->getFont()->getSubscript() !== null || $conditional->getStyle()->getFont()->getUnderline() !== null || $conditional->getStyle()->getFont()->getStrikethrough() !== null || $conditional->getStyle()->getFont()->getColor()->getARGB() !== null ) { $bFormatFont = 1; } else { $bFormatFont = 0; } // Alignment $flags = 0; $flags |= (1 == $bAlignHz ? 0x00000001 : 0); $flags |= (1 == $bAlignVt ? 0x00000002 : 0); $flags |= (1 == $bAlignWrapTx ? 0x00000004 : 0); $flags |= (1 == $bTxRotation ? 0x00000008 : 0); // Justify last line flag $flags |= (1 == self::$always1 ? 0x00000010 : 0); $flags |= (1 == $bIndent ? 0x00000020 : 0); $flags |= (1 == $bShrinkToFit ? 0x00000040 : 0); // Default $flags |= (1 == self::$always1 ? 0x00000080 : 0); // Protection $flags |= (1 == $bProtLocked ? 0x00000100 : 0); $flags |= (1 == $bProtHidden ? 0x00000200 : 0); // Border $flags |= (1 == $bBorderLeft ? 0x00000400 : 0); $flags |= (1 == $bBorderRight ? 0x00000800 : 0); $flags |= (1 == $bBorderTop ? 0x00001000 : 0); $flags |= (1 == $bBorderBottom ? 0x00002000 : 0); $flags |= (1 == self::$always1 ? 0x00004000 : 0); // Top left to Bottom right border $flags |= (1 == self::$always1 ? 0x00008000 : 0); // Bottom left to Top right border // Pattern $flags |= (1 == $bFillStyle ? 0x00010000 : 0); $flags |= (1 == $bFillColor ? 0x00020000 : 0); $flags |= (1 == $bFillColorBg ? 0x00040000 : 0); $flags |= (1 == self::$always1 ? 0x00380000 : 0); // Font $flags |= (1 == $bFormatFont ? 0x04000000 : 0); // Alignment: $flags |= (1 == $bFormatAlign ? 0x08000000 : 0); // Border $flags |= (1 == $bFormatBorder ? 0x10000000 : 0); // Pattern $flags |= (1 == $bFormatFill ? 0x20000000 : 0); // Protection $flags |= (1 == $bFormatProt ? 0x40000000 : 0); // Text direction $flags |= (1 == self::$always0 ? 0x80000000 : 0); $dataBlockFont = null; $dataBlockAlign = null; $dataBlockBorder = null; $dataBlockFill = null; // Data Blocks if ($bFormatFont == 1) { // Font Name if ($conditional->getStyle()->getFont()->getName() === null) { $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); } else { $dataBlockFont = StringHelper::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName()); } // Font Size if ($conditional->getStyle()->getFont()->getSize() === null) { $dataBlockFont .= pack('V', 20 * 11); } else { $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize()); } // Font Options $dataBlockFont .= pack('V', 0); // Font weight if ($conditional->getStyle()->getFont()->getBold() === true) { $dataBlockFont .= pack('v', 0x02BC); } else { $dataBlockFont .= pack('v', 0x0190); } // Escapement type if ($conditional->getStyle()->getFont()->getSubscript() === true) { $dataBlockFont .= pack('v', 0x02); $fontEscapement = 0; } elseif ($conditional->getStyle()->getFont()->getSuperscript() === true) { $dataBlockFont .= pack('v', 0x01); $fontEscapement = 0; } else { $dataBlockFont .= pack('v', 0x00); $fontEscapement = 1; } // Underline type switch ($conditional->getStyle()->getFont()->getUnderline()) { case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_NONE: $dataBlockFont .= pack('C', 0x00); $fontUnderline = 0; break; case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE: $dataBlockFont .= pack('C', 0x02); $fontUnderline = 0; break; case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING: $dataBlockFont .= pack('C', 0x22); $fontUnderline = 0; break; case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE: $dataBlockFont .= pack('C', 0x01); $fontUnderline = 0; break; case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING: $dataBlockFont .= pack('C', 0x21); $fontUnderline = 0; break; default: $dataBlockFont .= pack('C', 0x00); $fontUnderline = 1; break; } // Not used (3) $dataBlockFont .= pack('vC', 0x0000, 0x00); // Font color index $colorIdx = Style\ColorMap::lookup($conditional->getStyle()->getFont()->getColor(), 0x00); $dataBlockFont .= pack('V', $colorIdx); // Not used (4) $dataBlockFont .= pack('V', 0x00000000); // Options flags for modified font attributes $optionsFlags = 0; $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() === null ? 1 : 0); $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0); $optionsFlags |= (1 == self::$always1 ? 0x00000008 : 0); $optionsFlags |= (1 == self::$always1 ? 0x00000010 : 0); $optionsFlags |= (1 == self::$always0 ? 0x00000020 : 0); $optionsFlags |= (1 == self::$always1 ? 0x00000080 : 0); $dataBlockFont .= pack('V', $optionsFlags); // Escapement type $dataBlockFont .= pack('V', $fontEscapement); // Underline type $dataBlockFont .= pack('V', $fontUnderline); // Always $dataBlockFont .= pack('V', 0x00000000); // Always $dataBlockFont .= pack('V', 0x00000000); // Not used (8) $dataBlockFont .= pack('VV', 0x00000000, 0x00000000); // Always $dataBlockFont .= pack('v', 0x0001); } if ($bFormatAlign === 1) { // Alignment and text break $blockAlign = Style\CellAlignment::horizontal($conditional->getStyle()->getAlignment()); $blockAlign |= Style\CellAlignment::wrap($conditional->getStyle()->getAlignment()) << 3; $blockAlign |= Style\CellAlignment::vertical($conditional->getStyle()->getAlignment()) << 4; $blockAlign |= 0 << 7; // Text rotation angle $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation(); // Indentation $blockIndent = $conditional->getStyle()->getAlignment()->getIndent(); if ($conditional->getStyle()->getAlignment()->getShrinkToFit() === true) { $blockIndent |= 1 << 4; } else { $blockIndent |= 0 << 4; } $blockIndent |= 0 << 6; // Relative indentation $blockIndentRelative = 255; $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000); } if ($bFormatBorder === 1) { $blockLineStyle = Style\CellBorder::style($conditional->getStyle()->getBorders()->getLeft()); $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getRight()) << 4; $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getTop()) << 8; $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getBottom()) << 12; // TODO writeCFRule() => $blockLineStyle => Index Color for left line // TODO writeCFRule() => $blockLineStyle => Index Color for right line // TODO writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off // TODO writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off $blockColor = 0; // TODO writeCFRule() => $blockColor => Index Color for top line // TODO writeCFRule() => $blockColor => Index Color for bottom line // TODO writeCFRule() => $blockColor => Index Color for diagonal line $blockColor |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getDiagonal()) << 21; $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor); } if ($bFormatFill === 1) { // Fill Pattern Style $blockFillPatternStyle = Style\CellFill::style($conditional->getStyle()->getFill()); // Background Color $colorIdxBg = Style\ColorMap::lookup($conditional->getStyle()->getFill()->getStartColor(), 0x41); // Foreground Color $colorIdxFg = Style\ColorMap::lookup($conditional->getStyle()->getFill()->getEndColor(), 0x40); $dataBlockFill = pack('v', $blockFillPatternStyle); $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7)); } $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000); if ($bFormatFont === 1) { // Block Formatting : OK $data .= $dataBlockFont; } if ($bFormatAlign === 1) { $data .= $dataBlockAlign; } if ($bFormatBorder === 1) { $data .= $dataBlockBorder; } if ($bFormatFill === 1) { // Block Formatting : OK $data .= $dataBlockFill; } if ($bFormatProt == 1) { $data .= $this->getDataBlockProtection($conditional); } if ($operand1 !== null) { $data .= $operand1; } if ($operand2 !== null) { $data .= $operand2; } $header = pack('vv', $record, strlen($data)); $this->append($header . $data); } /** * Write CFHeader record. * * @param Conditional[] $conditionalStyles */ private function writeCFHeader(string $cellCoordinate, array $conditionalStyles): bool { $record = 0x01B0; // Record identifier $length = 0x0016; // Bytes to follow $numColumnMin = null; $numColumnMax = null; $numRowMin = null; $numRowMax = null; $arrConditional = []; foreach ($conditionalStyles as $conditional) { if (!in_array($conditional->getHashCode(), $arrConditional)) { $arrConditional[] = $conditional->getHashCode(); } // Cells $rangeCoordinates = Coordinate::rangeBoundaries($cellCoordinate); if ($numColumnMin === null || ($numColumnMin > $rangeCoordinates[0][0])) { $numColumnMin = $rangeCoordinates[0][0]; } if ($numColumnMax === null || ($numColumnMax < $rangeCoordinates[1][0])) { $numColumnMax = $rangeCoordinates[1][0]; } if ($numRowMin === null || ($numRowMin > $rangeCoordinates[0][1])) { $numRowMin = (int) $rangeCoordinates[0][1]; } if ($numRowMax === null || ($numRowMax < $rangeCoordinates[1][1])) { $numRowMax = (int) $rangeCoordinates[1][1]; } } if (count($arrConditional) === 0) { return false; } $needRedraw = 1; $cellRange = pack('vvvv', $numRowMin - 1, $numRowMax - 1, $numColumnMin - 1, $numColumnMax - 1); $header = pack('vv', $record, $length); $data = pack('vv', count($arrConditional), $needRedraw); $data .= $cellRange; $data .= pack('v', 0x0001); $data .= $cellRange; $this->append($header . $data); return true; } private function getDataBlockProtection(Conditional $conditional): int { $dataBlockProtection = 0; if ($conditional->getStyle()->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED) { $dataBlockProtection = 1; } if ($conditional->getStyle()->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED) { $dataBlockProtection = 1 << 1; } return $dataBlockProtection; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Font.php 0000644 00000006755 15002227416 0016746 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Font { /** * Color index. * * @var int */ private $colorIndex; /** * Font. * * @var \PhpOffice\PhpSpreadsheet\Style\Font */ private $font; /** * Constructor. */ public function __construct(\PhpOffice\PhpSpreadsheet\Style\Font $font) { $this->colorIndex = 0x7FFF; $this->font = $font; } /** * Set the color index. * * @param int $colorIndex */ public function setColorIndex($colorIndex): void { $this->colorIndex = $colorIndex; } /** @var int */ private static $notImplemented = 0; /** * Get font record data. * * @return string */ public function writeFont() { $font_outline = self::$notImplemented; $font_shadow = self::$notImplemented; $icv = $this->colorIndex; // Index to color palette if ($this->font->getSuperscript()) { $sss = 1; } elseif ($this->font->getSubscript()) { $sss = 2; } else { $sss = 0; } $bFamily = 0; // Font family $bCharSet = \PhpOffice\PhpSpreadsheet\Shared\Font::getCharsetFromFontName((string) $this->font->getName()); // Character set $record = 0x31; // Record identifier $reserved = 0x00; // Reserved $grbit = 0x00; // Font attributes if ($this->font->getItalic()) { $grbit |= 0x02; } if ($this->font->getStrikethrough()) { $grbit |= 0x08; } if ($font_outline) { $grbit |= 0x10; } if ($font_shadow) { $grbit |= 0x20; } $data = pack( 'vvvvvCCCC', // Fontsize (in twips) $this->font->getSize() * 20, $grbit, // Colour $icv, // Font weight self::mapBold($this->font->getBold()), // Superscript/Subscript $sss, self::mapUnderline((string) $this->font->getUnderline()), $bFamily, $bCharSet, $reserved ); $data .= StringHelper::UTF8toBIFF8UnicodeShort((string) $this->font->getName()); $length = strlen($data); $header = pack('vv', $record, $length); return $header . $data; } /** * Map to BIFF5-BIFF8 codes for bold. */ private static function mapBold(?bool $bold): int { if ($bold === true) { return 0x2BC; // 700 = Bold font weight } return 0x190; // 400 = Normal font weight } /** * Map of BIFF2-BIFF8 codes for underline styles. * * @var int[] */ private static $mapUnderline = [ \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_NONE => 0x00, \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE => 0x01, \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE => 0x02, \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING => 0x21, \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING => 0x22, ]; /** * Map underline. * * @param string $underline * * @return int */ private static function mapUnderline($underline) { if (isset(self::$mapUnderline[$underline])) { return self::$mapUnderline[$underline]; } return 0x00; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php 0000644 00000015664 15002227416 0020002 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; // Original file header of PEAR::Spreadsheet_Excel_Writer_BIFFwriter (used as the base for this class): // ----------------------------------------------------------------------------------------- // * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> // * // * The majority of this is _NOT_ my code. I simply ported it from the // * PERL Spreadsheet::WriteExcel module. // * // * The author of the Spreadsheet::WriteExcel module is John McNamara // * <jmcnamara@cpan.org> // * // * I _DO_ maintain this code, and John McNamara has nothing to do with the // * porting of this code to PHP. Any questions directly related to this // * class library should be directed to me. // * // * License Information: // * // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com // * // * This library is free software; you can redistribute it and/or // * modify it under the terms of the GNU Lesser General Public // * License as published by the Free Software Foundation; either // * version 2.1 of the License, or (at your option) any later version. // * // * This library is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // * Lesser General Public License for more details. // * // * You should have received a copy of the GNU Lesser General Public // * License along with this library; if not, write to the Free Software // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // */ class BIFFwriter { /** * The byte order of this architecture. 0 => little endian, 1 => big endian. * * @var ?int */ private static $byteOrder; /** * The string containing the data of the BIFF stream. * * @var null|string */ public $_data; /** * The size of the data in bytes. Should be the same as strlen($this->_data). * * @var int */ public $_datasize; /** * The maximum length for a BIFF record (excluding record header and length field). See addContinue(). * * @var int * * @see addContinue() */ private $limit = 8224; /** * Constructor. */ public function __construct() { $this->_data = ''; $this->_datasize = 0; } /** * Determine the byte order and store it as class data to avoid * recalculating it for each call to new(). * * @return int */ public static function getByteOrder() { if (!isset(self::$byteOrder)) { // Check if "pack" gives the required IEEE 64bit float $teststr = pack('d', 1.2345); $number = pack('C8', 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F); if ($number == $teststr) { $byte_order = 0; // Little Endian } elseif ($number == strrev($teststr)) { $byte_order = 1; // Big Endian } else { // Give up. I'll fix this in a later version. throw new WriterException('Required floating point format not supported on this platform.'); } self::$byteOrder = $byte_order; } return self::$byteOrder; } /** * General storage function. * * @param string $data binary data to append */ protected function append($data): void { if (strlen($data) - 4 > $this->limit) { $data = $this->addContinue($data); } $this->_data .= $data; $this->_datasize += strlen($data); } /** * General storage function like append, but returns string instead of modifying $this->_data. * * @param string $data binary data to write * * @return string */ public function writeData($data) { if (strlen($data) - 4 > $this->limit) { $data = $this->addContinue($data); } $this->_datasize += strlen($data); return $data; } /** * Writes Excel BOF record to indicate the beginning of a stream or * sub-stream in the BIFF file. * * @param int $type type of BIFF file to write: 0x0005 Workbook, * 0x0010 Worksheet */ protected function storeBof($type): void { $record = 0x0809; // Record identifier (BIFF5-BIFF8) $length = 0x0010; // by inspection of real files, MS Office Excel 2007 writes the following $unknown = pack('VV', 0x000100D1, 0x00000406); $build = 0x0DBB; // Excel 97 $year = 0x07CC; // Excel 97 $version = 0x0600; // BIFF8 $header = pack('vv', $record, $length); $data = pack('vvvv', $version, $type, $build, $year); $this->append($header . $data . $unknown); } /** * Writes Excel EOF record to indicate the end of a BIFF stream. */ protected function storeEof(): void { $record = 0x000A; // Record identifier $length = 0x0000; // Number of bytes to follow $header = pack('vv', $record, $length); $this->append($header); } /** * Writes Excel EOF record to indicate the end of a BIFF stream. */ public function writeEof(): string { $record = 0x000A; // Record identifier $length = 0x0000; // Number of bytes to follow $header = pack('vv', $record, $length); return $this->writeData($header); } /** * Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In * Excel 97 the limit is 8228 bytes. Records that are longer than these limits * must be split up into CONTINUE blocks. * * This function takes a long BIFF record and inserts CONTINUE records as * necessary. * * @param string $data The original binary data to be written * * @return string A very convenient string of continue blocks */ private function addContinue($data) { $limit = $this->limit; $record = 0x003C; // Record identifier // The first 2080/8224 bytes remain intact. However, we have to change // the length field of the record. $tmp = substr($data, 0, 2) . pack('v', $limit) . substr($data, 4, $limit); $header = pack('vv', $record, $limit); // Headers for continue records // Retrieve chunks of 2080/8224 bytes +4 for the header. $data_length = strlen($data); for ($i = $limit + 4; $i < ($data_length - $limit); $i += $limit) { $tmp .= $header; $tmp .= substr($data, $i, $limit); } // Retrieve the last chunk of data $header = pack('vv', $record, strlen($data) - $i); $tmp .= $header; $tmp .= substr($data, $i); return $tmp; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/ColorMap.php 0000644 00000005045 15002227416 0020643 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Color; class ColorMap { /** * @var array<string, int> */ private static $colorMap = [ '#000000' => 0x08, '#FFFFFF' => 0x09, '#FF0000' => 0x0A, '#00FF00' => 0x0B, '#0000FF' => 0x0C, '#FFFF00' => 0x0D, '#FF00FF' => 0x0E, '#00FFFF' => 0x0F, '#800000' => 0x10, '#008000' => 0x11, '#000080' => 0x12, '#808000' => 0x13, '#800080' => 0x14, '#008080' => 0x15, '#C0C0C0' => 0x16, '#808080' => 0x17, '#9999FF' => 0x18, '#993366' => 0x19, '#FFFFCC' => 0x1A, '#CCFFFF' => 0x1B, '#660066' => 0x1C, '#FF8080' => 0x1D, '#0066CC' => 0x1E, '#CCCCFF' => 0x1F, // '#000080' => 0x20, // '#FF00FF' => 0x21, // '#FFFF00' => 0x22, // '#00FFFF' => 0x23, // '#800080' => 0x24, // '#800000' => 0x25, // '#008080' => 0x26, // '#0000FF' => 0x27, '#00CCFF' => 0x28, // '#CCFFFF' => 0x29, '#CCFFCC' => 0x2A, '#FFFF99' => 0x2B, '#99CCFF' => 0x2C, '#FF99CC' => 0x2D, '#CC99FF' => 0x2E, '#FFCC99' => 0x2F, '#3366FF' => 0x30, '#33CCCC' => 0x31, '#99CC00' => 0x32, '#FFCC00' => 0x33, '#FF9900' => 0x34, '#FF6600' => 0x35, '#666699' => 0x36, '#969696' => 0x37, '#003366' => 0x38, '#339966' => 0x39, '#003300' => 0x3A, '#333300' => 0x3B, '#993300' => 0x3C, // '#993366' => 0x3D, '#333399' => 0x3E, '#333333' => 0x3F, ]; public static function lookup(Color $color, int $defaultIndex = 0x00): int { $colorRgb = $color->getRGB(); if (is_string($colorRgb) && array_key_exists("#{$colorRgb}", self::$colorMap)) { return self::$colorMap["#{$colorRgb}"]; } // TODO Try and map RGB value to nearest colour within the define pallette // $red = Color::getRed($colorRgb, false); // $green = Color::getGreen($colorRgb, false); // $blue = Color::getBlue($colorRgb, false); // $paletteSpace = 3; // $newColor = ($red * $paletteSpace / 256) * ($paletteSpace * $paletteSpace) + // ($green * $paletteSpace / 256) * $paletteSpace + // ($blue * $paletteSpace / 256); return $defaultIndex; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellBorder.php 0000644 00000002173 15002227416 0021143 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Border; class CellBorder { /** * @var array<string, int> */ protected static $styleMap = [ Border::BORDER_NONE => 0x00, Border::BORDER_THIN => 0x01, Border::BORDER_MEDIUM => 0x02, Border::BORDER_DASHED => 0x03, Border::BORDER_DOTTED => 0x04, Border::BORDER_THICK => 0x05, Border::BORDER_DOUBLE => 0x06, Border::BORDER_HAIR => 0x07, Border::BORDER_MEDIUMDASHED => 0x08, Border::BORDER_DASHDOT => 0x09, Border::BORDER_MEDIUMDASHDOT => 0x0A, Border::BORDER_DASHDOTDOT => 0x0B, Border::BORDER_MEDIUMDASHDOTDOT => 0x0C, Border::BORDER_SLANTDASHDOT => 0x0D, Border::BORDER_OMIT => 0x00, ]; public static function style(Border $border): int { $borderStyle = $border->getBorderStyle(); if (is_string($borderStyle) && array_key_exists($borderStyle, self::$styleMap)) { return self::$styleMap[$borderStyle]; } return self::$styleMap[Border::BORDER_NONE]; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellFill.php 0000644 00000002774 15002227416 0020623 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Fill; class CellFill { /** * @var array<string, int> */ protected static $fillStyleMap = [ Fill::FILL_NONE => 0x00, Fill::FILL_SOLID => 0x01, Fill::FILL_PATTERN_MEDIUMGRAY => 0x02, Fill::FILL_PATTERN_DARKGRAY => 0x03, Fill::FILL_PATTERN_LIGHTGRAY => 0x04, Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05, Fill::FILL_PATTERN_DARKVERTICAL => 0x06, Fill::FILL_PATTERN_DARKDOWN => 0x07, Fill::FILL_PATTERN_DARKUP => 0x08, Fill::FILL_PATTERN_DARKGRID => 0x09, Fill::FILL_PATTERN_DARKTRELLIS => 0x0A, Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B, Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C, Fill::FILL_PATTERN_LIGHTDOWN => 0x0D, Fill::FILL_PATTERN_LIGHTUP => 0x0E, Fill::FILL_PATTERN_LIGHTGRID => 0x0F, Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10, Fill::FILL_PATTERN_GRAY125 => 0x11, Fill::FILL_PATTERN_GRAY0625 => 0x12, Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8 Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8 ]; public static function style(Fill $fill): int { $fillStyle = $fill->getFillType(); if (is_string($fillStyle) && array_key_exists($fillStyle, self::$fillStyleMap)) { return self::$fillStyleMap[$fillStyle]; } return self::$fillStyleMap[Fill::FILL_NONE]; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellAlignment.php 0000644 00000003201 15002227416 0021635 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls\Style; use PhpOffice\PhpSpreadsheet\Style\Alignment; class CellAlignment { /** * @var array<string, int> */ private static $horizontalMap = [ Alignment::HORIZONTAL_GENERAL => 0, Alignment::HORIZONTAL_LEFT => 1, Alignment::HORIZONTAL_RIGHT => 3, Alignment::HORIZONTAL_CENTER => 2, Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6, Alignment::HORIZONTAL_JUSTIFY => 5, ]; /** * @var array<string, int> */ private static $verticalMap = [ Alignment::VERTICAL_BOTTOM => 2, Alignment::VERTICAL_TOP => 0, Alignment::VERTICAL_CENTER => 1, Alignment::VERTICAL_JUSTIFY => 3, ]; public static function horizontal(Alignment $alignment): int { $horizontalAlignment = $alignment->getHorizontal(); if (is_string($horizontalAlignment) && array_key_exists($horizontalAlignment, self::$horizontalMap)) { return self::$horizontalMap[$horizontalAlignment]; } return self::$horizontalMap[Alignment::HORIZONTAL_GENERAL]; } public static function wrap(Alignment $alignment): int { $wrap = $alignment->getWrapText(); return ($wrap === true) ? 1 : 0; } public static function vertical(Alignment $alignment): int { $verticalAlignment = $alignment->getVertical(); if (is_string($verticalAlignment) && array_key_exists($verticalAlignment, self::$verticalMap)) { return self::$verticalMap[$verticalAlignment]; } return self::$verticalMap[Alignment::VERTICAL_BOTTOM]; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/CellDataValidation.php 0000644 00000004624 15002227416 0021515 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; class CellDataValidation { /** * @var array<string, int> */ protected static $validationTypeMap = [ DataValidation::TYPE_NONE => 0x00, DataValidation::TYPE_WHOLE => 0x01, DataValidation::TYPE_DECIMAL => 0x02, DataValidation::TYPE_LIST => 0x03, DataValidation::TYPE_DATE => 0x04, DataValidation::TYPE_TIME => 0x05, DataValidation::TYPE_TEXTLENGTH => 0x06, DataValidation::TYPE_CUSTOM => 0x07, ]; /** * @var array<string, int> */ protected static $errorStyleMap = [ DataValidation::STYLE_STOP => 0x00, DataValidation::STYLE_WARNING => 0x01, DataValidation::STYLE_INFORMATION => 0x02, ]; /** * @var array<string, int> */ protected static $operatorMap = [ DataValidation::OPERATOR_BETWEEN => 0x00, DataValidation::OPERATOR_NOTBETWEEN => 0x01, DataValidation::OPERATOR_EQUAL => 0x02, DataValidation::OPERATOR_NOTEQUAL => 0x03, DataValidation::OPERATOR_GREATERTHAN => 0x04, DataValidation::OPERATOR_LESSTHAN => 0x05, DataValidation::OPERATOR_GREATERTHANOREQUAL => 0x06, DataValidation::OPERATOR_LESSTHANOREQUAL => 0x07, ]; public static function type(DataValidation $dataValidation): int { $validationType = $dataValidation->getType(); if (is_string($validationType) && array_key_exists($validationType, self::$validationTypeMap)) { return self::$validationTypeMap[$validationType]; } return self::$validationTypeMap[DataValidation::TYPE_NONE]; } public static function errorStyle(DataValidation $dataValidation): int { $errorStyle = $dataValidation->getErrorStyle(); if (is_string($errorStyle) && array_key_exists($errorStyle, self::$errorStyleMap)) { return self::$errorStyleMap[$errorStyle]; } return self::$errorStyleMap[DataValidation::STYLE_STOP]; } public static function operator(DataValidation $dataValidation): int { $operator = $dataValidation->getOperator(); if (is_string($operator) && array_key_exists($operator, self::$operatorMap)) { return self::$operatorMap[$operator]; } return self::$operatorMap[DataValidation::OPERATOR_BETWEEN]; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Escher.php 0000644 00000044003 15002227416 0017235 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\Escher as SharedEscher; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip; class Escher { /** * The object we are writing. * * @var Blip|BSE|BstoreContainer|DgContainer|DggContainer|Escher|SpContainer|SpgrContainer */ private $object; /** * The written binary data. * * @var string */ private $data; /** * Shape offsets. Positions in binary stream where a new shape record begins. * * @var array */ private $spOffsets; /** * Shape types. * * @var array */ private $spTypes; /** * Constructor. * * @param mixed $object */ public function __construct($object) { $this->object = $object; } /** * Process the object to be written. * * @return string */ public function close() { // initialize $this->data = ''; switch (get_class($this->object)) { case SharedEscher::class: if ($dggContainer = $this->object->/** @scrutinizer ignore-call */ getDggContainer()) { $writer = new self($dggContainer); $this->data = $writer->close(); } elseif ($dgContainer = $this->object->/** @scrutinizer ignore-call */ getDgContainer()) { $writer = new self($dgContainer); $this->data = $writer->close(); $this->spOffsets = $writer->getSpOffsets(); $this->spTypes = $writer->getSpTypes(); } break; case DggContainer::class: // this is a container record // initialize $innerData = ''; // write the dgg $recVer = 0x0; $recInstance = 0x0000; $recType = 0xF006; $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; // dgg data $dggData = pack( 'VVVV', $this->object->/** @scrutinizer ignore-call */ getSpIdMax(), // maximum shape identifier increased by one $this->object->/** @scrutinizer ignore-call */ getCDgSaved() + 1, // number of file identifier clusters increased by one $this->object->/** @scrutinizer ignore-call */ getCSpSaved(), $this->object->/** @scrutinizer ignore-call */ getCDgSaved() // count total number of drawings saved ); // add file identifier clusters (one per drawing) /** @scrutinizer ignore-call */ $IDCLs = $this->object->getIDCLs(); foreach ($IDCLs as $dgId => $maxReducedSpId) { $dggData .= pack('VV', $dgId, $maxReducedSpId + 1); } $header = pack('vvV', $recVerInstance, $recType, strlen($dggData)); $innerData .= $header . $dggData; // write the bstoreContainer if ($bstoreContainer = $this->object->/** @scrutinizer ignore-call */ getBstoreContainer()) { $writer = new self($bstoreContainer); $innerData .= $writer->close(); } // write the record $recVer = 0xF; $recInstance = 0x0000; $recType = 0xF000; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header . $innerData; break; case BstoreContainer::class: // this is a container record // initialize $innerData = ''; // treat the inner data if ($BSECollection = $this->object->/** @scrutinizer ignore-call */ getBSECollection()) { foreach ($BSECollection as $BSE) { $writer = new self($BSE); $innerData .= $writer->close(); } } // write the record $recVer = 0xF; $recInstance = count($this->object->/** @scrutinizer ignore-call */ getBSECollection()); $recType = 0xF001; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header . $innerData; break; case BSE::class: // this is a semi-container record // initialize $innerData = ''; // here we treat the inner data if ($blip = $this->object->/** @scrutinizer ignore-call */ getBlip()) { $writer = new self($blip); $innerData .= $writer->close(); } // initialize $data = ''; /** @scrutinizer ignore-call */ $btWin32 = $this->object->getBlipType(); /** @scrutinizer ignore-call */ $btMacOS = $this->object->getBlipType(); $data .= pack('CC', $btWin32, $btMacOS); $rgbUid = pack('VVVV', 0, 0, 0, 0); // todo $data .= $rgbUid; $tag = 0; $size = strlen($innerData); $cRef = 1; $foDelay = 0; //todo $unused1 = 0x0; $cbName = 0x0; $unused2 = 0x0; $unused3 = 0x0; $data .= pack('vVVVCCCC', $tag, $size, $cRef, $foDelay, $unused1, $cbName, $unused2, $unused3); $data .= $innerData; // write the record $recVer = 0x2; /** @scrutinizer ignore-call */ $recInstance = $this->object->getBlipType(); $recType = 0xF007; $length = strlen($data); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header; $this->data .= $data; break; case Blip::class: // this is an atom record // write the record switch ($this->object->/** @scrutinizer ignore-call */ getParent()->/** @scrutinizer ignore-call */ getBlipType()) { case BSE::BLIPTYPE_JPEG: // initialize $innerData = ''; $rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo $innerData .= $rgbUid1; $tag = 0xFF; // todo $innerData .= pack('C', $tag); $innerData .= $this->object->/** @scrutinizer ignore-call */ getData(); $recVer = 0x0; $recInstance = 0x46A; $recType = 0xF01D; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header; $this->data .= $innerData; break; case BSE::BLIPTYPE_PNG: // initialize $innerData = ''; $rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo $innerData .= $rgbUid1; $tag = 0xFF; // todo $innerData .= pack('C', $tag); $innerData .= $this->object->/** @scrutinizer ignore-call */ getData(); $recVer = 0x0; $recInstance = 0x6E0; $recType = 0xF01E; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header; $this->data .= $innerData; break; } break; case DgContainer::class: // this is a container record // initialize $innerData = ''; // write the dg $recVer = 0x0; /** @scrutinizer ignore-call */ $recInstance = $this->object->getDgId(); $recType = 0xF008; $length = 8; $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); // number of shapes in this drawing (including group shape) $countShapes = count($this->object->/** @scrutinizer ignore-call */ getSpgrContainerOrThrow()->getChildren()); $innerData .= $header . pack('VV', $countShapes, $this->object->/** @scrutinizer ignore-call */ getLastSpId()); // write the spgrContainer if ($spgrContainer = $this->object->/** @scrutinizer ignore-call */ getSpgrContainer()) { $writer = new self($spgrContainer); $innerData .= $writer->close(); // get the shape offsets relative to the spgrContainer record $spOffsets = $writer->getSpOffsets(); $spTypes = $writer->getSpTypes(); // save the shape offsets relative to dgContainer foreach ($spOffsets as &$spOffset) { $spOffset += 24; // add length of dgContainer header data (8 bytes) plus dg data (16 bytes) } $this->spOffsets = $spOffsets; $this->spTypes = $spTypes; } // write the record $recVer = 0xF; $recInstance = 0x0000; $recType = 0xF002; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header . $innerData; break; case SpgrContainer::class: // this is a container record // initialize $innerData = ''; // initialize spape offsets $totalSize = 8; $spOffsets = []; $spTypes = []; // treat the inner data foreach ($this->object->/** @scrutinizer ignore-call */ getChildren() as $spContainer) { $writer = new self($spContainer); $spData = $writer->close(); $innerData .= $spData; // save the shape offsets (where new shape records begin) $totalSize += strlen($spData); $spOffsets[] = $totalSize; $spTypes = array_merge($spTypes, $writer->getSpTypes()); } // write the record $recVer = 0xF; $recInstance = 0x0000; $recType = 0xF003; $length = strlen($innerData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header . $innerData; $this->spOffsets = $spOffsets; $this->spTypes = $spTypes; break; case SpContainer::class: // initialize $data = ''; // build the data // write group shape record, if necessary? if ($this->object->/** @scrutinizer ignore-call */ getSpgr()) { $recVer = 0x1; $recInstance = 0x0000; $recType = 0xF009; $length = 0x00000010; $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $data .= $header . pack('VVVV', 0, 0, 0, 0); } /** @scrutinizer ignore-call */ $this->spTypes[] = ($this->object->getSpType()); // write the shape record $recVer = 0x2; /** @scrutinizer ignore-call */ $recInstance = $this->object->getSpType(); // shape type $recType = 0xF00A; $length = 0x00000008; $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $data .= $header . pack('VV', $this->object->/** @scrutinizer ignore-call */ getSpId(), $this->object->/** @scrutinizer ignore-call */ getSpgr() ? 0x0005 : 0x0A00); // the options if ($this->object->/** @scrutinizer ignore-call */ getOPTCollection()) { $optData = ''; $recVer = 0x3; $recInstance = count($this->object->/** @scrutinizer ignore-call */ getOPTCollection()); $recType = 0xF00B; foreach ($this->object->/** @scrutinizer ignore-call */ getOPTCollection() as $property => $value) { $optData .= pack('vV', $property, $value); } $length = strlen($optData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $data .= $header . $optData; } // the client anchor if ($this->object->/** @scrutinizer ignore-call */ getStartCoordinates()) { $recVer = 0x0; $recInstance = 0x0; $recType = 0xF010; // start coordinates [$column, $row] = Coordinate::indexesFromString($this->object->/** @scrutinizer ignore-call */ getStartCoordinates()); $c1 = $column - 1; $r1 = $row - 1; // start offsetX /** @scrutinizer ignore-call */ $startOffsetX = $this->object->getStartOffsetX(); // start offsetY /** @scrutinizer ignore-call */ $startOffsetY = $this->object->getStartOffsetY(); // end coordinates [$column, $row] = Coordinate::indexesFromString($this->object->/** @scrutinizer ignore-call */ getEndCoordinates()); $c2 = $column - 1; $r2 = $row - 1; // end offsetX /** @scrutinizer ignore-call */ $endOffsetX = $this->object->getEndOffsetX(); // end offsetY /** @scrutinizer ignore-call */ $endOffsetY = $this->object->getEndOffsetY(); $clientAnchorData = pack('vvvvvvvvv', $this->object->/** @scrutinizer ignore-call */ getSpFlag(), $c1, $startOffsetX, $r1, $startOffsetY, $c2, $endOffsetX, $r2, $endOffsetY); $length = strlen($clientAnchorData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $data .= $header . $clientAnchorData; } // the client data, just empty for now if (!$this->object->/** @scrutinizer ignore-call */ getSpgr()) { $clientDataData = ''; $recVer = 0x0; $recInstance = 0x0; $recType = 0xF011; $length = strlen($clientDataData); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $data .= $header . $clientDataData; } // write the record $recVer = 0xF; $recInstance = 0x0000; $recType = 0xF004; $length = strlen($data); $recVerInstance = $recVer; $recVerInstance |= $recInstance << 4; $header = pack('vvV', $recVerInstance, $recType, $length); $this->data = $header . $data; break; } return $this->data; } /** * Gets the shape offsets. * * @return array */ public function getSpOffsets() { return $this->spOffsets; } /** * Gets the shape types. * * @return array */ public function getSpTypes() { return $this->spTypes; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Xf.php 0000644 00000030043 15002227416 0016400 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellAlignment; use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellBorder; use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellFill; // Original file header of PEAR::Spreadsheet_Excel_Writer_Format (used as the base for this class): // ----------------------------------------------------------------------------------------- // /* // * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> // * // * The majority of this is _NOT_ my code. I simply ported it from the // * PERL Spreadsheet::WriteExcel module. // * // * The author of the Spreadsheet::WriteExcel module is John McNamara // * <jmcnamara@cpan.org> // * // * I _DO_ maintain this code, and John McNamara has nothing to do with the // * porting of this code to PHP. Any questions directly related to this // * class library should be directed to me. // * // * License Information: // * // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com // * // * This library is free software; you can redistribute it and/or // * modify it under the terms of the GNU Lesser General Public // * License as published by the Free Software Foundation; either // * version 2.1 of the License, or (at your option) any later version. // * // * This library is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // * Lesser General Public License for more details. // * // * You should have received a copy of the GNU Lesser General Public // * License along with this library; if not, write to the Free Software // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // */ class Xf { /** * Style XF or a cell XF ? * * @var bool */ private $isStyleXf; /** * Index to the FONT record. Index 4 does not exist. * * @var int */ private $fontIndex; /** * An index (2 bytes) to a FORMAT record (number format). * * @var int */ private $numberFormatIndex; /** * 1 bit, apparently not used. * * @var int */ private $textJustLast; /** * The cell's foreground color. * * @var int */ private $foregroundColor; /** * The cell's background color. * * @var int */ private $backgroundColor; /** * Color of the bottom border of the cell. * * @var int */ private $bottomBorderColor; /** * Color of the top border of the cell. * * @var int */ private $topBorderColor; /** * Color of the left border of the cell. * * @var int */ private $leftBorderColor; /** * Color of the right border of the cell. * * @var int */ private $rightBorderColor; //private $diag; // theoretically int, not yet implemented /** * @var int */ private $diagColor; /** * @var Style */ private $style; /** * Constructor. * * @param Style $style The XF format */ public function __construct(Style $style) { $this->isStyleXf = false; $this->fontIndex = 0; $this->numberFormatIndex = 0; $this->textJustLast = 0; $this->foregroundColor = 0x40; $this->backgroundColor = 0x41; //$this->diag = 0; $this->bottomBorderColor = 0x40; $this->topBorderColor = 0x40; $this->leftBorderColor = 0x40; $this->rightBorderColor = 0x40; $this->diagColor = 0x40; $this->style = $style; } /** * Generate an Excel BIFF XF record (style or cell). * * @return string The XF record */ public function writeXf() { // Set the type of the XF record and some of the attributes. if ($this->isStyleXf) { $style = 0xFFF5; } else { $style = self::mapLocked($this->style->getProtection()->getLocked()); $style |= self::mapHidden($this->style->getProtection()->getHidden()) << 1; } // Flags to indicate if attributes have been set. $atr_num = ($this->numberFormatIndex != 0) ? 1 : 0; $atr_fnt = ($this->fontIndex != 0) ? 1 : 0; $atr_alc = ((int) $this->style->getAlignment()->getWrapText()) ? 1 : 0; $atr_bdr = (CellBorder::style($this->style->getBorders()->getBottom()) || CellBorder::style($this->style->getBorders()->getTop()) || CellBorder::style($this->style->getBorders()->getLeft()) || CellBorder::style($this->style->getBorders()->getRight())) ? 1 : 0; $atr_pat = ($this->foregroundColor != 0x40) ? 1 : 0; $atr_pat = ($this->backgroundColor != 0x41) ? 1 : $atr_pat; $atr_pat = CellFill::style($this->style->getFill()) ? 1 : $atr_pat; $atr_prot = self::mapLocked($this->style->getProtection()->getLocked()) | self::mapHidden($this->style->getProtection()->getHidden()); // Zero the default border colour if the border has not been set. if (CellBorder::style($this->style->getBorders()->getBottom()) == 0) { $this->bottomBorderColor = 0; } if (CellBorder::style($this->style->getBorders()->getTop()) == 0) { $this->topBorderColor = 0; } if (CellBorder::style($this->style->getBorders()->getRight()) == 0) { $this->rightBorderColor = 0; } if (CellBorder::style($this->style->getBorders()->getLeft()) == 0) { $this->leftBorderColor = 0; } if (CellBorder::style($this->style->getBorders()->getDiagonal()) == 0) { $this->diagColor = 0; } $record = 0x00E0; // Record identifier $length = 0x0014; // Number of bytes to follow $ifnt = $this->fontIndex; // Index to FONT record $ifmt = $this->numberFormatIndex; // Index to FORMAT record // Alignment $align = CellAlignment::horizontal($this->style->getAlignment()); $align |= CellAlignment::wrap($this->style->getAlignment()) << 3; $align |= CellAlignment::vertical($this->style->getAlignment()) << 4; $align |= $this->textJustLast << 7; $used_attrib = $atr_num << 2; $used_attrib |= $atr_fnt << 3; $used_attrib |= $atr_alc << 4; $used_attrib |= $atr_bdr << 5; $used_attrib |= $atr_pat << 6; $used_attrib |= $atr_prot << 7; $icv = $this->foregroundColor; // fg and bg pattern colors $icv |= $this->backgroundColor << 7; $border1 = CellBorder::style($this->style->getBorders()->getLeft()); // Border line style and color $border1 |= CellBorder::style($this->style->getBorders()->getRight()) << 4; $border1 |= CellBorder::style($this->style->getBorders()->getTop()) << 8; $border1 |= CellBorder::style($this->style->getBorders()->getBottom()) << 12; $border1 |= $this->leftBorderColor << 16; $border1 |= $this->rightBorderColor << 23; $diagonalDirection = $this->style->getBorders()->getDiagonalDirection(); $diag_tl_to_rb = $diagonalDirection == Borders::DIAGONAL_BOTH || $diagonalDirection == Borders::DIAGONAL_DOWN; $diag_tr_to_lb = $diagonalDirection == Borders::DIAGONAL_BOTH || $diagonalDirection == Borders::DIAGONAL_UP; $border1 |= $diag_tl_to_rb << 30; $border1 |= $diag_tr_to_lb << 31; $border2 = $this->topBorderColor; // Border color $border2 |= $this->bottomBorderColor << 7; $border2 |= $this->diagColor << 14; $border2 |= CellBorder::style($this->style->getBorders()->getDiagonal()) << 21; $border2 |= CellFill::style($this->style->getFill()) << 26; $header = pack('vv', $record, $length); //BIFF8 options: identation, shrinkToFit and text direction $biff8_options = $this->style->getAlignment()->getIndent(); $biff8_options |= (int) $this->style->getAlignment()->getShrinkToFit() << 4; $data = pack('vvvC', $ifnt, $ifmt, $style, $align); $data .= pack('CCC', self::mapTextRotation((int) $this->style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib); $data .= pack('VVv', $border1, $border2, $icv); return $header . $data; } /** * Is this a style XF ? * * @param bool $value */ public function setIsStyleXf($value): void { $this->isStyleXf = $value; } /** * Sets the cell's bottom border color. * * @param int $colorIndex Color index */ public function setBottomColor($colorIndex): void { $this->bottomBorderColor = $colorIndex; } /** * Sets the cell's top border color. * * @param int $colorIndex Color index */ public function setTopColor($colorIndex): void { $this->topBorderColor = $colorIndex; } /** * Sets the cell's left border color. * * @param int $colorIndex Color index */ public function setLeftColor($colorIndex): void { $this->leftBorderColor = $colorIndex; } /** * Sets the cell's right border color. * * @param int $colorIndex Color index */ public function setRightColor($colorIndex): void { $this->rightBorderColor = $colorIndex; } /** * Sets the cell's diagonal border color. * * @param int $colorIndex Color index */ public function setDiagColor($colorIndex): void { $this->diagColor = $colorIndex; } /** * Sets the cell's foreground color. * * @param int $colorIndex Color index */ public function setFgColor($colorIndex): void { $this->foregroundColor = $colorIndex; } /** * Sets the cell's background color. * * @param int $colorIndex Color index */ public function setBgColor($colorIndex): void { $this->backgroundColor = $colorIndex; } /** * Sets the index to the number format record * It can be date, time, currency, etc... * * @param int $numberFormatIndex Index to format record */ public function setNumberFormatIndex($numberFormatIndex): void { $this->numberFormatIndex = $numberFormatIndex; } /** * Set the font index. * * @param int $value Font index, note that value 4 does not exist */ public function setFontIndex($value): void { $this->fontIndex = $value; } /** * Map to BIFF8 codes for text rotation angle. * * @param int $textRotation * * @return int */ private static function mapTextRotation($textRotation) { if ($textRotation >= 0) { return $textRotation; } if ($textRotation == Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) { return Alignment::TEXTROTATION_STACK_EXCEL; } return 90 - $textRotation; } private const LOCK_ARRAY = [ Protection::PROTECTION_INHERIT => 1, Protection::PROTECTION_PROTECTED => 1, Protection::PROTECTION_UNPROTECTED => 0, ]; /** * Map locked values. * * @param string $locked * * @return int */ private static function mapLocked($locked) { return array_key_exists($locked, self::LOCK_ARRAY) ? self::LOCK_ARRAY[$locked] : 1; } private const HIDDEN_ARRAY = [ Protection::PROTECTION_INHERIT => 0, Protection::PROTECTION_PROTECTED => 1, Protection::PROTECTION_UNPROTECTED => 0, ]; /** * Map hidden. * * @param string $hidden * * @return int */ private static function mapHidden($hidden) { return array_key_exists($hidden, self::HIDDEN_ARRAY) ? self::HIDDEN_ARRAY[$hidden] : 0; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Workbook.php 0000644 00000121173 15002227416 0017625 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Style; // Original file header of PEAR::Spreadsheet_Excel_Writer_Workbook (used as the base for this class): // ----------------------------------------------------------------------------------------- // /* // * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> // * // * The majority of this is _NOT_ my code. I simply ported it from the // * PERL Spreadsheet::WriteExcel module. // * // * The author of the Spreadsheet::WriteExcel module is John McNamara // * <jmcnamara@cpan.org> // * // * I _DO_ maintain this code, and John McNamara has nothing to do with the // * porting of this code to PHP. Any questions directly related to this // * class library should be directed to me. // * // * License Information: // * // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com // * // * This library is free software; you can redistribute it and/or // * modify it under the terms of the GNU Lesser General Public // * License as published by the Free Software Foundation; either // * version 2.1 of the License, or (at your option) any later version. // * // * This library is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // * Lesser General Public License for more details. // * // * You should have received a copy of the GNU Lesser General Public // * License along with this library; if not, write to the Free Software // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // */ class Workbook extends BIFFwriter { /** * Formula parser. * * @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Parser */ private $parser; /** * The BIFF file size for the workbook. Not currently used. * * @var int * * @see calcSheetOffsets() */ private $biffSize; // @phpstan-ignore-line /** * XF Writers. * * @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Xf[] */ private $xfWriters = []; /** * Array containing the colour palette. * * @var array */ private $palette; /** * The codepage indicates the text encoding used for strings. * * @var int */ private $codepage; /** * The country code used for localization. * * @var int */ private $countryCode; /** * Workbook. * * @var Spreadsheet */ private $spreadsheet; /** * Fonts writers. * * @var Font[] */ private $fontWriters = []; /** * Added fonts. Maps from font's hash => index in workbook. * * @var array */ private $addedFonts = []; /** * Shared number formats. * * @var array */ private $numberFormats = []; /** * Added number formats. Maps from numberFormat's hash => index in workbook. * * @var array */ private $addedNumberFormats = []; /** * Sizes of the binary worksheet streams. * * @var array */ private $worksheetSizes = []; /** * Offsets of the binary worksheet streams relative to the start of the global workbook stream. * * @var array */ private $worksheetOffsets = []; /** * Total number of shared strings in workbook. * * @var int */ private $stringTotal; /** * Number of unique shared strings in workbook. * * @var int */ private $stringUnique; /** * Array of unique shared strings in workbook. * * @var array */ private $stringTable; /** * Color cache. * * @var array */ private $colors; /** * Escher object corresponding to MSODRAWINGGROUP. * * @var null|\PhpOffice\PhpSpreadsheet\Shared\Escher */ private $escher; /** @var mixed */ private static $scrutinizerFalse = false; /** * Class constructor. * * @param Spreadsheet $spreadsheet The Workbook * @param int $str_total Total number of strings * @param int $str_unique Total number of unique strings * @param array $str_table String Table * @param array $colors Colour Table * @param Parser $parser The formula parser created for the Workbook */ public function __construct(Spreadsheet $spreadsheet, &$str_total, &$str_unique, &$str_table, &$colors, Parser $parser) { // It needs to call its parent's constructor explicitly parent::__construct(); $this->parser = $parser; $this->biffSize = 0; $this->palette = []; $this->countryCode = -1; $this->stringTotal = &$str_total; $this->stringUnique = &$str_unique; $this->stringTable = &$str_table; $this->colors = &$colors; $this->setPaletteXl97(); $this->spreadsheet = $spreadsheet; $this->codepage = 0x04B0; // Add empty sheets and Build color cache $countSheets = $spreadsheet->getSheetCount(); for ($i = 0; $i < $countSheets; ++$i) { $phpSheet = $spreadsheet->getSheet($i); $this->parser->setExtSheet($phpSheet->getTitle(), $i); // Register worksheet name with parser $supbook_index = 0x00; $ref = pack('vvv', $supbook_index, $i, $i); $this->parser->references[] = $ref; // Register reference with parser // Sheet tab colors? if ($phpSheet->isTabColorSet()) { $this->addColor($phpSheet->getTabColor()->getRGB()); } } } /** * Add a new XF writer. * * @param bool $isStyleXf Is it a style XF? * * @return int Index to XF record */ public function addXfWriter(Style $style, $isStyleXf = false) { $xfWriter = new Xf($style); $xfWriter->setIsStyleXf($isStyleXf); // Add the font if not already added $fontIndex = $this->addFont($style->getFont()); // Assign the font index to the xf record $xfWriter->setFontIndex($fontIndex); // Background colors, best to treat these after the font so black will come after white in custom palette $xfWriter->setFgColor($this->addColor($style->getFill()->getStartColor()->getRGB())); $xfWriter->setBgColor($this->addColor($style->getFill()->getEndColor()->getRGB())); $xfWriter->setBottomColor($this->addColor($style->getBorders()->getBottom()->getColor()->getRGB())); $xfWriter->setTopColor($this->addColor($style->getBorders()->getTop()->getColor()->getRGB())); $xfWriter->setRightColor($this->addColor($style->getBorders()->getRight()->getColor()->getRGB())); $xfWriter->setLeftColor($this->addColor($style->getBorders()->getLeft()->getColor()->getRGB())); $xfWriter->setDiagColor($this->addColor($style->getBorders()->getDiagonal()->getColor()->getRGB())); // Add the number format if it is not a built-in one and not already added if ($style->getNumberFormat()->getBuiltInFormatCode() === self::$scrutinizerFalse) { $numberFormatHashCode = $style->getNumberFormat()->getHashCode(); if (isset($this->addedNumberFormats[$numberFormatHashCode])) { $numberFormatIndex = $this->addedNumberFormats[$numberFormatHashCode]; } else { $numberFormatIndex = 164 + count($this->numberFormats); $this->numberFormats[$numberFormatIndex] = $style->getNumberFormat(); $this->addedNumberFormats[$numberFormatHashCode] = $numberFormatIndex; } } else { $numberFormatIndex = (int) $style->getNumberFormat()->getBuiltInFormatCode(); } // Assign the number format index to xf record $xfWriter->setNumberFormatIndex($numberFormatIndex); $this->xfWriters[] = $xfWriter; return count($this->xfWriters) - 1; } /** * Add a font to added fonts. * * @return int Index to FONT record */ public function addFont(\PhpOffice\PhpSpreadsheet\Style\Font $font) { $fontHashCode = $font->getHashCode(); if (isset($this->addedFonts[$fontHashCode])) { $fontIndex = $this->addedFonts[$fontHashCode]; } else { $countFonts = count($this->fontWriters); $fontIndex = ($countFonts < 4) ? $countFonts : $countFonts + 1; $fontWriter = new Font($font); $fontWriter->setColorIndex($this->addColor($font->getColor()->getRGB())); $this->fontWriters[] = $fontWriter; $this->addedFonts[$fontHashCode] = $fontIndex; } return $fontIndex; } /** * Alter color palette adding a custom color. * * @param string $rgb E.g. 'FF00AA' * * @return int Color index */ private function addColor($rgb) { if (!isset($this->colors[$rgb])) { $color = [ hexdec(substr($rgb, 0, 2)), hexdec(substr($rgb, 2, 2)), hexdec(substr($rgb, 4)), 0, ]; $colorIndex = array_search($color, $this->palette); if ($colorIndex) { $this->colors[$rgb] = $colorIndex; } else { if (count($this->colors) === 0) { $lastColor = 7; } else { $lastColor = end($this->colors); } if ($lastColor < 57) { // then we add a custom color altering the palette $colorIndex = $lastColor + 1; $this->palette[$colorIndex] = $color; $this->colors[$rgb] = $colorIndex; } else { // no room for more custom colors, just map to black $colorIndex = 0; } } } else { // fetch already added custom color $colorIndex = $this->colors[$rgb]; } return $colorIndex; } /** * Sets the colour palette to the Excel 97+ default. */ private function setPaletteXl97(): void { $this->palette = [ 0x08 => [0x00, 0x00, 0x00, 0x00], 0x09 => [0xff, 0xff, 0xff, 0x00], 0x0A => [0xff, 0x00, 0x00, 0x00], 0x0B => [0x00, 0xff, 0x00, 0x00], 0x0C => [0x00, 0x00, 0xff, 0x00], 0x0D => [0xff, 0xff, 0x00, 0x00], 0x0E => [0xff, 0x00, 0xff, 0x00], 0x0F => [0x00, 0xff, 0xff, 0x00], 0x10 => [0x80, 0x00, 0x00, 0x00], 0x11 => [0x00, 0x80, 0x00, 0x00], 0x12 => [0x00, 0x00, 0x80, 0x00], 0x13 => [0x80, 0x80, 0x00, 0x00], 0x14 => [0x80, 0x00, 0x80, 0x00], 0x15 => [0x00, 0x80, 0x80, 0x00], 0x16 => [0xc0, 0xc0, 0xc0, 0x00], 0x17 => [0x80, 0x80, 0x80, 0x00], 0x18 => [0x99, 0x99, 0xff, 0x00], 0x19 => [0x99, 0x33, 0x66, 0x00], 0x1A => [0xff, 0xff, 0xcc, 0x00], 0x1B => [0xcc, 0xff, 0xff, 0x00], 0x1C => [0x66, 0x00, 0x66, 0x00], 0x1D => [0xff, 0x80, 0x80, 0x00], 0x1E => [0x00, 0x66, 0xcc, 0x00], 0x1F => [0xcc, 0xcc, 0xff, 0x00], 0x20 => [0x00, 0x00, 0x80, 0x00], 0x21 => [0xff, 0x00, 0xff, 0x00], 0x22 => [0xff, 0xff, 0x00, 0x00], 0x23 => [0x00, 0xff, 0xff, 0x00], 0x24 => [0x80, 0x00, 0x80, 0x00], 0x25 => [0x80, 0x00, 0x00, 0x00], 0x26 => [0x00, 0x80, 0x80, 0x00], 0x27 => [0x00, 0x00, 0xff, 0x00], 0x28 => [0x00, 0xcc, 0xff, 0x00], 0x29 => [0xcc, 0xff, 0xff, 0x00], 0x2A => [0xcc, 0xff, 0xcc, 0x00], 0x2B => [0xff, 0xff, 0x99, 0x00], 0x2C => [0x99, 0xcc, 0xff, 0x00], 0x2D => [0xff, 0x99, 0xcc, 0x00], 0x2E => [0xcc, 0x99, 0xff, 0x00], 0x2F => [0xff, 0xcc, 0x99, 0x00], 0x30 => [0x33, 0x66, 0xff, 0x00], 0x31 => [0x33, 0xcc, 0xcc, 0x00], 0x32 => [0x99, 0xcc, 0x00, 0x00], 0x33 => [0xff, 0xcc, 0x00, 0x00], 0x34 => [0xff, 0x99, 0x00, 0x00], 0x35 => [0xff, 0x66, 0x00, 0x00], 0x36 => [0x66, 0x66, 0x99, 0x00], 0x37 => [0x96, 0x96, 0x96, 0x00], 0x38 => [0x00, 0x33, 0x66, 0x00], 0x39 => [0x33, 0x99, 0x66, 0x00], 0x3A => [0x00, 0x33, 0x00, 0x00], 0x3B => [0x33, 0x33, 0x00, 0x00], 0x3C => [0x99, 0x33, 0x00, 0x00], 0x3D => [0x99, 0x33, 0x66, 0x00], 0x3E => [0x33, 0x33, 0x99, 0x00], 0x3F => [0x33, 0x33, 0x33, 0x00], ]; } /** * Assemble worksheets into a workbook and send the BIFF data to an OLE * storage. * * @param array $worksheetSizes The sizes in bytes of the binary worksheet streams * * @return string Binary data for workbook stream */ public function writeWorkbook(array $worksheetSizes) { $this->worksheetSizes = $worksheetSizes; // Calculate the number of selected worksheet tabs and call the finalization // methods for each worksheet $total_worksheets = $this->spreadsheet->getSheetCount(); // Add part 1 of the Workbook globals, what goes before the SHEET records $this->storeBof(0x0005); $this->writeCodepage(); $this->writeWindow1(); $this->writeDateMode(); $this->writeAllFonts(); $this->writeAllNumberFormats(); $this->writeAllXfs(); $this->writeAllStyles(); $this->writePalette(); // Prepare part 3 of the workbook global stream, what goes after the SHEET records $part3 = ''; if ($this->countryCode !== -1) { $part3 .= $this->writeCountry(); } $part3 .= $this->writeRecalcId(); $part3 .= $this->writeSupbookInternal(); /* TODO: store external SUPBOOK records and XCT and CRN records in case of external references for BIFF8 */ $part3 .= $this->writeExternalsheetBiff8(); $part3 .= $this->writeAllDefinedNamesBiff8(); $part3 .= $this->writeMsoDrawingGroup(); $part3 .= $this->writeSharedStringsTable(); $part3 .= $this->writeEof(); // Add part 2 of the Workbook globals, the SHEET records $this->calcSheetOffsets(); for ($i = 0; $i < $total_worksheets; ++$i) { $this->writeBoundSheet($this->spreadsheet->getSheet($i), $this->worksheetOffsets[$i]); } // Add part 3 of the Workbook globals $this->_data .= $part3; return $this->_data; } /** * Calculate offsets for Worksheet BOF records. */ private function calcSheetOffsets(): void { $boundsheet_length = 10; // fixed length for a BOUNDSHEET record // size of Workbook globals part 1 + 3 $offset = $this->_datasize; // add size of Workbook globals part 2, the length of the SHEET records $total_worksheets = count($this->spreadsheet->getAllSheets()); foreach ($this->spreadsheet->getWorksheetIterator() as $sheet) { $offset += $boundsheet_length + strlen(StringHelper::UTF8toBIFF8UnicodeShort($sheet->getTitle())); } // add the sizes of each of the Sheet substreams, respectively for ($i = 0; $i < $total_worksheets; ++$i) { $this->worksheetOffsets[$i] = $offset; $offset += $this->worksheetSizes[$i]; } $this->biffSize = $offset; } /** * Store the Excel FONT records. */ private function writeAllFonts(): void { foreach ($this->fontWriters as $fontWriter) { $this->append($fontWriter->writeFont()); } } /** * Store user defined numerical formats i.e. FORMAT records. */ private function writeAllNumberFormats(): void { foreach ($this->numberFormats as $numberFormatIndex => $numberFormat) { $this->writeNumberFormat($numberFormat->getFormatCode(), $numberFormatIndex); } } /** * Write all XF records. */ private function writeAllXfs(): void { foreach ($this->xfWriters as $xfWriter) { $this->append($xfWriter->writeXf()); } } /** * Write all STYLE records. */ private function writeAllStyles(): void { $this->writeStyle(); } private function parseDefinedNameValue(DefinedName $definedName): string { $definedRange = $definedName->getValue(); $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF . '/mui', $definedRange, $splitRanges, PREG_OFFSET_CAPTURE ); $lengths = array_map('strlen', array_column($splitRanges[0], 0)); $offsets = array_column($splitRanges[0], 1); $worksheets = $splitRanges[2]; $columns = $splitRanges[6]; $rows = $splitRanges[7]; while ($splitCount > 0) { --$splitCount; $length = $lengths[$splitCount]; $offset = $offsets[$splitCount]; $worksheet = $worksheets[$splitCount][0]; $column = $columns[$splitCount][0]; $row = $rows[$splitCount][0]; $newRange = ''; if (empty($worksheet)) { if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) { // We should have a worksheet $worksheet = $definedName->getWorksheet() ? $definedName->getWorksheet()->getTitle() : null; } } else { $worksheet = str_replace("''", "'", trim($worksheet, "'")); } if (!empty($worksheet)) { $newRange = "'" . str_replace("'", "''", $worksheet) . "'!"; } if (!empty($column)) { $newRange .= "\${$column}"; } if (!empty($row)) { $newRange .= "\${$row}"; } $definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length); } return $definedRange; } /** * Writes all the DEFINEDNAME records (BIFF8). * So far this is only used for repeating rows/columns (print titles) and print areas. */ private function writeAllDefinedNamesBiff8(): string { $chunk = ''; // Named ranges $definedNames = $this->spreadsheet->getDefinedNames(); if (count($definedNames) > 0) { // Loop named ranges foreach ($definedNames as $definedName) { $range = $this->parseDefinedNameValue($definedName); // parse formula try { $this->parser->parse($range); $formulaData = $this->parser->toReversePolish(); // make sure tRef3d is of type tRef3dR (0x3A) if (isset($formulaData[0]) && ($formulaData[0] == "\x7A" || $formulaData[0] == "\x5A")) { $formulaData = "\x3A" . substr($formulaData, 1); } if ($definedName->getLocalOnly()) { // local scope $scopeWs = $definedName->getScope(); $scope = ($scopeWs === null) ? 0 : ($this->spreadsheet->getIndex($scopeWs) + 1); } else { // global scope $scope = 0; } $chunk .= $this->writeData($this->writeDefinedNameBiff8($definedName->getName(), $formulaData, $scope, false)); } catch (PhpSpreadsheetException $e) { // do nothing } } } // total number of sheets $total_worksheets = $this->spreadsheet->getSheetCount(); // write the print titles (repeating rows, columns), if any for ($i = 0; $i < $total_worksheets; ++$i) { $sheetSetup = $this->spreadsheet->getSheet($i)->getPageSetup(); // simultaneous repeatColumns repeatRows if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) { $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); $colmin = Coordinate::columnIndexFromString($repeat[0]) - 1; $colmax = Coordinate::columnIndexFromString($repeat[1]) - 1; $repeat = $sheetSetup->getRowsToRepeatAtTop(); $rowmin = $repeat[0] - 1; $rowmax = $repeat[1] - 1; // construct formula data manually $formulaData = pack('Cv', 0x29, 0x17); // tMemFunc $formulaData .= pack('Cvvvvv', 0x3B, $i, 0, 65535, $colmin, $colmax); // tArea3d $formulaData .= pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, 0, 255); // tArea3d $formulaData .= pack('C', 0x10); // tList // store the DEFINEDNAME record $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true)); } elseif ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) { // (exclusive) either repeatColumns or repeatRows. // Columns to repeat if ($sheetSetup->isColumnsToRepeatAtLeftSet()) { $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); $colmin = Coordinate::columnIndexFromString($repeat[0]) - 1; $colmax = Coordinate::columnIndexFromString($repeat[1]) - 1; } else { $colmin = 0; $colmax = 255; } // Rows to repeat if ($sheetSetup->isRowsToRepeatAtTopSet()) { $repeat = $sheetSetup->getRowsToRepeatAtTop(); $rowmin = $repeat[0] - 1; $rowmax = $repeat[1] - 1; } else { $rowmin = 0; $rowmax = 65535; } // construct formula data manually because parser does not recognize absolute 3d cell references $formulaData = pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, $colmin, $colmax); // store the DEFINEDNAME record $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true)); } } // write the print areas, if any for ($i = 0; $i < $total_worksheets; ++$i) { $sheetSetup = $this->spreadsheet->getSheet($i)->getPageSetup(); if ($sheetSetup->isPrintAreaSet()) { // Print area, e.g. A3:J6,H1:X20 $printArea = Coordinate::splitRange($sheetSetup->getPrintArea()); $countPrintArea = count($printArea); $formulaData = ''; for ($j = 0; $j < $countPrintArea; ++$j) { $printAreaRect = $printArea[$j]; // e.g. A3:J6 $printAreaRect[0] = Coordinate::indexesFromString($printAreaRect[0]); $printAreaRect[1] = Coordinate::indexesFromString($printAreaRect[1]); $print_rowmin = $printAreaRect[0][1] - 1; $print_rowmax = $printAreaRect[1][1] - 1; $print_colmin = $printAreaRect[0][0] - 1; $print_colmax = $printAreaRect[1][0] - 1; // construct formula data manually because parser does not recognize absolute 3d cell references $formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax); if ($j > 0) { $formulaData .= pack('C', 0x10); // list operator token ',' } } // store the DEFINEDNAME record $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x06), $formulaData, $i + 1, true)); } } // write autofilters, if any for ($i = 0; $i < $total_worksheets; ++$i) { $sheetAutoFilter = $this->spreadsheet->getSheet($i)->getAutoFilter(); $autoFilterRange = $sheetAutoFilter->getRange(); if (!empty($autoFilterRange)) { $rangeBounds = Coordinate::rangeBoundaries($autoFilterRange); //Autofilter built in name $name = pack('C', 0x0D); $chunk .= $this->writeData($this->writeShortNameBiff8($name, $i + 1, $rangeBounds, true)); } } return $chunk; } /** * Write a DEFINEDNAME record for BIFF8 using explicit binary formula data. * * @param string $name The name in UTF-8 * @param string $formulaData The binary formula data * @param int $sheetIndex 1-based sheet index the defined name applies to. 0 = global * @param bool $isBuiltIn Built-in name? * * @return string Complete binary record data */ private function writeDefinedNameBiff8($name, $formulaData, $sheetIndex = 0, $isBuiltIn = false) { $record = 0x0018; // option flags $options = $isBuiltIn ? 0x20 : 0x00; // length of the name, character count $nlen = StringHelper::countCharacters($name); // name with stripped length field $name = substr(StringHelper::UTF8toBIFF8UnicodeLong($name), 2); // size of the formula (in bytes) $sz = strlen($formulaData); // combine the parts $data = pack('vCCvvvCCCC', $options, 0, $nlen, $sz, 0, $sheetIndex, 0, 0, 0, 0) . $name . $formulaData; $length = strlen($data); $header = pack('vv', $record, $length); return $header . $data; } /** * Write a short NAME record. * * @param string $name * @param int $sheetIndex 1-based sheet index the defined name applies to. 0 = global * @param int[][] $rangeBounds range boundaries * @param bool $isHidden * * @return string Complete binary record data * */ private function writeShortNameBiff8($name, $sheetIndex, $rangeBounds, $isHidden = false) { $record = 0x0018; // option flags $options = ($isHidden ? 0x21 : 0x00); $extra = pack( 'Cvvvvv', 0x3B, $sheetIndex - 1, $rangeBounds[0][1] - 1, $rangeBounds[1][1] - 1, $rangeBounds[0][0] - 1, $rangeBounds[1][0] - 1 ); // size of the formula (in bytes) $sz = strlen($extra); // combine the parts $data = pack('vCCvvvCCCCC', $options, 0, 1, $sz, 0, $sheetIndex, 0, 0, 0, 0, 0) . $name . $extra; $length = strlen($data); $header = pack('vv', $record, $length); return $header . $data; } /** * Stores the CODEPAGE biff record. */ private function writeCodepage(): void { $record = 0x0042; // Record identifier $length = 0x0002; // Number of bytes to follow $cv = $this->codepage; // The code page $header = pack('vv', $record, $length); $data = pack('v', $cv); $this->append($header . $data); } /** * Write Excel BIFF WINDOW1 record. */ private function writeWindow1(): void { $record = 0x003D; // Record identifier $length = 0x0012; // Number of bytes to follow $xWn = 0x0000; // Horizontal position of window $yWn = 0x0000; // Vertical position of window $dxWn = 0x25BC; // Width of window $dyWn = 0x1572; // Height of window $grbit = 0x0038; // Option flags // not supported by PhpSpreadsheet, so there is only one selected sheet, the active $ctabsel = 1; // Number of workbook tabs selected $wTabRatio = 0x0258; // Tab to scrollbar ratio // not supported by PhpSpreadsheet, set to 0 $itabFirst = 0; // 1st displayed worksheet $itabCur = $this->spreadsheet->getActiveSheetIndex(); // Active worksheet $header = pack('vv', $record, $length); $data = pack('vvvvvvvvv', $xWn, $yWn, $dxWn, $dyWn, $grbit, $itabCur, $itabFirst, $ctabsel, $wTabRatio); $this->append($header . $data); } /** * Writes Excel BIFF BOUNDSHEET record. * * @param int $offset Location of worksheet BOF */ private function writeBoundSheet(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet, $offset): void { $sheetname = $sheet->getTitle(); $record = 0x0085; // Record identifier // sheet state switch ($sheet->getSheetState()) { case \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VISIBLE: $ss = 0x00; break; case \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_HIDDEN: $ss = 0x01; break; case \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VERYHIDDEN: $ss = 0x02; break; default: $ss = 0x00; break; } // sheet type $st = 0x00; //$grbit = 0x0000; // Visibility and sheet type $data = pack('VCC', $offset, $ss, $st); $data .= StringHelper::UTF8toBIFF8UnicodeShort($sheetname); $length = strlen($data); $header = pack('vv', $record, $length); $this->append($header . $data); } /** * Write Internal SUPBOOK record. */ private function writeSupbookInternal(): string { $record = 0x01AE; // Record identifier $length = 0x0004; // Bytes to follow $header = pack('vv', $record, $length); $data = pack('vv', $this->spreadsheet->getSheetCount(), 0x0401); return $this->writeData($header . $data); } /** * Writes the Excel BIFF EXTERNSHEET record. These references are used by * formulas. */ private function writeExternalsheetBiff8(): string { $totalReferences = count($this->parser->references); $record = 0x0017; // Record identifier $length = 2 + 6 * $totalReferences; // Number of bytes to follow //$supbook_index = 0; // FIXME: only using internal SUPBOOK record $header = pack('vv', $record, $length); $data = pack('v', $totalReferences); for ($i = 0; $i < $totalReferences; ++$i) { $data .= $this->parser->references[$i]; } return $this->writeData($header . $data); } /** * Write Excel BIFF STYLE records. */ private function writeStyle(): void { $record = 0x0293; // Record identifier $length = 0x0004; // Bytes to follow $ixfe = 0x8000; // Index to cell style XF $BuiltIn = 0x00; // Built-in style $iLevel = 0xff; // Outline style level $header = pack('vv', $record, $length); $data = pack('vCC', $ixfe, $BuiltIn, $iLevel); $this->append($header . $data); } /** * Writes Excel FORMAT record for non "built-in" numerical formats. * * @param string $format Custom format string * @param int $ifmt Format index code */ private function writeNumberFormat($format, $ifmt): void { $record = 0x041E; // Record identifier $numberFormatString = StringHelper::UTF8toBIFF8UnicodeLong($format); $length = 2 + strlen($numberFormatString); // Number of bytes to follow $header = pack('vv', $record, $length); $data = pack('v', $ifmt) . $numberFormatString; $this->append($header . $data); } /** * Write DATEMODE record to indicate the date system in use (1904 or 1900). */ private function writeDateMode(): void { $record = 0x0022; // Record identifier $length = 0x0002; // Bytes to follow $f1904 = (Date::getExcelCalendar() === Date::CALENDAR_MAC_1904) ? 1 : 0; // Flag for 1904 date system $header = pack('vv', $record, $length); $data = pack('v', $f1904); $this->append($header . $data); } /** * Stores the COUNTRY record for localization. * * @return string */ private function writeCountry() { $record = 0x008C; // Record identifier $length = 4; // Number of bytes to follow $header = pack('vv', $record, $length); // using the same country code always for simplicity $data = pack('vv', $this->countryCode, $this->countryCode); return $this->writeData($header . $data); } /** * Write the RECALCID record. * * @return string */ private function writeRecalcId() { $record = 0x01C1; // Record identifier $length = 8; // Number of bytes to follow $header = pack('vv', $record, $length); // by inspection of real Excel files, MS Office Excel 2007 writes this $data = pack('VV', 0x000001C1, 0x00001E667); return $this->writeData($header . $data); } /** * Stores the PALETTE biff record. */ private function writePalette(): void { $aref = $this->palette; $record = 0x0092; // Record identifier $length = 2 + 4 * count($aref); // Number of bytes to follow $ccv = count($aref); // Number of RGB values to follow $data = ''; // The RGB data // Pack the RGB data foreach ($aref as $color) { foreach ($color as $byte) { $data .= pack('C', $byte); } } $header = pack('vvv', $record, $length, $ccv); $this->append($header . $data); } /** * Handling of the SST continue blocks is complicated by the need to include an * additional continuation byte depending on whether the string is split between * blocks or whether it starts at the beginning of the block. (There are also * additional complications that will arise later when/if Rich Strings are * supported). * * The Excel documentation says that the SST record should be followed by an * EXTSST record. The EXTSST record is a hash table that is used to optimise * access to SST. However, despite the documentation it doesn't seem to be * required so we will ignore it. * * @return string Binary data */ private function writeSharedStringsTable() { // maximum size of record data (excluding record header) $continue_limit = 8224; // initialize array of record data blocks $recordDatas = []; // start SST record data block with total number of strings, total number of unique strings $recordData = pack('VV', $this->stringTotal, $this->stringUnique); // loop through all (unique) strings in shared strings table foreach (array_keys($this->stringTable) as $string) { // here $string is a BIFF8 encoded string // length = character count $headerinfo = unpack('vlength/Cencoding', $string); // currently, this is always 1 = uncompressed $encoding = $headerinfo['encoding'] ?? 1; // initialize finished writing current $string $finished = false; while ($finished === false) { // normally, there will be only one cycle, but if string cannot immediately be written as is // there will be need for more than one cylcle, if string longer than one record data block, there // may be need for even more cycles if (strlen($recordData) + strlen($string) <= $continue_limit) { // then we can write the string (or remainder of string) without any problems $recordData .= $string; if (strlen($recordData) + strlen($string) == $continue_limit) { // we close the record data block, and initialize a new one $recordDatas[] = $recordData; $recordData = ''; } // we are finished writing this string $finished = true; } else { // special treatment writing the string (or remainder of the string) // If the string is very long it may need to be written in more than one CONTINUE record. // check how many bytes more there is room for in the current record $space_remaining = $continue_limit - strlen($recordData); // minimum space needed // uncompressed: 2 byte string length length field + 1 byte option flags + 2 byte character // compressed: 2 byte string length length field + 1 byte option flags + 1 byte character $min_space_needed = ($encoding == 1) ? 5 : 4; // We have two cases // 1. space remaining is less than minimum space needed // here we must waste the space remaining and move to next record data block // 2. space remaining is greater than or equal to minimum space needed // here we write as much as we can in the current block, then move to next record data block if ($space_remaining < $min_space_needed) { // 1. space remaining is less than minimum space needed. // we close the block, store the block data $recordDatas[] = $recordData; // and start new record data block where we start writing the string $recordData = ''; } else { // 2. space remaining is greater than or equal to minimum space needed. // initialize effective remaining space, for Unicode strings this may need to be reduced by 1, see below $effective_space_remaining = $space_remaining; // for uncompressed strings, sometimes effective space remaining is reduced by 1 if ($encoding == 1 && (strlen($string) - $space_remaining) % 2 == 1) { --$effective_space_remaining; } // one block fininshed, store the block data $recordData .= substr($string, 0, $effective_space_remaining); $string = substr($string, $effective_space_remaining); // for next cycle in while loop $recordDatas[] = $recordData; // start new record data block with the repeated option flags $recordData = pack('C', $encoding); } } } } // Store the last record data block unless it is empty // if there was no need for any continue records, this will be the for SST record data block itself if (strlen($recordData) > 0) { $recordDatas[] = $recordData; } // combine into one chunk with all the blocks SST, CONTINUE,... $chunk = ''; foreach ($recordDatas as $i => $recordData) { // first block should have the SST record header, remaing should have CONTINUE header $record = ($i == 0) ? 0x00FC : 0x003C; $header = pack('vv', $record, strlen($recordData)); $data = $header . $recordData; $chunk .= $this->writeData($data); } return $chunk; } /** * Writes the MSODRAWINGGROUP record if needed. Possibly split using CONTINUE records. */ private function writeMsoDrawingGroup(): string { // write the Escher stream if necessary if (isset($this->escher)) { $writer = new Escher($this->escher); $data = $writer->close(); $record = 0x00EB; $length = strlen($data); $header = pack('vv', $record, $length); return $this->writeData($header . $data); } return ''; } /** * Get Escher object. */ public function getEscher(): ?\PhpOffice\PhpSpreadsheet\Shared\Escher { return $this->escher; } /** * Set Escher object. */ public function setEscher(?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher): void { $this->escher = $escher; } } phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Parser.php 0000644 00000153350 15002227416 0017266 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; // Original file header of PEAR::Spreadsheet_Excel_Writer_Parser (used as the base for this class): // ----------------------------------------------------------------------------------------- // * Class for parsing Excel formulas // * // * License Information: // * // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com // * // * This library is free software; you can redistribute it and/or // * modify it under the terms of the GNU Lesser General Public // * License as published by the Free Software Foundation; either // * version 2.1 of the License, or (at your option) any later version. // * // * This library is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // * Lesser General Public License for more details. // * // * You should have received a copy of the GNU Lesser General Public // * License along with this library; if not, write to the Free Software // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // */ class Parser { /** Constants */ // Sheet title in unquoted form // Invalid sheet title characters cannot occur in the sheet title: // *:/\?[] // Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?) // +-% '^&<>=,;#()"{} const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+'; // Sheet title in quoted form (without surrounding quotes) // Invalid sheet title characters cannot occur in the sheet title: // *:/\?[] (usual invalid sheet title characters) // Single quote is represented as a pair '' const REGEX_SHEET_TITLE_QUOTED = '(([^\*\:\/\\\\\?\[\]\\\'])+|(\\\'\\\')+)+'; /** * The index of the character we are currently looking at. * * @var int */ public $currentCharacter; /** * The token we are working on. * * @var string */ public $currentToken; /** * The formula to parse. * * @var string */ private $formula; /** * The character ahead of the current char. * * @var string */ public $lookAhead; /** * The parse tree to be generated. * * @var array|string */ public $parseTree; /** * Array of external sheets. * * @var array */ private $externalSheets; /** * Array of sheet references in the form of REF structures. * * @var array */ public $references; /** * The Excel ptg indices. * * @var array */ private $ptg = [ 'ptgExp' => 0x01, 'ptgTbl' => 0x02, 'ptgAdd' => 0x03, 'ptgSub' => 0x04, 'ptgMul' => 0x05, 'ptgDiv' => 0x06, 'ptgPower' => 0x07, 'ptgConcat' => 0x08, 'ptgLT' => 0x09, 'ptgLE' => 0x0A, 'ptgEQ' => 0x0B, 'ptgGE' => 0x0C, 'ptgGT' => 0x0D, 'ptgNE' => 0x0E, 'ptgIsect' => 0x0F, 'ptgUnion' => 0x10, 'ptgRange' => 0x11, 'ptgUplus' => 0x12, 'ptgUminus' => 0x13, 'ptgPercent' => 0x14, 'ptgParen' => 0x15, 'ptgMissArg' => 0x16, 'ptgStr' => 0x17, 'ptgAttr' => 0x19, 'ptgSheet' => 0x1A, 'ptgEndSheet' => 0x1B, 'ptgErr' => 0x1C, 'ptgBool' => 0x1D, 'ptgInt' => 0x1E, 'ptgNum' => 0x1F, 'ptgArray' => 0x20, 'ptgFunc' => 0x21, 'ptgFuncVar' => 0x22, 'ptgName' => 0x23, 'ptgRef' => 0x24, 'ptgArea' => 0x25, 'ptgMemArea' => 0x26, 'ptgMemErr' => 0x27, 'ptgMemNoMem' => 0x28, 'ptgMemFunc' => 0x29, 'ptgRefErr' => 0x2A, 'ptgAreaErr' => 0x2B, 'ptgRefN' => 0x2C, 'ptgAreaN' => 0x2D, 'ptgMemAreaN' => 0x2E, 'ptgMemNoMemN' => 0x2F, 'ptgNameX' => 0x39, 'ptgRef3d' => 0x3A, 'ptgArea3d' => 0x3B, 'ptgRefErr3d' => 0x3C, 'ptgAreaErr3d' => 0x3D, 'ptgArrayV' => 0x40, 'ptgFuncV' => 0x41, 'ptgFuncVarV' => 0x42, 'ptgNameV' => 0x43, 'ptgRefV' => 0x44, 'ptgAreaV' => 0x45, 'ptgMemAreaV' => 0x46, 'ptgMemErrV' => 0x47, 'ptgMemNoMemV' => 0x48, 'ptgMemFuncV' => 0x49, 'ptgRefErrV' => 0x4A, 'ptgAreaErrV' => 0x4B, 'ptgRefNV' => 0x4C, 'ptgAreaNV' => 0x4D, 'ptgMemAreaNV' => 0x4E, 'ptgMemNoMemNV' => 0x4F, 'ptgFuncCEV' => 0x58, 'ptgNameXV' => 0x59, 'ptgRef3dV' => 0x5A, 'ptgArea3dV' => 0x5B, 'ptgRefErr3dV' => 0x5C, 'ptgAreaErr3dV' => 0x5D, 'ptgArrayA' => 0x60, 'ptgFuncA' => 0x61, 'ptgFuncVarA' => 0x62, 'ptgNameA' => 0x63, 'ptgRefA' => 0x64, 'ptgAreaA' => 0x65, 'ptgMemAreaA' => 0x66, 'ptgMemErrA' => 0x67, 'ptgMemNoMemA' => 0x68, 'ptgMemFuncA' => 0x69, 'ptgRefErrA' => 0x6A, 'ptgAreaErrA' => 0x6B, 'ptgRefNA' => 0x6C, 'ptgAreaNA' => 0x6D, 'ptgMemAreaNA' => 0x6E, 'ptgMemNoMemNA' => 0x6F, 'ptgFuncCEA' => 0x78, 'ptgNameXA' => 0x79, 'ptgRef3dA' => 0x7A, 'ptgArea3dA' => 0x7B, 'ptgRefErr3dA' => 0x7C, 'ptgAreaErr3dA' => 0x7D, ]; /** * Thanks to Michael Meeks and Gnumeric for the initial arg values. * * The following hash was generated by "function_locale.pl" in the distro. * Refer to function_locale.pl for non-English function names. * * The array elements are as follow: * ptg: The Excel function ptg code. * args: The number of arguments that the function takes: * >=0 is a fixed number of arguments. * -1 is a variable number of arguments. * class: The reference, value or array class of the function args. * vol: The function is volatile. * * @var array */ private $functions = [ // function ptg args class vol 'COUNT' => [0, -1, 0, 0], 'IF' => [1, -1, 1, 0], 'ISNA' => [2, 1, 1, 0], 'ISERROR' => [3, 1, 1, 0], 'SUM' => [4, -1, 0, 0], 'AVERAGE' => [5, -1, 0, 0], 'MIN' => [6, -1, 0, 0], 'MAX' => [7, -1, 0, 0], 'ROW' => [8, -1, 0, 0], 'COLUMN' => [9, -1, 0, 0], 'NA' => [10, 0, 0, 0], 'NPV' => [11, -1, 1, 0], 'STDEV' => [12, -1, 0, 0], 'DOLLAR' => [13, -1, 1, 0], 'FIXED' => [14, -1, 1, 0], 'SIN' => [15, 1, 1, 0], 'COS' => [16, 1, 1, 0], 'TAN' => [17, 1, 1, 0], 'ATAN' => [18, 1, 1, 0], 'PI' => [19, 0, 1, 0], 'SQRT' => [20, 1, 1, 0], 'EXP' => [21, 1, 1, 0], 'LN' => [22, 1, 1, 0], 'LOG10' => [23, 1, 1, 0], 'ABS' => [24, 1, 1, 0], 'INT' => [25, 1, 1, 0], 'SIGN' => [26, 1, 1, 0], 'ROUND' => [27, 2, 1, 0], 'LOOKUP' => [28, -1, 0, 0], 'INDEX' => [29, -1, 0, 1], 'REPT' => [30, 2, 1, 0], 'MID' => [31, 3, 1, 0], 'LEN' => [32, 1, 1, 0], 'VALUE' => [33, 1, 1, 0], 'TRUE' => [34, 0, 1, 0], 'FALSE' => [35, 0, 1, 0], 'AND' => [36, -1, 0, 0], 'OR' => [37, -1, 0, 0], 'NOT' => [38, 1, 1, 0], 'MOD' => [39, 2, 1, 0], 'DCOUNT' => [40, 3, 0, 0], 'DSUM' => [41, 3, 0, 0], 'DAVERAGE' => [42, 3, 0, 0], 'DMIN' => [43, 3, 0, 0], 'DMAX' => [44, 3, 0, 0], 'DSTDEV' => [45, 3, 0, 0], 'VAR' => [46, -1, 0, 0], 'DVAR' => [47, 3, 0, 0], 'TEXT' => [48, 2, 1, 0], 'LINEST' => [49, -1, 0, 0], 'TREND' => [50, -1, 0, 0], 'LOGEST' => [51, -1, 0, 0], 'GROWTH' => [52, -1, 0, 0], 'PV' => [56, -1, 1, 0], 'FV' => [57, -1, 1, 0], 'NPER' => [58, -1, 1, 0], 'PMT' => [59, -1, 1, 0], 'RATE' => [60, -1, 1, 0], 'MIRR' => [61, 3, 0, 0], 'IRR' => [62, -1, 0, 0], 'RAND' => [63, 0, 1, 1], 'MATCH' => [64, -1, 0, 0], 'DATE' => [65, 3, 1, 0], 'TIME' => [66, 3, 1, 0], 'DAY' => [67, 1, 1, 0], 'MONTH' => [68, 1, 1, 0], 'YEAR' => [69, 1, 1, 0], 'WEEKDAY' => [70, -1, 1, 0], 'HOUR' => [71, 1, 1, 0], 'MINUTE' => [72, 1, 1, 0], 'SECOND' => [73, 1, 1, 0], 'NOW' => [74, 0, 1, 1], 'AREAS' => [75, 1, 0, 1], 'ROWS' => [76, 1, 0, 1], 'COLUMNS' => [77, 1, 0, 1], 'OFFSET' => [78, -1, 0, 1], 'SEARCH' => [82, -1, 1, 0], 'TRANSPOSE' => [83, 1, 1, 0], 'TYPE' => [86, 1, 1, 0], 'ATAN2' => [97, 2, 1, 0], 'ASIN' => [98, 1, 1, 0], 'ACOS' => [99, 1, 1, 0], 'CHOOSE' => [100, -1, 1, 0], 'HLOOKUP' => [101, -1, 0, 0], 'VLOOKUP' => [102, -1, 0, 0], 'ISREF' => [105, 1, 0, 0], 'LOG' => [109, -1, 1, 0], 'CHAR' => [111, 1, 1, 0], 'LOWER' => [112, 1, 1, 0], 'UPPER' => [113, 1, 1, 0], 'PROPER' => [114, 1, 1, 0], 'LEFT' => [115, -1, 1, 0], 'RIGHT' => [116, -1, 1, 0], 'EXACT' => [117, 2, 1, 0], 'TRIM' => [118, 1, 1, 0], 'REPLACE' => [119, 4, 1, 0], 'SUBSTITUTE' => [120, -1, 1, 0], 'CODE' => [121, 1, 1, 0], 'FIND' => [124, -1, 1, 0], 'CELL' => [125, -1, 0, 1], 'ISERR' => [126, 1, 1, 0], 'ISTEXT' => [127, 1, 1, 0], 'ISNUMBER' => [128, 1, 1, 0], 'ISBLANK' => [129, 1, 1, 0], 'T' => [130, 1, 0, 0], 'N' => [131, 1, 0, 0], 'DATEVALUE' => [140, 1, 1, 0], 'TIMEVALUE' => [141, 1, 1, 0], 'SLN' => [142, 3, 1, 0], 'SYD' => [143, 4, 1, 0], 'DDB' => [144, -1, 1, 0], 'INDIRECT' => [148, -1, 1, 1], 'CALL' => [150, -1, 1, 0], 'CLEAN' => [162, 1, 1, 0], 'MDETERM' => [163, 1, 2, 0], 'MINVERSE' => [164, 1, 2, 0], 'MMULT' => [165, 2, 2, 0], 'IPMT' => [167, -1, 1, 0], 'PPMT' => [168, -1, 1, 0], 'COUNTA' => [169, -1, 0, 0], 'PRODUCT' => [183, -1, 0, 0], 'FACT' => [184, 1, 1, 0], 'DPRODUCT' => [189, 3, 0, 0], 'ISNONTEXT' => [190, 1, 1, 0], 'STDEVP' => [193, -1, 0, 0], 'VARP' => [194, -1, 0, 0], 'DSTDEVP' => [195, 3, 0, 0], 'DVARP' => [196, 3, 0, 0], 'TRUNC' => [197, -1, 1, 0], 'ISLOGICAL' => [198, 1, 1, 0], 'DCOUNTA' => [199, 3, 0, 0], 'USDOLLAR' => [204, -1, 1, 0], 'FINDB' => [205, -1, 1, 0], 'SEARCHB' => [206, -1, 1, 0], 'REPLACEB' => [207, 4, 1, 0], 'LEFTB' => [208, -1, 1, 0], 'RIGHTB' => [209, -1, 1, 0], 'MIDB' => [210, 3, 1, 0], 'LENB' => [211, 1, 1, 0], 'ROUNDUP' => [212, 2, 1, 0], 'ROUNDDOWN' => [213, 2, 1, 0], 'ASC' => [214, 1, 1, 0], 'DBCS' => [215, 1, 1, 0], 'RANK' => [216, -1, 0, 0], 'ADDRESS' => [219, -1, 1, 0], 'DAYS360' => [220, -1, 1, 0], 'TODAY' => [221, 0, 1, 1], 'VDB' => [222, -1, 1, 0], 'MEDIAN' => [227, -1, 0, 0], 'SUMPRODUCT' => [228, -1, 2, 0], 'SINH' => [229, 1, 1, 0], 'COSH' => [230, 1, 1, 0], 'TANH' => [231, 1, 1, 0], 'ASINH' => [232, 1, 1, 0], 'ACOSH' => [233, 1, 1, 0], 'ATANH' => [234, 1, 1, 0], 'DGET' => [235, 3, 0, 0], 'INFO' => [244, 1, 1, 1], 'DB' => [247, -1, 1, 0], 'FREQUENCY' => [252, 2, 0, 0], 'ERROR.TYPE' => [261, 1, 1, 0], 'REGISTER.ID' => [267, -1, 1, 0], 'AVEDEV' => [269, -1, 0, 0], 'BETADIST' => [270, -1, 1, 0], 'GAMMALN' => [271, 1, 1, 0], 'BETAINV' => [272, -1, 1, 0], 'BINOMDIST' => [273, 4, 1, 0], 'CHIDIST' => [274, 2, 1, 0], 'CHIINV' => [275, 2, 1, 0], 'COMBIN' => [276, 2, 1, 0], 'CONFIDENCE' => [277, 3, 1, 0], 'CRITBINOM' => [278, 3, 1, 0], 'EVEN' => [279, 1, 1, 0], 'EXPONDIST' => [280, 3, 1, 0], 'FDIST' => [281, 3, 1, 0], 'FINV' => [282, 3, 1, 0], 'FISHER' => [283, 1, 1, 0], 'FISHERINV' => [284, 1, 1, 0], 'FLOOR' => [285, 2, 1, 0], 'GAMMADIST' => [286, 4, 1, 0], 'GAMMAINV' => [287, 3, 1, 0], 'CEILING' => [288, 2, 1, 0], 'HYPGEOMDIST' => [289, 4, 1, 0], 'LOGNORMDIST' => [290, 3, 1, 0], 'LOGINV' => [291, 3, 1, 0], 'NEGBINOMDIST' => [292, 3, 1, 0], 'NORMDIST' => [293, 4, 1, 0], 'NORMSDIST' => [294, 1, 1, 0], 'NORMINV' => [295, 3, 1, 0], 'NORMSINV' => [296, 1, 1, 0], 'STANDARDIZE' => [297, 3, 1, 0], 'ODD' => [298, 1, 1, 0], 'PERMUT' => [299, 2, 1, 0], 'POISSON' => [300, 3, 1, 0], 'TDIST' => [301, 3, 1, 0], 'WEIBULL' => [302, 4, 1, 0], 'SUMXMY2' => [303, 2, 2, 0], 'SUMX2MY2' => [304, 2, 2, 0], 'SUMX2PY2' => [305, 2, 2, 0], 'CHITEST' => [306, 2, 2, 0], 'CORREL' => [307, 2, 2, 0], 'COVAR' => [308, 2, 2, 0], 'FORECAST' => [309, 3, 2, 0], 'FTEST' => [310, 2, 2, 0], 'INTERCEPT' => [311, 2, 2, 0], 'PEARSON' => [312, 2, 2, 0], 'RSQ' => [313, 2, 2, 0], 'STEYX' => [314, 2, 2, 0], 'SLOPE' => [315, 2, 2, 0], 'TTEST' => [316, 4, 2, 0], 'PROB' => [317, -1, 2, 0], 'DEVSQ' => [318, -1, 0, 0], 'GEOMEAN' => [319, -1, 0, 0], 'HARMEAN' => [320, -1, 0, 0], 'SUMSQ' => [321, -1, 0, 0], 'KURT' => [322, -1, 0, 0], 'SKEW' => [323, -1, 0, 0], 'ZTEST' => [324, -1, 0, 0], 'LARGE' => [325, 2, 0, 0], 'SMALL' => [326, 2, 0, 0], 'QUARTILE' => [327, 2, 0, 0], 'PERCENTILE' => [328, 2, 0, 0], 'PERCENTRANK' => [329, -1, 0, 0], 'MODE' => [330, -1, 2, 0], 'TRIMMEAN' => [331, 2, 0, 0], 'TINV' => [332, 2, 1, 0], 'CONCATENATE' => [336, -1, 1, 0], 'POWER' => [337, 2, 1, 0], 'RADIANS' => [342, 1, 1, 0], 'DEGREES' => [343, 1, 1, 0], 'SUBTOTAL' => [344, -1, 0, 0], 'SUMIF' => [345, -1, 0, 0], 'COUNTIF' => [346, 2, 0, 0], 'COUNTBLANK' => [347, 1, 0, 0], 'ISPMT' => [350, 4, 1, 0], 'DATEDIF' => [351, 3, 1, 0], 'DATESTRING' => [352, 1, 1, 0], 'NUMBERSTRING' => [353, 2, 1, 0], 'ROMAN' => [354, -1, 1, 0], 'GETPIVOTDATA' => [358, -1, 0, 0], 'HYPERLINK' => [359, -1, 1, 0], 'PHONETIC' => [360, 1, 0, 0], 'AVERAGEA' => [361, -1, 0, 0], 'MAXA' => [362, -1, 0, 0], 'MINA' => [363, -1, 0, 0], 'STDEVPA' => [364, -1, 0, 0], 'VARPA' => [365, -1, 0, 0], 'STDEVA' => [366, -1, 0, 0], 'VARA' => [367, -1, 0, 0], 'BAHTTEXT' => [368, 1, 0, 0], ]; /** @var Spreadsheet */ private $spreadsheet; /** * The class constructor. */ public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; $this->currentCharacter = 0; $this->currentToken = ''; // The token we are working on. $this->formula = ''; // The formula to parse. $this->lookAhead = ''; // The character ahead of the current char. $this->parseTree = ''; // The parse tree to be generated. $this->externalSheets = []; $this->references = []; } /** * Convert a token to the proper ptg value. * * @param mixed $token the token to convert * * @return mixed the converted token on success */ private function convert($token) { if (preg_match('/"([^"]|""){0,255}"/', $token)) { return $this->convertString($token); } if (is_numeric($token)) { return $this->convertNumber($token); } // match references like A1 or $A$1 if (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/', $token)) { return $this->convertRef2d($token); } // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1 if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?(\\d+)$/u', $token)) { return $this->convertRef3d($token); } // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1 if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\\d+)$/u", $token)) { return $this->convertRef3d($token); } // match ranges like A1:B2 or $A$1:$B$2 if (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) { return $this->convertRange2d($token); } // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2 if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?(\\d+)\\:\$?([A-Ia-i]?[A-Za-z])?\$?(\\d+)$/u', $token)) { return $this->convertRange3d($token); } // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2 if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\\d+)\\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\\d+)$/u", $token)) { return $this->convertRange3d($token); } // operators (including parentheses) if (isset($this->ptg[$token])) { return pack('C', $this->ptg[$token]); } // match error codes if (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) || $token == '#N/A') { return $this->convertError($token); } if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $token) && $this->spreadsheet->getDefinedName($token) !== null) { return $this->convertDefinedName($token); } // commented so argument number can be processed correctly. See toReversePolish(). /*if (preg_match("/[A-Z0-9\xc0-\xdc\.]+/", $token)) { return($this->convertFunction($token, $this->_func_args)); }*/ // if it's an argument, ignore the token (the argument remains) if ($token == 'arg') { return ''; } if (preg_match('/^true$/i', $token)) { return $this->convertBool(1); } if (preg_match('/^false$/i', $token)) { return $this->convertBool(0); } // TODO: use real error codes throw new WriterException("Unknown token $token"); } /** * Convert a number token to ptgInt or ptgNum. * * @param mixed $num an integer or double for conversion to its ptg value * * @return string */ private function convertNumber($num) { // Integer in the range 0..2**16-1 if ((preg_match('/^\\d+$/', $num)) && ($num <= 65535)) { return pack('Cv', $this->ptg['ptgInt'], $num); } // A float if (BIFFwriter::getByteOrder()) { // if it's Big Endian $num = strrev($num); } return pack('Cd', $this->ptg['ptgNum'], $num); } private function convertBool(int $num): string { return pack('CC', $this->ptg['ptgBool'], $num); } /** * Convert a string token to ptgStr. * * @param string $string a string for conversion to its ptg value * * @return mixed the converted token on success */ private function convertString($string) { // chop away beggining and ending quotes $string = substr($string, 1, -1); if (strlen($string) > 255) { throw new WriterException('String is too long'); } return pack('C', $this->ptg['ptgStr']) . StringHelper::UTF8toBIFF8UnicodeShort($string); } /** * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of * args that it takes. * * @param string $token the name of the function for convertion to ptg value * @param int $num_args the number of arguments the function receives * * @return string The packed ptg for the function */ private function convertFunction($token, $num_args) { $args = $this->functions[$token][1]; // Fixed number of args eg. TIME($i, $j, $k). if ($args >= 0) { return pack('Cv', $this->ptg['ptgFuncV'], $this->functions[$token][0]); } // Variable number of args eg. SUM($i, $j, $k, ..). return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]); } /** * Convert an Excel range such as A1:D4 to a ptgRefV. * * @param string $range An Excel range in the A1:A2 * @param int $class * * @return string */ private function convertRange2d($range, $class = 0) { // TODO: possible class value 0,1,2 check Formula.pm // Split the range into 2 cell refs if (preg_match('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) { [$cell1, $cell2] = explode(':', $range); } else { // TODO: use real error codes throw new WriterException('Unknown range separator'); } // Convert the cell references [$row1, $col1] = $this->cellToPackedRowcol($cell1); [$row2, $col2] = $this->cellToPackedRowcol($cell2); // The ptg value depends on the class of the ptg. if ($class == 0) { $ptgArea = pack('C', $this->ptg['ptgArea']); } elseif ($class == 1) { $ptgArea = pack('C', $this->ptg['ptgAreaV']); } elseif ($class == 2) { $ptgArea = pack('C', $this->ptg['ptgAreaA']); } else { // TODO: use real error codes throw new WriterException("Unknown class $class"); } return $ptgArea . $row1 . $row2 . $col1 . $col2; } /** * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to * a ptgArea3d. * * @param string $token an Excel range in the Sheet1!A1:A2 format * * @return mixed the packed ptgArea3d token on success */ private function convertRange3d($token) { // Split the ref at the ! symbol [$ext_ref, $range] = PhpspreadsheetWorksheet::extractSheetTitle($token, true); // Convert the external reference part (different for BIFF8) $ext_ref = $this->getRefIndex($ext_ref); // Split the range into 2 cell refs [$cell1, $cell2] = explode(':', $range); // Convert the cell references if (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\\d+)$/', $cell1)) { [$row1, $col1] = $this->cellToPackedRowcol($cell1); [$row2, $col2] = $this->cellToPackedRowcol($cell2); } else { // It's a rows range (like 26:27) [$row1, $col1, $row2, $col2] = $this->rangeToPackedRange($cell1 . ':' . $cell2); } // The ptg value depends on the class of the ptg. $ptgArea = pack('C', $this->ptg['ptgArea3d']); return $ptgArea . $ext_ref . $row1 . $row2 . $col1 . $col2; } /** * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV. * * @param string $cell An Excel cell reference * * @return string The cell in packed() format with the corresponding ptg */ private function convertRef2d($cell) { // Convert the cell reference $cell_array = $this->cellToPackedRowcol($cell); [$row, $col] = $cell_array; // The ptg value depends on the class of the ptg. $ptgRef = pack('C', $this->ptg['ptgRefA']); return $ptgRef . $row . $col; } /** * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a * ptgRef3d. * * @param string $cell An Excel cell reference * * @return mixed the packed ptgRef3d token on success */ private function convertRef3d($cell) { // Split the ref at the ! symbol [$ext_ref, $cell] = PhpspreadsheetWorksheet::extractSheetTitle($cell, true); // Convert the external reference part (different for BIFF8) $ext_ref = $this->getRefIndex($ext_ref); // Convert the cell reference part [$row, $col] = $this->cellToPackedRowcol($cell); // The ptg value depends on the class of the ptg. $ptgRef = pack('C', $this->ptg['ptgRef3dA']); return $ptgRef . $ext_ref . $row . $col; } /** * Convert an error code to a ptgErr. * * @param string $errorCode The error code for conversion to its ptg value * * @return string The error code ptgErr */ private function convertError($errorCode) { switch ($errorCode) { case '#NULL!': return pack('C', 0x00); case '#DIV/0!': return pack('C', 0x07); case '#VALUE!': return pack('C', 0x0F); case '#REF!': return pack('C', 0x17); case '#NAME?': return pack('C', 0x1D); case '#NUM!': return pack('C', 0x24); case '#N/A': return pack('C', 0x2A); } return pack('C', 0xFF); } /** @var bool */ private $tryDefinedName = false; private function convertDefinedName(string $name): string { if (strlen($name) > 255) { throw new WriterException('Defined Name is too long'); } if ($this->tryDefinedName) { // @codeCoverageIgnoreStart $nameReference = 1; foreach ($this->spreadsheet->getDefinedNames() as $definedName) { if ($name === $definedName->getName()) { break; } ++$nameReference; } $ptgRef = pack('Cvxx', $this->ptg['ptgName'], $nameReference); return $ptgRef; // @codeCoverageIgnoreEnd } throw new WriterException('Cannot yet write formulae with defined names to Xls'); } /** * Look up the REF index that corresponds to an external sheet name * (or range). If it doesn't exist yet add it to the workbook's references * array. It assumes all sheet names given must exist. * * @param string $ext_ref The name of the external reference * * @return mixed The reference index in packed() format on success */ private function getRefIndex($ext_ref) { $ext_ref = (string) preg_replace(["/^'/", "/'$/"], ['', ''], $ext_ref); // Remove leading and trailing ' if any. $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with ' // Check if there is a sheet range eg., Sheet1:Sheet2. if (preg_match('/:/', $ext_ref)) { [$sheet_name1, $sheet_name2] = explode(':', $ext_ref); $sheet1 = $this->getSheetIndex($sheet_name1); if ($sheet1 == -1) { throw new WriterException("Unknown sheet name $sheet_name1 in formula"); } $sheet2 = $this->getSheetIndex($sheet_name2); if ($sheet2 == -1) { throw new WriterException("Unknown sheet name $sheet_name2 in formula"); } // Reverse max and min sheet numbers if necessary if ($sheet1 > $sheet2) { [$sheet1, $sheet2] = [$sheet2, $sheet1]; } } else { // Single sheet name only. $sheet1 = $this->getSheetIndex($ext_ref); if ($sheet1 == -1) { throw new WriterException("Unknown sheet name $ext_ref in formula"); } $sheet2 = $sheet1; } // assume all references belong to this document $supbook_index = 0x00; $ref = pack('vvv', $supbook_index, $sheet1, $sheet2); $totalreferences = count($this->references); $index = -1; for ($i = 0; $i < $totalreferences; ++$i) { if ($ref == $this->references[$i]) { $index = $i; break; } } // if REF was not found add it to references array if ($index == -1) { $this->references[$totalreferences] = $ref; $index = $totalreferences; } return pack('v', $index); } /** * Look up the index that corresponds to an external sheet name. The hash of * sheet names is updated by the addworksheet() method of the * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class. * * @param string $sheet_name Sheet name * * @return int The sheet index, -1 if the sheet was not found */ private function getSheetIndex($sheet_name) { if (!isset($this->externalSheets[$sheet_name])) { return -1; } return $this->externalSheets[$sheet_name]; } /** * This method is used to update the array of sheet names. It is * called by the addWorksheet() method of the * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class. * * @param string $name The name of the worksheet being added * @param int $index The index of the worksheet being added * * @see \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook::addWorksheet() */ public function setExtSheet($name, $index): void { $this->externalSheets[$name] = $index; } /** * pack() row and column into the required 3 or 4 byte format. * * @param string $cell The Excel cell reference to be packed * * @return array Array containing the row and column in packed() format */ private function cellToPackedRowcol($cell) { $cell = strtoupper($cell); [$row, $col, $row_rel, $col_rel] = $this->cellToRowcol($cell); if ($col >= 256) { throw new WriterException("Column in: $cell greater than 255"); } if ($row >= 65536) { throw new WriterException("Row in: $cell greater than 65536 "); } // Set the high bits to indicate if row or col are relative. $col |= $col_rel << 14; $col |= $row_rel << 15; $col = pack('v', $col); $row = pack('v', $row); return [$row, $col]; } /** * pack() row range into the required 3 or 4 byte format. * Just using maximum col/rows, which is probably not the correct solution. * * @param string $range The Excel range to be packed * * @return array Array containing (row1,col1,row2,col2) in packed() format */ private function rangeToPackedRange($range) { preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match); // return absolute rows if there is a $ in the ref $row1_rel = empty($match[1]) ? 1 : 0; $row1 = $match[2]; $row2_rel = empty($match[3]) ? 1 : 0; $row2 = $match[4]; // Convert 1-index to zero-index --$row1; --$row2; // Trick poor inocent Excel $col1 = 0; $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!) // FIXME: this changes for BIFF8 if (($row1 >= 65536) || ($row2 >= 65536)) { throw new WriterException("Row in: $range greater than 65536 "); } // Set the high bits to indicate if rows are relative. $col1 |= $row1_rel << 15; $col2 |= $row2_rel << 15; $col1 = pack('v', $col1); $col2 = pack('v', $col2); $row1 = pack('v', $row1); $row2 = pack('v', $row2); return [$row1, $col1, $row2, $col2]; } /** * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero * indexed row and column number. Also returns two (0,1) values to indicate * whether the row or column are relative references. * * @param string $cell the Excel cell reference in A1 format * * @return array */ private function cellToRowcol($cell) { preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/', $cell, $match); // return absolute column if there is a $ in the ref $col_rel = empty($match[1]) ? 1 : 0; $col_ref = $match[2]; $row_rel = empty($match[3]) ? 1 : 0; $row = $match[4]; // Convert base26 column string to a number. $expn = strlen($col_ref) - 1; $col = 0; $col_ref_length = strlen($col_ref); for ($i = 0; $i < $col_ref_length; ++$i) { $col += (ord($col_ref[$i]) - 64) * 26 ** $expn; --$expn; } // Convert 1-index to zero-index --$row; --$col; return [$row, $col, $row_rel, $col_rel]; } /** * Advance to the next valid token. */ private function advance(): void { $token = ''; $i = $this->currentCharacter; $formula_length = strlen($this->formula); // eat up white spaces if ($i < $formula_length) { while ($this->formula[$i] == ' ') { ++$i; } if ($i < ($formula_length - 1)) { $this->lookAhead = $this->formula[$i + 1]; } $token = ''; } while ($i < $formula_length) { $token .= $this->formula[$i]; if ($i < ($formula_length - 1)) { $this->lookAhead = $this->formula[$i + 1]; } else { $this->lookAhead = ''; } if ($this->match($token) != '') { $this->currentCharacter = $i + 1; $this->currentToken = $token; return; } if ($i < ($formula_length - 2)) { $this->lookAhead = $this->formula[$i + 2]; } else { // if we run out of characters lookAhead becomes empty $this->lookAhead = ''; } ++$i; } //die("Lexical error ".$this->currentCharacter); } /** * Checks if it's a valid token. * * @param mixed $token the token to check * * @return mixed The checked token or false on failure */ private function match($token) { switch ($token) { case '+': case '-': case '*': case '/': case '(': case ')': case ',': case ';': case '>=': case '<=': case '=': case '<>': case '^': case '&': case '%': return $token; case '>': if ($this->lookAhead === '=') { // it's a GE token break; } return $token; case '<': // it's a LE or a NE token if (($this->lookAhead === '=') || ($this->lookAhead === '>')) { break; } return $token; } // if it's a reference A1 or $A$1 or $A1 or A$1 if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.') && ($this->lookAhead !== '!')) { return $token; } // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u', $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.')) { return $token; } // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?[A-Ia-i]?[A-Za-z]\\$?\\d+$/u", $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.')) { return $token; } // if it's a range A1:A2 or $A$1:$A$2 if (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $token) && !preg_match('/\d/', $this->lookAhead)) { return $token; } // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2 if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u', $token) && !preg_match('/\d/', $this->lookAhead)) { return $token; } // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2 if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+:\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+$/u", $token) && !preg_match('/\d/', $this->lookAhead)) { return $token; } // If it's a number (check that it's not a sheet name or range) if (is_numeric($token) && (!is_numeric($token . $this->lookAhead) || ($this->lookAhead == '')) && ($this->lookAhead !== '!') && ($this->lookAhead !== ':')) { return $token; } if (preg_match('/"([^"]|""){0,255}"/', $token) && $this->lookAhead !== '"' && (substr_count($token, '"') % 2 == 0)) { // If it's a string (of maximum 255 characters) return $token; } // If it's an error code if (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) || $token === '#N/A') { return $token; } // if it's a function call if (preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $token) && ($this->lookAhead === '(')) { return $token; } if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token) && $this->spreadsheet->getDefinedName($token) !== null) { return $token; } if (preg_match('/^true$/i', $token) && ($this->lookAhead === ')' || $this->lookAhead === ',')) { return $token; } if (preg_match('/^false$/i', $token) && ($this->lookAhead === ')' || $this->lookAhead === ',')) { return $token; } if (substr($token, -1) === ')') { // It's an argument of some description (e.g. a named range), // precise nature yet to be determined return $token; } return ''; } /** * The parsing method. It parses a formula. * * @param string $formula the formula to parse, without the initial equal * sign (=) * * @return mixed true on success */ public function parse($formula) { $this->currentCharacter = 0; $this->formula = (string) $formula; $this->lookAhead = $formula[1] ?? ''; $this->advance(); $this->parseTree = $this->condition(); return true; } /** * It parses a condition. It assumes the following rule: * Cond -> Expr [(">" | "<") Expr]. * * @return mixed The parsed ptg'd tree on success */ private function condition() { $result = $this->expression(); if ($this->currentToken == '<') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgLT', $result, $result2); } elseif ($this->currentToken == '>') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgGT', $result, $result2); } elseif ($this->currentToken == '<=') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgLE', $result, $result2); } elseif ($this->currentToken == '>=') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgGE', $result, $result2); } elseif ($this->currentToken == '=') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgEQ', $result, $result2); } elseif ($this->currentToken == '<>') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgNE', $result, $result2); } return $result; } /** * It parses a expression. It assumes the following rule: * Expr -> Term [("+" | "-") Term] * -> "string" * -> "-" Term : Negative value * -> "+" Term : Positive value * -> Error code. * * @return mixed The parsed ptg'd tree on success */ private function expression() { // If it's a string return a string node if (preg_match('/"([^"]|""){0,255}"/', $this->currentToken)) { $tmp = str_replace('""', '"', $this->currentToken); if (($tmp == '"') || ($tmp == '')) { // Trap for "" that has been used for an empty string $tmp = '""'; } $result = $this->createTree($tmp, '', ''); $this->advance(); return $result; } elseif (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $this->currentToken) || $this->currentToken == '#N/A') { // error code $result = $this->createTree($this->currentToken, 'ptgErr', ''); $this->advance(); return $result; } elseif ($this->currentToken == '-') { // negative value // catch "-" Term $this->advance(); $result2 = $this->expression(); return $this->createTree('ptgUminus', $result2, ''); } elseif ($this->currentToken == '+') { // positive value // catch "+" Term $this->advance(); $result2 = $this->expression(); return $this->createTree('ptgUplus', $result2, ''); } $result = $this->term(); while ($this->currentToken === '&') { $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgConcat', $result, $result2); } while ( ($this->currentToken == '+') || ($this->currentToken == '-') || ($this->currentToken == '^') ) { if ($this->currentToken == '+') { $this->advance(); $result2 = $this->term(); $result = $this->createTree('ptgAdd', $result, $result2); } elseif ($this->currentToken == '-') { $this->advance(); $result2 = $this->term(); $result = $this->createTree('ptgSub', $result, $result2); } else { $this->advance(); $result2 = $this->term(); $result = $this->createTree('ptgPower', $result, $result2); } } return $result; } /** * This function just introduces a ptgParen element in the tree, so that Excel * doesn't get confused when working with a parenthesized formula afterwards. * * @return array The parsed ptg'd tree * * @see fact() */ private function parenthesizedExpression() { return $this->createTree('ptgParen', $this->expression(), ''); } /** * It parses a term. It assumes the following rule: * Term -> Fact [("*" | "/") Fact]. * * @return mixed The parsed ptg'd tree on success */ private function term() { $result = $this->fact(); while ( ($this->currentToken == '*') || ($this->currentToken == '/') ) { if ($this->currentToken == '*') { $this->advance(); $result2 = $this->fact(); $result = $this->createTree('ptgMul', $result, $result2); } else { $this->advance(); $result2 = $this->fact(); $result = $this->createTree('ptgDiv', $result, $result2); } } return $result; } /** * It parses a factor. It assumes the following rule: * Fact -> ( Expr ) * | CellRef * | CellRange * | Number * | Function. * * @return mixed The parsed ptg'd tree on success */ private function fact() { $currentToken = $this->currentToken; if ($currentToken === '(') { $this->advance(); // eat the "(" $result = $this->parenthesizedExpression(); if ($this->currentToken !== ')') { throw new WriterException("')' token expected."); } $this->advance(); // eat the ")" return $result; } // if it's a reference if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $this->currentToken)) { $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u', $this->currentToken)) { // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?[A-Ia-i]?[A-Za-z]\\$?\\d+$/u", $this->currentToken)) { // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if ( preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $this->currentToken) || preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $this->currentToken) ) { // if it's a range A1:B2 or $A$1:$B$2 // must be an error? $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u', $this->currentToken)) { // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2) // must be an error? $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+:\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+$/u", $this->currentToken)) { // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2) // must be an error? $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } if (is_numeric($this->currentToken)) { // If it's a number or a percent if ($this->lookAhead === '%') { $result = $this->createTree('ptgPercent', $this->currentToken, ''); $this->advance(); // Skip the percentage operator once we've pre-built that tree } else { $result = $this->createTree($this->currentToken, '', ''); } $this->advance(); return $result; } if (preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $this->currentToken) && ($this->lookAhead === '(')) { // if it's a function call return $this->func(); } if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $this->currentToken) && $this->spreadsheet->getDefinedName($this->currentToken) !== null) { $result = $this->createTree('ptgName', $this->currentToken, ''); $this->advance(); return $result; } if (preg_match('/^true|false$/i', $this->currentToken)) { $result = $this->createTree($this->currentToken, '', ''); $this->advance(); return $result; } throw new WriterException('Syntax error: ' . $this->currentToken . ', lookahead: ' . $this->lookAhead . ', current char: ' . $this->currentCharacter); } /** * It parses a function call. It assumes the following rule: * Func -> ( Expr [,Expr]* ). * * @return mixed The parsed ptg'd tree on success */ private function func() { $num_args = 0; // number of arguments received $function = strtoupper($this->currentToken); $result = ''; // initialize result $this->advance(); $this->advance(); // eat the "(" while ($this->currentToken !== ')') { if ($num_args > 0) { if ($this->currentToken === ',' || $this->currentToken === ';') { $this->advance(); // eat the "," or ";" } else { throw new WriterException("Syntax error: comma expected in function $function, arg #{$num_args}"); } $result2 = $this->condition(); $result = $this->createTree('arg', $result, $result2); } else { // first argument $result2 = $this->condition(); $result = $this->createTree('arg', '', $result2); } ++$num_args; } if (!isset($this->functions[$function])) { throw new WriterException("Function $function() doesn't exist"); } $args = $this->functions[$function][1]; // If fixed number of args eg. TIME($i, $j, $k). Check that the number of args is valid. if (($args >= 0) && ($args != $num_args)) { throw new WriterException("Incorrect number of arguments in function $function() "); } $result = $this->createTree($function, $result, $num_args); $this->advance(); // eat the ")" return $result; } /** * Creates a tree. In fact an array which may have one or two arrays (sub-trees) * as elements. * * @param mixed $value the value of this node * @param mixed $left the left array (sub-tree) or a final node * @param mixed $right the right array (sub-tree) or a final node * * @return array A tree */ private function createTree($value, $left, $right) { return ['value' => $value, 'left' => $left, 'right' => $right]; } /** * Builds a string containing the tree in reverse polish notation (What you * would use in a HP calculator stack). * The following tree:. * * + * / \ * 2 3 * * produces: "23+" * * The following tree: * * + * / \ * 3 * * / \ * 6 A1 * * produces: "36A1*+" * * In fact all operands, functions, references, etc... are written as ptg's * * @param array $tree the optional tree to convert * * @return string The tree in reverse polish notation */ public function toReversePolish($tree = []) { $polish = ''; // the string we are going to return if (empty($tree)) { // If it's the first call use parseTree $tree = $this->parseTree; } if (!is_array($tree) || !isset($tree['left'], $tree['right'], $tree['value'])) { throw new WriterException('Unexpected non-array'); } if (is_array($tree['left'])) { $converted_tree = $this->toReversePolish($tree['left']); $polish .= $converted_tree; } elseif ($tree['left'] != '') { // It's a final node $converted_tree = $this->convert($tree['left']); $polish .= $converted_tree; } if (is_array($tree['right'])) { $converted_tree = $this->toReversePolish($tree['right']); $polish .= $converted_tree; } elseif ($tree['right'] != '') { // It's a final node $converted_tree = $this->convert($tree['right']); $polish .= $converted_tree; } // if it's a function convert it here (so we can set it's arguments) if ( preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/", $tree['value']) && !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/', $tree['value']) && !preg_match('/^[A-Ia-i]?[A-Za-z](\\d+)\\.\\.[A-Ia-i]?[A-Za-z](\\d+)$/', $tree['value']) && !is_numeric($tree['value']) && !isset($this->ptg[$tree['value']]) ) { // left subtree for a function is always an array. if ($tree['left'] != '') { $left_tree = $this->toReversePolish($tree['left']); } else { $left_tree = ''; } // add its left subtree and return. return $left_tree . $this->convertFunction($tree['value'], $tree['right']); } $converted_tree = $this->convert($tree['value']); return $polish . $converted_tree; } } phpspreadsheet/src/PhpSpreadsheet/Settings.php 0000644 00000014001 15002227416 0015575 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Chart\Renderer\IRenderer; use PhpOffice\PhpSpreadsheet\Collection\Memory; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestFactoryInterface; use Psr\SimpleCache\CacheInterface; use ReflectionClass; class Settings { /** * Class name of the chart renderer used for rendering charts * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph. * * @var ?string */ private static $chartRenderer; /** * Default options for libxml loader. * * @var ?int */ private static $libXmlLoaderOptions; /** * The cache implementation to be used for cell collection. * * @var ?CacheInterface */ private static $cache; /** * The HTTP client implementation to be used for network request. * * @var null|ClientInterface */ private static $httpClient; /** * @var null|RequestFactoryInterface */ private static $requestFactory; /** * Set the locale code to use for formula translations and any special formatting. * * @param string $locale The locale code to use (e.g. "fr" or "pt_br" or "en_uk") * * @return bool Success or failure */ public static function setLocale(string $locale) { return Calculation::getInstance()->setLocale($locale); } public static function getLocale(): string { return Calculation::getInstance()->getLocale(); } /** * Identify to PhpSpreadsheet the external library to use for rendering charts. * * @param string $rendererClassName Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph */ public static function setChartRenderer(string $rendererClassName): void { if (!is_a($rendererClassName, IRenderer::class, true)) { throw new Exception('Chart renderer must implement ' . IRenderer::class); } self::$chartRenderer = $rendererClassName; } /** * Return the Chart Rendering Library that PhpSpreadsheet is currently configured to use. * * @return null|string Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph */ public static function getChartRenderer(): ?string { return self::$chartRenderer; } public static function htmlEntityFlags(): int { return \ENT_COMPAT; } /** * Set default options for libxml loader. * * @param ?int $options Default options for libxml loader */ public static function setLibXmlLoaderOptions($options): int { if ($options === null) { $options = defined('LIBXML_DTDLOAD') ? (LIBXML_DTDLOAD | LIBXML_DTDATTR) : 0; } self::$libXmlLoaderOptions = $options; return $options; } /** * Get default options for libxml loader. * Defaults to LIBXML_DTDLOAD | LIBXML_DTDATTR when not set explicitly. * * @return int Default options for libxml loader */ public static function getLibXmlLoaderOptions(): int { if (self::$libXmlLoaderOptions === null) { return self::setLibXmlLoaderOptions(null); } return self::$libXmlLoaderOptions; } /** * Deprecated, has no effect. * * @param bool $state * * @deprecated will be removed without replacement as it is no longer necessary on PHP 7.3.0+ * * @codeCoverageIgnore */ public static function setLibXmlDisableEntityLoader(/** @scrutinizer ignore-unused */ $state): void { // noop } /** * Deprecated, has no effect. * * @return bool $state * * @deprecated will be removed without replacement as it is no longer necessary on PHP 7.3.0+ * * @codeCoverageIgnore */ public static function getLibXmlDisableEntityLoader(): bool { return true; } /** * Sets the implementation of cache that should be used for cell collection. */ public static function setCache(?CacheInterface $cache): void { self::$cache = $cache; } /** * Gets the implementation of cache that is being used for cell collection. */ public static function getCache(): CacheInterface { if (!self::$cache) { self::$cache = self::useSimpleCacheVersion3() ? new Memory\SimpleCache3() : new Memory\SimpleCache1(); } return self::$cache; } public static function useSimpleCacheVersion3(): bool { return PHP_MAJOR_VERSION === 8 && (new ReflectionClass(CacheInterface::class))->getMethod('get')->getReturnType() !== null; } /** * Set the HTTP client implementation to be used for network request. */ public static function setHttpClient(ClientInterface $httpClient, RequestFactoryInterface $requestFactory): void { self::$httpClient = $httpClient; self::$requestFactory = $requestFactory; } /** * Unset the HTTP client configuration. */ public static function unsetHttpClient(): void { self::$httpClient = null; self::$requestFactory = null; } /** * Get the HTTP client implementation to be used for network request. */ public static function getHttpClient(): ClientInterface { if (!self::$httpClient || !self::$requestFactory) { throw new Exception('HTTP client must be configured via Settings::setHttpClient() to be able to use WEBSERVICE function.'); } return self::$httpClient; } /** * Get the HTTP request factory. */ public static function getRequestFactory(): RequestFactoryInterface { if (!self::$httpClient || !self::$requestFactory) { throw new Exception('HTTP client must be configured via Settings::setHttpClient() to be able to use WEBSERVICE function.'); } return self::$requestFactory; } } phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php 0000644 00000032732 15002227416 0017145 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Collection; use Generator; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Psr\SimpleCache\CacheInterface; class Cells { protected const MAX_COLUMN_ID = 16384; /** * @var CacheInterface */ private $cache; /** * Parent worksheet. * * @var null|Worksheet */ private $parent; /** * The currently active Cell. * * @var null|Cell */ private $currentCell; /** * Coordinate of the currently active Cell. * * @var null|string */ private $currentCoordinate; /** * Flag indicating whether the currently active Cell requires saving. * * @var bool */ private $currentCellIsDirty = false; /** * An index of existing cells. int pointer to the coordinate (0-base-indexed row * 16,384 + 1-base indexed column) * indexed by their coordinate. * * @var int[] */ private $index = []; /** * Prefix used to uniquely identify cache data for this worksheet. * * @var string */ private $cachePrefix; /** * Initialise this new cell collection. * * @param Worksheet $parent The worksheet for this cell collection */ public function __construct(Worksheet $parent, CacheInterface $cache) { // Set our parent worksheet. // This is maintained here to facilitate re-attaching it to Cell objects when // they are woken from a serialized state $this->parent = $parent; $this->cache = $cache; $this->cachePrefix = $this->getUniqueID(); } /** * Return the parent worksheet for this cell collection. * * @return null|Worksheet */ public function getParent() { return $this->parent; } /** * Whether the collection holds a cell for the given coordinate. * * @param string $cellCoordinate Coordinate of the cell to check */ public function has($cellCoordinate): bool { return ($cellCoordinate === $this->currentCoordinate) || isset($this->index[$cellCoordinate]); } /** * Add or update a cell in the collection. * * @param Cell $cell Cell to update */ public function update(Cell $cell): Cell { return $this->add($cell->getCoordinate(), $cell); } /** * Delete a cell in cache identified by coordinate. * * @param string $cellCoordinate Coordinate of the cell to delete */ public function delete($cellCoordinate): void { if ($cellCoordinate === $this->currentCoordinate && $this->currentCell !== null) { $this->currentCell->detach(); $this->currentCoordinate = null; $this->currentCell = null; $this->currentCellIsDirty = false; } unset($this->index[$cellCoordinate]); // Delete the entry from cache $this->cache->delete($this->cachePrefix . $cellCoordinate); } /** * Get a list of all cell coordinates currently held in the collection. * * @return string[] */ public function getCoordinates() { return array_keys($this->index); } /** * Get a sorted list of all cell coordinates currently held in the collection by row and column. * * @return string[] */ public function getSortedCoordinates() { asort($this->index); return array_keys($this->index); } /** * Return the cell coordinate of the currently active cell object. * * @return null|string */ public function getCurrentCoordinate() { return $this->currentCoordinate; } /** * Return the column coordinate of the currently active cell object. */ public function getCurrentColumn(): string { $column = 0; $row = ''; sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row); return (string) $column; } /** * Return the row coordinate of the currently active cell object. */ public function getCurrentRow(): int { $column = 0; $row = ''; sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row); return (int) $row; } /** * Get highest worksheet column and highest row that have cell records. * * @return array Highest column name and highest row number */ public function getHighestRowAndColumn() { // Lookup highest column and highest row $maxRow = $maxColumn = 1; foreach ($this->index as $coordinate) { $row = (int) floor($coordinate / self::MAX_COLUMN_ID) + 1; $maxRow = ($maxRow > $row) ? $maxRow : $row; $column = $coordinate % self::MAX_COLUMN_ID; $maxColumn = ($maxColumn > $column) ? $maxColumn : $column; } return [ 'row' => $maxRow, 'column' => Coordinate::stringFromColumnIndex($maxColumn), ]; } /** * Get highest worksheet column. * * @param null|int|string $row Return the highest column for the specified row, * or the highest column of any row if no row number is passed * * @return string Highest column name */ public function getHighestColumn($row = null) { if ($row === null) { return $this->getHighestRowAndColumn()['column']; } $row = (int) $row; if ($row <= 0) { throw new PhpSpreadsheetException('Row number must be a positive integer'); } $maxColumn = 1; $toRow = $row * self::MAX_COLUMN_ID; $fromRow = --$row * self::MAX_COLUMN_ID; foreach ($this->index as $coordinate) { if ($coordinate < $fromRow || $coordinate >= $toRow) { continue; } $column = $coordinate % self::MAX_COLUMN_ID; $maxColumn = $maxColumn > $column ? $maxColumn : $column; } return Coordinate::stringFromColumnIndex($maxColumn); } /** * Get highest worksheet row. * * @param null|string $column Return the highest row for the specified column, * or the highest row of any column if no column letter is passed * * @return int Highest row number */ public function getHighestRow($column = null) { if ($column === null) { return $this->getHighestRowAndColumn()['row']; } $maxRow = 1; $columnIndex = Coordinate::columnIndexFromString($column); foreach ($this->index as $coordinate) { if ($coordinate % self::MAX_COLUMN_ID !== $columnIndex) { continue; } $row = (int) floor($coordinate / self::MAX_COLUMN_ID) + 1; $maxRow = ($maxRow > $row) ? $maxRow : $row; } return $maxRow; } /** * Generate a unique ID for cache referencing. * * @return string Unique Reference */ private function getUniqueID() { $cacheType = Settings::getCache(); return ($cacheType instanceof Memory\SimpleCache1 || $cacheType instanceof Memory\SimpleCache3) ? random_bytes(7) . ':' : uniqid('phpspreadsheet.', true) . '.'; } /** * Clone the cell collection. * * @return self */ public function cloneCellCollection(Worksheet $worksheet) { $this->storeCurrentCell(); $newCollection = clone $this; $newCollection->parent = $worksheet; $newCollection->cachePrefix = $newCollection->getUniqueID(); foreach ($this->index as $key => $value) { $newCollection->index[$key] = $value; $stored = $newCollection->cache->set( $newCollection->cachePrefix . $key, clone $this->cache->get($this->cachePrefix . $key) ); if ($stored === false) { $this->destructIfNeeded($newCollection, 'Failed to copy cells in cache'); } } return $newCollection; } /** * Remove a row, deleting all cells in that row. * * @param int|string $row Row number to remove */ public function removeRow($row): void { $this->storeCurrentCell(); $row = (int) $row; if ($row <= 0) { throw new PhpSpreadsheetException('Row number must be a positive integer'); } $toRow = $row * self::MAX_COLUMN_ID; $fromRow = --$row * self::MAX_COLUMN_ID; foreach ($this->index as $coordinate) { if ($coordinate >= $fromRow && $coordinate < $toRow) { $row = (int) floor($coordinate / self::MAX_COLUMN_ID) + 1; $column = Coordinate::stringFromColumnIndex($coordinate % self::MAX_COLUMN_ID); $this->delete("{$column}{$row}"); } } } /** * Remove a column, deleting all cells in that column. * * @param string $column Column ID to remove */ public function removeColumn($column): void { $this->storeCurrentCell(); $columnIndex = Coordinate::columnIndexFromString($column); foreach ($this->index as $coordinate) { if ($coordinate % self::MAX_COLUMN_ID === $columnIndex) { $row = (int) floor($coordinate / self::MAX_COLUMN_ID) + 1; $column = Coordinate::stringFromColumnIndex($coordinate % self::MAX_COLUMN_ID); $this->delete("{$column}{$row}"); } } } /** * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object. */ private function storeCurrentCell(): void { if ($this->currentCellIsDirty && isset($this->currentCoordinate, $this->currentCell)) { $this->currentCell->/** @scrutinizer ignore-call */ detach(); $stored = $this->cache->set($this->cachePrefix . $this->currentCoordinate, $this->currentCell); if ($stored === false) { $this->destructIfNeeded($this, "Failed to store cell {$this->currentCoordinate} in cache"); } $this->currentCellIsDirty = false; } $this->currentCoordinate = null; $this->currentCell = null; } private function destructIfNeeded(self $cells, string $message): void { $cells->__destruct(); throw new PhpSpreadsheetException($message); } /** * Add or update a cell identified by its coordinate into the collection. * * @param string $cellCoordinate Coordinate of the cell to update * @param Cell $cell Cell to update * * @return Cell */ public function add($cellCoordinate, Cell $cell) { if ($cellCoordinate !== $this->currentCoordinate) { $this->storeCurrentCell(); } $column = 0; $row = ''; sscanf($cellCoordinate, '%[A-Z]%d', $column, $row); $this->index[$cellCoordinate] = (--$row * self::MAX_COLUMN_ID) + Coordinate::columnIndexFromString((string) $column); $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; $this->currentCellIsDirty = true; return $cell; } /** * Get cell at a specific coordinate. * * @param string $cellCoordinate Coordinate of the cell * * @return null|Cell Cell that was found, or null if not found */ public function get($cellCoordinate) { if ($cellCoordinate === $this->currentCoordinate) { return $this->currentCell; } $this->storeCurrentCell(); // Return null if requested entry doesn't exist in collection if ($this->has($cellCoordinate) === false) { return null; } // Check if the entry that has been requested actually exists in the cache $cell = $this->cache->get($this->cachePrefix . $cellCoordinate); if ($cell === null) { throw new PhpSpreadsheetException("Cell entry {$cellCoordinate} no longer exists in cache. This probably means that the cache was cleared by someone else."); } // Set current entry to the requested entry $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; // Re-attach this as the cell's parent $this->currentCell->attach($this); // Return requested entry return $this->currentCell; } /** * Clear the cell collection and disconnect from our parent. */ public function unsetWorksheetCells(): void { if ($this->currentCell !== null) { $this->currentCell->detach(); $this->currentCell = null; $this->currentCoordinate = null; } // Flush the cache $this->__destruct(); $this->index = []; // detach ourself from the worksheet, so that it can then delete this object successfully $this->parent = null; } /** * Destroy this cell collection. */ public function __destruct() { $this->cache->deleteMultiple($this->getAllCacheKeys()); } /** * Returns all known cache keys. * * @return Generator|string[] */ private function getAllCacheKeys() { foreach ($this->index as $coordinate => $value) { yield $this->cachePrefix . $coordinate; } } } phpspreadsheet/src/PhpSpreadsheet/Collection/Memory/SimpleCache3.php 0000644 00000004136 15002227416 0021610 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Collection\Memory; use DateInterval; use Psr\SimpleCache\CacheInterface; /** * This is the default implementation for in-memory cell collection. * * Alternatives implementation should leverage off-memory, non-volatile storage * to reduce overall memory usage. */ class SimpleCache3 implements CacheInterface { /** * @var array Cell Cache */ private $cache = []; public function clear(): bool { $this->cache = []; return true; } /** * @param string $key */ public function delete($key): bool { unset($this->cache[$key]); return true; } /** * @param iterable $keys */ public function deleteMultiple($keys): bool { foreach ($keys as $key) { $this->delete($key); } return true; } /** * @param string $key * @param mixed $default */ public function get($key, $default = null): mixed { if ($this->has($key)) { return $this->cache[$key]; } return $default; } /** * @param iterable $keys * @param mixed $default */ public function getMultiple($keys, $default = null): iterable { $results = []; foreach ($keys as $key) { $results[$key] = $this->get($key, $default); } return $results; } /** * @param string $key */ public function has($key): bool { return array_key_exists($key, $this->cache); } /** * @param string $key * @param mixed $value * @param null|DateInterval|int $ttl */ public function set($key, $value, $ttl = null): bool { $this->cache[$key] = $value; return true; } /** * @param iterable $values * @param null|DateInterval|int $ttl */ public function setMultiple($values, $ttl = null): bool { foreach ($values as $key => $value) { $this->set($key, $value); } return true; } } phpspreadsheet/src/PhpSpreadsheet/Collection/Memory/SimpleCache1.php 0000644 00000004417 15002227416 0021610 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Collection\Memory; use DateInterval; use Psr\SimpleCache\CacheInterface; /** * This is the default implementation for in-memory cell collection. * * Alternatives implementation should leverage off-memory, non-volatile storage * to reduce overall memory usage. */ class SimpleCache1 implements CacheInterface { /** * @var array Cell Cache */ private $cache = []; /** * @return bool */ public function clear() { $this->cache = []; return true; } /** * @param string $key * * @return bool */ public function delete($key) { unset($this->cache[$key]); return true; } /** * @param iterable $keys * * @return bool */ public function deleteMultiple($keys) { foreach ($keys as $key) { $this->delete($key); } return true; } /** * @param string $key * @param mixed $default * * @return mixed */ public function get($key, $default = null) { if ($this->has($key)) { return $this->cache[$key]; } return $default; } /** * @param iterable $keys * @param mixed $default * * @return iterable */ public function getMultiple($keys, $default = null) { $results = []; foreach ($keys as $key) { $results[$key] = $this->get($key, $default); } return $results; } /** * @param string $key * * @return bool */ public function has($key) { return array_key_exists($key, $this->cache); } /** * @param string $key * @param mixed $value * @param null|DateInterval|int $ttl * * @return bool */ public function set($key, $value, $ttl = null) { $this->cache[$key] = $value; return true; } /** * @param iterable $values * @param null|DateInterval|int $ttl * * @return bool */ public function setMultiple($values, $ttl = null) { foreach ($values as $key => $value) { $this->set($key, $value); } return true; } } phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php 0000644 00000000714 15002227416 0020470 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Collection; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; abstract class CellsFactory { /** * Initialise the cache storage. * * @param Worksheet $worksheet Enable cell caching for this worksheet * * */ public static function getInstance(Worksheet $worksheet): Cells { return new Cells($worksheet, Settings::getCache()); } } phpspreadsheet/src/PhpSpreadsheet/NamedRange.php 0000644 00000002342 15002227416 0016003 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class NamedRange extends DefinedName { /** * Create a new Named Range. */ public function __construct( string $name, ?Worksheet $worksheet = null, string $range = 'A1', bool $localOnly = false, ?Worksheet $scope = null ) { if ($worksheet === null && $scope === null) { throw new Exception('You must specify a worksheet or a scope for a Named Range'); } parent::__construct($name, $worksheet, $range, $localOnly, $scope); } /** * Get the range value. */ public function getRange(): string { return $this->value; } /** * Set the range value. */ public function setRange(string $range): self { if (!empty($range)) { $this->value = $range; } return $this; } public function getCellsInRange(): array { $range = $this->value; if (substr($range, 0, 1) === '=') { $range = substr($range, 1); } return Coordinate::extractAllCellReferencesInRange($range); } } phpspreadsheet/src/PhpSpreadsheet/CellReferenceHelper.php 0000644 00000010406 15002227416 0017640 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; class CellReferenceHelper { /** * @var string */ protected $beforeCellAddress; /** * @var int */ protected $beforeColumn; /** * @var int */ protected $beforeRow; /** * @var int */ protected $numberOfColumns; /** * @var int */ protected $numberOfRows; public function __construct(string $beforeCellAddress = 'A1', int $numberOfColumns = 0, int $numberOfRows = 0) { $this->beforeCellAddress = str_replace('$', '', $beforeCellAddress); $this->numberOfColumns = $numberOfColumns; $this->numberOfRows = $numberOfRows; // Get coordinate of $beforeCellAddress [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress); $this->beforeColumn = (int) Coordinate::columnIndexFromString($beforeColumn); $this->beforeRow = (int) $beforeRow; } public function beforeCellAddress(): string { return $this->beforeCellAddress; } public function refreshRequired(string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): bool { return $this->beforeCellAddress !== $beforeCellAddress || $this->numberOfColumns !== $numberOfColumns || $this->numberOfRows !== $numberOfRows; } public function updateCellReference(string $cellReference = 'A1', bool $includeAbsoluteReferences = false): string { if (Coordinate::coordinateIsRange($cellReference)) { throw new Exception('Only single cell references may be passed to this method.'); } // Get coordinate of $cellReference [$newColumn, $newRow] = Coordinate::coordinateFromString($cellReference); $newColumnIndex = (int) Coordinate::columnIndexFromString(str_replace('$', '', $newColumn)); $newRowIndex = (int) str_replace('$', '', $newRow); $absoluteColumn = $newColumn[0] === '$' ? '$' : ''; $absoluteRow = $newRow[0] === '$' ? '$' : ''; // Verify which parts should be updated if ($includeAbsoluteReferences === false) { $updateColumn = (($absoluteColumn !== '$') && $newColumnIndex >= $this->beforeColumn); $updateRow = (($absoluteRow !== '$') && $newRowIndex >= $this->beforeRow); } else { $updateColumn = ($newColumnIndex >= $this->beforeColumn); $updateRow = ($newRowIndex >= $this->beforeRow); } // Create new column reference if ($updateColumn) { $newColumn = $this->updateColumnReference($newColumnIndex, $absoluteColumn); } // Create new row reference if ($updateRow) { $newRow = $this->updateRowReference($newRowIndex, $absoluteRow); } // Return new reference return "{$newColumn}{$newRow}"; } public function cellAddressInDeleteRange(string $cellAddress): bool { [$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress); $cellColumnIndex = Coordinate::columnIndexFromString($cellColumn); // Is cell within the range of rows/columns if we're deleting if ( $this->numberOfRows < 0 && ($cellRow >= ($this->beforeRow + $this->numberOfRows)) && ($cellRow < $this->beforeRow) ) { return true; } elseif ( $this->numberOfColumns < 0 && ($cellColumnIndex >= ($this->beforeColumn + $this->numberOfColumns)) && ($cellColumnIndex < $this->beforeColumn) ) { return true; } return false; } protected function updateColumnReference(int $newColumnIndex, string $absoluteColumn): string { $newColumn = Coordinate::stringFromColumnIndex(min($newColumnIndex + $this->numberOfColumns, AddressRange::MAX_COLUMN_INT)); return "{$absoluteColumn}{$newColumn}"; } protected function updateRowReference(int $newRowIndex, string $absoluteRow): string { $newRow = $newRowIndex + $this->numberOfRows; $newRow = ($newRow > AddressRange::MAX_ROW) ? AddressRange::MAX_ROW : $newRow; return "{$absoluteRow}{$newRow}"; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php 0000644 00000121274 15002227416 0020041 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use DateTime; use DateTimeZone; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; class AutoFilter { /** * Autofilter Worksheet. * * @var null|Worksheet */ private $workSheet; /** * Autofilter Range. * * @var string */ private $range = ''; /** * Autofilter Column Ruleset. * * @var AutoFilter\Column[] */ private $columns = []; /** @var bool */ private $evaluated = false; public function getEvaluated(): bool { return $this->evaluated; } public function setEvaluated(bool $value): void { $this->evaluated = $value; } /** * Create a new AutoFilter. * * @param AddressRange|array<int>|string $range * A simple string containing a Cell range like 'A1:E10' is permitted * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. */ public function __construct($range = '', ?Worksheet $worksheet = null) { if ($range !== '') { [, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true); } $this->range = $range; $this->workSheet = $worksheet; } /** * Get AutoFilter Parent Worksheet. * * @return null|Worksheet */ public function getParent() { return $this->workSheet; } /** * Set AutoFilter Parent Worksheet. * * @return $this */ public function setParent(?Worksheet $worksheet = null) { $this->evaluated = false; $this->workSheet = $worksheet; return $this; } /** * Get AutoFilter Range. * * @return string */ public function getRange() { return $this->range; } /** * Set AutoFilter Cell Range. * * @param AddressRange|array<int>|string $range * A simple string containing a Cell range like 'A1:E10' or a Cell address like 'A1' is permitted * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. */ public function setRange($range = ''): self { $this->evaluated = false; // extract coordinate if ($range !== '') { [, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true); } if (empty($range)) { // Discard all column rules $this->columns = []; $this->range = ''; return $this; } if (ctype_digit($range) || ctype_alpha($range)) { throw new Exception("{$range} is an invalid range for AutoFilter"); } $this->range = $range; // Discard any column rules that are no longer valid within this range [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); foreach ($this->columns as $key => $value) { $colIndex = Coordinate::columnIndexFromString($key); if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { unset($this->columns[$key]); } } return $this; } public function setRangeToMaxRow(): self { $this->evaluated = false; if ($this->workSheet !== null) { $thisrange = $this->range; $range = (string) preg_replace('/\\d+$/', (string) $this->workSheet->getHighestRow(), $thisrange); if ($range !== $thisrange) { $this->setRange($range); } } return $this; } /** * Get all AutoFilter Columns. * * @return AutoFilter\Column[] */ public function getColumns() { return $this->columns; } /** * Validate that the specified column is in the AutoFilter range. * * @param string $column Column name (e.g. A) * * @return int The column offset within the autofilter range */ public function testColumnInRange($column) { if (empty($this->range)) { throw new Exception('No autofilter range is defined.'); } $columnIndex = Coordinate::columnIndexFromString($column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) { throw new Exception('Column is outside of current autofilter range.'); } return $columnIndex - $rangeStart[0]; } /** * Get a specified AutoFilter Column Offset within the defined AutoFilter range. * * @param string $column Column name (e.g. A) * * @return int The offset of the specified column within the autofilter range */ public function getColumnOffset($column) { return $this->testColumnInRange($column); } /** * Get a specified AutoFilter Column. * * @param string $column Column name (e.g. A) * * @return AutoFilter\Column */ public function getColumn($column) { $this->testColumnInRange($column); if (!isset($this->columns[$column])) { $this->columns[$column] = new AutoFilter\Column($column, $this); } return $this->columns[$column]; } /** * Get a specified AutoFilter Column by it's offset. * * @param int $columnOffset Column offset within range (starting from 0) * * @return AutoFilter\Column */ public function getColumnByOffset($columnOffset) { [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset); return $this->getColumn($pColumn); } /** * Set AutoFilter. * * @param AutoFilter\Column|string $columnObjectOrString * A simple string containing a Column ID like 'A' is permitted * * @return $this */ public function setColumn($columnObjectOrString) { $this->evaluated = false; if ((is_string($columnObjectOrString)) && (!empty($columnObjectOrString))) { $column = $columnObjectOrString; } elseif (is_object($columnObjectOrString) && ($columnObjectOrString instanceof AutoFilter\Column)) { $column = $columnObjectOrString->getColumnIndex(); } else { throw new Exception('Column is not within the autofilter range.'); } $this->testColumnInRange($column); if (is_string($columnObjectOrString)) { $this->columns[$columnObjectOrString] = new AutoFilter\Column($columnObjectOrString, $this); } else { $columnObjectOrString->setParent($this); $this->columns[$column] = $columnObjectOrString; } ksort($this->columns); return $this; } /** * Clear a specified AutoFilter Column. * * @param string $column Column name (e.g. A) * * @return $this */ public function clearColumn($column) { $this->evaluated = false; $this->testColumnInRange($column); if (isset($this->columns[$column])) { unset($this->columns[$column]); } return $this; } /** * Shift an AutoFilter Column Rule to a different column. * * Note: This method bypasses validation of the destination column to ensure it is within this AutoFilter range. * Nor does it verify whether any column rule already exists at $toColumn, but will simply override any existing value. * Use with caution. * * @param string $fromColumn Column name (e.g. A) * @param string $toColumn Column name (e.g. B) * * @return $this */ public function shiftColumn($fromColumn, $toColumn) { $this->evaluated = false; $fromColumn = strtoupper($fromColumn); $toColumn = strtoupper($toColumn); if (($fromColumn !== null) && (isset($this->columns[$fromColumn])) && ($toColumn !== null)) { $this->columns[$fromColumn]->setParent(); $this->columns[$fromColumn]->setColumnIndex($toColumn); $this->columns[$toColumn] = $this->columns[$fromColumn]; $this->columns[$toColumn]->setParent($this); unset($this->columns[$fromColumn]); ksort($this->columns); } return $this; } /** * Test if cell value is in the defined set of values. * * @param mixed $cellValue * @param mixed[] $dataSet * * @return bool */ protected static function filterTestInSimpleDataSet($cellValue, $dataSet) { $dataSetValues = $dataSet['filterValues']; $blanks = $dataSet['blanks']; if (($cellValue == '') || ($cellValue === null)) { return $blanks; } return in_array($cellValue, $dataSetValues); } /** * Test if cell value is in the defined set of Excel date values. * * @param mixed $cellValue * @param mixed[] $dataSet * * @return bool */ protected static function filterTestInDateGroupSet($cellValue, $dataSet) { $dateSet = $dataSet['filterValues']; $blanks = $dataSet['blanks']; if (($cellValue == '') || ($cellValue === null)) { return $blanks; } $timeZone = new DateTimeZone('UTC'); if (is_numeric($cellValue)) { $dateTime = Date::excelToDateTimeObject((float) $cellValue, $timeZone); $cellValue = (float) $cellValue; if ($cellValue < 1) { // Just the time part $dtVal = $dateTime->format('His'); $dateSet = $dateSet['time']; } elseif ($cellValue == floor($cellValue)) { // Just the date part $dtVal = $dateTime->format('Ymd'); $dateSet = $dateSet['date']; } else { // date and time parts $dtVal = $dateTime->format('YmdHis'); $dateSet = $dateSet['dateTime']; } foreach ($dateSet as $dateValue) { // Use of substr to extract value at the appropriate group level if (substr($dtVal, 0, strlen($dateValue)) == $dateValue) { return true; } } } return false; } /** * Test if cell value is within a set of values defined by a ruleset. * * @param mixed $cellValue * @param mixed[] $ruleSet * * @return bool */ protected static function filterTestInCustomDataSet($cellValue, $ruleSet) { /** @var array[] */ $dataSet = $ruleSet['filterRules']; $join = $ruleSet['join']; $customRuleForBlanks = $ruleSet['customRuleForBlanks'] ?? false; if (!$customRuleForBlanks) { // Blank cells are always ignored, so return a FALSE if (($cellValue == '') || ($cellValue === null)) { return false; } } $returnVal = ($join == AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND); foreach ($dataSet as $rule) { /** @var string */ $ruleValue = $rule['value']; /** @var string */ $ruleOperator = $rule['operator']; /** @var string */ $cellValueString = $cellValue ?? ''; $retVal = false; if (is_numeric($ruleValue)) { // Numeric values are tested using the appropriate operator $numericTest = is_numeric($cellValue); switch ($ruleOperator) { case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: $retVal = $numericTest && ($cellValue == $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: $retVal = !$numericTest || ($cellValue != $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: $retVal = $numericTest && ($cellValue > $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: $retVal = $numericTest && ($cellValue >= $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: $retVal = $numericTest && ($cellValue < $ruleValue); break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: $retVal = $numericTest && ($cellValue <= $ruleValue); break; } } elseif ($ruleValue == '') { switch ($ruleOperator) { case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: $retVal = (($cellValue == '') || ($cellValue === null)); break; case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: $retVal = (($cellValue != '') && ($cellValue !== null)); break; default: $retVal = true; break; } } else { // String values are always tested for equality, factoring in for wildcards (hence a regexp test) switch ($ruleOperator) { case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: $retVal = (bool) preg_match('/^' . $ruleValue . '$/i', $cellValueString); break; case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: $retVal = !((bool) preg_match('/^' . $ruleValue . '$/i', $cellValueString)); break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: $retVal = strcasecmp($cellValueString, $ruleValue) > 0; break; case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: $retVal = strcasecmp($cellValueString, $ruleValue) >= 0; break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: $retVal = strcasecmp($cellValueString, $ruleValue) < 0; break; case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: $retVal = strcasecmp($cellValueString, $ruleValue) <= 0; break; } } // If there are multiple conditions, then we need to test both using the appropriate join operator switch ($join) { case AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR: $returnVal = $returnVal || $retVal; // Break as soon as we have a TRUE match for OR joins, // to avoid unnecessary additional code execution if ($returnVal) { return $returnVal; } break; case AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND: $returnVal = $returnVal && $retVal; break; } } return $returnVal; } /** * Test if cell date value is matches a set of values defined by a set of months. * * @param mixed $cellValue * @param mixed[] $monthSet * * @return bool */ protected static function filterTestInPeriodDateSet($cellValue, $monthSet) { // Blank cells are always ignored, so return a FALSE if (($cellValue == '') || ($cellValue === null)) { return false; } if (is_numeric($cellValue)) { $dateObject = Date::excelToDateTimeObject((float) $cellValue, new DateTimeZone('UTC')); $dateValue = (int) $dateObject->format('m'); if (in_array($dateValue, $monthSet)) { return true; } } return false; } private static function makeDateObject(int $year, int $month, int $day, int $hour = 0, int $minute = 0, int $second = 0): DateTime { $baseDate = new DateTime(); $baseDate->setDate($year, $month, $day); $baseDate->setTime($hour, $minute, $second); return $baseDate; } private const DATE_FUNCTIONS = [ Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH => 'dynamicLastMonth', Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER => 'dynamicLastQuarter', Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK => 'dynamicLastWeek', Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR => 'dynamicLastYear', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH => 'dynamicNextMonth', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER => 'dynamicNextQuarter', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK => 'dynamicNextWeek', Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR => 'dynamicNextYear', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH => 'dynamicThisMonth', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER => 'dynamicThisQuarter', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK => 'dynamicThisWeek', Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR => 'dynamicThisYear', Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY => 'dynamicToday', Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW => 'dynamicTomorrow', Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE => 'dynamicYearToDate', Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY => 'dynamicYesterday', ]; private static function dynamicLastMonth(): array { $maxval = new DateTime(); $year = (int) $maxval->format('Y'); $month = (int) $maxval->format('m'); $maxval->setDate($year, $month, 1); $maxval->setTime(0, 0, 0); $val = clone $maxval; $val->modify('-1 month'); return [$val, $maxval]; } private static function firstDayOfQuarter(): DateTime { $val = new DateTime(); $year = (int) $val->format('Y'); $month = (int) $val->format('m'); $month = 3 * intdiv($month - 1, 3) + 1; $val->setDate($year, $month, 1); $val->setTime(0, 0, 0); return $val; } private static function dynamicLastQuarter(): array { $maxval = self::firstDayOfQuarter(); $val = clone $maxval; $val->modify('-3 months'); return [$val, $maxval]; } private static function dynamicLastWeek(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $dayOfWeek = (int) $val->format('w'); // Sunday is 0 $subtract = $dayOfWeek + 7; // revert to prior Sunday $val->modify("-$subtract days"); $maxval = clone $val; $maxval->modify('+7 days'); return [$val, $maxval]; } private static function dynamicLastYear(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $val = self::makeDateObject($year - 1, 1, 1); $maxval = self::makeDateObject($year, 1, 1); return [$val, $maxval]; } private static function dynamicNextMonth(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $month = (int) $val->format('m'); $val->setDate($year, $month, 1); $val->setTime(0, 0, 0); $val->modify('+1 month'); $maxval = clone $val; $maxval->modify('+1 month'); return [$val, $maxval]; } private static function dynamicNextQuarter(): array { $val = self::firstDayOfQuarter(); $val->modify('+3 months'); $maxval = clone $val; $maxval->modify('+3 months'); return [$val, $maxval]; } private static function dynamicNextWeek(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $dayOfWeek = (int) $val->format('w'); // Sunday is 0 $add = 7 - $dayOfWeek; // move to next Sunday $val->modify("+$add days"); $maxval = clone $val; $maxval->modify('+7 days'); return [$val, $maxval]; } private static function dynamicNextYear(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $val = self::makeDateObject($year + 1, 1, 1); $maxval = self::makeDateObject($year + 2, 1, 1); return [$val, $maxval]; } private static function dynamicThisMonth(): array { $baseDate = new DateTime(); $baseDate->setTime(0, 0, 0); $year = (int) $baseDate->format('Y'); $month = (int) $baseDate->format('m'); $val = self::makeDateObject($year, $month, 1); $maxval = clone $val; $maxval->modify('+1 month'); return [$val, $maxval]; } private static function dynamicThisQuarter(): array { $val = self::firstDayOfQuarter(); $maxval = clone $val; $maxval->modify('+3 months'); return [$val, $maxval]; } private static function dynamicThisWeek(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $dayOfWeek = (int) $val->format('w'); // Sunday is 0 $subtract = $dayOfWeek; // revert to Sunday $val->modify("-$subtract days"); $maxval = clone $val; $maxval->modify('+7 days'); return [$val, $maxval]; } private static function dynamicThisYear(): array { $val = new DateTime(); $year = (int) $val->format('Y'); $val = self::makeDateObject($year, 1, 1); $maxval = self::makeDateObject($year + 1, 1, 1); return [$val, $maxval]; } private static function dynamicToday(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $maxval = clone $val; $maxval->modify('+1 day'); return [$val, $maxval]; } private static function dynamicTomorrow(): array { $val = new DateTime(); $val->setTime(0, 0, 0); $val->modify('+1 day'); $maxval = clone $val; $maxval->modify('+1 day'); return [$val, $maxval]; } private static function dynamicYearToDate(): array { $maxval = new DateTime(); $maxval->setTime(0, 0, 0); $val = self::makeDateObject((int) $maxval->format('Y'), 1, 1); $maxval->modify('+1 day'); return [$val, $maxval]; } private static function dynamicYesterday(): array { $maxval = new DateTime(); $maxval->setTime(0, 0, 0); $val = clone $maxval; $val->modify('-1 day'); return [$val, $maxval]; } /** * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation. * * @param string $dynamicRuleType * * @return mixed[] */ private function dynamicFilterDateRange($dynamicRuleType, AutoFilter\Column &$filterColumn) { $ruleValues = []; $callBack = [__CLASS__, self::DATE_FUNCTIONS[$dynamicRuleType]]; // What if not found? // Calculate start/end dates for the required date range based on current date // Val is lowest permitted value. // Maxval is greater than highest permitted value $val = $maxval = 0; if (is_callable($callBack)) { [$val, $maxval] = $callBack(); } $val = Date::dateTimeToExcel($val); $maxval = Date::dateTimeToExcel($maxval); // Set the filter column rule attributes ready for writing $filterColumn->setAttributes(['val' => $val, 'maxVal' => $maxval]); // Set the rules for identifying rows for hide/show $ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val]; $ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxval]; return ['method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND]]; } /** * Apply the AutoFilter rules to the AutoFilter Range. * * @param string $columnID * @param int $startRow * @param int $endRow * @param ?string $ruleType * @param mixed $ruleValue * * @return mixed */ private function calculateTopTenValue($columnID, $startRow, $endRow, $ruleType, $ruleValue) { $range = $columnID . $startRow . ':' . $columnID . $endRow; $retVal = null; if ($this->workSheet !== null) { $dataValues = Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false)); $dataValues = array_filter($dataValues); if ($ruleType == Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) { rsort($dataValues); } else { sort($dataValues); } $slice = array_slice($dataValues, 0, $ruleValue); $retVal = array_pop($slice); } return $retVal; } /** * Apply the AutoFilter rules to the AutoFilter Range. * * @return $this */ public function showHideRows() { if ($this->workSheet === null) { return $this; } [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); // The heading row should always be visible $this->workSheet->getRowDimension($rangeStart[1])->setVisible(true); $columnFilterTests = []; foreach ($this->columns as $columnID => $filterColumn) { $rules = $filterColumn->getRules(); switch ($filterColumn->getFilterType()) { case AutoFilter\Column::AUTOFILTER_FILTERTYPE_FILTER: $ruleType = null; $ruleValues = []; // Build a list of the filter value selections foreach ($rules as $rule) { $ruleType = $rule->getRuleType(); $ruleValues[] = $rule->getValue(); } // Test if we want to include blanks in our filter criteria $blanks = false; $ruleDataSet = array_filter($ruleValues); if (count($ruleValues) != count($ruleDataSet)) { $blanks = true; } if ($ruleType == Rule::AUTOFILTER_RULETYPE_FILTER) { // Filter on absolute values $columnFilterTests[$columnID] = [ 'method' => 'filterTestInSimpleDataSet', 'arguments' => ['filterValues' => $ruleDataSet, 'blanks' => $blanks], ]; } else { // Filter on date group values $arguments = [ 'date' => [], 'time' => [], 'dateTime' => [], ]; foreach ($ruleDataSet as $ruleValue) { if (!is_array($ruleValue)) { continue; } $date = $time = ''; if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '') ) { $date .= sprintf('%04d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '') ) { $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '') ) { $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '') ) { $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '') ) { $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]); } if ( (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) && ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '') ) { $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]); } $dateTime = $date . $time; $arguments['date'][] = $date; $arguments['time'][] = $time; $arguments['dateTime'][] = $dateTime; } // Remove empty elements $arguments['date'] = array_filter($arguments['date']); $arguments['time'] = array_filter($arguments['time']); $arguments['dateTime'] = array_filter($arguments['dateTime']); $columnFilterTests[$columnID] = [ 'method' => 'filterTestInDateGroupSet', 'arguments' => ['filterValues' => $arguments, 'blanks' => $blanks], ]; } break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER: $customRuleForBlanks = true; $ruleValues = []; // Build a list of the filter value selections foreach ($rules as $rule) { $ruleValue = $rule->getValue(); if (!is_array($ruleValue) && !is_numeric($ruleValue)) { // Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards $ruleValue = WildcardMatch::wildcard($ruleValue); if (trim($ruleValue) == '') { $customRuleForBlanks = true; $ruleValue = trim($ruleValue); } } $ruleValues[] = ['operator' => $rule->getOperator(), 'value' => $ruleValue]; } $join = $filterColumn->getJoin(); $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => $join, 'customRuleForBlanks' => $customRuleForBlanks], ]; break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER: $ruleValues = []; foreach ($rules as $rule) { // We should only ever have one Dynamic Filter Rule anyway $dynamicRuleType = $rule->getGrouping(); if ( ($dynamicRuleType == Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) || ($dynamicRuleType == Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE) ) { // Number (Average) based // Calculate the average $averageFormula = '=AVERAGE(' . $columnID . ($rangeStart[1] + 1) . ':' . $columnID . $rangeEnd[1] . ')'; $spreadsheet = ($this->workSheet === null) ? null : $this->workSheet->getParent(); $average = Calculation::getInstance($spreadsheet)->calculateFormula($averageFormula, null, $this->workSheet->getCell('A1')); while (is_array($average)) { $average = array_pop($average); } // Set above/below rule based on greaterThan or LessTan $operator = ($dynamicRuleType === Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) ? Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN : Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; $ruleValues[] = [ 'operator' => $operator, 'value' => $average, ]; $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR], ]; } else { // Date based if ($dynamicRuleType[0] == 'M' || $dynamicRuleType[0] == 'Q') { $periodType = ''; $period = 0; // Month or Quarter sscanf($dynamicRuleType, '%[A-Z]%d', $periodType, $period); if ($periodType == 'M') { $ruleValues = [$period]; } else { --$period; $periodEnd = (1 + $period) * 3; $periodStart = 1 + $period * 3; $ruleValues = range($periodStart, $periodEnd); } $columnFilterTests[$columnID] = [ 'method' => 'filterTestInPeriodDateSet', 'arguments' => $ruleValues, ]; $filterColumn->setAttributes([]); } else { // Date Range $columnFilterTests[$columnID] = $this->dynamicFilterDateRange($dynamicRuleType, $filterColumn); break; } } } break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER: $ruleValues = []; $dataRowCount = $rangeEnd[1] - $rangeStart[1]; $toptenRuleType = null; $ruleValue = 0; $ruleOperator = null; foreach ($rules as $rule) { // We should only ever have one Dynamic Filter Rule anyway $toptenRuleType = $rule->getGrouping(); $ruleValue = $rule->getValue(); $ruleOperator = $rule->getOperator(); } if (is_numeric($ruleValue) && $ruleOperator === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) { $ruleValue = floor((float) $ruleValue * ($dataRowCount / 100)); } if (!is_array($ruleValue) && $ruleValue < 1) { $ruleValue = 1; } if (!is_array($ruleValue) && $ruleValue > 500) { $ruleValue = 500; } $maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1] + 1, (int) $rangeEnd[1], $toptenRuleType, $ruleValue); $operator = ($toptenRuleType == Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL : Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL; $ruleValues[] = ['operator' => $operator, 'value' => $maxVal]; $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_OR], ]; $filterColumn->setAttributes(['maxVal' => $maxVal]); break; } } $rangeEnd[1] = $this->autoExtendRange($rangeStart[1], $rangeEnd[1]); // Execute the column tests for each row in the autoFilter range to determine show/hide, for ($row = $rangeStart[1] + 1; $row <= $rangeEnd[1]; ++$row) { $result = true; foreach ($columnFilterTests as $columnID => $columnFilterTest) { $cellValue = $this->workSheet->getCell($columnID . $row)->getCalculatedValue(); // Execute the filter test $result = // $result && // phpstan says $result is always true here // @phpstan-ignore-next-line call_user_func_array([self::class, $columnFilterTest['method']], [$cellValue, $columnFilterTest['arguments']]); // If filter test has resulted in FALSE, exit the loop straightaway rather than running any more tests if (!$result) { break; } } // Set show/hide for the row based on the result of the autoFilter result $this->workSheet->getRowDimension((int) $row)->setVisible($result); } $this->evaluated = true; return $this; } /** * Magic Range Auto-sizing. * For a single row rangeSet, we follow MS Excel rules, and search for the first empty row to determine our range. */ public function autoExtendRange(int $startRow, int $endRow): int { if ($startRow === $endRow && $this->workSheet !== null) { try { $rowIterator = $this->workSheet->getRowIterator($startRow + 1); } catch (Exception $e) { // If there are no rows below $startRow return $startRow; } foreach ($rowIterator as $row) { if ($row->isEmpty(CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL) === true) { return $row->getRowIndex() - 1; } } } return $endRow; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { if ($key === 'workSheet') { // Detach from worksheet $this->{$key} = null; } else { $this->{$key} = clone $value; } } elseif ((is_array($value)) && ($key == 'columns')) { // The columns array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter objects $this->{$key} = []; foreach ($value as $k => $v) { $this->{$key}[$k] = clone $v; // attach the new cloned Column to this new cloned Autofilter object $this->{$key}[$k]->setParent($this); } } else { $this->{$key} = $value; } } } /** * toString method replicates previous behavior by returning the range if object is * referenced as a property of its parent. */ public function __toString() { return (string) $this->range; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooterDrawing.php 0000644 00000000676 15002227416 0021650 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class HeaderFooterDrawing extends Drawing { /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->getPath() . $this->name . $this->offsetX . $this->offsetY . $this->width . $this->height . __CLASS__ ); } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php 0000644 00000002361 15002227416 0017547 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Spreadsheet; /** * @implements \Iterator<int, Worksheet> */ class Iterator implements \Iterator { /** * Spreadsheet to iterate. * * @var Spreadsheet */ private $subject; /** * Current iterator position. * * @var int */ private $position = 0; /** * Create a new worksheet iterator. */ public function __construct(Spreadsheet $subject) { // Set subject $this->subject = $subject; } /** * Rewind iterator. */ public function rewind(): void { $this->position = 0; } /** * Current Worksheet. */ public function current(): Worksheet { return $this->subject->getSheet($this->position); } /** * Current key. */ public function key(): int { return $this->position; } /** * Next value. */ public function next(): void { ++$this->position; } /** * Are there more Worksheet instances available? */ public function valid(): bool { return $this->position < $this->subject->getSheetCount() && $this->position >= 0; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php 0000644 00000007034 15002227416 0020241 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use Iterator as NativeIterator; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @implements NativeIterator<int, Row> */ class RowIterator implements NativeIterator { /** * Worksheet to iterate. * * @var Worksheet */ private $subject; /** * Current iterator position. * * @var int */ private $position = 1; /** * Start position. * * @var int */ private $startRow = 1; /** * End position. * * @var int */ private $endRow = 1; /** * Create a new row iterator. * * @param Worksheet $subject The worksheet to iterate over * @param int $startRow The row number at which to start iterating * @param int $endRow Optionally, the row number at which to stop iterating */ public function __construct(Worksheet $subject, $startRow = 1, $endRow = null) { // Set subject $this->subject = $subject; $this->resetEnd($endRow); $this->resetStart($startRow); } public function __destruct() { $this->subject = null; // @phpstan-ignore-line } /** * (Re)Set the start row and the current row pointer. * * @param int $startRow The row number at which to start iterating * * @return $this */ public function resetStart(int $startRow = 1) { if ($startRow > $this->subject->getHighestRow()) { throw new PhpSpreadsheetException( "Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})" ); } $this->startRow = $startRow; if ($this->endRow < $this->startRow) { $this->endRow = $this->startRow; } $this->seek($startRow); return $this; } /** * (Re)Set the end row. * * @param int $endRow The row number at which to stop iterating * * @return $this */ public function resetEnd($endRow = null) { $this->endRow = $endRow ?: $this->subject->getHighestRow(); return $this; } /** * Set the row pointer to the selected row. * * @param int $row The row number to set the current pointer at * * @return $this */ public function seek(int $row = 1) { if (($row < $this->startRow) || ($row > $this->endRow)) { throw new PhpSpreadsheetException("Row $row is out of range ({$this->startRow} - {$this->endRow})"); } $this->position = $row; return $this; } /** * Rewind the iterator to the starting row. */ public function rewind(): void { $this->position = $this->startRow; } /** * Return the current row in this worksheet. */ public function current(): Row { return new Row($this->subject, $this->position); } /** * Return the current iterator key. */ public function key(): int { return $this->position; } /** * Set the iterator to its next value. */ public function next(): void { ++$this->position; } /** * Set the iterator to its previous value. */ public function prev(): void { --$this->position; } /** * Indicate if more rows exist in the worksheet range of rows that we're iterating. */ public function valid(): bool { return $this->position <= $this->endRow && $this->position >= $this->startRow; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php 0000644 00000010612 15002227416 0020723 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use Iterator as NativeIterator; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @implements NativeIterator<string, Column> */ class ColumnIterator implements NativeIterator { /** * Worksheet to iterate. * * @var Worksheet */ private $worksheet; /** * Current iterator position. * * @var int */ private $currentColumnIndex = 1; /** * Start position. * * @var int */ private $startColumnIndex = 1; /** * End position. * * @var int */ private $endColumnIndex = 1; /** * Create a new column iterator. * * @param Worksheet $worksheet The worksheet to iterate over * @param string $startColumn The column address at which to start iterating * @param string $endColumn Optionally, the column address at which to stop iterating */ public function __construct(Worksheet $worksheet, $startColumn = 'A', $endColumn = null) { // Set subject $this->worksheet = $worksheet; $this->resetEnd($endColumn); $this->resetStart($startColumn); } /** * Destructor. */ public function __destruct() { // @phpstan-ignore-next-line $this->worksheet = null; } /** * (Re)Set the start column and the current column pointer. * * @param string $startColumn The column address at which to start iterating * * @return $this */ public function resetStart(string $startColumn = 'A') { $startColumnIndex = Coordinate::columnIndexFromString($startColumn); if ($startColumnIndex > Coordinate::columnIndexFromString($this->worksheet->getHighestColumn())) { throw new Exception( "Start column ({$startColumn}) is beyond highest column ({$this->worksheet->getHighestColumn()})" ); } $this->startColumnIndex = $startColumnIndex; if ($this->endColumnIndex < $this->startColumnIndex) { $this->endColumnIndex = $this->startColumnIndex; } $this->seek($startColumn); return $this; } /** * (Re)Set the end column. * * @param string $endColumn The column address at which to stop iterating * * @return $this */ public function resetEnd($endColumn = null) { $endColumn = $endColumn ?: $this->worksheet->getHighestColumn(); $this->endColumnIndex = Coordinate::columnIndexFromString($endColumn); return $this; } /** * Set the column pointer to the selected column. * * @param string $column The column address to set the current pointer at * * @return $this */ public function seek(string $column = 'A') { $column = Coordinate::columnIndexFromString($column); if (($column < $this->startColumnIndex) || ($column > $this->endColumnIndex)) { throw new PhpSpreadsheetException( "Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})" ); } $this->currentColumnIndex = $column; return $this; } /** * Rewind the iterator to the starting column. */ public function rewind(): void { $this->currentColumnIndex = $this->startColumnIndex; } /** * Return the current column in this worksheet. */ public function current(): Column { return new Column($this->worksheet, Coordinate::stringFromColumnIndex($this->currentColumnIndex)); } /** * Return the current iterator key. */ public function key(): string { return Coordinate::stringFromColumnIndex($this->currentColumnIndex); } /** * Set the iterator to its next value. */ public function next(): void { ++$this->currentColumnIndex; } /** * Set the iterator to its previous value. */ public function prev(): void { --$this->currentColumnIndex; } /** * Indicate if more columns exist in the worksheet range of columns that we're iterating. */ public function valid(): bool { return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php 0000644 00000035132 15002227416 0022202 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; class Rule { const AUTOFILTER_RULETYPE_FILTER = 'filter'; const AUTOFILTER_RULETYPE_DATEGROUP = 'dateGroupItem'; const AUTOFILTER_RULETYPE_CUSTOMFILTER = 'customFilter'; const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter'; const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter'; private const RULE_TYPES = [ // Currently we're not handling // colorFilter // extLst // iconFilter self::AUTOFILTER_RULETYPE_FILTER, self::AUTOFILTER_RULETYPE_DATEGROUP, self::AUTOFILTER_RULETYPE_CUSTOMFILTER, self::AUTOFILTER_RULETYPE_DYNAMICFILTER, self::AUTOFILTER_RULETYPE_TOPTENFILTER, ]; const AUTOFILTER_RULETYPE_DATEGROUP_YEAR = 'year'; const AUTOFILTER_RULETYPE_DATEGROUP_MONTH = 'month'; const AUTOFILTER_RULETYPE_DATEGROUP_DAY = 'day'; const AUTOFILTER_RULETYPE_DATEGROUP_HOUR = 'hour'; const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute'; const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second'; private const DATE_TIME_GROUPS = [ self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR, self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH, self::AUTOFILTER_RULETYPE_DATEGROUP_DAY, self::AUTOFILTER_RULETYPE_DATEGROUP_HOUR, self::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE, self::AUTOFILTER_RULETYPE_DATEGROUP_SECOND, ]; const AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY = 'yesterday'; const AUTOFILTER_RULETYPE_DYNAMIC_TODAY = 'today'; const AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW = 'tomorrow'; const AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE = 'yearToDate'; const AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR = 'thisYear'; const AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER = 'thisQuarter'; const AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH = 'thisMonth'; const AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK = 'thisWeek'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR = 'lastYear'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER = 'lastQuarter'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH = 'lastMonth'; const AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK = 'lastWeek'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR = 'nextYear'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER = 'nextQuarter'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH = 'nextMonth'; const AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK = 'nextWeek'; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 = 'M1'; const AUTOFILTER_RULETYPE_DYNAMIC_JANUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 = 'M2'; const AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 = 'M3'; const AUTOFILTER_RULETYPE_DYNAMIC_MARCH = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 = 'M4'; const AUTOFILTER_RULETYPE_DYNAMIC_APRIL = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 = 'M5'; const AUTOFILTER_RULETYPE_DYNAMIC_MAY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 = 'M6'; const AUTOFILTER_RULETYPE_DYNAMIC_JUNE = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 = 'M7'; const AUTOFILTER_RULETYPE_DYNAMIC_JULY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 = 'M8'; const AUTOFILTER_RULETYPE_DYNAMIC_AUGUST = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 = 'M9'; const AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 = 'M10'; const AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 = 'M11'; const AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11; const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 = 'M12'; const AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 = 'Q1'; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 = 'Q2'; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 = 'Q3'; const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 = 'Q4'; const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage'; const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage'; private const DYNAMIC_TYPES = [ self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW, self::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE, self::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR, self::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER, self::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH, self::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH, self::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH, self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11, self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3, self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4, self::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE, self::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE, ]; // Filter rule operators for filter and customFilter types. const AUTOFILTER_COLUMN_RULE_EQUAL = 'equal'; const AUTOFILTER_COLUMN_RULE_NOTEQUAL = 'notEqual'; const AUTOFILTER_COLUMN_RULE_GREATERTHAN = 'greaterThan'; const AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL = 'greaterThanOrEqual'; const AUTOFILTER_COLUMN_RULE_LESSTHAN = 'lessThan'; const AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL = 'lessThanOrEqual'; private const OPERATORS = [ self::AUTOFILTER_COLUMN_RULE_EQUAL, self::AUTOFILTER_COLUMN_RULE_NOTEQUAL, self::AUTOFILTER_COLUMN_RULE_GREATERTHAN, self::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, self::AUTOFILTER_COLUMN_RULE_LESSTHAN, self::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL, ]; const AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE = 'byValue'; const AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT = 'byPercent'; private const TOP_TEN_VALUE = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, self::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, ]; const AUTOFILTER_COLUMN_RULE_TOPTEN_TOP = 'top'; const AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM = 'bottom'; private const TOP_TEN_TYPE = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, self::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, ]; // Unimplented Rule Operators (Numeric, Boolean etc) // const AUTOFILTER_COLUMN_RULE_BETWEEN = 'between'; // greaterThanOrEqual 1 && lessThanOrEqual 2 // Rule Operators (Numeric Special) which are translated to standard numeric operators with calculated values // Rule Operators (String) which are set as wild-carded values // const AUTOFILTER_COLUMN_RULE_BEGINSWITH = 'beginsWith'; // A* // const AUTOFILTER_COLUMN_RULE_ENDSWITH = 'endsWith'; // *Z // const AUTOFILTER_COLUMN_RULE_CONTAINS = 'contains'; // *B* // const AUTOFILTER_COLUMN_RULE_DOESNTCONTAIN = 'notEqual'; // notEqual *B* // Rule Operators (Date Special) which are translated to standard numeric operators with calculated values // const AUTOFILTER_COLUMN_RULE_BEFORE = 'lessThan'; // const AUTOFILTER_COLUMN_RULE_AFTER = 'greaterThan'; /** * Autofilter Column. * * @var ?Column */ private $parent; /** * Autofilter Rule Type. * * @var string */ private $ruleType = self::AUTOFILTER_RULETYPE_FILTER; /** * Autofilter Rule Value. * * @var int|int[]|string|string[] */ private $value = ''; /** * Autofilter Rule Operator. * * @var string */ private $operator = self::AUTOFILTER_COLUMN_RULE_EQUAL; /** * DateTimeGrouping Group Value. * * @var string */ private $grouping = ''; /** * Create a new Rule. */ public function __construct(?Column $parent = null) { $this->parent = $parent; } private function setEvaluatedFalse(): void { if ($this->parent !== null) { $this->parent->setEvaluatedFalse(); } } /** * Get AutoFilter Rule Type. * * @return string */ public function getRuleType() { return $this->ruleType; } /** * Set AutoFilter Rule Type. * * @param string $ruleType see self::AUTOFILTER_RULETYPE_* * * @return $this */ public function setRuleType($ruleType) { $this->setEvaluatedFalse(); if (!in_array($ruleType, self::RULE_TYPES)) { throw new PhpSpreadsheetException('Invalid rule type for column AutoFilter Rule.'); } $this->ruleType = $ruleType; return $this; } /** * Get AutoFilter Rule Value. * * @return int|int[]|string|string[] */ public function getValue() { return $this->value; } /** * Set AutoFilter Rule Value. * * @param int|int[]|string|string[] $value * * @return $this */ public function setValue($value) { $this->setEvaluatedFalse(); if (is_array($value)) { $grouping = -1; foreach ($value as $key => $v) { // Validate array entries if (!in_array($key, self::DATE_TIME_GROUPS)) { // Remove any invalid entries from the value array unset($value[$key]); } else { // Work out what the dateTime grouping will be $grouping = max($grouping, array_search($key, self::DATE_TIME_GROUPS)); } } if (count($value) == 0) { throw new PhpSpreadsheetException('Invalid rule value for column AutoFilter Rule.'); } // Set the dateTime grouping that we've anticipated $this->setGrouping(self::DATE_TIME_GROUPS[$grouping]); } $this->value = $value; return $this; } /** * Get AutoFilter Rule Operator. * * @return string */ public function getOperator() { return $this->operator; } /** * Set AutoFilter Rule Operator. * * @param string $operator see self::AUTOFILTER_COLUMN_RULE_* * * @return $this */ public function setOperator($operator) { $this->setEvaluatedFalse(); if (empty($operator)) { $operator = self::AUTOFILTER_COLUMN_RULE_EQUAL; } if ( (!in_array($operator, self::OPERATORS)) && (!in_array($operator, self::TOP_TEN_VALUE)) ) { throw new PhpSpreadsheetException('Invalid operator for column AutoFilter Rule.'); } $this->operator = $operator; return $this; } /** * Get AutoFilter Rule Grouping. * * @return string */ public function getGrouping() { return $this->grouping; } /** * Set AutoFilter Rule Grouping. * * @param string $grouping * * @return $this */ public function setGrouping($grouping) { $this->setEvaluatedFalse(); if ( ($grouping !== null) && (!in_array($grouping, self::DATE_TIME_GROUPS)) && (!in_array($grouping, self::DYNAMIC_TYPES)) && (!in_array($grouping, self::TOP_TEN_TYPE)) ) { throw new PhpSpreadsheetException('Invalid grouping for column AutoFilter Rule.'); } $this->grouping = $grouping; return $this; } /** * Set AutoFilter Rule. * * @param string $operator see self::AUTOFILTER_COLUMN_RULE_* * @param int|int[]|string|string[] $value * @param string $grouping * * @return $this */ public function setRule($operator, $value, $grouping = null) { $this->setEvaluatedFalse(); $this->setOperator($operator); $this->setValue($value); // Only set grouping if it's been passed in as a user-supplied argument, // otherwise we're calculating it when we setValue() and don't want to overwrite that // If the user supplies an argumnet for grouping, then on their own head be it if ($grouping !== null) { $this->setGrouping($grouping); } return $this; } /** * Get this Rule's AutoFilter Column Parent. * * @return ?Column */ public function getParent() { return $this->parent; } /** * Set this Rule's AutoFilter Column Parent. * * @return $this */ public function setParent(?Column $parent = null) { $this->setEvaluatedFalse(); $this->parent = $parent; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { if ($key == 'parent') { // this is only object // Detach from autofilter column parent $this->$key = null; } } else { $this->$key = $value; } } } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php 0000644 00000022476 15002227416 0021302 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; class Column { const AUTOFILTER_FILTERTYPE_FILTER = 'filters'; const AUTOFILTER_FILTERTYPE_CUSTOMFILTER = 'customFilters'; // Supports no more than 2 rules, with an And/Or join criteria // if more than 1 rule is defined const AUTOFILTER_FILTERTYPE_DYNAMICFILTER = 'dynamicFilter'; // Even though the filter rule is constant, the filtered data can vary // e.g. filtered by date = TODAY const AUTOFILTER_FILTERTYPE_TOPTENFILTER = 'top10'; /** * Types of autofilter rules. * * @var string[] */ private static $filterTypes = [ // Currently we're not handling // colorFilter // extLst // iconFilter self::AUTOFILTER_FILTERTYPE_FILTER, self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER, self::AUTOFILTER_FILTERTYPE_DYNAMICFILTER, self::AUTOFILTER_FILTERTYPE_TOPTENFILTER, ]; // Multiple Rule Connections const AUTOFILTER_COLUMN_JOIN_AND = 'and'; const AUTOFILTER_COLUMN_JOIN_OR = 'or'; /** * Join options for autofilter rules. * * @var string[] */ private static $ruleJoins = [ self::AUTOFILTER_COLUMN_JOIN_AND, self::AUTOFILTER_COLUMN_JOIN_OR, ]; /** * Autofilter. * * @var null|AutoFilter */ private $parent; /** * Autofilter Column Index. * * @var string */ private $columnIndex = ''; /** * Autofilter Column Filter Type. * * @var string */ private $filterType = self::AUTOFILTER_FILTERTYPE_FILTER; /** * Autofilter Multiple Rules And/Or. * * @var string */ private $join = self::AUTOFILTER_COLUMN_JOIN_OR; /** * Autofilter Column Rules. * * @var Column\Rule[] */ private $ruleset = []; /** * Autofilter Column Dynamic Attributes. * * @var mixed[] */ private $attributes = []; /** * Create a new Column. * * @param string $column Column (e.g. A) * @param AutoFilter $parent Autofilter for this column */ public function __construct($column, ?AutoFilter $parent = null) { $this->columnIndex = $column; $this->parent = $parent; } public function setEvaluatedFalse(): void { if ($this->parent !== null) { $this->parent->setEvaluated(false); } } /** * Get AutoFilter column index as string eg: 'A'. * * @return string */ public function getColumnIndex() { return $this->columnIndex; } /** * Set AutoFilter column index as string eg: 'A'. * * @param string $column Column (e.g. A) * * @return $this */ public function setColumnIndex($column) { $this->setEvaluatedFalse(); // Uppercase coordinate $column = strtoupper($column); if ($this->parent !== null) { $this->parent->testColumnInRange($column); } $this->columnIndex = $column; return $this; } /** * Get this Column's AutoFilter Parent. * * @return null|AutoFilter */ public function getParent() { return $this->parent; } /** * Set this Column's AutoFilter Parent. * * @return $this */ public function setParent(?AutoFilter $parent = null) { $this->setEvaluatedFalse(); $this->parent = $parent; return $this; } /** * Get AutoFilter Type. * * @return string */ public function getFilterType() { return $this->filterType; } /** * Set AutoFilter Type. * * @param string $filterType * * @return $this */ public function setFilterType($filterType) { $this->setEvaluatedFalse(); if (!in_array($filterType, self::$filterTypes)) { throw new PhpSpreadsheetException('Invalid filter type for column AutoFilter.'); } if ($filterType === self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER && count($this->ruleset) > 2) { throw new PhpSpreadsheetException('No more than 2 rules are allowed in a Custom Filter'); } $this->filterType = $filterType; return $this; } /** * Get AutoFilter Multiple Rules And/Or Join. * * @return string */ public function getJoin() { return $this->join; } /** * Set AutoFilter Multiple Rules And/Or. * * @param string $join And/Or * * @return $this */ public function setJoin($join) { $this->setEvaluatedFalse(); // Lowercase And/Or $join = strtolower($join); if (!in_array($join, self::$ruleJoins)) { throw new PhpSpreadsheetException('Invalid rule connection for column AutoFilter.'); } $this->join = $join; return $this; } /** * Set AutoFilter Attributes. * * @param mixed[] $attributes * * @return $this */ public function setAttributes($attributes) { $this->setEvaluatedFalse(); $this->attributes = $attributes; return $this; } /** * Set An AutoFilter Attribute. * * @param string $name Attribute Name * @param int|string $value Attribute Value * * @return $this */ public function setAttribute($name, $value) { $this->setEvaluatedFalse(); $this->attributes[$name] = $value; return $this; } /** * Get AutoFilter Column Attributes. * * @return int[]|string[] */ public function getAttributes() { return $this->attributes; } /** * Get specific AutoFilter Column Attribute. * * @param string $name Attribute Name * * @return null|int|string */ public function getAttribute($name) { if (isset($this->attributes[$name])) { return $this->attributes[$name]; } return null; } public function ruleCount(): int { return count($this->ruleset); } /** * Get all AutoFilter Column Rules. * * @return Column\Rule[] */ public function getRules() { return $this->ruleset; } /** * Get a specified AutoFilter Column Rule. * * @param int $index Rule index in the ruleset array * * @return Column\Rule */ public function getRule($index) { if (!isset($this->ruleset[$index])) { $this->ruleset[$index] = new Column\Rule($this); } return $this->ruleset[$index]; } /** * Create a new AutoFilter Column Rule in the ruleset. * * @return Column\Rule */ public function createRule() { $this->setEvaluatedFalse(); if ($this->filterType === self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER && count($this->ruleset) >= 2) { throw new PhpSpreadsheetException('No more than 2 rules are allowed in a Custom Filter'); } $this->ruleset[] = new Column\Rule($this); return end($this->ruleset); } /** * Add a new AutoFilter Column Rule to the ruleset. * * @return $this */ public function addRule(Column\Rule $rule) { $this->setEvaluatedFalse(); $rule->setParent($this); $this->ruleset[] = $rule; return $this; } /** * Delete a specified AutoFilter Column Rule * If the number of rules is reduced to 1, then we reset And/Or logic to Or. * * @param int $index Rule index in the ruleset array * * @return $this */ public function deleteRule($index) { $this->setEvaluatedFalse(); if (isset($this->ruleset[$index])) { unset($this->ruleset[$index]); // If we've just deleted down to a single rule, then reset And/Or joining to Or if (count($this->ruleset) <= 1) { $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); } } return $this; } /** * Delete all AutoFilter Column Rules. * * @return $this */ public function clearRules() { $this->setEvaluatedFalse(); $this->ruleset = []; $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if ($key === 'parent') { // Detach from autofilter parent $this->parent = null; } elseif ($key === 'ruleset') { // The columns array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\AutoFilter objects $this->ruleset = []; foreach ($value as $k => $v) { $cloned = clone $v; $cloned->setParent($this); // attach the new cloned Rule to this new cloned Autofilter Cloned object $this->ruleset[$k] = $cloned; } } else { $this->$key = $value; } } } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/TableStyle.php 0000644 00000013712 15002227416 0021057 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Worksheet\Table; class TableStyle { const TABLE_STYLE_NONE = ''; const TABLE_STYLE_LIGHT1 = 'TableStyleLight1'; const TABLE_STYLE_LIGHT2 = 'TableStyleLight2'; const TABLE_STYLE_LIGHT3 = 'TableStyleLight3'; const TABLE_STYLE_LIGHT4 = 'TableStyleLight4'; const TABLE_STYLE_LIGHT5 = 'TableStyleLight5'; const TABLE_STYLE_LIGHT6 = 'TableStyleLight6'; const TABLE_STYLE_LIGHT7 = 'TableStyleLight7'; const TABLE_STYLE_LIGHT8 = 'TableStyleLight8'; const TABLE_STYLE_LIGHT9 = 'TableStyleLight9'; const TABLE_STYLE_LIGHT10 = 'TableStyleLight10'; const TABLE_STYLE_LIGHT11 = 'TableStyleLight11'; const TABLE_STYLE_LIGHT12 = 'TableStyleLight12'; const TABLE_STYLE_LIGHT13 = 'TableStyleLight13'; const TABLE_STYLE_LIGHT14 = 'TableStyleLight14'; const TABLE_STYLE_LIGHT15 = 'TableStyleLight15'; const TABLE_STYLE_LIGHT16 = 'TableStyleLight16'; const TABLE_STYLE_LIGHT17 = 'TableStyleLight17'; const TABLE_STYLE_LIGHT18 = 'TableStyleLight18'; const TABLE_STYLE_LIGHT19 = 'TableStyleLight19'; const TABLE_STYLE_LIGHT20 = 'TableStyleLight20'; const TABLE_STYLE_LIGHT21 = 'TableStyleLight21'; const TABLE_STYLE_MEDIUM1 = 'TableStyleMedium1'; const TABLE_STYLE_MEDIUM2 = 'TableStyleMedium2'; const TABLE_STYLE_MEDIUM3 = 'TableStyleMedium3'; const TABLE_STYLE_MEDIUM4 = 'TableStyleMedium4'; const TABLE_STYLE_MEDIUM5 = 'TableStyleMedium5'; const TABLE_STYLE_MEDIUM6 = 'TableStyleMedium6'; const TABLE_STYLE_MEDIUM7 = 'TableStyleMedium7'; const TABLE_STYLE_MEDIUM8 = 'TableStyleMedium8'; const TABLE_STYLE_MEDIUM9 = 'TableStyleMedium9'; const TABLE_STYLE_MEDIUM10 = 'TableStyleMedium10'; const TABLE_STYLE_MEDIUM11 = 'TableStyleMedium11'; const TABLE_STYLE_MEDIUM12 = 'TableStyleMedium12'; const TABLE_STYLE_MEDIUM13 = 'TableStyleMedium13'; const TABLE_STYLE_MEDIUM14 = 'TableStyleMedium14'; const TABLE_STYLE_MEDIUM15 = 'TableStyleMedium15'; const TABLE_STYLE_MEDIUM16 = 'TableStyleMedium16'; const TABLE_STYLE_MEDIUM17 = 'TableStyleMedium17'; const TABLE_STYLE_MEDIUM18 = 'TableStyleMedium18'; const TABLE_STYLE_MEDIUM19 = 'TableStyleMedium19'; const TABLE_STYLE_MEDIUM20 = 'TableStyleMedium20'; const TABLE_STYLE_MEDIUM21 = 'TableStyleMedium21'; const TABLE_STYLE_MEDIUM22 = 'TableStyleMedium22'; const TABLE_STYLE_MEDIUM23 = 'TableStyleMedium23'; const TABLE_STYLE_MEDIUM24 = 'TableStyleMedium24'; const TABLE_STYLE_MEDIUM25 = 'TableStyleMedium25'; const TABLE_STYLE_MEDIUM26 = 'TableStyleMedium26'; const TABLE_STYLE_MEDIUM27 = 'TableStyleMedium27'; const TABLE_STYLE_MEDIUM28 = 'TableStyleMedium28'; const TABLE_STYLE_DARK1 = 'TableStyleDark1'; const TABLE_STYLE_DARK2 = 'TableStyleDark2'; const TABLE_STYLE_DARK3 = 'TableStyleDark3'; const TABLE_STYLE_DARK4 = 'TableStyleDark4'; const TABLE_STYLE_DARK5 = 'TableStyleDark5'; const TABLE_STYLE_DARK6 = 'TableStyleDark6'; const TABLE_STYLE_DARK7 = 'TableStyleDark7'; const TABLE_STYLE_DARK8 = 'TableStyleDark8'; const TABLE_STYLE_DARK9 = 'TableStyleDark9'; const TABLE_STYLE_DARK10 = 'TableStyleDark10'; const TABLE_STYLE_DARK11 = 'TableStyleDark11'; /** * Theme. * * @var string */ private $theme; /** * Show First Column. * * @var bool */ private $showFirstColumn = false; /** * Show Last Column. * * @var bool */ private $showLastColumn = false; /** * Show Row Stripes. * * @var bool */ private $showRowStripes = false; /** * Show Column Stripes. * * @var bool */ private $showColumnStripes = false; /** * Table. * * @var null|Table */ private $table; /** * Create a new Table Style. * * @param string $theme (e.g. TableStyle::TABLE_STYLE_MEDIUM2) */ public function __construct(string $theme = self::TABLE_STYLE_MEDIUM2) { $this->theme = $theme; } /** * Get theme. */ public function getTheme(): string { return $this->theme; } /** * Set theme. */ public function setTheme(string $theme): self { $this->theme = $theme; return $this; } /** * Get show First Column. */ public function getShowFirstColumn(): bool { return $this->showFirstColumn; } /** * Set show First Column. */ public function setShowFirstColumn(bool $showFirstColumn): self { $this->showFirstColumn = $showFirstColumn; return $this; } /** * Get show Last Column. */ public function getShowLastColumn(): bool { return $this->showLastColumn; } /** * Set show Last Column. */ public function setShowLastColumn(bool $showLastColumn): self { $this->showLastColumn = $showLastColumn; return $this; } /** * Get show Row Stripes. */ public function getShowRowStripes(): bool { return $this->showRowStripes; } /** * Set show Row Stripes. */ public function setShowRowStripes(bool $showRowStripes): self { $this->showRowStripes = $showRowStripes; return $this; } /** * Get show Column Stripes. */ public function getShowColumnStripes(): bool { return $this->showColumnStripes; } /** * Set show Column Stripes. */ public function setShowColumnStripes(bool $showColumnStripes): self { $this->showColumnStripes = $showColumnStripes; return $this; } /** * Get this Style's Table. */ public function getTable(): ?Table { return $this->table; } /** * Set this Style's Table. */ public function setTable(?Table $table = null): self { $this->table = $table; return $this; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/Column.php 0000644 00000013771 15002227416 0020251 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Column { /** * Table Column Index. * * @var string */ private $columnIndex = ''; /** * Show Filter Button. * * @var bool */ private $showFilterButton = true; /** * Total Row Label. * * @var string */ private $totalsRowLabel; /** * Total Row Function. * * @var string */ private $totalsRowFunction; /** * Total Row Formula. * * @var string */ private $totalsRowFormula; /** * Column Formula. * * @var string */ private $columnFormula; /** * Table. * * @var null|Table */ private $table; /** * Create a new Column. * * @param string $column Column (e.g. A) * @param Table $table Table for this column */ public function __construct($column, ?Table $table = null) { $this->columnIndex = $column; $this->table = $table; } /** * Get Table column index as string eg: 'A'. */ public function getColumnIndex(): string { return $this->columnIndex; } /** * Set Table column index as string eg: 'A'. * * @param string $column Column (e.g. A) */ public function setColumnIndex($column): self { // Uppercase coordinate $column = strtoupper($column); if ($this->table !== null) { $this->table->isColumnInRange($column); } $this->columnIndex = $column; return $this; } /** * Get show Filter Button. */ public function getShowFilterButton(): bool { return $this->showFilterButton; } /** * Set show Filter Button. */ public function setShowFilterButton(bool $showFilterButton): self { $this->showFilterButton = $showFilterButton; return $this; } /** * Get total Row Label. */ public function getTotalsRowLabel(): ?string { return $this->totalsRowLabel; } /** * Set total Row Label. */ public function setTotalsRowLabel(string $totalsRowLabel): self { $this->totalsRowLabel = $totalsRowLabel; return $this; } /** * Get total Row Function. */ public function getTotalsRowFunction(): ?string { return $this->totalsRowFunction; } /** * Set total Row Function. */ public function setTotalsRowFunction(string $totalsRowFunction): self { $this->totalsRowFunction = $totalsRowFunction; return $this; } /** * Get total Row Formula. */ public function getTotalsRowFormula(): ?string { return $this->totalsRowFormula; } /** * Set total Row Formula. */ public function setTotalsRowFormula(string $totalsRowFormula): self { $this->totalsRowFormula = $totalsRowFormula; return $this; } /** * Get column Formula. */ public function getColumnFormula(): ?string { return $this->columnFormula; } /** * Set column Formula. */ public function setColumnFormula(string $columnFormula): self { $this->columnFormula = $columnFormula; return $this; } /** * Get this Column's Table. */ public function getTable(): ?Table { return $this->table; } /** * Set this Column's Table. */ public function setTable(?Table $table = null): self { $this->table = $table; return $this; } public static function updateStructuredReferences(?Worksheet $workSheet, ?string $oldTitle, ?string $newTitle): void { if ($workSheet === null || $oldTitle === null || $oldTitle === '' || $newTitle === null) { return; } // Remember that table headings are case-insensitive if (StringHelper::strToLower($oldTitle) !== StringHelper::strToLower($newTitle)) { // We need to check all formula cells that might contain Structured References that refer // to this column, and update those formulae to reference the new column text $spreadsheet = $workSheet->getParentOrThrow(); foreach ($spreadsheet->getWorksheetIterator() as $sheet) { self::updateStructuredReferencesInCells($sheet, $oldTitle, $newTitle); } self::updateStructuredReferencesInNamedFormulae($spreadsheet, $oldTitle, $newTitle); } } private static function updateStructuredReferencesInCells(Worksheet $worksheet, string $oldTitle, string $newTitle): void { $pattern = '/\[(@?)' . preg_quote($oldTitle, '/') . '\]/mui'; foreach ($worksheet->getCoordinates(false) as $coordinate) { $cell = $worksheet->getCell($coordinate); if ($cell->getDataType() === DataType::TYPE_FORMULA) { $formula = $cell->getValue(); if (preg_match($pattern, $formula) === 1) { $formula = preg_replace($pattern, "[$1{$newTitle}]", $formula); $cell->setValueExplicit($formula, DataType::TYPE_FORMULA); } } } } private static function updateStructuredReferencesInNamedFormulae(Spreadsheet $spreadsheet, string $oldTitle, string $newTitle): void { $pattern = '/\[(@?)' . preg_quote($oldTitle, '/') . '\]/mui'; foreach ($spreadsheet->getNamedFormulae() as $namedFormula) { $formula = $namedFormula->getValue(); if (preg_match($pattern, $formula) === 1) { $formula = preg_replace($pattern, "[$1{$newTitle}]", $formula); $namedFormula->setValue($formula); // @phpstan-ignore-line } } } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php 0000644 00000006455 15002227416 0021071 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; class ColumnDimension extends Dimension { /** * Column index. * * @var ?string */ private $columnIndex; /** * Column width. * * When this is set to a negative value, the column width should be ignored by IWriter * * @var float */ private $width = -1; /** * Auto size? * * @var bool */ private $autoSize = false; /** * Create a new ColumnDimension. * * @param ?string $index Character column index */ public function __construct($index = 'A') { // Initialise values $this->columnIndex = $index; // set dimension as unformatted by default parent::__construct(0); } /** * Get column index as string eg: 'A'. */ public function getColumnIndex(): ?string { return $this->columnIndex; } /** * Set column index as string eg: 'A'. */ public function setColumnIndex(string $index): self { $this->columnIndex = $index; return $this; } /** * Get column index as numeric. */ public function getColumnNumeric(): int { return Coordinate::columnIndexFromString($this->columnIndex ?? ''); } /** * Set column index as numeric. */ public function setColumnNumeric(int $index): self { $this->columnIndex = Coordinate::stringFromColumnIndex($index); return $this; } /** * Get Width. * * Each unit of column width is equal to the width of one character in the default font size. A value of -1 * tells Excel to display this column in its default width. * By default, this will be the return value; but this method also accepts an optional unit of measure argument * and will convert the returned value to the specified UoM.. */ public function getWidth(?string $unitOfMeasure = null): float { return ($unitOfMeasure === null || $this->width < 0) ? $this->width : (new CssDimension((string) $this->width))->toUnit($unitOfMeasure); } /** * Set Width. * * Each unit of column width is equal to the width of one character in the default font size. A value of -1 * tells Excel to display this column in its default width. * By default, this will be the unit of measure for the passed value; but this method also accepts an * optional unit of measure argument, and will convert the value from the specified UoM using an * approximation method. * * @return $this */ public function setWidth(float $width, ?string $unitOfMeasure = null) { $this->width = ($unitOfMeasure === null || $width < 0) ? $width : (new CssDimension("{$width}{$unitOfMeasure}"))->width(); return $this; } /** * Get Auto Size. */ public function getAutoSize(): bool { return $this->autoSize; } /** * Set Auto Size. * * @return $this */ public function setAutoSize(bool $autosizeEnabled) { $this->autoSize = $autosizeEnabled; return $this; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php 0000644 00000007700 15002227416 0017663 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class SheetView { // Sheet View types const SHEETVIEW_NORMAL = 'normal'; const SHEETVIEW_PAGE_LAYOUT = 'pageLayout'; const SHEETVIEW_PAGE_BREAK_PREVIEW = 'pageBreakPreview'; private const SHEET_VIEW_TYPES = [ self::SHEETVIEW_NORMAL, self::SHEETVIEW_PAGE_LAYOUT, self::SHEETVIEW_PAGE_BREAK_PREVIEW, ]; /** * ZoomScale. * * Valid values range from 10 to 400. * * @var ?int */ private $zoomScale = 100; /** * ZoomScaleNormal. * * Valid values range from 10 to 400. * * @var ?int */ private $zoomScaleNormal = 100; /** * ShowZeros. * * If true, "null" values from a calculation will be shown as "0". This is the default Excel behaviour and can be changed * with the advanced worksheet option "Show a zero in cells that have zero value" * * @var bool */ private $showZeros = true; /** * View. * * Valid values range from 10 to 400. * * @var string */ private $sheetviewType = self::SHEETVIEW_NORMAL; /** * Create a new SheetView. */ public function __construct() { } /** * Get ZoomScale. * * @return ?int */ public function getZoomScale() { return $this->zoomScale; } /** * Set ZoomScale. * Valid values range from 10 to 400. * * @param ?int $zoomScale * * @return $this */ public function setZoomScale($zoomScale) { // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, // but it is apparently still able to handle any scale >= 1 if ($zoomScale === null || $zoomScale >= 1) { $this->zoomScale = $zoomScale; } else { throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.'); } return $this; } /** * Get ZoomScaleNormal. * * @return ?int */ public function getZoomScaleNormal() { return $this->zoomScaleNormal; } /** * Set ZoomScale. * Valid values range from 10 to 400. * * @param ?int $zoomScaleNormal * * @return $this */ public function setZoomScaleNormal($zoomScaleNormal) { if ($zoomScaleNormal === null || $zoomScaleNormal >= 1) { $this->zoomScaleNormal = $zoomScaleNormal; } else { throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.'); } return $this; } /** * Set ShowZeroes setting. * * @param bool $showZeros */ public function setShowZeros($showZeros): void { $this->showZeros = $showZeros; } /** * @return bool */ public function getShowZeros() { return $this->showZeros; } /** * Get View. * * @return string */ public function getView() { return $this->sheetviewType; } /** * Set View. * * Valid values are * 'normal' self::SHEETVIEW_NORMAL * 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT * 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW * * @param ?string $sheetViewType * * @return $this */ public function setView($sheetViewType) { // MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview' via the user interface if ($sheetViewType === null) { $sheetViewType = self::SHEETVIEW_NORMAL; } if (in_array($sheetViewType, self::SHEET_VIEW_TYPES)) { $this->sheetviewType = $sheetViewType; } else { throw new PhpSpreadsheetException('Invalid sheetview layout type.'); } return $this; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Validations.php 0000644 00000011073 15002227416 0020233 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\CellAddress; use PhpOffice\PhpSpreadsheet\Cell\CellRange; use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException; class Validations { /** * Validate a cell address. * * @param null|array<int>|CellAddress|string $cellAddress Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. */ public static function validateCellAddress($cellAddress): string { if (is_string($cellAddress)) { [$worksheet, $address] = Worksheet::extractSheetTitle($cellAddress, true); // if (!empty($worksheet) && $worksheet !== $this->getTitle()) { // throw new Exception('Reference is not for this worksheet'); // } return empty($worksheet) ? strtoupper("$address") : $worksheet . '!' . strtoupper("$address"); } if (is_array($cellAddress)) { $cellAddress = CellAddress::fromColumnRowArray($cellAddress); } return (string) $cellAddress; } /** * Validate a cell address or cell range. * * @param AddressRange|array<int>|CellAddress|int|string $cellRange Coordinate of the cells as a string, eg: 'C5:F12'; * or as an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 12]), * or as a CellAddress or AddressRange object. */ public static function validateCellOrCellRange($cellRange): string { if (is_string($cellRange) || is_numeric($cellRange)) { // Convert a single column reference like 'A' to 'A:A', // a single row reference like '1' to '1:1' $cellRange = (string) preg_replace('/^([A-Z]+|\d+)$/', '${1}:${1}', (string) $cellRange); } elseif (is_object($cellRange) && $cellRange instanceof CellAddress) { $cellRange = new CellRange($cellRange, $cellRange); } return self::validateCellRange($cellRange); } private const SETMAXROW = '${1}1:${2}' . AddressRange::MAX_ROW; private const SETMAXCOL = 'A${1}:' . AddressRange::MAX_COLUMN . '${2}'; /** * Validate a cell range. * * @param AddressRange|array<int>|string $cellRange Coordinate of the cells as a string, eg: 'C5:F12'; * or as an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 12]), * or as an AddressRange object. */ public static function validateCellRange($cellRange): string { if (is_string($cellRange)) { [$worksheet, $addressRange] = Worksheet::extractSheetTitle($cellRange, true); // Convert Column ranges like 'A:C' to 'A1:C1048576' // or Row ranges like '1:3' to 'A1:XFD3' $addressRange = (string) preg_replace( ['/^([A-Z]+):([A-Z]+)$/i', '/^(\\d+):(\\d+)$/'], [self::SETMAXROW, self::SETMAXCOL], $addressRange ); return empty($worksheet) ? strtoupper($addressRange) : $worksheet . '!' . strtoupper($addressRange); } if (is_array($cellRange)) { switch (count($cellRange)) { case 2: $from = [$cellRange[0], $cellRange[1]]; $to = [$cellRange[0], $cellRange[1]]; break; case 4: $from = [$cellRange[0], $cellRange[1]]; $to = [$cellRange[2], $cellRange[3]]; break; default: throw new SpreadsheetException('CellRange array length must be 2 or 4'); } $cellRange = new CellRange(CellAddress::fromColumnRowArray($from), CellAddress::fromColumnRowArray($to)); } return (string) $cellRange; } public static function definedNameToCoordinate(string $coordinate, Worksheet $worksheet): string { // Uppercase coordinate $coordinate = strtoupper($coordinate); // Eliminate leading equal sign $testCoordinate = (string) preg_replace('/^=/', '', $coordinate); $defined = $worksheet->getParentOrThrow()->getDefinedName($testCoordinate, $worksheet); if ($defined !== null) { if ($defined->getWorksheet() === $worksheet && !$defined->isFormula()) { $coordinate = (string) preg_replace('/^=/', '', $defined->getValue()); } } return $coordinate; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php 0000644 00000012655 15002227416 0017360 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use ZipArchive; class Drawing extends BaseDrawing { const IMAGE_TYPES_CONVERTION_MAP = [ IMAGETYPE_GIF => IMAGETYPE_PNG, IMAGETYPE_JPEG => IMAGETYPE_JPEG, IMAGETYPE_PNG => IMAGETYPE_PNG, IMAGETYPE_BMP => IMAGETYPE_PNG, ]; /** * Path. * * @var string */ private $path; /** * Whether or not we are dealing with a URL. * * @var bool */ private $isUrl; /** * Create a new Drawing. */ public function __construct() { // Initialise values $this->path = ''; $this->isUrl = false; // Initialize parent parent::__construct(); } /** * Get Filename. * * @return string */ public function getFilename() { return basename($this->path); } /** * Get indexed filename (using image index). */ public function getIndexedFilename(): string { return md5($this->path) . '.' . $this->getExtension(); } /** * Get Extension. * * @return string */ public function getExtension() { $exploded = explode('.', basename($this->path)); return $exploded[count($exploded) - 1]; } /** * Get full filepath to store drawing in zip archive. * * @return string */ public function getMediaFilename() { 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()); } /** * Get Path. * * @return string */ public function getPath() { return $this->path; } /** * Set Path. * * @param string $path File path * @param bool $verifyFile Verify file * @param ZipArchive $zip Zip archive instance * * @return $this */ public function setPath($path, $verifyFile = true, $zip = null) { if ($verifyFile && preg_match('~^data:image/[a-z]+;base64,~', $path) !== 1) { // Check if a URL has been passed. https://stackoverflow.com/a/2058596/1252979 if (filter_var($path, FILTER_VALIDATE_URL)) { $this->path = $path; // Implicit that it is a URL, rather store info than running check above on value in other places. $this->isUrl = true; $imageContents = file_get_contents($path); $filePath = tempnam(sys_get_temp_dir(), 'Drawing'); if ($filePath) { file_put_contents($filePath, $imageContents); if (file_exists($filePath)) { $this->setSizesAndType($filePath); unlink($filePath); } } } elseif (file_exists($path)) { $this->path = $path; $this->setSizesAndType($path); } elseif ($zip instanceof ZipArchive) { $zipPath = explode('#', $path)[1]; if ($zip->locateName($zipPath) !== false) { $this->path = $path; $this->setSizesAndType($path); } } else { throw new PhpSpreadsheetException("File $path not found!"); } } else { $this->path = $path; } return $this; } /** * Get isURL. */ public function getIsURL(): bool { return $this->isUrl; } /** * Set isURL. * * @return $this */ public function setIsURL(bool $isUrl): self { $this->isUrl = $isUrl; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->path . parent::getHashCode() . __CLASS__ ); } /** * Get Image Type for Save. */ public function getImageTypeForSave(): int { 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 self::IMAGE_TYPES_CONVERTION_MAP[$this->type]; } /** * Get Image file extention for Save. */ 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); return "$result"; } /** * Get Image mime type. */ 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]); } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php 0000644 00000026253 15002227416 0020333 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; /** * <code> * Header/Footer Formatting Syntax taken from Office Open XML Part 4 - Markup Language Reference, page 1970:. * * There are a number of formatting codes that can be written inline with the actual header / footer text, which * affect the formatting in the header or footer. * * Example: This example shows the text "Center Bold Header" on the first line (center section), and the date on * the second line (center section). * &CCenter &"-,Bold"Bold&"-,Regular"Header_x000A_&D * * General Rules: * There is no required order in which these codes must appear. * * The first occurrence of the following codes turns the formatting ON, the second occurrence turns it OFF again: * - strikethrough * - superscript * - subscript * Superscript and subscript cannot both be ON at same time. Whichever comes first wins and the other is ignored, * while the first is ON. * &L - code for "left section" (there are three header / footer locations, "left", "center", and "right"). When * two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the * order of appearance, and placed into the left section. * &P - code for "current page #" * &N - code for "total pages" * &font size - code for "text font size", where font size is a font size in points. * &K - code for "text font color" * RGB Color is specified as RRGGBB * Theme Color is specifed as TTSNN where TT is the theme color Id, S is either "+" or "-" of the tint/shade * value, NN is the tint/shade value. * &S - code for "text strikethrough" on / off * &X - code for "text super script" on / off * &Y - code for "text subscript" on / off * &C - code for "center section". When two or more occurrences of this section marker exist, the contents * from all markers are concatenated, in the order of appearance, and placed into the center section. * * &D - code for "date" * &T - code for "time" * &G - code for "picture as background" * &U - code for "text single underline" * &E - code for "double underline" * &R - code for "right section". When two or more occurrences of this section marker exist, the contents * from all markers are concatenated, in the order of appearance, and placed into the right section. * &Z - code for "this workbook's file path" * &F - code for "this workbook's file name" * &A - code for "sheet tab name" * &+ - code for add to page #. * &- - code for subtract from page #. * &"font name,font type" - code for "text font name" and "text font type", where font name and font type * are strings specifying the name and type of the font, separated by a comma. When a hyphen appears in font * name, it means "none specified". Both of font name and font type can be localized values. * &"-,Bold" - code for "bold font style" * &B - also means "bold font style". * &"-,Regular" - code for "regular font style" * &"-,Italic" - code for "italic font style" * &I - also means "italic font style" * &"-,Bold Italic" code for "bold italic font style" * &O - code for "outline style" * &H - code for "shadow style" * </code> */ class HeaderFooter { // Header/footer image location const IMAGE_HEADER_LEFT = 'LH'; const IMAGE_HEADER_CENTER = 'CH'; const IMAGE_HEADER_RIGHT = 'RH'; const IMAGE_FOOTER_LEFT = 'LF'; const IMAGE_FOOTER_CENTER = 'CF'; const IMAGE_FOOTER_RIGHT = 'RF'; /** * OddHeader. * * @var string */ private $oddHeader = ''; /** * OddFooter. * * @var string */ private $oddFooter = ''; /** * EvenHeader. * * @var string */ private $evenHeader = ''; /** * EvenFooter. * * @var string */ private $evenFooter = ''; /** * FirstHeader. * * @var string */ private $firstHeader = ''; /** * FirstFooter. * * @var string */ private $firstFooter = ''; /** * Different header for Odd/Even, defaults to false. * * @var bool */ private $differentOddEven = false; /** * Different header for first page, defaults to false. * * @var bool */ private $differentFirst = false; /** * Scale with document, defaults to true. * * @var bool */ private $scaleWithDocument = true; /** * Align with margins, defaults to true. * * @var bool */ private $alignWithMargins = true; /** * Header/footer images. * * @var HeaderFooterDrawing[] */ private $headerFooterImages = []; /** * Create a new HeaderFooter. */ public function __construct() { } /** * Get OddHeader. * * @return string */ public function getOddHeader() { return $this->oddHeader; } /** * Set OddHeader. * * @param string $oddHeader * * @return $this */ public function setOddHeader($oddHeader) { $this->oddHeader = $oddHeader; return $this; } /** * Get OddFooter. * * @return string */ public function getOddFooter() { return $this->oddFooter; } /** * Set OddFooter. * * @param string $oddFooter * * @return $this */ public function setOddFooter($oddFooter) { $this->oddFooter = $oddFooter; return $this; } /** * Get EvenHeader. * * @return string */ public function getEvenHeader() { return $this->evenHeader; } /** * Set EvenHeader. * * @param string $eventHeader * * @return $this */ public function setEvenHeader($eventHeader) { $this->evenHeader = $eventHeader; return $this; } /** * Get EvenFooter. * * @return string */ public function getEvenFooter() { return $this->evenFooter; } /** * Set EvenFooter. * * @param string $evenFooter * * @return $this */ public function setEvenFooter($evenFooter) { $this->evenFooter = $evenFooter; return $this; } /** * Get FirstHeader. * * @return string */ public function getFirstHeader() { return $this->firstHeader; } /** * Set FirstHeader. * * @param string $firstHeader * * @return $this */ public function setFirstHeader($firstHeader) { $this->firstHeader = $firstHeader; return $this; } /** * Get FirstFooter. * * @return string */ public function getFirstFooter() { return $this->firstFooter; } /** * Set FirstFooter. * * @param string $firstFooter * * @return $this */ public function setFirstFooter($firstFooter) { $this->firstFooter = $firstFooter; return $this; } /** * Get DifferentOddEven. * * @return bool */ public function getDifferentOddEven() { return $this->differentOddEven; } /** * Set DifferentOddEven. * * @param bool $differentOddEvent * * @return $this */ public function setDifferentOddEven($differentOddEvent) { $this->differentOddEven = $differentOddEvent; return $this; } /** * Get DifferentFirst. * * @return bool */ public function getDifferentFirst() { return $this->differentFirst; } /** * Set DifferentFirst. * * @param bool $differentFirst * * @return $this */ public function setDifferentFirst($differentFirst) { $this->differentFirst = $differentFirst; return $this; } /** * Get ScaleWithDocument. * * @return bool */ public function getScaleWithDocument() { return $this->scaleWithDocument; } /** * Set ScaleWithDocument. * * @param bool $scaleWithDocument * * @return $this */ public function setScaleWithDocument($scaleWithDocument) { $this->scaleWithDocument = $scaleWithDocument; return $this; } /** * Get AlignWithMargins. * * @return bool */ public function getAlignWithMargins() { return $this->alignWithMargins; } /** * Set AlignWithMargins. * * @param bool $alignWithMargins * * @return $this */ public function setAlignWithMargins($alignWithMargins) { $this->alignWithMargins = $alignWithMargins; return $this; } /** * Add header/footer image. * * @param string $location * * @return $this */ public function addImage(HeaderFooterDrawing $image, $location = self::IMAGE_HEADER_LEFT) { $this->headerFooterImages[$location] = $image; return $this; } /** * Remove header/footer image. * * @param string $location * * @return $this */ public function removeImage($location = self::IMAGE_HEADER_LEFT) { if (isset($this->headerFooterImages[$location])) { unset($this->headerFooterImages[$location]); } return $this; } /** * Set header/footer images. * * @param HeaderFooterDrawing[] $images * * @return $this */ public function setImages(array $images) { $this->headerFooterImages = $images; return $this; } /** * Get header/footer images. * * @return HeaderFooterDrawing[] */ public function getImages() { // Sort array $images = []; if (isset($this->headerFooterImages[self::IMAGE_HEADER_LEFT])) { $images[self::IMAGE_HEADER_LEFT] = $this->headerFooterImages[self::IMAGE_HEADER_LEFT]; } if (isset($this->headerFooterImages[self::IMAGE_HEADER_CENTER])) { $images[self::IMAGE_HEADER_CENTER] = $this->headerFooterImages[self::IMAGE_HEADER_CENTER]; } if (isset($this->headerFooterImages[self::IMAGE_HEADER_RIGHT])) { $images[self::IMAGE_HEADER_RIGHT] = $this->headerFooterImages[self::IMAGE_HEADER_RIGHT]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_LEFT])) { $images[self::IMAGE_FOOTER_LEFT] = $this->headerFooterImages[self::IMAGE_FOOTER_LEFT]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_CENTER])) { $images[self::IMAGE_FOOTER_CENTER] = $this->headerFooterImages[self::IMAGE_FOOTER_CENTER]; } if (isset($this->headerFooterImages[self::IMAGE_FOOTER_RIGHT])) { $images[self::IMAGE_FOOTER_RIGHT] = $this->headerFooterImages[self::IMAGE_FOOTER_RIGHT]; } $this->headerFooterImages = $images; return $this->headerFooterImages; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php 0000644 00000065233 15002227416 0017662 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * <code> * Paper size taken from Office Open XML Part 4 - Markup Language Reference, page 1988:. * * 1 = Letter paper (8.5 in. by 11 in.) * 2 = Letter small paper (8.5 in. by 11 in.) * 3 = Tabloid paper (11 in. by 17 in.) * 4 = Ledger paper (17 in. by 11 in.) * 5 = Legal paper (8.5 in. by 14 in.) * 6 = Statement paper (5.5 in. by 8.5 in.) * 7 = Executive paper (7.25 in. by 10.5 in.) * 8 = A3 paper (297 mm by 420 mm) * 9 = A4 paper (210 mm by 297 mm) * 10 = A4 small paper (210 mm by 297 mm) * 11 = A5 paper (148 mm by 210 mm) * 12 = B4 paper (250 mm by 353 mm) * 13 = B5 paper (176 mm by 250 mm) * 14 = Folio paper (8.5 in. by 13 in.) * 15 = Quarto paper (215 mm by 275 mm) * 16 = Standard paper (10 in. by 14 in.) * 17 = Standard paper (11 in. by 17 in.) * 18 = Note paper (8.5 in. by 11 in.) * 19 = #9 envelope (3.875 in. by 8.875 in.) * 20 = #10 envelope (4.125 in. by 9.5 in.) * 21 = #11 envelope (4.5 in. by 10.375 in.) * 22 = #12 envelope (4.75 in. by 11 in.) * 23 = #14 envelope (5 in. by 11.5 in.) * 24 = C paper (17 in. by 22 in.) * 25 = D paper (22 in. by 34 in.) * 26 = E paper (34 in. by 44 in.) * 27 = DL envelope (110 mm by 220 mm) * 28 = C5 envelope (162 mm by 229 mm) * 29 = C3 envelope (324 mm by 458 mm) * 30 = C4 envelope (229 mm by 324 mm) * 31 = C6 envelope (114 mm by 162 mm) * 32 = C65 envelope (114 mm by 229 mm) * 33 = B4 envelope (250 mm by 353 mm) * 34 = B5 envelope (176 mm by 250 mm) * 35 = B6 envelope (176 mm by 125 mm) * 36 = Italy envelope (110 mm by 230 mm) * 37 = Monarch envelope (3.875 in. by 7.5 in.). * 38 = 6 3/4 envelope (3.625 in. by 6.5 in.) * 39 = US standard fanfold (14.875 in. by 11 in.) * 40 = German standard fanfold (8.5 in. by 12 in.) * 41 = German legal fanfold (8.5 in. by 13 in.) * 42 = ISO B4 (250 mm by 353 mm) * 43 = Japanese double postcard (200 mm by 148 mm) * 44 = Standard paper (9 in. by 11 in.) * 45 = Standard paper (10 in. by 11 in.) * 46 = Standard paper (15 in. by 11 in.) * 47 = Invite envelope (220 mm by 220 mm) * 50 = Letter extra paper (9.275 in. by 12 in.) * 51 = Legal extra paper (9.275 in. by 15 in.) * 52 = Tabloid extra paper (11.69 in. by 18 in.) * 53 = A4 extra paper (236 mm by 322 mm) * 54 = Letter transverse paper (8.275 in. by 11 in.) * 55 = A4 transverse paper (210 mm by 297 mm) * 56 = Letter extra transverse paper (9.275 in. by 12 in.) * 57 = SuperA/SuperA/A4 paper (227 mm by 356 mm) * 58 = SuperB/SuperB/A3 paper (305 mm by 487 mm) * 59 = Letter plus paper (8.5 in. by 12.69 in.) * 60 = A4 plus paper (210 mm by 330 mm) * 61 = A5 transverse paper (148 mm by 210 mm) * 62 = JIS B5 transverse paper (182 mm by 257 mm) * 63 = A3 extra paper (322 mm by 445 mm) * 64 = A5 extra paper (174 mm by 235 mm) * 65 = ISO B5 extra paper (201 mm by 276 mm) * 66 = A2 paper (420 mm by 594 mm) * 67 = A3 transverse paper (297 mm by 420 mm) * 68 = A3 extra transverse paper (322 mm by 445 mm) * </code> */ class PageSetup { // Paper size const PAPERSIZE_LETTER = 1; const PAPERSIZE_LETTER_SMALL = 2; const PAPERSIZE_TABLOID = 3; const PAPERSIZE_LEDGER = 4; const PAPERSIZE_LEGAL = 5; const PAPERSIZE_STATEMENT = 6; const PAPERSIZE_EXECUTIVE = 7; const PAPERSIZE_A3 = 8; const PAPERSIZE_A4 = 9; const PAPERSIZE_A4_SMALL = 10; const PAPERSIZE_A5 = 11; const PAPERSIZE_B4 = 12; const PAPERSIZE_B5 = 13; const PAPERSIZE_FOLIO = 14; const PAPERSIZE_QUARTO = 15; const PAPERSIZE_STANDARD_1 = 16; const PAPERSIZE_STANDARD_2 = 17; const PAPERSIZE_NOTE = 18; const PAPERSIZE_NO9_ENVELOPE = 19; const PAPERSIZE_NO10_ENVELOPE = 20; const PAPERSIZE_NO11_ENVELOPE = 21; const PAPERSIZE_NO12_ENVELOPE = 22; const PAPERSIZE_NO14_ENVELOPE = 23; const PAPERSIZE_C = 24; const PAPERSIZE_D = 25; const PAPERSIZE_E = 26; const PAPERSIZE_DL_ENVELOPE = 27; const PAPERSIZE_C5_ENVELOPE = 28; const PAPERSIZE_C3_ENVELOPE = 29; const PAPERSIZE_C4_ENVELOPE = 30; const PAPERSIZE_C6_ENVELOPE = 31; const PAPERSIZE_C65_ENVELOPE = 32; const PAPERSIZE_B4_ENVELOPE = 33; const PAPERSIZE_B5_ENVELOPE = 34; const PAPERSIZE_B6_ENVELOPE = 35; const PAPERSIZE_ITALY_ENVELOPE = 36; const PAPERSIZE_MONARCH_ENVELOPE = 37; const PAPERSIZE_6_3_4_ENVELOPE = 38; const PAPERSIZE_US_STANDARD_FANFOLD = 39; const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40; const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41; const PAPERSIZE_ISO_B4 = 42; const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43; const PAPERSIZE_STANDARD_PAPER_1 = 44; const PAPERSIZE_STANDARD_PAPER_2 = 45; const PAPERSIZE_STANDARD_PAPER_3 = 46; const PAPERSIZE_INVITE_ENVELOPE = 47; const PAPERSIZE_LETTER_EXTRA_PAPER = 48; const PAPERSIZE_LEGAL_EXTRA_PAPER = 49; const PAPERSIZE_TABLOID_EXTRA_PAPER = 50; const PAPERSIZE_A4_EXTRA_PAPER = 51; const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52; const PAPERSIZE_A4_TRANSVERSE_PAPER = 53; const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54; const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55; const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56; const PAPERSIZE_LETTER_PLUS_PAPER = 57; const PAPERSIZE_A4_PLUS_PAPER = 58; const PAPERSIZE_A5_TRANSVERSE_PAPER = 59; const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60; const PAPERSIZE_A3_EXTRA_PAPER = 61; const PAPERSIZE_A5_EXTRA_PAPER = 62; const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63; const PAPERSIZE_A2_PAPER = 64; const PAPERSIZE_A3_TRANSVERSE_PAPER = 65; const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66; // Page orientation const ORIENTATION_DEFAULT = 'default'; const ORIENTATION_LANDSCAPE = 'landscape'; const ORIENTATION_PORTRAIT = 'portrait'; // Print Range Set Method const SETPRINTRANGE_OVERWRITE = 'O'; const SETPRINTRANGE_INSERT = 'I'; const PAGEORDER_OVER_THEN_DOWN = 'overThenDown'; const PAGEORDER_DOWN_THEN_OVER = 'downThenOver'; /** * Paper size default. * * @var int */ private static $paperSizeDefault = self::PAPERSIZE_LETTER; /** * Paper size. * * @var ?int */ private $paperSize; /** * Orientation default. * * @var string */ private static $orientationDefault = self::ORIENTATION_DEFAULT; /** * Orientation. * * @var string */ private $orientation; /** * Scale (Print Scale). * * Print scaling. Valid values range from 10 to 400 * This setting is overridden when fitToWidth and/or fitToHeight are in use * * @var null|int */ private $scale = 100; /** * Fit To Page * Whether scale or fitToWith / fitToHeight applies. * * @var bool */ private $fitToPage = false; /** * Fit To Height * Number of vertical pages to fit on. * * @var null|int */ private $fitToHeight = 1; /** * Fit To Width * Number of horizontal pages to fit on. * * @var null|int */ private $fitToWidth = 1; /** * Columns to repeat at left. * * @var array Containing start column and end column, empty array if option unset */ private $columnsToRepeatAtLeft = ['', '']; /** * Rows to repeat at top. * * @var array Containing start row number and end row number, empty array if option unset */ private $rowsToRepeatAtTop = [0, 0]; /** * Center page horizontally. * * @var bool */ private $horizontalCentered = false; /** * Center page vertically. * * @var bool */ private $verticalCentered = false; /** * Print area. * * @var null|string */ private $printArea; /** * First page number. * * @var ?int */ private $firstPageNumber; /** @var string */ private $pageOrder = self::PAGEORDER_DOWN_THEN_OVER; /** * Create a new PageSetup. */ public function __construct() { $this->orientation = self::$orientationDefault; } /** * Get Paper Size. * * @return int */ public function getPaperSize() { return $this->paperSize ?? self::$paperSizeDefault; } /** * Set Paper Size. * * @param int $paperSize see self::PAPERSIZE_* * * @return $this */ public function setPaperSize($paperSize) { $this->paperSize = $paperSize; return $this; } /** * Get Paper Size default. */ public static function getPaperSizeDefault(): int { return self::$paperSizeDefault; } /** * Set Paper Size Default. */ public static function setPaperSizeDefault(int $paperSize): void { self::$paperSizeDefault = $paperSize; } /** * Get Orientation. * * @return string */ public function getOrientation() { return $this->orientation; } /** * Set Orientation. * * @param string $orientation see self::ORIENTATION_* * * @return $this */ public function setOrientation($orientation) { if ($orientation === self::ORIENTATION_LANDSCAPE || $orientation === self::ORIENTATION_PORTRAIT || $orientation === self::ORIENTATION_DEFAULT) { $this->orientation = $orientation; } return $this; } public static function getOrientationDefault(): string { return self::$orientationDefault; } public static function setOrientationDefault(string $orientation): void { if ($orientation === self::ORIENTATION_LANDSCAPE || $orientation === self::ORIENTATION_PORTRAIT || $orientation === self::ORIENTATION_DEFAULT) { self::$orientationDefault = $orientation; } } /** * Get Scale. * * @return null|int */ public function getScale() { return $this->scale; } /** * Set Scale. * Print scaling. Valid values range from 10 to 400 * This setting is overridden when fitToWidth and/or fitToHeight are in use. * * @param null|int $scale * @param bool $update Update fitToPage so scaling applies rather than fitToHeight / fitToWidth * * @return $this */ public function setScale($scale, $update = true) { // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, // but it is apparently still able to handle any scale >= 0, where 0 results in 100 if ($scale === null || $scale >= 0) { $this->scale = $scale; if ($update) { $this->fitToPage = false; } } else { throw new PhpSpreadsheetException('Scale must not be negative'); } return $this; } /** * Get Fit To Page. * * @return bool */ public function getFitToPage() { return $this->fitToPage; } /** * Set Fit To Page. * * @param bool $fitToPage * * @return $this */ public function setFitToPage($fitToPage) { $this->fitToPage = $fitToPage; return $this; } /** * Get Fit To Height. * * @return null|int */ public function getFitToHeight() { return $this->fitToHeight; } /** * Set Fit To Height. * * @param null|int $fitToHeight * @param bool $update Update fitToPage so it applies rather than scaling * * @return $this */ public function setFitToHeight($fitToHeight, $update = true) { $this->fitToHeight = $fitToHeight; if ($update) { $this->fitToPage = true; } return $this; } /** * Get Fit To Width. * * @return null|int */ public function getFitToWidth() { return $this->fitToWidth; } /** * Set Fit To Width. * * @param null|int $value * @param bool $update Update fitToPage so it applies rather than scaling * * @return $this */ public function setFitToWidth($value, $update = true) { $this->fitToWidth = $value; if ($update) { $this->fitToPage = true; } return $this; } /** * Is Columns to repeat at left set? * * @return bool */ public function isColumnsToRepeatAtLeftSet() { if (!empty($this->columnsToRepeatAtLeft)) { if ($this->columnsToRepeatAtLeft[0] != '' && $this->columnsToRepeatAtLeft[1] != '') { return true; } } return false; } /** * Get Columns to repeat at left. * * @return array Containing start column and end column, empty array if option unset */ public function getColumnsToRepeatAtLeft() { return $this->columnsToRepeatAtLeft; } /** * Set Columns to repeat at left. * * @param array $columnsToRepeatAtLeft Containing start column and end column, empty array if option unset * * @return $this */ public function setColumnsToRepeatAtLeft(array $columnsToRepeatAtLeft) { $this->columnsToRepeatAtLeft = $columnsToRepeatAtLeft; return $this; } /** * Set Columns to repeat at left by start and end. * * @param string $start eg: 'A' * @param string $end eg: 'B' * * @return $this */ public function setColumnsToRepeatAtLeftByStartAndEnd($start, $end) { $this->columnsToRepeatAtLeft = [$start, $end]; return $this; } /** * Is Rows to repeat at top set? * * @return bool */ public function isRowsToRepeatAtTopSet() { if (!empty($this->rowsToRepeatAtTop)) { if ($this->rowsToRepeatAtTop[0] != 0 && $this->rowsToRepeatAtTop[1] != 0) { return true; } } return false; } /** * Get Rows to repeat at top. * * @return array Containing start column and end column, empty array if option unset */ public function getRowsToRepeatAtTop() { return $this->rowsToRepeatAtTop; } /** * Set Rows to repeat at top. * * @param array $rowsToRepeatAtTop Containing start column and end column, empty array if option unset * * @return $this */ public function setRowsToRepeatAtTop(array $rowsToRepeatAtTop) { $this->rowsToRepeatAtTop = $rowsToRepeatAtTop; return $this; } /** * Set Rows to repeat at top by start and end. * * @param int $start eg: 1 * @param int $end eg: 1 * * @return $this */ public function setRowsToRepeatAtTopByStartAndEnd($start, $end) { $this->rowsToRepeatAtTop = [$start, $end]; return $this; } /** * Get center page horizontally. * * @return bool */ public function getHorizontalCentered() { return $this->horizontalCentered; } /** * Set center page horizontally. * * @param bool $value * * @return $this */ public function setHorizontalCentered($value) { $this->horizontalCentered = $value; return $this; } /** * Get center page vertically. * * @return bool */ public function getVerticalCentered() { return $this->verticalCentered; } /** * Set center page vertically. * * @param bool $value * * @return $this */ public function setVerticalCentered($value) { $this->verticalCentered = $value; return $this; } /** * Get print area. * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or a index value of 0, will return all ranges as a comma-separated string * Otherwise, the specific range identified by the value of $index will be returned * Print areas are numbered from 1 * * @return string */ public function getPrintArea($index = 0) { if ($index == 0) { return (string) $this->printArea; } $printAreas = explode(',', (string) $this->printArea); if (isset($printAreas[$index - 1])) { return $printAreas[$index - 1]; } throw new PhpSpreadsheetException('Requested Print Area does not exist'); } /** * Is print area set? * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or an index value of 0, will identify whether any print range is set * Otherwise, existence of the range identified by the value of $index will be returned * Print areas are numbered from 1 * * @return bool */ public function isPrintAreaSet($index = 0) { if ($index == 0) { return $this->printArea !== null; } $printAreas = explode(',', (string) $this->printArea); return isset($printAreas[$index - 1]); } /** * Clear a print area. * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or an index value of 0, will clear all print ranges that are set * Otherwise, the range identified by the value of $index will be removed from the series * Print areas are numbered from 1 * * @return $this */ public function clearPrintArea($index = 0) { if ($index == 0) { $this->printArea = null; } else { $printAreas = explode(',', (string) $this->printArea); if (isset($printAreas[$index - 1])) { unset($printAreas[$index - 1]); $this->printArea = implode(',', $printAreas); } } return $this; } /** * Set print area. e.g. 'A1:D10' or 'A1:D10,G5:M20'. * * @param string $value * @param int $index Identifier for a specific print area range allowing several ranges to be set * When the method is "O"verwrite, then a positive integer index will overwrite that indexed * entry in the print areas list; a negative index value will identify which entry to * overwrite working bacward through the print area to the list, with the last entry as -1. * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. * When the method is "I"nsert, then a positive index will insert after that indexed entry in * the print areas list, while a negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * @param string $method Determines the method used when setting multiple print areas * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list * * @return $this */ public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) { if (strpos($value, '!') !== false) { throw new PhpSpreadsheetException('Cell coordinate must not specify a worksheet.'); } elseif (strpos($value, ':') === false) { throw new PhpSpreadsheetException('Cell coordinate must be a range of cells.'); } elseif (strpos($value, '$') !== false) { throw new PhpSpreadsheetException('Cell coordinate must not be absolute.'); } $value = strtoupper($value); if (!$this->printArea) { $index = 0; } if ($method == self::SETPRINTRANGE_OVERWRITE) { if ($index == 0) { $this->printArea = $value; } else { $printAreas = explode(',', (string) $this->printArea); if ($index < 0) { $index = count($printAreas) - abs($index) + 1; } if (($index <= 0) || ($index > count($printAreas))) { throw new PhpSpreadsheetException('Invalid index for setting print range.'); } $printAreas[$index - 1] = $value; $this->printArea = implode(',', $printAreas); } } elseif ($method == self::SETPRINTRANGE_INSERT) { if ($index == 0) { $this->printArea = $this->printArea ? ($this->printArea . ',' . $value) : $value; } else { $printAreas = explode(',', (string) $this->printArea); if ($index < 0) { $index = (int) abs($index) - 1; } if ($index > count($printAreas)) { throw new PhpSpreadsheetException('Invalid index for setting print range.'); } $printAreas = array_merge(array_slice($printAreas, 0, $index), [$value], array_slice($printAreas, $index)); $this->printArea = implode(',', $printAreas); } } else { throw new PhpSpreadsheetException('Invalid method for setting print range.'); } return $this; } /** * Add a new print area (e.g. 'A1:D10' or 'A1:D10,G5:M20') to the list of print areas. * * @param string $value * @param int $index Identifier for a specific print area range allowing several ranges to be set * A positive index will insert after that indexed entry in the print areas list, while a * negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * * @return $this */ public function addPrintArea($value, $index = -1) { return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT); } /** * Set print area. * * @param int $column1 Column 1 * @param int $row1 Row 1 * @param int $column2 Column 2 * @param int $row2 Row 2 * @param int $index Identifier for a specific print area range allowing several ranges to be set * When the method is "O"verwrite, then a positive integer index will overwrite that indexed * entry in the print areas list; a negative index value will identify which entry to * overwrite working backward through the print area to the list, with the last entry as -1. * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. * When the method is "I"nsert, then a positive index will insert after that indexed entry in * the print areas list, while a negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * @param string $method Determines the method used when setting multiple print areas * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list * * @return $this */ public function setPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) { return $this->setPrintArea( Coordinate::stringFromColumnIndex($column1) . $row1 . ':' . Coordinate::stringFromColumnIndex($column2) . $row2, $index, $method ); } /** * Add a new print area to the list of print areas. * * @param int $column1 Start Column for the print area * @param int $row1 Start Row for the print area * @param int $column2 End Column for the print area * @param int $row2 End Row for the print area * @param int $index Identifier for a specific print area range allowing several ranges to be set * A positive index will insert after that indexed entry in the print areas list, while a * negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * * @return $this */ public function addPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = -1) { return $this->setPrintArea( Coordinate::stringFromColumnIndex($column1) . $row1 . ':' . Coordinate::stringFromColumnIndex($column2) . $row2, $index, self::SETPRINTRANGE_INSERT ); } /** * Get first page number. * * @return ?int */ public function getFirstPageNumber() { return $this->firstPageNumber; } /** * Set first page number. * * @param ?int $value * * @return $this */ public function setFirstPageNumber($value) { $this->firstPageNumber = $value; return $this; } /** * Reset first page number. * * @return $this */ public function resetFirstPageNumber() { return $this->setFirstPageNumber(null); } public function getPageOrder(): string { return $this->pageOrder; } public function setPageOrder(?string $pageOrder): self { if ($pageOrder === null || $pageOrder === self::PAGEORDER_DOWN_THEN_OVER || $pageOrder === self::PAGEORDER_OVER_THEN_DOWN) { $this->pageOrder = $pageOrder ?? self::PAGEORDER_DOWN_THEN_OVER; } return $this; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php 0000644 00000013525 15002227416 0021043 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @extends CellIterator<string> */ class RowCellIterator extends CellIterator { /** * Current iterator position. * * @var int */ private $currentColumnIndex; /** * Row index. * * @var int */ private $rowIndex = 1; /** * Start position. * * @var int */ private $startColumnIndex = 1; /** * End position. * * @var int */ private $endColumnIndex = 1; /** * Create a new column iterator. * * @param Worksheet $worksheet The worksheet to iterate over * @param int $rowIndex The row that we want to iterate * @param string $startColumn The column address at which to start iterating * @param string $endColumn Optionally, the column address at which to stop iterating */ public function __construct(Worksheet $worksheet, $rowIndex = 1, $startColumn = 'A', $endColumn = null) { // Set subject and row index $this->worksheet = $worksheet; $this->cellCollection = $worksheet->getCellCollection(); $this->rowIndex = $rowIndex; $this->resetEnd($endColumn); $this->resetStart($startColumn); } /** * (Re)Set the start column and the current column pointer. * * @param string $startColumn The column address at which to start iterating * * @return $this */ public function resetStart(string $startColumn = 'A') { $this->startColumnIndex = Coordinate::columnIndexFromString($startColumn); $this->adjustForExistingOnlyRange(); $this->seek(Coordinate::stringFromColumnIndex($this->startColumnIndex)); return $this; } /** * (Re)Set the end column. * * @param string $endColumn The column address at which to stop iterating * * @return $this */ public function resetEnd($endColumn = null) { $endColumn = $endColumn ?: $this->worksheet->getHighestColumn(); $this->endColumnIndex = Coordinate::columnIndexFromString($endColumn); $this->adjustForExistingOnlyRange(); return $this; } /** * Set the column pointer to the selected column. * * @param string $column The column address to set the current pointer at * * @return $this */ public function seek(string $column = 'A') { $columnId = Coordinate::columnIndexFromString($column); if ($this->onlyExistingCells && !($this->cellCollection->has($column . $this->rowIndex))) { throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist'); } if (($columnId < $this->startColumnIndex) || ($columnId > $this->endColumnIndex)) { throw new PhpSpreadsheetException("Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})"); } $this->currentColumnIndex = $columnId; return $this; } /** * Rewind the iterator to the starting column. */ public function rewind(): void { $this->currentColumnIndex = $this->startColumnIndex; } /** * Return the current cell in this worksheet row. */ public function current(): ?Cell { $cellAddress = Coordinate::stringFromColumnIndex($this->currentColumnIndex) . $this->rowIndex; return $this->cellCollection->has($cellAddress) ? $this->cellCollection->get($cellAddress) : ( $this->ifNotExists === self::IF_NOT_EXISTS_CREATE_NEW ? $this->worksheet->createNewCell($cellAddress) : null ); } /** * Return the current iterator key. */ public function key(): string { return Coordinate::stringFromColumnIndex($this->currentColumnIndex); } /** * Set the iterator to its next value. */ public function next(): void { do { ++$this->currentColumnIndex; } while (($this->onlyExistingCells) && (!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->currentColumnIndex) . $this->rowIndex)) && ($this->currentColumnIndex <= $this->endColumnIndex)); } /** * Set the iterator to its previous value. */ public function prev(): void { do { --$this->currentColumnIndex; } while (($this->onlyExistingCells) && (!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->currentColumnIndex) . $this->rowIndex)) && ($this->currentColumnIndex >= $this->startColumnIndex)); } /** * Indicate if more columns exist in the worksheet range of columns that we're iterating. */ public function valid(): bool { return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex; } /** * Return the current iterator position. */ public function getCurrentColumnIndex(): int { return $this->currentColumnIndex; } /** * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary. */ protected function adjustForExistingOnlyRange(): void { if ($this->onlyExistingCells) { while ((!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->startColumnIndex) . $this->rowIndex)) && ($this->startColumnIndex <= $this->endColumnIndex)) { ++$this->startColumnIndex; } while ((!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->endColumnIndex) . $this->rowIndex)) && ($this->endColumnIndex >= $this->startColumnIndex)) { --$this->endColumnIndex; } } } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php 0000644 00000007750 15002227416 0016534 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class Row { /** * \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet. * * @var Worksheet */ private $worksheet; /** * Row index. * * @var int */ private $rowIndex = 0; /** * Create a new row. * * @param int $rowIndex */ public function __construct(Worksheet $worksheet, $rowIndex = 1) { // Set parent and row index $this->worksheet = $worksheet; $this->rowIndex = $rowIndex; } /** * Destructor. */ public function __destruct() { $this->worksheet = null; // @phpstan-ignore-line } /** * Get row index. */ public function getRowIndex(): int { return $this->rowIndex; } /** * Get cell iterator. * * @param string $startColumn The column address at which to start iterating * @param string $endColumn Optionally, the column address at which to stop iterating */ public function getCellIterator($startColumn = 'A', $endColumn = null): RowCellIterator { return new RowCellIterator($this->worksheet, $this->rowIndex, $startColumn, $endColumn); } /** * Get column iterator. Synonym for getCellIterator(). * * @param string $startColumn The column address at which to start iterating * @param string $endColumn Optionally, the column address at which to stop iterating */ public function getColumnIterator($startColumn = 'A', $endColumn = null): RowCellIterator { return $this->getCellIterator($startColumn, $endColumn); } /** * Returns a boolean true if the row contains no cells. By default, this means that no cell records exist in the * collection for this row. false will be returned otherwise. * This rule can be modified by passing a $definitionOfEmptyFlags value: * 1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value * cells, then the row will be considered empty. * 2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty * string value cells, then the row will be considered empty. * 3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * If the only cells in the collection are null value or empty string value cells, then the row * will be considered empty. * * @param int $definitionOfEmptyFlags * Possible Flag Values are: * CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL * CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * @param string $startColumn The column address at which to start checking if cells are empty * @param string $endColumn Optionally, the column address at which to stop checking if cells are empty */ public function isEmpty(int $definitionOfEmptyFlags = 0, $startColumn = 'A', $endColumn = null): bool { $nullValueCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL); $emptyStringCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL); $cellIterator = $this->getCellIterator($startColumn, $endColumn); $cellIterator->setIterateOnlyExistingCells(true); foreach ($cellIterator as $cell) { /** @scrutinizer ignore-call */ $value = $cell->getValue(); if ($value === null && $nullValueCellIsEmpty === true) { continue; } if ($value === '' && $emptyStringCellIsEmpty === true) { continue; } return false; } return true; } /** * Returns bound worksheet. */ public function getWorksheet(): Worksheet { return $this->worksheet; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php 0000644 00000021264 15002227416 0020545 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use GdImage; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Shared\File; class MemoryDrawing extends BaseDrawing { // Rendering functions const RENDERING_DEFAULT = 'imagepng'; const RENDERING_PNG = 'imagepng'; const RENDERING_GIF = 'imagegif'; const RENDERING_JPEG = 'imagejpeg'; // MIME types const MIMETYPE_DEFAULT = 'image/png'; const MIMETYPE_PNG = 'image/png'; const MIMETYPE_GIF = 'image/gif'; const MIMETYPE_JPEG = 'image/jpeg'; const SUPPORTED_MIME_TYPES = [ self::MIMETYPE_GIF, self::MIMETYPE_JPEG, self::MIMETYPE_PNG, ]; /** * Image resource. * * @var null|GdImage|resource */ private $imageResource; /** * Rendering function. * * @var string */ private $renderingFunction; /** * Mime type. * * @var string */ private $mimeType; /** * Unique name. * * @var string */ private $uniqueName; /** @var null|resource */ private $alwaysNull; /** * Create a new MemoryDrawing. */ public function __construct() { // Initialise values $this->renderingFunction = self::RENDERING_DEFAULT; $this->mimeType = self::MIMETYPE_DEFAULT; $this->uniqueName = md5(mt_rand(0, 9999) . time() . mt_rand(0, 9999)); $this->alwaysNull = null; // Initialize parent parent::__construct(); } public function __destruct() { if ($this->imageResource) { $rslt = @imagedestroy($this->imageResource); // "Fix" for Scrutinizer $this->imageResource = $rslt ? null : $this->alwaysNull; } } public function __clone() { parent::__clone(); $this->cloneResource(); } private function cloneResource(): void { if (!$this->imageResource) { return; } $width = (int) imagesx($this->imageResource); $height = (int) imagesy($this->imageResource); if (imageistruecolor($this->imageResource)) { $clone = imagecreatetruecolor($width, $height); if (!$clone) { throw new Exception('Could not clone image resource'); } imagealphablending($clone, false); imagesavealpha($clone, true); } else { $clone = imagecreate($width, $height); if (!$clone) { throw new Exception('Could not clone image resource'); } // If the image has transparency... $transparent = imagecolortransparent($this->imageResource); if ($transparent >= 0) { $rgb = imagecolorsforindex($this->imageResource, $transparent); if (empty($rgb)) { throw new Exception('Could not get image colors'); } imagesavealpha($clone, true); $color = imagecolorallocatealpha($clone, $rgb['red'], $rgb['green'], $rgb['blue'], $rgb['alpha']); if ($color === false) { throw new Exception('Could not get image alpha color'); } imagefill($clone, 0, 0, $color); } } //Create the Clone!! imagecopy($clone, $this->imageResource, 0, 0, 0, 0, $width, $height); $this->imageResource = $clone; } /** * @param resource $imageStream Stream data to be converted to a Memory Drawing * * @throws Exception */ public static function fromStream($imageStream): self { $streamValue = stream_get_contents($imageStream); if ($streamValue === false) { throw new Exception('Unable to read data from stream'); } return self::fromString($streamValue); } /** * @param string $imageString String data to be converted to a Memory Drawing * * @throws Exception */ public static function fromString(string $imageString): self { $gdImage = @imagecreatefromstring($imageString); if ($gdImage === false) { throw new Exception('Value cannot be converted to an image'); } $mimeType = self::identifyMimeType($imageString); $renderingFunction = self::identifyRenderingFunction($mimeType); $drawing = new self(); $drawing->setImageResource($gdImage); $drawing->setRenderingFunction($renderingFunction); $drawing->setMimeType($mimeType); return $drawing; } private static function identifyRenderingFunction(string $mimeType): string { switch ($mimeType) { case self::MIMETYPE_PNG: return self::RENDERING_PNG; case self::MIMETYPE_JPEG: return self::RENDERING_JPEG; case self::MIMETYPE_GIF: return self::RENDERING_GIF; } return self::RENDERING_DEFAULT; } /** * @throws Exception */ private static function identifyMimeType(string $imageString): string { $temporaryFileName = File::temporaryFilename(); file_put_contents($temporaryFileName, $imageString); $mimeType = self::identifyMimeTypeUsingExif($temporaryFileName); if ($mimeType !== null) { unlink($temporaryFileName); return $mimeType; } $mimeType = self::identifyMimeTypeUsingGd($temporaryFileName); if ($mimeType !== null) { unlink($temporaryFileName); return $mimeType; } unlink($temporaryFileName); return self::MIMETYPE_DEFAULT; } private static function identifyMimeTypeUsingExif(string $temporaryFileName): ?string { if (function_exists('exif_imagetype')) { $imageType = @exif_imagetype($temporaryFileName); $mimeType = ($imageType) ? image_type_to_mime_type($imageType) : null; return self::supportedMimeTypes($mimeType); } return null; } private static function identifyMimeTypeUsingGd(string $temporaryFileName): ?string { if (function_exists('getimagesize')) { $imageSize = @getimagesize($temporaryFileName); if (is_array($imageSize)) { $mimeType = $imageSize['mime'] ?? null; return self::supportedMimeTypes($mimeType); } } return null; } private static function supportedMimeTypes(?string $mimeType = null): ?string { if (in_array($mimeType, self::SUPPORTED_MIME_TYPES, true)) { return $mimeType; } return null; } /** * Get image resource. * * @return null|GdImage|resource */ public function getImageResource() { return $this->imageResource; } /** * Set image resource. * * @param GdImage|resource $value * * @return $this */ public function setImageResource($value) { $this->imageResource = $value; if ($this->imageResource !== null) { // Get width/height $this->width = (int) imagesx($this->imageResource); $this->height = (int) imagesy($this->imageResource); } return $this; } /** * Get rendering function. * * @return string */ public function getRenderingFunction() { return $this->renderingFunction; } /** * Set rendering function. * * @param string $value see self::RENDERING_* * * @return $this */ public function setRenderingFunction($value) { $this->renderingFunction = $value; return $this; } /** * Get mime type. * * @return string */ public function getMimeType() { return $this->mimeType; } /** * Set mime type. * * @param string $value see self::MIMETYPE_* * * @return $this */ public function setMimeType($value) { $this->mimeType = $value; return $this; } /** * Get indexed filename (using image index). */ public function getIndexedFilename(): string { $extension = strtolower($this->getMimeType()); $extension = explode('/', $extension); $extension = $extension[1]; return $this->uniqueName . $this->getImageIndex() . '.' . $extension; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->renderingFunction . $this->mimeType . $this->uniqueName . parent::getHashCode() . __CLASS__ ); } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php 0000644 00000004361 15002227416 0017705 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; abstract class Dimension { /** * Visible? * * @var bool */ private $visible = true; /** * Outline level. * * @var int */ private $outlineLevel = 0; /** * Collapsed. * * @var bool */ private $collapsed = false; /** * Index to cellXf. Null value means row has no explicit cellXf format. * * @var null|int */ private $xfIndex; /** * Create a new Dimension. * * @param int $initialValue Numeric row index */ public function __construct($initialValue = null) { // set dimension as unformatted by default $this->xfIndex = $initialValue; } /** * Get Visible. */ public function getVisible(): bool { return $this->visible; } /** * Set Visible. * * @return $this */ public function setVisible(bool $visible) { $this->visible = $visible; return $this; } /** * Get Outline Level. */ public function getOutlineLevel(): int { return $this->outlineLevel; } /** * Set Outline Level. * Value must be between 0 and 7. * * @return $this */ public function setOutlineLevel(int $level) { if ($level < 0 || $level > 7) { throw new PhpSpreadsheetException('Outline level must range between 0 and 7.'); } $this->outlineLevel = $level; return $this; } /** * Get Collapsed. */ public function getCollapsed(): bool { return $this->collapsed; } /** * Set Collapsed. * * @return $this */ public function setCollapsed(bool $collapsed) { $this->collapsed = $collapsed; return $this; } /** * Get index to cellXf. * * @return int */ public function getXfIndex(): ?int { return $this->xfIndex; } /** * Set index to cellXf. * * @return $this */ public function setXfIndex(int $XfIndex) { $this->xfIndex = $XfIndex; return $this; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table.php 0000644 00000041616 15002227416 0017013 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Table\TableStyle; class Table { /** * Table Name. * * @var string */ private $name; /** * Show Header Row. * * @var bool */ private $showHeaderRow = true; /** * Show Totals Row. * * @var bool */ private $showTotalsRow = false; /** * Table Range. * * @var string */ private $range = ''; /** * Table Worksheet. * * @var null|Worksheet */ private $workSheet; /** * Table allow filter. * * @var bool */ private $allowFilter = true; /** * Table Column. * * @var Table\Column[] */ private $columns = []; /** * Table Style. * * @var TableStyle */ private $style; /** * Table AutoFilter. * * @var AutoFilter */ private $autoFilter; /** * Create a new Table. * * @param AddressRange|array<int>|string $range * A simple string containing a Cell range like 'A1:E10' is permitted * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. * @param string $name (e.g. Table1) */ public function __construct($range = '', string $name = '') { $this->style = new TableStyle(); $this->autoFilter = new AutoFilter($range); $this->setRange($range); $this->setName($name); } /** * Get Table name. */ public function getName(): string { return $this->name; } /** * Set Table name. * * @throws PhpSpreadsheetException */ public function setName(string $name): self { $name = trim($name); if (!empty($name)) { if (strlen($name) === 1 && in_array($name, ['C', 'c', 'R', 'r'])) { throw new PhpSpreadsheetException('The table name is invalid'); } if (StringHelper::countCharacters($name) > 255) { throw new PhpSpreadsheetException('The table name cannot be longer than 255 characters'); } // Check for A1 or R1C1 cell reference notation if ( preg_match(Coordinate::A1_COORDINATE_REGEX, $name) || preg_match('/^R\[?\-?[0-9]*\]?C\[?\-?[0-9]*\]?$/i', $name) ) { throw new PhpSpreadsheetException('The table name can\'t be the same as a cell reference'); } if (!preg_match('/^[\p{L}_\\\\]/iu', $name)) { throw new PhpSpreadsheetException('The table name must begin a name with a letter, an underscore character (_), or a backslash (\)'); } if (!preg_match('/^[\p{L}_\\\\][\p{L}\p{M}0-9\._]+$/iu', $name)) { throw new PhpSpreadsheetException('The table name contains invalid characters'); } $this->checkForDuplicateTableNames($name, $this->workSheet); $this->updateStructuredReferences($name); } $this->name = $name; return $this; } /** * @throws PhpSpreadsheetException */ private function checkForDuplicateTableNames(string $name, ?Worksheet $worksheet): void { // Remember that table names are case-insensitive $tableName = StringHelper::strToLower($name); if ($worksheet !== null && StringHelper::strToLower($this->name) !== $name) { $spreadsheet = $worksheet->getParentOrThrow(); foreach ($spreadsheet->getWorksheetIterator() as $sheet) { foreach ($sheet->getTableCollection() as $table) { if (StringHelper::strToLower($table->getName()) === $tableName && $table != $this) { throw new PhpSpreadsheetException("Spreadsheet already contains a table named '{$this->name}'"); } } } } } private function updateStructuredReferences(string $name): void { if ($this->workSheet === null || $this->name === null || $this->name === '') { return; } // Remember that table names are case-insensitive if (StringHelper::strToLower($this->name) !== StringHelper::strToLower($name)) { // We need to check all formula cells that might contain fully-qualified Structured References // that refer to this table, and update those formulae to reference the new table name $spreadsheet = $this->workSheet->getParentOrThrow(); foreach ($spreadsheet->getWorksheetIterator() as $sheet) { $this->updateStructuredReferencesInCells($sheet, $name); } $this->updateStructuredReferencesInNamedFormulae($spreadsheet, $name); } } private function updateStructuredReferencesInCells(Worksheet $worksheet, string $newName): void { $pattern = '/' . preg_quote($this->name, '/') . '\[/mui'; foreach ($worksheet->getCoordinates(false) as $coordinate) { $cell = $worksheet->getCell($coordinate); if ($cell->getDataType() === DataType::TYPE_FORMULA) { $formula = $cell->getValue(); if (preg_match($pattern, $formula) === 1) { $formula = preg_replace($pattern, "{$newName}[", $formula); $cell->setValueExplicit($formula, DataType::TYPE_FORMULA); } } } } private function updateStructuredReferencesInNamedFormulae(Spreadsheet $spreadsheet, string $newName): void { $pattern = '/' . preg_quote($this->name, '/') . '\[/mui'; foreach ($spreadsheet->getNamedFormulae() as $namedFormula) { $formula = $namedFormula->getValue(); if (preg_match($pattern, $formula) === 1) { $formula = preg_replace($pattern, "{$newName}[", $formula); $namedFormula->setValue($formula); // @phpstan-ignore-line } } } /** * Get show Header Row. */ public function getShowHeaderRow(): bool { return $this->showHeaderRow; } /** * Set show Header Row. */ public function setShowHeaderRow(bool $showHeaderRow): self { $this->showHeaderRow = $showHeaderRow; return $this; } /** * Get show Totals Row. */ public function getShowTotalsRow(): bool { return $this->showTotalsRow; } /** * Set show Totals Row. */ public function setShowTotalsRow(bool $showTotalsRow): self { $this->showTotalsRow = $showTotalsRow; return $this; } /** * Get allow filter. * If false, autofiltering is disabled for the table, if true it is enabled. */ public function getAllowFilter(): bool { return $this->allowFilter; } /** * Set show Autofiltering. * Disabling autofiltering has the same effect as hiding the filter button on all the columns in the table. */ public function setAllowFilter(bool $allowFilter): self { $this->allowFilter = $allowFilter; return $this; } /** * Get Table Range. */ public function getRange(): string { return $this->range; } /** * Set Table Cell Range. * * @param AddressRange|array<int>|string $range * A simple string containing a Cell range like 'A1:E10' is permitted * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. */ public function setRange($range = ''): self { // extract coordinate if ($range !== '') { [, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true); } if (empty($range)) { // Discard all column rules $this->columns = []; $this->range = ''; return $this; } if (strpos($range, ':') === false) { throw new PhpSpreadsheetException('Table must be set on a range of cells.'); } [$width, $height] = Coordinate::rangeDimension($range); if ($width < 1 || $height < 1) { throw new PhpSpreadsheetException('The table range must be at least 1 column and row'); } $this->range = $range; $this->autoFilter->setRange($range); // Discard any column rules that are no longer valid within this range [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); foreach ($this->columns as $key => $value) { $colIndex = Coordinate::columnIndexFromString($key); if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { unset($this->columns[$key]); } } return $this; } /** * Set Table Cell Range to max row. */ public function setRangeToMaxRow(): self { if ($this->workSheet !== null) { $thisrange = $this->range; $range = (string) preg_replace('/\\d+$/', (string) $this->workSheet->getHighestRow(), $thisrange); if ($range !== $thisrange) { $this->setRange($range); } } return $this; } /** * Get Table's Worksheet. */ public function getWorksheet(): ?Worksheet { return $this->workSheet; } /** * Set Table's Worksheet. */ public function setWorksheet(?Worksheet $worksheet = null): self { if ($this->name !== '' && $worksheet !== null) { $spreadsheet = $worksheet->getParentOrThrow(); $tableName = StringHelper::strToUpper($this->name); foreach ($spreadsheet->getWorksheetIterator() as $sheet) { foreach ($sheet->getTableCollection() as $table) { if (StringHelper::strToUpper($table->getName()) === $tableName) { throw new PhpSpreadsheetException("Workbook already contains a table named '{$this->name}'"); } } } } $this->workSheet = $worksheet; $this->autoFilter->setParent($worksheet); return $this; } /** * Get all Table Columns. * * @return Table\Column[] */ public function getColumns(): array { return $this->columns; } /** * Validate that the specified column is in the Table range. * * @param string $column Column name (e.g. A) * * @return int The column offset within the table range */ public function isColumnInRange(string $column): int { if (empty($this->range)) { throw new PhpSpreadsheetException('No table range is defined.'); } $columnIndex = Coordinate::columnIndexFromString($column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) { throw new PhpSpreadsheetException('Column is outside of current table range.'); } return $columnIndex - $rangeStart[0]; } /** * Get a specified Table Column Offset within the defined Table range. * * @param string $column Column name (e.g. A) * * @return int The offset of the specified column within the table range */ public function getColumnOffset($column): int { return $this->isColumnInRange($column); } /** * Get a specified Table Column. * * @param string $column Column name (e.g. A) */ public function getColumn($column): Table\Column { $this->isColumnInRange($column); if (!isset($this->columns[$column])) { $this->columns[$column] = new Table\Column($column, $this); } return $this->columns[$column]; } /** * Get a specified Table Column by it's offset. * * @param int $columnOffset Column offset within range (starting from 0) */ public function getColumnByOffset($columnOffset): Table\Column { [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset); return $this->getColumn($pColumn); } /** * Set Table. * * @param string|Table\Column $columnObjectOrString * A simple string containing a Column ID like 'A' is permitted */ public function setColumn($columnObjectOrString): self { if ((is_string($columnObjectOrString)) && (!empty($columnObjectOrString))) { $column = $columnObjectOrString; } elseif (is_object($columnObjectOrString) && ($columnObjectOrString instanceof Table\Column)) { $column = $columnObjectOrString->getColumnIndex(); } else { throw new PhpSpreadsheetException('Column is not within the table range.'); } $this->isColumnInRange($column); if (is_string($columnObjectOrString)) { $this->columns[$columnObjectOrString] = new Table\Column($columnObjectOrString, $this); } else { $columnObjectOrString->setTable($this); $this->columns[$column] = $columnObjectOrString; } ksort($this->columns); return $this; } /** * Clear a specified Table Column. * * @param string $column Column name (e.g. A) */ public function clearColumn($column): self { $this->isColumnInRange($column); if (isset($this->columns[$column])) { unset($this->columns[$column]); } return $this; } /** * Shift an Table Column Rule to a different column. * * Note: This method bypasses validation of the destination column to ensure it is within this Table range. * Nor does it verify whether any column rule already exists at $toColumn, but will simply override any existing value. * Use with caution. * * @param string $fromColumn Column name (e.g. A) * @param string $toColumn Column name (e.g. B) */ public function shiftColumn($fromColumn, $toColumn): self { $fromColumn = strtoupper($fromColumn); $toColumn = strtoupper($toColumn); if (($fromColumn !== null) && (isset($this->columns[$fromColumn])) && ($toColumn !== null)) { $this->columns[$fromColumn]->setTable(); $this->columns[$fromColumn]->setColumnIndex($toColumn); $this->columns[$toColumn] = $this->columns[$fromColumn]; $this->columns[$toColumn]->setTable($this); unset($this->columns[$fromColumn]); ksort($this->columns); } return $this; } /** * Get table Style. */ public function getStyle(): Table\TableStyle { return $this->style; } /** * Set table Style. */ public function setStyle(TableStyle $style): self { $this->style = $style; return $this; } /** * Get AutoFilter. */ public function getAutoFilter(): AutoFilter { return $this->autoFilter; } /** * Set AutoFilter. */ public function setAutoFilter(AutoFilter $autoFilter): self { $this->autoFilter = $autoFilter; return $this; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { if ($key === 'workSheet') { // Detach from worksheet $this->{$key} = null; } else { $this->{$key} = clone $value; } } elseif ((is_array($value)) && ($key === 'columns')) { // The columns array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\Table objects $this->{$key} = []; foreach ($value as $k => $v) { $this->{$key}[$k] = clone $v; // attach the new cloned Column to this new cloned Table object $this->{$key}[$k]->setTable($this); } } else { $this->{$key} = $value; } } } /** * toString method replicates previous behavior by returning the range if object is * referenced as a property of its worksheet. */ public function __toString() { return (string) $this->range; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php 0000644 00000005252 15002227416 0020375 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; class RowDimension extends Dimension { /** * Row index. * * @var ?int */ private $rowIndex; /** * Row height (in pt). * * When this is set to a negative value, the row height should be ignored by IWriter * * @var float */ private $height = -1; /** * ZeroHeight for Row? * * @var bool */ private $zeroHeight = false; /** * Create a new RowDimension. * * @param ?int $index Numeric row index */ public function __construct($index = 0) { // Initialise values $this->rowIndex = $index; // set dimension as unformatted by default parent::__construct(null); } /** * Get Row Index. */ public function getRowIndex(): ?int { return $this->rowIndex; } /** * Set Row Index. * * @return $this */ public function setRowIndex(int $index) { $this->rowIndex = $index; return $this; } /** * Get Row Height. * By default, this will be in points; but this method also accepts an optional unit of measure * argument, and will convert the value from points to the specified UoM. * A value of -1 tells Excel to display this column in its default height. * * @return float */ public function getRowHeight(?string $unitOfMeasure = null) { return ($unitOfMeasure === null || $this->height < 0) ? $this->height : (new CssDimension($this->height . CssDimension::UOM_POINTS))->toUnit($unitOfMeasure); } /** * Set Row Height. * * @param float $height in points. A value of -1 tells Excel to display this column in its default height. * By default, this will be the passed argument value; but this method also accepts an optional unit of measure * argument, and will convert the passed argument value to points from the specified UoM * * @return $this */ public function setRowHeight($height, ?string $unitOfMeasure = null) { $this->height = ($unitOfMeasure === null || $height < 0) ? $height : (new CssDimension("{$height}{$unitOfMeasure}"))->height(); return $this; } /** * Get ZeroHeight. */ public function getZeroHeight(): bool { return $this->zeroHeight; } /** * Set ZeroHeight. * * @return $this */ public function setZeroHeight(bool $zeroHeight) { $this->zeroHeight = $zeroHeight; return $this; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php 0000644 00000347727 15002227416 0017753 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use ArrayObject; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\CellAddress; use PhpOffice\PhpSpreadsheet\Cell\CellRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Cell\Hyperlink; use PhpOffice\PhpSpreadsheet\Cell\IValueBinder; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\Collection\Cells; use PhpOffice\PhpSpreadsheet\Collection\CellsFactory; use PhpOffice\PhpSpreadsheet\Comment; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Style; class Worksheet implements IComparable { // Break types public const BREAK_NONE = 0; public const BREAK_ROW = 1; public const BREAK_COLUMN = 2; // Maximum column for row break public const BREAK_ROW_MAX_COLUMN = 16383; // Sheet state public const SHEETSTATE_VISIBLE = 'visible'; public const SHEETSTATE_HIDDEN = 'hidden'; public const SHEETSTATE_VERYHIDDEN = 'veryHidden'; public const MERGE_CELL_CONTENT_EMPTY = 'empty'; public const MERGE_CELL_CONTENT_HIDE = 'hide'; public const MERGE_CELL_CONTENT_MERGE = 'merge'; protected const SHEET_NAME_REQUIRES_NO_QUOTES = '/^[_\p{L}][_\p{L}\p{N}]*$/mui'; /** * Maximum 31 characters allowed for sheet title. * * @var int */ const SHEET_TITLE_MAXIMUM_LENGTH = 31; /** * Invalid characters in sheet title. * * @var array */ private static $invalidCharacters = ['*', ':', '/', '\\', '?', '[', ']']; /** * Parent spreadsheet. * * @var ?Spreadsheet */ private $parent; /** * Collection of cells. * * @var Cells */ private $cellCollection; /** * Collection of row dimensions. * * @var RowDimension[] */ private $rowDimensions = []; /** * Default row dimension. * * @var RowDimension */ private $defaultRowDimension; /** * Collection of column dimensions. * * @var ColumnDimension[] */ private $columnDimensions = []; /** * Default column dimension. * * @var ColumnDimension */ private $defaultColumnDimension; /** * Collection of drawings. * * @var ArrayObject<int, BaseDrawing> */ private $drawingCollection; /** * Collection of Chart objects. * * @var ArrayObject<int, Chart> */ private $chartCollection; /** * Collection of Table objects. * * @var ArrayObject<int, Table> */ private $tableCollection; /** * Worksheet title. * * @var string */ private $title; /** * Sheet state. * * @var string */ private $sheetState; /** * Page setup. * * @var PageSetup */ private $pageSetup; /** * Page margins. * * @var PageMargins */ private $pageMargins; /** * Page header/footer. * * @var HeaderFooter */ private $headerFooter; /** * Sheet view. * * @var SheetView */ private $sheetView; /** * Protection. * * @var Protection */ private $protection; /** * Collection of styles. * * @var Style[] */ private $styles = []; /** * Conditional styles. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $conditionalStylesCollection = []; /** * Collection of row breaks. * * @var PageBreak[] */ private $rowBreaks = []; /** * Collection of column breaks. * * @var PageBreak[] */ private $columnBreaks = []; /** * Collection of merged cell ranges. * * @var string[] */ private $mergeCells = []; /** * Collection of protected cell ranges. * * @var string[] */ private $protectedCells = []; /** * Autofilter Range and selection. * * @var AutoFilter */ private $autoFilter; /** * Freeze pane. * * @var null|string */ private $freezePane; /** * Default position of the right bottom pane. * * @var null|string */ private $topLeftCell; /** * Show gridlines? * * @var bool */ private $showGridlines = true; /** * Print gridlines? * * @var bool */ private $printGridlines = false; /** * Show row and column headers? * * @var bool */ private $showRowColHeaders = true; /** * Show summary below? (Row/Column outline). * * @var bool */ private $showSummaryBelow = true; /** * Show summary right? (Row/Column outline). * * @var bool */ private $showSummaryRight = true; /** * Collection of comments. * * @var Comment[] */ private $comments = []; /** * Active cell. (Only one!). * * @var string */ private $activeCell = 'A1'; /** * Selected cells. * * @var string */ private $selectedCells = 'A1'; /** * Cached highest column. * * @var int */ private $cachedHighestColumn = 1; /** * Cached highest row. * * @var int */ private $cachedHighestRow = 1; /** * Right-to-left? * * @var bool */ private $rightToLeft = false; /** * Hyperlinks. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $hyperlinkCollection = []; /** * Data validation objects. Indexed by cell coordinate, e.g. 'A1'. * * @var array */ private $dataValidationCollection = []; /** * Tab color. * * @var null|Color */ private $tabColor; /** * Dirty flag. * * @var bool */ private $dirty = true; /** * Hash. * * @var string */ private $hash; /** * CodeName. * * @var string */ private $codeName; /** * Create a new worksheet. * * @param string $title */ public function __construct(?Spreadsheet $parent = null, $title = 'Worksheet') { // Set parent and title $this->parent = $parent; $this->setTitle($title, false); // setTitle can change $pTitle $this->setCodeName($this->getTitle()); $this->setSheetState(self::SHEETSTATE_VISIBLE); $this->cellCollection = CellsFactory::getInstance($this); // Set page setup $this->pageSetup = new PageSetup(); // Set page margins $this->pageMargins = new PageMargins(); // Set page header/footer $this->headerFooter = new HeaderFooter(); // Set sheet view $this->sheetView = new SheetView(); // Drawing collection $this->drawingCollection = new ArrayObject(); // Chart collection $this->chartCollection = new ArrayObject(); // Protection $this->protection = new Protection(); // Default row dimension $this->defaultRowDimension = new RowDimension(null); // Default column dimension $this->defaultColumnDimension = new ColumnDimension(null); // AutoFilter $this->autoFilter = new AutoFilter('', $this); // Table collection $this->tableCollection = new ArrayObject(); } /** * Disconnect all cells from this Worksheet object, * typically so that the worksheet object can be unset. */ public function disconnectCells(): void { if ($this->cellCollection !== null) { $this->cellCollection->unsetWorksheetCells(); // @phpstan-ignore-next-line $this->cellCollection = null; } // detach ourself from the workbook, so that it can then delete this worksheet successfully $this->parent = null; } /** * Code to execute when this worksheet is unset(). */ public function __destruct() { Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title); $this->disconnectCells(); $this->rowDimensions = []; } /** * Return the cell collection. * * @return Cells */ public function getCellCollection() { return $this->cellCollection; } /** * Get array of invalid characters for sheet title. * * @return array */ public static function getInvalidCharacters() { return self::$invalidCharacters; } /** * Check sheet code name for valid Excel syntax. * * @param string $sheetCodeName The string to check * * @return string The valid string */ private static function checkSheetCodeName($sheetCodeName) { $charCount = Shared\StringHelper::countCharacters($sheetCodeName); if ($charCount == 0) { throw new Exception('Sheet code name cannot be empty.'); } // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'" if ( (str_replace(self::$invalidCharacters, '', $sheetCodeName) !== $sheetCodeName) || (Shared\StringHelper::substring($sheetCodeName, -1, 1) == '\'') || (Shared\StringHelper::substring($sheetCodeName, 0, 1) == '\'') ) { throw new Exception('Invalid character found in sheet code name'); } // Enforce maximum characters allowed for sheet title if ($charCount > self::SHEET_TITLE_MAXIMUM_LENGTH) { throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.'); } return $sheetCodeName; } /** * Check sheet title for valid Excel syntax. * * @param string $sheetTitle The string to check * * @return string The valid string */ private static function checkSheetTitle($sheetTitle) { // Some of the printable ASCII characters are invalid: * : / \ ? [ ] if (str_replace(self::$invalidCharacters, '', $sheetTitle) !== $sheetTitle) { throw new Exception('Invalid character found in sheet title'); } // Enforce maximum characters allowed for sheet title if (Shared\StringHelper::countCharacters($sheetTitle) > self::SHEET_TITLE_MAXIMUM_LENGTH) { throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.'); } return $sheetTitle; } /** * Get a sorted list of all cell coordinates currently held in the collection by row and column. * * @param bool $sorted Also sort the cell collection? * * @return string[] */ public function getCoordinates($sorted = true) { if ($this->cellCollection == null) { return []; } if ($sorted) { return $this->cellCollection->getSortedCoordinates(); } return $this->cellCollection->getCoordinates(); } /** * Get collection of row dimensions. * * @return RowDimension[] */ public function getRowDimensions() { return $this->rowDimensions; } /** * Get default row dimension. * * @return RowDimension */ public function getDefaultRowDimension() { return $this->defaultRowDimension; } /** * Get collection of column dimensions. * * @return ColumnDimension[] */ public function getColumnDimensions() { /** @var callable */ $callable = [self::class, 'columnDimensionCompare']; uasort($this->columnDimensions, $callable); return $this->columnDimensions; } private static function columnDimensionCompare(ColumnDimension $a, ColumnDimension $b): int { return $a->getColumnNumeric() - $b->getColumnNumeric(); } /** * Get default column dimension. * * @return ColumnDimension */ public function getDefaultColumnDimension() { return $this->defaultColumnDimension; } /** * Get collection of drawings. * * @return ArrayObject<int, BaseDrawing> */ public function getDrawingCollection() { return $this->drawingCollection; } /** * Get collection of charts. * * @return ArrayObject<int, Chart> */ public function getChartCollection() { return $this->chartCollection; } /** * Add chart. * * @param null|int $chartIndex Index where chart should go (0,1,..., or null for last) * * @return Chart */ public function addChart(Chart $chart, $chartIndex = null) { $chart->setWorksheet($this); if ($chartIndex === null) { $this->chartCollection[] = $chart; } else { // Insert the chart at the requested index // @phpstan-ignore-next-line array_splice(/** @scrutinizer ignore-type */ $this->chartCollection, $chartIndex, 0, [$chart]); } return $chart; } /** * Return the count of charts on this worksheet. * * @return int The number of charts */ public function getChartCount() { return count($this->chartCollection); } /** * Get a chart by its index position. * * @param ?string $index Chart index position * * @return Chart|false */ public function getChartByIndex($index) { $chartCount = count($this->chartCollection); if ($chartCount == 0) { return false; } if ($index === null) { $index = --$chartCount; } if (!isset($this->chartCollection[$index])) { return false; } return $this->chartCollection[$index]; } /** * Return an array of the names of charts on this worksheet. * * @return string[] The names of charts */ public function getChartNames() { $chartNames = []; foreach ($this->chartCollection as $chart) { $chartNames[] = $chart->getName(); } return $chartNames; } /** * Get a chart by name. * * @param string $chartName Chart name * * @return Chart|false */ public function getChartByName($chartName) { foreach ($this->chartCollection as $index => $chart) { if ($chart->getName() == $chartName) { return $chart; } } return false; } /** * Refresh column dimensions. * * @return $this */ public function refreshColumnDimensions() { $newColumnDimensions = []; foreach ($this->getColumnDimensions() as $objColumnDimension) { $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension; } $this->columnDimensions = $newColumnDimensions; return $this; } /** * Refresh row dimensions. * * @return $this */ public function refreshRowDimensions() { $newRowDimensions = []; foreach ($this->getRowDimensions() as $objRowDimension) { $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension; } $this->rowDimensions = $newRowDimensions; return $this; } /** * Calculate worksheet dimension. * * @return string String containing the dimension of this worksheet */ public function calculateWorksheetDimension() { // Return return 'A1:' . $this->getHighestColumn() . $this->getHighestRow(); } /** * Calculate worksheet data dimension. * * @return string String containing the dimension of this worksheet that actually contain data */ public function calculateWorksheetDataDimension() { // Return return 'A1:' . $this->getHighestDataColumn() . $this->getHighestDataRow(); } /** * Calculate widths for auto-size columns. * * @return $this */ public function calculateColumnWidths() { // initialize $autoSizes array $autoSizes = []; foreach ($this->getColumnDimensions() as $colDimension) { if ($colDimension->getAutoSize()) { $autoSizes[$colDimension->getColumnIndex()] = -1; } } // There is only something to do if there are some auto-size columns if (!empty($autoSizes)) { // build list of cells references that participate in a merge $isMergeCell = []; foreach ($this->getMergeCells() as $cells) { foreach (Coordinate::extractAllCellReferencesInRange($cells) as $cellReference) { $isMergeCell[$cellReference] = true; } } $autoFilterIndentRanges = (new AutoFit($this))->getAutoFilterIndentRanges(); // loop through all cells in the worksheet foreach ($this->getCoordinates(false) as $coordinate) { $cell = $this->getCellOrNull($coordinate); if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) { //Determine if cell is in merge range $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]); //By default merged cells should be ignored $isMergedButProceed = false; //The only exception is if it's a merge range value cell of a 'vertical' range (1 column wide) if ($isMerged && $cell->isMergeRangeValueCell()) { $range = (string) $cell->getMergeRange(); $rangeBoundaries = Coordinate::rangeDimension($range); if ($rangeBoundaries[0] === 1) { $isMergedButProceed = true; } } // Determine width if cell is not part of a merge or does and is a value cell of 1-column wide range if (!$isMerged || $isMergedButProceed) { // Determine if we need to make an adjustment for the first row in an AutoFilter range that // has a column filter dropdown $filterAdjustment = false; if (!empty($autoFilterIndentRanges)) { foreach ($autoFilterIndentRanges as $autoFilterFirstRowRange) { if ($cell->isInRange($autoFilterFirstRowRange)) { $filterAdjustment = true; break; } } } $indentAdjustment = $cell->getStyle()->getAlignment()->getIndent(); $indentAdjustment += (int) ($cell->getStyle()->getAlignment()->getHorizontal() === Alignment::HORIZONTAL_CENTER); // Calculated value // To formatted string $cellValue = NumberFormat::toFormattedString( $cell->getCalculatedValue(), (string) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex()) ->getNumberFormat()->getFormatCode() ); if ($cellValue !== null && $cellValue !== '') { $autoSizes[$this->cellCollection->getCurrentColumn()] = max( $autoSizes[$this->cellCollection->getCurrentColumn()], round( Shared\Font::calculateColumnWidth( $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont(), $cellValue, (int) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex()) ->getAlignment()->getTextRotation(), $this->getParentOrThrow()->getDefaultStyle()->getFont(), $filterAdjustment, $indentAdjustment ), 3 ) ); } } } } // adjust column widths foreach ($autoSizes as $columnIndex => $width) { if ($width == -1) { $width = $this->getDefaultColumnDimension()->getWidth(); } $this->getColumnDimension($columnIndex)->setWidth($width); } } return $this; } /** * Get parent or null. */ public function getParent(): ?Spreadsheet { return $this->parent; } /** * Get parent, throw exception if null. */ public function getParentOrThrow(): Spreadsheet { if ($this->parent !== null) { return $this->parent; } throw new Exception('Sheet does not have a parent.'); } /** * Re-bind parent. * * @return $this */ public function rebindParent(Spreadsheet $parent) { if ($this->parent !== null) { $definedNames = $this->parent->getDefinedNames(); foreach ($definedNames as $definedName) { $parent->addDefinedName($definedName); } $this->parent->removeSheetByIndex( $this->parent->getIndex($this) ); } $this->parent = $parent; return $this; } /** * Get title. * * @return string */ public function getTitle() { return $this->title; } /** * Set title. * * @param string $title String containing the dimension of this worksheet * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should * be updated to reflect the new sheet name. * This should be left as the default true, unless you are * certain that no formula cells on any worksheet contain * references to this worksheet * @param bool $validate False to skip validation of new title. WARNING: This should only be set * at parse time (by Readers), where titles can be assumed to be valid. * * @return $this */ public function setTitle($title, $updateFormulaCellReferences = true, $validate = true) { // Is this a 'rename' or not? if ($this->getTitle() == $title) { return $this; } // Old title $oldTitle = $this->getTitle(); if ($validate) { // Syntax check self::checkSheetTitle($title); if ($this->parent) { // Is there already such sheet name? if ($this->parent->sheetNameExists($title)) { // Use name, but append with lowest possible integer if (Shared\StringHelper::countCharacters($title) > 29) { $title = Shared\StringHelper::substring($title, 0, 29); } $i = 1; while ($this->parent->sheetNameExists($title . ' ' . $i)) { ++$i; if ($i == 10) { if (Shared\StringHelper::countCharacters($title) > 28) { $title = Shared\StringHelper::substring($title, 0, 28); } } elseif ($i == 100) { if (Shared\StringHelper::countCharacters($title) > 27) { $title = Shared\StringHelper::substring($title, 0, 27); } } } $title .= " $i"; } } } // Set title $this->title = $title; $this->dirty = true; if ($this->parent && $this->parent->getCalculationEngine()) { // New title $newTitle = $this->getTitle(); $this->parent->getCalculationEngine() ->renameCalculationCacheForWorksheet($oldTitle, $newTitle); if ($updateFormulaCellReferences) { ReferenceHelper::getInstance()->updateNamedFormulae($this->parent, $oldTitle, $newTitle); } } return $this; } /** * Get sheet state. * * @return string Sheet state (visible, hidden, veryHidden) */ public function getSheetState() { return $this->sheetState; } /** * Set sheet state. * * @param string $value Sheet state (visible, hidden, veryHidden) * * @return $this */ public function setSheetState($value) { $this->sheetState = $value; return $this; } /** * Get page setup. * * @return PageSetup */ public function getPageSetup() { return $this->pageSetup; } /** * Set page setup. * * @return $this */ public function setPageSetup(PageSetup $pageSetup) { $this->pageSetup = $pageSetup; return $this; } /** * Get page margins. * * @return PageMargins */ public function getPageMargins() { return $this->pageMargins; } /** * Set page margins. * * @return $this */ public function setPageMargins(PageMargins $pageMargins) { $this->pageMargins = $pageMargins; return $this; } /** * Get page header/footer. * * @return HeaderFooter */ public function getHeaderFooter() { return $this->headerFooter; } /** * Set page header/footer. * * @return $this */ public function setHeaderFooter(HeaderFooter $headerFooter) { $this->headerFooter = $headerFooter; return $this; } /** * Get sheet view. * * @return SheetView */ public function getSheetView() { return $this->sheetView; } /** * Set sheet view. * * @return $this */ public function setSheetView(SheetView $sheetView) { $this->sheetView = $sheetView; return $this; } /** * Get Protection. * * @return Protection */ public function getProtection() { return $this->protection; } /** * Set Protection. * * @return $this */ public function setProtection(Protection $protection) { $this->protection = $protection; $this->dirty = true; return $this; } /** * Get highest worksheet column. * * @param null|int|string $row Return the data highest column for the specified row, * or the highest column of any row if no row number is passed * * @return string Highest column name */ public function getHighestColumn($row = null) { if ($row === null) { return Coordinate::stringFromColumnIndex($this->cachedHighestColumn); } return $this->getHighestDataColumn($row); } /** * Get highest worksheet column that contains data. * * @param null|int|string $row Return the highest data column for the specified row, * or the highest data column of any row if no row number is passed * * @return string Highest column name that contains data */ public function getHighestDataColumn($row = null) { return $this->cellCollection->getHighestColumn($row); } /** * Get highest worksheet row. * * @param null|string $column Return the highest data row for the specified column, * or the highest row of any column if no column letter is passed * * @return int Highest row number */ public function getHighestRow($column = null) { if ($column === null) { return $this->cachedHighestRow; } return $this->getHighestDataRow($column); } /** * Get highest worksheet row that contains data. * * @param null|string $column Return the highest data row for the specified column, * or the highest data row of any column if no column letter is passed * * @return int Highest row number that contains data */ public function getHighestDataRow($column = null) { return $this->cellCollection->getHighestRow($column); } /** * Get highest worksheet column and highest row that have cell records. * * @return array Highest column name and highest row number */ public function getHighestRowAndColumn() { return $this->cellCollection->getHighestRowAndColumn(); } /** * Set a cell value. * * @param array<int>|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @param mixed $value Value for the cell * @param null|IValueBinder $binder Value Binder to override the currently set Value Binder * * @return $this */ public function setCellValue($coordinate, $value, ?IValueBinder $binder = null) { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); $this->getCell($cellAddress)->setValue($value, $binder); return $this; } /** * Set a cell value by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the setCellValue() method with a cell address such as 'C5' instead;, * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @see Worksheet::setCellValue() * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param mixed $value Value of the cell * @param null|IValueBinder $binder Value Binder to override the currently set Value Binder * * @return $this */ public function setCellValueByColumnAndRow($columnIndex, $row, $value, ?IValueBinder $binder = null) { $this->getCell(Coordinate::stringFromColumnIndex($columnIndex) . $row)->setValue($value, $binder); return $this; } /** * Set a cell value. * * @param array<int>|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @param mixed $value Value of the cell * @param string $dataType Explicit data type, see DataType::TYPE_* * Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this * method, then it is your responsibility as an end-user developer to validate that the value and * the datatype match. * If you do mismatch value and datatpe, then the value you enter may be changed to match the datatype * that you specify. * * @see DataType * * @return $this */ public function setCellValueExplicit($coordinate, $value, $dataType) { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); $this->getCell($cellAddress)->setValueExplicit($value, $dataType); return $this; } /** * Set a cell value by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the setCellValueExplicit() method with a cell address such as 'C5' instead;, * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @see Worksheet::setCellValueExplicit() * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param mixed $value Value of the cell * @param string $dataType Explicit data type, see DataType::TYPE_* * Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this * method, then it is your responsibility as an end-user developer to validate that the value and * the datatype match. * If you do mismatch value and datatpe, then the value you enter may be changed to match the datatype * that you specify. * * @see DataType * * @return $this */ public function setCellValueExplicitByColumnAndRow($columnIndex, $row, $value, $dataType) { $this->getCell(Coordinate::stringFromColumnIndex($columnIndex) . $row)->setValueExplicit($value, $dataType); return $this; } /** * Get cell at a specific coordinate. * * @param array<int>|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * * @return Cell Cell that was found or created * WARNING: Because the cell collection can be cached to reduce memory, it only allows one * "active" cell at a time in memory. If you assign that cell to a variable, then select * another cell using getCell() or any of its variants, the newly selected cell becomes * the "active" cell, and any previous assignment becomes a disconnected reference because * the active cell has changed. */ public function getCell($coordinate): Cell { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); // Shortcut for increased performance for the vast majority of simple cases if ($this->cellCollection->has($cellAddress)) { /** @var Cell $cell */ $cell = $this->cellCollection->get($cellAddress); return $cell; } /** @var Worksheet $sheet */ [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress); $cell = $sheet->cellCollection->get($finalCoordinate); return $cell ?? $sheet->createNewCell($finalCoordinate); } /** * Get the correct Worksheet and coordinate from a coordinate that may * contains reference to another sheet or a named range. * * @return array{0: Worksheet, 1: string} */ private function getWorksheetAndCoordinate(string $coordinate): array { $sheet = null; $finalCoordinate = null; // Worksheet reference? if (strpos($coordinate, '!') !== false) { $worksheetReference = self::extractSheetTitle($coordinate, true); $sheet = $this->getParentOrThrow()->getSheetByName($worksheetReference[0]); $finalCoordinate = strtoupper($worksheetReference[1]); if ($sheet === null) { throw new Exception('Sheet not found for name: ' . $worksheetReference[0]); } } elseif ( !preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $coordinate) && preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/iu', $coordinate) ) { // Named range? $namedRange = $this->validateNamedRange($coordinate, true); if ($namedRange !== null) { $sheet = $namedRange->getWorksheet(); if ($sheet === null) { throw new Exception('Sheet not found for named range: ' . $namedRange->getName()); } /** @phpstan-ignore-next-line */ $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!'); $finalCoordinate = str_replace('$', '', $cellCoordinate); } } if ($sheet === null || $finalCoordinate === null) { $sheet = $this; $finalCoordinate = strtoupper($coordinate); } if (Coordinate::coordinateIsRange($finalCoordinate)) { throw new Exception('Cell coordinate string can not be a range of cells.'); } elseif (strpos($finalCoordinate, '$') !== false) { throw new Exception('Cell coordinate must not be absolute.'); } return [$sheet, $finalCoordinate]; } /** * Get an existing cell at a specific coordinate, or null. * * @param string $coordinate Coordinate of the cell, eg: 'A1' * * @return null|Cell Cell that was found or null */ private function getCellOrNull($coordinate): ?Cell { // Check cell collection if ($this->cellCollection->has($coordinate)) { return $this->cellCollection->get($coordinate); } return null; } /** * Get cell at a specific coordinate by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the getCell() method with a cell address such as 'C5' instead;, * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @see Worksheet::getCell() * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * * @return Cell Cell that was found/created or null * WARNING: Because the cell collection can be cached to reduce memory, it only allows one * "active" cell at a time in memory. If you assign that cell to a variable, then select * another cell using getCell() or any of its variants, the newly selected cell becomes * the "active" cell, and any previous assignment becomes a disconnected reference because * the active cell has changed. */ public function getCellByColumnAndRow($columnIndex, $row): Cell { return $this->getCell(Coordinate::stringFromColumnIndex($columnIndex) . $row); } /** * Create a new cell at the specified coordinate. * * @param string $coordinate Coordinate of the cell * * @return Cell Cell that was created * WARNING: Because the cell collection can be cached to reduce memory, it only allows one * "active" cell at a time in memory. If you assign that cell to a variable, then select * another cell using getCell() or any of its variants, the newly selected cell becomes * the "active" cell, and any previous assignment becomes a disconnected reference because * the active cell has changed. */ public function createNewCell($coordinate): Cell { [$column, $row, $columnString] = Coordinate::indexesFromString($coordinate); $cell = new Cell(null, DataType::TYPE_NULL, $this); $this->cellCollection->add($coordinate, $cell); // Coordinates if ($column > $this->cachedHighestColumn) { $this->cachedHighestColumn = $column; } if ($row > $this->cachedHighestRow) { $this->cachedHighestRow = $row; } // Cell needs appropriate xfIndex from dimensions records // but don't create dimension records if they don't already exist $rowDimension = $this->rowDimensions[$row] ?? null; $columnDimension = $this->columnDimensions[$columnString] ?? null; if ($rowDimension !== null) { $rowXf = (int) $rowDimension->getXfIndex(); if ($rowXf > 0) { // then there is a row dimension with explicit style, assign it to the cell $cell->setXfIndex($rowXf); } } elseif ($columnDimension !== null) { $colXf = (int) $columnDimension->getXfIndex(); if ($colXf > 0) { // then there is a column dimension, assign it to the cell $cell->setXfIndex($colXf); } } return $cell; } /** * Does the cell at a specific coordinate exist? * * @param array<int>|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. */ public function cellExists($coordinate): bool { $cellAddress = Validations::validateCellAddress($coordinate); /** @var Worksheet $sheet */ [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress); return $sheet->cellCollection->has($finalCoordinate); } /** * Cell at a specific coordinate by using numeric cell coordinates exists? * * @deprecated 1.23.0 * Use the cellExists() method with a cell address such as 'C5' instead;, * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @see Worksheet::cellExists() * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell */ public function cellExistsByColumnAndRow($columnIndex, $row): bool { return $this->cellExists(Coordinate::stringFromColumnIndex($columnIndex) . $row); } /** * Get row dimension at a specific row. * * @param int $row Numeric index of the row */ public function getRowDimension(int $row): RowDimension { // Get row dimension if (!isset($this->rowDimensions[$row])) { $this->rowDimensions[$row] = new RowDimension($row); $this->cachedHighestRow = max($this->cachedHighestRow, $row); } return $this->rowDimensions[$row]; } public function rowDimensionExists(int $row): bool { return isset($this->rowDimensions[$row]); } /** * Get column dimension at a specific column. * * @param string $column String index of the column eg: 'A' */ public function getColumnDimension(string $column): ColumnDimension { // Uppercase coordinate $column = strtoupper($column); // Fetch dimensions if (!isset($this->columnDimensions[$column])) { $this->columnDimensions[$column] = new ColumnDimension($column); $columnIndex = Coordinate::columnIndexFromString($column); if ($this->cachedHighestColumn < $columnIndex) { $this->cachedHighestColumn = $columnIndex; } } return $this->columnDimensions[$column]; } /** * Get column dimension at a specific column by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell */ public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension { return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex)); } /** * Get styles. * * @return Style[] */ public function getStyles() { return $this->styles; } /** * Get style for cell. * * @param AddressRange|array<int>|CellAddress|int|string $cellCoordinate * A simple string containing a cell address like 'A1' or a cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or a CellAddress or AddressRange object. */ public function getStyle($cellCoordinate): Style { $cellCoordinate = Validations::validateCellOrCellRange($cellCoordinate); // set this sheet as active $this->getParentOrThrow()->setActiveSheetIndex($this->getParentOrThrow()->getIndex($this)); // set cell coordinate as active $this->setSelectedCells($cellCoordinate); return $this->getParentOrThrow()->getCellXfSupervisor(); } /** * Get style for cell by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the getStyle() method with a cell address range such as 'C5:F8' instead;, * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. * @see Worksheet::getStyle() * * @param int $columnIndex1 Numeric column coordinate of the cell * @param int $row1 Numeric row coordinate of the cell * @param null|int $columnIndex2 Numeric column coordinate of the range cell * @param null|int $row2 Numeric row coordinate of the range cell * * @return Style */ public function getStyleByColumnAndRow($columnIndex1, $row1, $columnIndex2 = null, $row2 = null) { if ($columnIndex2 !== null && $row2 !== null) { $cellRange = new CellRange( CellAddress::fromColumnAndRow($columnIndex1, $row1), CellAddress::fromColumnAndRow($columnIndex2, $row2) ); return $this->getStyle($cellRange); } return $this->getStyle(CellAddress::fromColumnAndRow($columnIndex1, $row1)); } /** * Get conditional styles for a cell. * * @param string $coordinate eg: 'A1' or 'A1:A3'. * If a single cell is referenced, then the array of conditional styles will be returned if the cell is * included in a conditional style range. * If a range of cells is specified, then the styles will only be returned if the range matches the entire * range of the conditional. * * @return Conditional[] */ public function getConditionalStyles(string $coordinate): array { $coordinate = strtoupper($coordinate); if (strpos($coordinate, ':') !== false) { return $this->conditionalStylesCollection[$coordinate] ?? []; } $cell = $this->getCell($coordinate); foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) { if ($cell->isInRange($conditionalRange)) { return $this->conditionalStylesCollection[$conditionalRange]; } } return []; } public function getConditionalRange(string $coordinate): ?string { $coordinate = strtoupper($coordinate); $cell = $this->getCell($coordinate); foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) { if ($cell->isInRange($conditionalRange)) { return $conditionalRange; } } return null; } /** * Do conditional styles exist for this cell? * * @param string $coordinate eg: 'A1' or 'A1:A3'. * If a single cell is specified, then this method will return true if that cell is included in a * conditional style range. * If a range of cells is specified, then true will only be returned if the range matches the entire * range of the conditional. */ public function conditionalStylesExists($coordinate): bool { $coordinate = strtoupper($coordinate); if (strpos($coordinate, ':') !== false) { return isset($this->conditionalStylesCollection[$coordinate]); } $cell = $this->getCell($coordinate); foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) { if ($cell->isInRange($conditionalRange)) { return true; } } return false; } /** * Removes conditional styles for a cell. * * @param string $coordinate eg: 'A1' * * @return $this */ public function removeConditionalStyles($coordinate) { unset($this->conditionalStylesCollection[strtoupper($coordinate)]); return $this; } /** * Get collection of conditional styles. * * @return array */ public function getConditionalStylesCollection() { return $this->conditionalStylesCollection; } /** * Set conditional styles. * * @param string $coordinate eg: 'A1' * @param Conditional[] $styles * * @return $this */ public function setConditionalStyles($coordinate, $styles) { $this->conditionalStylesCollection[strtoupper($coordinate)] = $styles; return $this; } /** * Duplicate cell style to a range of cells. * * Please note that this will overwrite existing cell styles for cells in range! * * @param Style $style Cell style to duplicate * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * * @return $this */ public function duplicateStyle(Style $style, $range) { // Add the style to the workbook if necessary $workbook = $this->getParentOrThrow(); if ($existingStyle = $workbook->getCellXfByHashCode($style->getHashCode())) { // there is already such cell Xf in our collection $xfIndex = $existingStyle->getIndex(); } else { // we don't have such a cell Xf, need to add $workbook->addCellXf($style); $xfIndex = $style->getIndex(); } // Calculate range outer borders [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range); // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { $tmp = $rangeStart; $rangeStart = $rangeEnd; $rangeEnd = $tmp; } // Loop through cells and apply styles for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { $this->getCell(Coordinate::stringFromColumnIndex($col) . $row)->setXfIndex($xfIndex); } } return $this; } /** * Duplicate conditional style to a range of cells. * * Please note that this will overwrite existing cell styles for cells in range! * * @param Conditional[] $styles Cell style to duplicate * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * * @return $this */ public function duplicateConditionalStyle(array $styles, $range = '') { foreach ($styles as $cellStyle) { if (!($cellStyle instanceof Conditional)) { throw new Exception('Style is not a conditional style'); } } // Calculate range outer borders [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range); // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { $tmp = $rangeStart; $rangeStart = $rangeEnd; $rangeEnd = $tmp; } // Loop through cells and apply styles for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $styles); } } return $this; } /** * Set break on a cell. * * @param array<int>|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @param int $break Break type (type of Worksheet::BREAK_*) * * @return $this */ public function setBreak($coordinate, $break, int $max = -1) { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); if ($break === self::BREAK_NONE) { unset($this->rowBreaks[$cellAddress], $this->columnBreaks[$cellAddress]); } elseif ($break === self::BREAK_ROW) { $this->rowBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max); } elseif ($break === self::BREAK_COLUMN) { $this->columnBreaks[$cellAddress] = new PageBreak($break, $cellAddress, $max); } return $this; } /** * Set break on a cell by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the setBreak() method with a cell address such as 'C5' instead;, * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @see Worksheet::setBreak() * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param int $break Break type (type of Worksheet::BREAK_*) * * @return $this */ public function setBreakByColumnAndRow($columnIndex, $row, $break) { return $this->setBreak(Coordinate::stringFromColumnIndex($columnIndex) . $row, $break); } /** * Get breaks. * * @return int[] */ public function getBreaks() { $breaks = []; /** @var callable */ $compareFunction = [self::class, 'compareRowBreaks']; uksort($this->rowBreaks, $compareFunction); foreach ($this->rowBreaks as $break) { $breaks[$break->getCoordinate()] = self::BREAK_ROW; } /** @var callable */ $compareFunction = [self::class, 'compareColumnBreaks']; uksort($this->columnBreaks, $compareFunction); foreach ($this->columnBreaks as $break) { $breaks[$break->getCoordinate()] = self::BREAK_COLUMN; } return $breaks; } /** * Get row breaks. * * @return PageBreak[] */ public function getRowBreaks() { /** @var callable */ $compareFunction = [self::class, 'compareRowBreaks']; uksort($this->rowBreaks, $compareFunction); return $this->rowBreaks; } protected static function compareRowBreaks(string $coordinate1, string $coordinate2): int { $row1 = Coordinate::indexesFromString($coordinate1)[1]; $row2 = Coordinate::indexesFromString($coordinate2)[1]; return $row1 - $row2; } protected static function compareColumnBreaks(string $coordinate1, string $coordinate2): int { $column1 = Coordinate::indexesFromString($coordinate1)[0]; $column2 = Coordinate::indexesFromString($coordinate2)[0]; return $column1 - $column2; } /** * Get column breaks. * * @return PageBreak[] */ public function getColumnBreaks() { /** @var callable */ $compareFunction = [self::class, 'compareColumnBreaks']; uksort($this->columnBreaks, $compareFunction); return $this->columnBreaks; } /** * Set merge on a cell range. * * @param AddressRange|array<int>|string $range A simple string containing a Cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange. * @param string $behaviour How the merged cells should behave. * Possible values are: * MERGE_CELL_CONTENT_EMPTY - Empty the content of the hidden cells * MERGE_CELL_CONTENT_HIDE - Keep the content of the hidden cells * MERGE_CELL_CONTENT_MERGE - Move the content of the hidden cells into the first cell * * @return $this */ public function mergeCells($range, $behaviour = self::MERGE_CELL_CONTENT_EMPTY) { $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range)); if (strpos($range, ':') === false) { $range .= ":{$range}"; } if (preg_match('/^([A-Z]+)(\\d+):([A-Z]+)(\\d+)$/', $range, $matches) !== 1) { throw new Exception('Merge must be on a valid range of cells.'); } $this->mergeCells[$range] = $range; $firstRow = (int) $matches[2]; $lastRow = (int) $matches[4]; $firstColumn = $matches[1]; $lastColumn = $matches[3]; $firstColumnIndex = Coordinate::columnIndexFromString($firstColumn); $lastColumnIndex = Coordinate::columnIndexFromString($lastColumn); $numberRows = $lastRow - $firstRow; $numberColumns = $lastColumnIndex - $firstColumnIndex; if ($numberRows === 1 && $numberColumns === 1) { return $this; } // create upper left cell if it does not already exist $upperLeft = "{$firstColumn}{$firstRow}"; if (!$this->cellExists($upperLeft)) { $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL); } if ($behaviour !== self::MERGE_CELL_CONTENT_HIDE) { // Blank out the rest of the cells in the range (if they exist) if ($numberRows > $numberColumns) { $this->clearMergeCellsByColumn($firstColumn, $lastColumn, $firstRow, $lastRow, $upperLeft, $behaviour); } else { $this->clearMergeCellsByRow($firstColumn, $lastColumnIndex, $firstRow, $lastRow, $upperLeft, $behaviour); } } return $this; } private function clearMergeCellsByColumn(string $firstColumn, string $lastColumn, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void { $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE) ? [$this->getCell($upperLeft)->getFormattedValue()] : []; foreach ($this->getColumnIterator($firstColumn, $lastColumn) as $column) { $iterator = $column->getCellIterator($firstRow); $iterator->setIterateOnlyExistingCells(true); foreach ($iterator as $cell) { if ($cell !== null) { $row = $cell->getRow(); if ($row > $lastRow) { break; } $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue); } } } if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) { $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING); } } private function clearMergeCellsByRow(string $firstColumn, int $lastColumnIndex, int $firstRow, int $lastRow, string $upperLeft, string $behaviour): void { $leftCellValue = ($behaviour === self::MERGE_CELL_CONTENT_MERGE) ? [$this->getCell($upperLeft)->getFormattedValue()] : []; foreach ($this->getRowIterator($firstRow, $lastRow) as $row) { $iterator = $row->getCellIterator($firstColumn); $iterator->setIterateOnlyExistingCells(true); foreach ($iterator as $cell) { if ($cell !== null) { $column = $cell->getColumn(); $columnIndex = Coordinate::columnIndexFromString($column); if ($columnIndex > $lastColumnIndex) { break; } $leftCellValue = $this->mergeCellBehaviour($cell, $upperLeft, $behaviour, $leftCellValue); } } } if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) { $this->getCell($upperLeft)->setValueExplicit(implode(' ', $leftCellValue), DataType::TYPE_STRING); } } public function mergeCellBehaviour(Cell $cell, string $upperLeft, string $behaviour, array $leftCellValue): array { if ($cell->getCoordinate() !== $upperLeft) { Calculation::getInstance($cell->getWorksheet()->getParentOrThrow())->flushInstance(); if ($behaviour === self::MERGE_CELL_CONTENT_MERGE) { $cellValue = $cell->getFormattedValue(); if ($cellValue !== '') { $leftCellValue[] = $cellValue; } } $cell->setValueExplicit(null, DataType::TYPE_NULL); } return $leftCellValue; } /** * Set merge on a cell range by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the mergeCells() method with a cell address range such as 'C5:F8' instead;, * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. * @see Worksheet::mergeCells() * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * @param string $behaviour How the merged cells should behave. * Possible values are: * MERGE_CELL_CONTENT_EMPTY - Empty the content of the hidden cells * MERGE_CELL_CONTENT_HIDE - Keep the content of the hidden cells * MERGE_CELL_CONTENT_MERGE - Move the content of the hidden cells into the first cell * * @return $this */ public function mergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2, $behaviour = self::MERGE_CELL_CONTENT_EMPTY) { $cellRange = new CellRange( CellAddress::fromColumnAndRow($columnIndex1, $row1), CellAddress::fromColumnAndRow($columnIndex2, $row2) ); return $this->mergeCells($cellRange, $behaviour); } /** * Remove merge on a cell range. * * @param AddressRange|array<int>|string $range A simple string containing a Cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange. * * @return $this */ public function unmergeCells($range) { $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range)); if (strpos($range, ':') !== false) { if (isset($this->mergeCells[$range])) { unset($this->mergeCells[$range]); } else { throw new Exception('Cell range ' . $range . ' not known as merged.'); } } else { throw new Exception('Merge can only be removed from a range of cells.'); } return $this; } /** * Remove merge on a cell range by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the unmergeCells() method with a cell address range such as 'C5:F8' instead;, * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. * @see Worksheet::unmergeCells() * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * * @return $this */ public function unmergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2) { $cellRange = new CellRange( CellAddress::fromColumnAndRow($columnIndex1, $row1), CellAddress::fromColumnAndRow($columnIndex2, $row2) ); return $this->unmergeCells($cellRange); } /** * Get merge cells array. * * @return string[] */ public function getMergeCells() { return $this->mergeCells; } /** * Set merge cells array for the entire sheet. Use instead mergeCells() to merge * a single cell range. * * @param string[] $mergeCells * * @return $this */ public function setMergeCells(array $mergeCells) { $this->mergeCells = $mergeCells; return $this; } /** * Set protection on a cell or cell range. * * @param AddressRange|array<int>|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or a CellAddress or AddressRange object. * @param string $password Password to unlock the protection * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ public function protectCells($range, $password, $alreadyHashed = false) { $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range)); if (!$alreadyHashed) { $password = Shared\PasswordHasher::hashPassword($password); } $this->protectedCells[$range] = $password; return $this; } /** * Set protection on a cell range by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the protectCells() method with a cell address range such as 'C5:F8' instead;, * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. * @see Worksheet::protectCells() * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * @param string $password Password to unlock the protection * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ public function protectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2, $password, $alreadyHashed = false) { $cellRange = new CellRange( CellAddress::fromColumnAndRow($columnIndex1, $row1), CellAddress::fromColumnAndRow($columnIndex2, $row2) ); return $this->protectCells($cellRange, $password, $alreadyHashed); } /** * Remove protection on a cell or cell range. * * @param AddressRange|array<int>|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or a CellAddress or AddressRange object. * * @return $this */ public function unprotectCells($range) { $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range)); if (isset($this->protectedCells[$range])) { unset($this->protectedCells[$range]); } else { throw new Exception('Cell range ' . $range . ' not known as protected.'); } return $this; } /** * Remove protection on a cell range by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the unprotectCells() method with a cell address range such as 'C5:F8' instead;, * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object. * @see Worksheet::unprotectCells() * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * * @return $this */ public function unprotectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2) { $cellRange = new CellRange( CellAddress::fromColumnAndRow($columnIndex1, $row1), CellAddress::fromColumnAndRow($columnIndex2, $row2) ); return $this->unprotectCells($cellRange); } /** * Get protected cells. * * @return string[] */ public function getProtectedCells() { return $this->protectedCells; } /** * Get Autofilter. * * @return AutoFilter */ public function getAutoFilter() { return $this->autoFilter; } /** * Set AutoFilter. * * @param AddressRange|array<int>|AutoFilter|string $autoFilterOrRange * A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange. * * @return $this */ public function setAutoFilter($autoFilterOrRange) { if (is_object($autoFilterOrRange) && ($autoFilterOrRange instanceof AutoFilter)) { $this->autoFilter = $autoFilterOrRange; } else { $cellRange = Functions::trimSheetFromCellReference(Validations::validateCellRange($autoFilterOrRange)); $this->autoFilter->setRange($cellRange); } return $this; } /** * Set Autofilter Range by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the setAutoFilter() method with a cell address range such as 'C5:F8' instead;, * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or an AddressRange object or AutoFilter object. * @see Worksheet::setAutoFilter() * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the second cell * @param int $row2 Numeric row coordinate of the second cell * * @return $this */ public function setAutoFilterByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2) { $cellRange = new CellRange( CellAddress::fromColumnAndRow($columnIndex1, $row1), CellAddress::fromColumnAndRow($columnIndex2, $row2) ); return $this->setAutoFilter($cellRange); } /** * Remove autofilter. */ public function removeAutoFilter(): self { $this->autoFilter->setRange(''); return $this; } /** * Get collection of Tables. * * @return ArrayObject<int, Table> */ public function getTableCollection() { return $this->tableCollection; } /** * Add Table. * * @return $this */ public function addTable(Table $table): self { $table->setWorksheet($this); $this->tableCollection[] = $table; return $this; } /** * @return string[] array of Table names */ public function getTableNames(): array { $tableNames = []; foreach ($this->tableCollection as $table) { /** @var Table $table */ $tableNames[] = $table->getName(); } return $tableNames; } /** @var null|Table */ private static $scrutinizerNullTable; /** @var null|int */ private static $scrutinizerNullInt; /** * @param string $name the table name to search * * @return null|Table The table from the tables collection, or null if not found */ public function getTableByName(string $name): ?Table { $tableIndex = $this->getTableIndexByName($name); return ($tableIndex === null) ? self::$scrutinizerNullTable : $this->tableCollection[$tableIndex]; } /** * @param string $name the table name to search * * @return null|int The index of the located table in the tables collection, or null if not found */ protected function getTableIndexByName(string $name): ?int { $name = Shared\StringHelper::strToUpper($name); foreach ($this->tableCollection as $index => $table) { /** @var Table $table */ if (Shared\StringHelper::strToUpper($table->getName()) === $name) { return $index; } } return self::$scrutinizerNullInt; } /** * Remove Table by name. * * @param string $name Table name * * @return $this */ public function removeTableByName(string $name): self { $tableIndex = $this->getTableIndexByName($name); if ($tableIndex !== null) { unset($this->tableCollection[$tableIndex]); } return $this; } /** * Remove collection of Tables. */ public function removeTableCollection(): self { $this->tableCollection = new ArrayObject(); return $this; } /** * Get Freeze Pane. * * @return null|string */ public function getFreezePane() { return $this->freezePane; } /** * Freeze Pane. * * Examples: * * - A2 will freeze the rows above cell A2 (i.e row 1) * - B1 will freeze the columns to the left of cell B1 (i.e column A) * - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A) * * @param null|array<int>|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * Passing a null value for this argument will clear any existing freeze pane for this worksheet. * @param null|array<int>|CellAddress|string $topLeftCell default position of the right bottom pane * Coordinate of the cell as a string, eg: 'C5'; or as an array of [$columnIndex, $row] (e.g. [3, 5]), * or a CellAddress object. * * @return $this */ public function freezePane($coordinate, $topLeftCell = null) { $cellAddress = ($coordinate !== null) ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)) : null; if ($cellAddress !== null && Coordinate::coordinateIsRange($cellAddress)) { throw new Exception('Freeze pane can not be set on a range of cells.'); } $topLeftCell = ($topLeftCell !== null) ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($topLeftCell)) : null; if ($cellAddress !== null && $topLeftCell === null) { $coordinate = Coordinate::coordinateFromString($cellAddress); $topLeftCell = $coordinate[0] . $coordinate[1]; } $this->freezePane = $cellAddress; $this->topLeftCell = $topLeftCell; return $this; } public function setTopLeftCell(string $topLeftCell): self { $this->topLeftCell = $topLeftCell; return $this; } /** * Freeze Pane by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the freezePane() method with a cell address such as 'C5' instead;, * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @see Worksheet::freezePane() * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * * @return $this */ public function freezePaneByColumnAndRow($columnIndex, $row) { return $this->freezePane(Coordinate::stringFromColumnIndex($columnIndex) . $row); } /** * Unfreeze Pane. * * @return $this */ public function unfreezePane() { return $this->freezePane(null); } /** * Get the default position of the right bottom pane. * * @return null|string */ public function getTopLeftCell() { return $this->topLeftCell; } /** * Insert a new row, updating all possible related data. * * @param int $before Insert before this row number * @param int $numberOfRows Number of new rows to insert * * @return $this */ public function insertNewRowBefore(int $before, int $numberOfRows = 1) { if ($before >= 1) { $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore('A' . $before, 0, $numberOfRows, $this); } else { throw new Exception('Rows can only be inserted before at least row 1.'); } return $this; } /** * Insert a new column, updating all possible related data. * * @param string $before Insert before this column Name, eg: 'A' * @param int $numberOfColumns Number of new columns to insert * * @return $this */ public function insertNewColumnBefore(string $before, int $numberOfColumns = 1) { if (!is_numeric($before)) { $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore($before . '1', $numberOfColumns, 0, $this); } else { throw new Exception('Column references should not be numeric.'); } return $this; } /** * Insert a new column, updating all possible related data. * * @param int $beforeColumnIndex Insert before this column ID (numeric column coordinate of the cell) * @param int $numberOfColumns Number of new columns to insert * * @return $this */ public function insertNewColumnBeforeByIndex(int $beforeColumnIndex, int $numberOfColumns = 1) { if ($beforeColumnIndex >= 1) { return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $numberOfColumns); } throw new Exception('Columns can only be inserted before at least column A (1).'); } /** * Delete a row, updating all possible related data. * * @param int $row Remove rows, starting with this row number * @param int $numberOfRows Number of rows to remove * * @return $this */ public function removeRow(int $row, int $numberOfRows = 1) { if ($row < 1) { throw new Exception('Rows to be deleted should at least start from row 1.'); } $holdRowDimensions = $this->removeRowDimensions($row, $numberOfRows); $highestRow = $this->getHighestDataRow(); $removedRowsCounter = 0; for ($r = 0; $r < $numberOfRows; ++$r) { if ($row + $r <= $highestRow) { $this->getCellCollection()->removeRow($row + $r); ++$removedRowsCounter; } } $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore('A' . ($row + $numberOfRows), 0, -$numberOfRows, $this); for ($r = 0; $r < $removedRowsCounter; ++$r) { $this->getCellCollection()->removeRow($highestRow); --$highestRow; } $this->rowDimensions = $holdRowDimensions; return $this; } private function removeRowDimensions(int $row, int $numberOfRows): array { $highRow = $row + $numberOfRows - 1; $holdRowDimensions = []; foreach ($this->rowDimensions as $rowDimension) { $num = $rowDimension->getRowIndex(); if ($num < $row) { $holdRowDimensions[$num] = $rowDimension; } elseif ($num > $highRow) { $num -= $numberOfRows; $cloneDimension = clone $rowDimension; $cloneDimension->setRowIndex(/** @scrutinizer ignore-type */ $num); $holdRowDimensions[$num] = $cloneDimension; } } return $holdRowDimensions; } /** * Remove a column, updating all possible related data. * * @param string $column Remove columns starting with this column name, eg: 'A' * @param int $numberOfColumns Number of columns to remove * * @return $this */ public function removeColumn(string $column, int $numberOfColumns = 1) { if (is_numeric($column)) { throw new Exception('Column references should not be numeric.'); } $highestColumn = $this->getHighestDataColumn(); $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn); $pColumnIndex = Coordinate::columnIndexFromString($column); $holdColumnDimensions = $this->removeColumnDimensions($pColumnIndex, $numberOfColumns); $column = Coordinate::stringFromColumnIndex($pColumnIndex + $numberOfColumns); $objReferenceHelper = ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore($column . '1', -$numberOfColumns, 0, $this); $this->columnDimensions = $holdColumnDimensions; if ($pColumnIndex > $highestColumnIndex) { return $this; } $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1; for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) { $this->getCellCollection()->removeColumn($highestColumn); $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1); } $this->garbageCollect(); return $this; } private function removeColumnDimensions(int $pColumnIndex, int $numberOfColumns): array { $highCol = $pColumnIndex + $numberOfColumns - 1; $holdColumnDimensions = []; foreach ($this->columnDimensions as $columnDimension) { $num = $columnDimension->getColumnNumeric(); if ($num < $pColumnIndex) { $str = $columnDimension->getColumnIndex(); $holdColumnDimensions[$str] = $columnDimension; } elseif ($num > $highCol) { $cloneDimension = clone $columnDimension; $cloneDimension->setColumnNumeric($num - $numberOfColumns); $str = $cloneDimension->getColumnIndex(); $holdColumnDimensions[$str] = $cloneDimension; } } return $holdColumnDimensions; } /** * Remove a column, updating all possible related data. * * @param int $columnIndex Remove starting with this column Index (numeric column coordinate) * @param int $numColumns Number of columns to remove * * @return $this */ public function removeColumnByIndex(int $columnIndex, int $numColumns = 1) { if ($columnIndex >= 1) { return $this->removeColumn(Coordinate::stringFromColumnIndex($columnIndex), $numColumns); } throw new Exception('Columns to be deleted should at least start from column A (1)'); } /** * Show gridlines? */ public function getShowGridlines(): bool { return $this->showGridlines; } /** * Set show gridlines. * * @param bool $showGridLines Show gridlines (true/false) * * @return $this */ public function setShowGridlines(bool $showGridLines): self { $this->showGridlines = $showGridLines; return $this; } /** * Print gridlines? */ public function getPrintGridlines(): bool { return $this->printGridlines; } /** * Set print gridlines. * * @param bool $printGridLines Print gridlines (true/false) * * @return $this */ public function setPrintGridlines(bool $printGridLines): self { $this->printGridlines = $printGridLines; return $this; } /** * Show row and column headers? */ public function getShowRowColHeaders(): bool { return $this->showRowColHeaders; } /** * Set show row and column headers. * * @param bool $showRowColHeaders Show row and column headers (true/false) * * @return $this */ public function setShowRowColHeaders(bool $showRowColHeaders): self { $this->showRowColHeaders = $showRowColHeaders; return $this; } /** * Show summary below? (Row/Column outlining). */ public function getShowSummaryBelow(): bool { return $this->showSummaryBelow; } /** * Set show summary below. * * @param bool $showSummaryBelow Show summary below (true/false) * * @return $this */ public function setShowSummaryBelow(bool $showSummaryBelow): self { $this->showSummaryBelow = $showSummaryBelow; return $this; } /** * Show summary right? (Row/Column outlining). */ public function getShowSummaryRight(): bool { return $this->showSummaryRight; } /** * Set show summary right. * * @param bool $showSummaryRight Show summary right (true/false) * * @return $this */ public function setShowSummaryRight(bool $showSummaryRight): self { $this->showSummaryRight = $showSummaryRight; return $this; } /** * Get comments. * * @return Comment[] */ public function getComments() { return $this->comments; } /** * Set comments array for the entire sheet. * * @param Comment[] $comments * * @return $this */ public function setComments(array $comments): self { $this->comments = $comments; return $this; } /** * Remove comment from cell. * * @param array<int>|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * * @return $this */ public function removeComment($cellCoordinate): self { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate)); if (Coordinate::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells.'); } elseif (strpos($cellAddress, '$') !== false) { throw new Exception('Cell coordinate string must not be absolute.'); } elseif ($cellAddress == '') { throw new Exception('Cell coordinate can not be zero-length string.'); } // Check if we have a comment for this cell and delete it if (isset($this->comments[$cellAddress])) { unset($this->comments[$cellAddress]); } return $this; } /** * Get comment for cell. * * @param array<int>|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5'; * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. */ public function getComment($cellCoordinate): Comment { $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate)); if (Coordinate::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells.'); } elseif (strpos($cellAddress, '$') !== false) { throw new Exception('Cell coordinate string must not be absolute.'); } elseif ($cellAddress == '') { throw new Exception('Cell coordinate can not be zero-length string.'); } // Check if we already have a comment for this cell. if (isset($this->comments[$cellAddress])) { return $this->comments[$cellAddress]; } // If not, create a new comment. $newComment = new Comment(); $this->comments[$cellAddress] = $newComment; return $newComment; } /** * Get comment for cell by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the getComment() method with a cell address such as 'C5' instead;, * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @see Worksheet::getComment() * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell */ public function getCommentByColumnAndRow($columnIndex, $row): Comment { return $this->getComment(Coordinate::stringFromColumnIndex($columnIndex) . $row); } /** * Get active cell. * * @return string Example: 'A1' */ public function getActiveCell() { return $this->activeCell; } /** * Get selected cells. * * @return string */ public function getSelectedCells() { return $this->selectedCells; } /** * Selected cell. * * @param string $coordinate Cell (i.e. A1) * * @return $this */ public function setSelectedCell($coordinate) { return $this->setSelectedCells($coordinate); } /** * Select a range of cells. * * @param AddressRange|array<int>|CellAddress|int|string $coordinate A simple string containing a Cell range like 'A1:E10' * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), * or a CellAddress or AddressRange object. * * @return $this */ public function setSelectedCells($coordinate) { if (is_string($coordinate)) { $coordinate = Validations::definedNameToCoordinate($coordinate, $this); } $coordinate = Validations::validateCellOrCellRange($coordinate); if (Coordinate::coordinateIsRange($coordinate)) { [$first] = Coordinate::splitRange($coordinate); $this->activeCell = $first[0]; } else { $this->activeCell = $coordinate; } $this->selectedCells = $coordinate; return $this; } /** * Selected cell by using numeric cell coordinates. * * @deprecated 1.23.0 * Use the setSelectedCells() method with a cell address such as 'C5' instead;, * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * @see Worksheet::setSelectedCells() * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * * @return $this */ public function setSelectedCellByColumnAndRow($columnIndex, $row) { return $this->setSelectedCells(Coordinate::stringFromColumnIndex($columnIndex) . $row); } /** * Get right-to-left. * * @return bool */ public function getRightToLeft() { return $this->rightToLeft; } /** * Set right-to-left. * * @param bool $value Right-to-left true/false * * @return $this */ public function setRightToLeft($value) { $this->rightToLeft = $value; return $this; } /** * Fill worksheet from values in array. * * @param array $source Source array * @param mixed $nullValue Value in source array that stands for blank cell * @param string $startCell Insert array starting from this cell address as the top left coordinate * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array * * @return $this */ public function fromArray(array $source, $nullValue = null, $startCell = 'A1', $strictNullComparison = false) { // Convert a 1-D array to 2-D (for ease of looping) if (!is_array(end($source))) { $source = [$source]; } // start coordinate [$startColumn, $startRow] = Coordinate::coordinateFromString($startCell); // Loop through $source foreach ($source as $rowData) { $currentColumn = $startColumn; foreach ($rowData as $cellValue) { if ($strictNullComparison) { if ($cellValue !== $nullValue) { // Set cell value $this->getCell($currentColumn . $startRow)->setValue($cellValue); } } else { if ($cellValue != $nullValue) { // Set cell value $this->getCell($currentColumn . $startRow)->setValue($cellValue); } } ++$currentColumn; } ++$startRow; } return $this; } /** * @param mixed $nullValue * * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception * * @return mixed */ protected function cellToArray(Cell $cell, bool $calculateFormulas, bool $formatData, $nullValue) { $returnValue = $nullValue; if ($cell->getValue() !== null) { if ($cell->getValue() instanceof RichText) { $returnValue = $cell->getValue()->getPlainText(); } else { $returnValue = ($calculateFormulas) ? $cell->getCalculatedValue() : $cell->getValue(); } if ($formatData) { $style = $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex()); $returnValue = NumberFormat::toFormattedString( $returnValue, $style->getNumberFormat()->getFormatCode() ?? NumberFormat::FORMAT_GENERAL ); } } return $returnValue; } /** * Create array from a range of cells. * * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden. * True - Don't return values for rows/columns that are defined as hidden. */ public function rangeToArray( string $range, $nullValue = null, bool $calculateFormulas = true, bool $formatData = true, bool $returnCellRef = false, bool $ignoreHidden = false ): array { $range = Validations::validateCellOrCellRange($range); $returnValue = []; // Identify the range that we need to extract from the worksheet [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range); $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]); $minRow = $rangeStart[1]; $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]); $maxRow = $rangeEnd[1]; ++$maxCol; // Loop through rows $r = -1; for ($row = $minRow; $row <= $maxRow; ++$row) { if (($ignoreHidden === true) && ($this->getRowDimension($row)->getVisible() === false)) { continue; } $rowRef = $returnCellRef ? $row : ++$r; $c = -1; // Loop through columns in the current row for ($col = $minCol; $col !== $maxCol; ++$col) { if (($ignoreHidden === true) && ($this->getColumnDimension($col)->getVisible() === false)) { continue; } $columnRef = $returnCellRef ? $col : ++$c; // Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen // so we test and retrieve directly against cellCollection $cell = $this->cellCollection->get("{$col}{$row}"); $returnValue[$rowRef][$columnRef] = $nullValue; if ($cell !== null) { $returnValue[$rowRef][$columnRef] = $this->cellToArray($cell, $calculateFormulas, $formatData, $nullValue); } } } // Return return $returnValue; } private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName { $namedRange = DefinedName::resolveName($definedName, $this); if ($namedRange === null) { if ($returnNullIfInvalid) { return null; } throw new Exception('Named Range ' . $definedName . ' does not exist.'); } if ($namedRange->isFormula()) { if ($returnNullIfInvalid) { return null; } throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.'); } if ($namedRange->getLocalOnly()) { $worksheet = $namedRange->getWorksheet(); if ($worksheet === null || $this->getHashCode() !== $worksheet->getHashCode()) { if ($returnNullIfInvalid) { return null; } throw new Exception( 'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle() ); } } return $namedRange; } /** * Create array from a range of cells. * * @param string $definedName The Named Range that should be returned * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden. * True - Don't return values for rows/columns that are defined as hidden. */ public function namedRangeToArray( string $definedName, $nullValue = null, bool $calculateFormulas = true, bool $formatData = true, bool $returnCellRef = false, bool $ignoreHidden = false ): array { $retVal = []; $namedRange = $this->validateNamedRange($definedName); if ($namedRange !== null) { $cellRange = ltrim(substr($namedRange->getValue(), (int) strrpos($namedRange->getValue(), '!')), '!'); $cellRange = str_replace('$', '', $cellRange); $workSheet = $namedRange->getWorksheet(); if ($workSheet !== null) { $retVal = $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden); } } return $retVal; } /** * Create array from worksheet. * * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * @param bool $ignoreHidden False - Return values for rows/columns even if they are defined as hidden. * True - Don't return values for rows/columns that are defined as hidden. */ public function toArray( $nullValue = null, bool $calculateFormulas = true, bool $formatData = true, bool $returnCellRef = false, bool $ignoreHidden = false ): array { // Garbage collect... $this->garbageCollect(); // Identify the range that we need to extract from the worksheet $maxCol = $this->getHighestColumn(); $maxRow = $this->getHighestRow(); // Return return $this->rangeToArray("A1:{$maxCol}{$maxRow}", $nullValue, $calculateFormulas, $formatData, $returnCellRef, $ignoreHidden); } /** * Get row iterator. * * @param int $startRow The row number at which to start iterating * @param int $endRow The row number at which to stop iterating * * @return RowIterator */ public function getRowIterator($startRow = 1, $endRow = null) { return new RowIterator($this, $startRow, $endRow); } /** * Get column iterator. * * @param string $startColumn The column address at which to start iterating * @param string $endColumn The column address at which to stop iterating * * @return ColumnIterator */ public function getColumnIterator($startColumn = 'A', $endColumn = null) { return new ColumnIterator($this, $startColumn, $endColumn); } /** * Run PhpSpreadsheet garbage collector. * * @return $this */ public function garbageCollect() { // Flush cache $this->cellCollection->get('A1'); // Lookup highest column and highest row if cells are cleaned $colRow = $this->cellCollection->getHighestRowAndColumn(); $highestRow = $colRow['row']; $highestColumn = Coordinate::columnIndexFromString($colRow['column']); // Loop through column dimensions foreach ($this->columnDimensions as $dimension) { $highestColumn = max($highestColumn, Coordinate::columnIndexFromString($dimension->getColumnIndex())); } // Loop through row dimensions foreach ($this->rowDimensions as $dimension) { $highestRow = max($highestRow, $dimension->getRowIndex()); } // Cache values if ($highestColumn < 1) { $this->cachedHighestColumn = 1; } else { $this->cachedHighestColumn = $highestColumn; } $this->cachedHighestRow = $highestRow; // Return return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { if ($this->dirty) { $this->hash = md5($this->title . $this->autoFilter . ($this->protection->isProtectionEnabled() ? 't' : 'f') . __CLASS__); $this->dirty = false; } return $this->hash; } /** * Extract worksheet title from range. * * Example: extractSheetTitle("testSheet!A1") ==> 'A1' * Example: extractSheetTitle("testSheet!A1:C3") ==> 'A1:C3' * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1']; * Example: extractSheetTitle("'testSheet 1'!A1:C3", true) ==> ['testSheet 1', 'A1:C3']; * Example: extractSheetTitle("A1", true) ==> ['', 'A1']; * Example: extractSheetTitle("A1:C3", true) ==> ['', 'A1:C3'] * * @param string $range Range to extract title from * @param bool $returnRange Return range? (see example) * * @return mixed */ public static function extractSheetTitle($range, $returnRange = false) { if (empty($range)) { return $returnRange ? [null, null] : null; } // Sheet title included? if (($sep = strrpos($range, '!')) === false) { return $returnRange ? ['', $range] : ''; } if ($returnRange) { return [substr($range, 0, $sep), substr($range, $sep + 1)]; } return substr($range, $sep + 1); } /** * Get hyperlink. * * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1' * * @return Hyperlink */ public function getHyperlink($cellCoordinate) { // return hyperlink if we already have one if (isset($this->hyperlinkCollection[$cellCoordinate])) { return $this->hyperlinkCollection[$cellCoordinate]; } // else create hyperlink $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink(); return $this->hyperlinkCollection[$cellCoordinate]; } /** * Set hyperlink. * * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1' * * @return $this */ public function setHyperlink($cellCoordinate, ?Hyperlink $hyperlink = null) { if ($hyperlink === null) { unset($this->hyperlinkCollection[$cellCoordinate]); } else { $this->hyperlinkCollection[$cellCoordinate] = $hyperlink; } return $this; } /** * Hyperlink at a specific coordinate exists? * * @param string $coordinate eg: 'A1' * * @return bool */ public function hyperlinkExists($coordinate) { return isset($this->hyperlinkCollection[$coordinate]); } /** * Get collection of hyperlinks. * * @return Hyperlink[] */ public function getHyperlinkCollection() { return $this->hyperlinkCollection; } /** * Get data validation. * * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1' * * @return DataValidation */ public function getDataValidation($cellCoordinate) { // return data validation if we already have one if (isset($this->dataValidationCollection[$cellCoordinate])) { return $this->dataValidationCollection[$cellCoordinate]; } // else create data validation $this->dataValidationCollection[$cellCoordinate] = new DataValidation(); return $this->dataValidationCollection[$cellCoordinate]; } /** * Set data validation. * * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1' * * @return $this */ public function setDataValidation($cellCoordinate, ?DataValidation $dataValidation = null) { if ($dataValidation === null) { unset($this->dataValidationCollection[$cellCoordinate]); } else { $this->dataValidationCollection[$cellCoordinate] = $dataValidation; } return $this; } /** * Data validation at a specific coordinate exists? * * @param string $coordinate eg: 'A1' * * @return bool */ public function dataValidationExists($coordinate) { return isset($this->dataValidationCollection[$coordinate]); } /** * Get collection of data validations. * * @return DataValidation[] */ public function getDataValidationCollection() { return $this->dataValidationCollection; } /** * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet. * * @param string $range * * @return string Adjusted range value */ public function shrinkRangeToFit($range) { $maxCol = $this->getHighestColumn(); $maxRow = $this->getHighestRow(); $maxCol = Coordinate::columnIndexFromString($maxCol); $rangeBlocks = explode(' ', $range); foreach ($rangeBlocks as &$rangeSet) { $rangeBoundaries = Coordinate::getRangeBoundaries($rangeSet); if (Coordinate::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) { $rangeBoundaries[0][0] = Coordinate::stringFromColumnIndex($maxCol); } if ($rangeBoundaries[0][1] > $maxRow) { $rangeBoundaries[0][1] = $maxRow; } if (Coordinate::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) { $rangeBoundaries[1][0] = Coordinate::stringFromColumnIndex($maxCol); } if ($rangeBoundaries[1][1] > $maxRow) { $rangeBoundaries[1][1] = $maxRow; } $rangeSet = $rangeBoundaries[0][0] . $rangeBoundaries[0][1] . ':' . $rangeBoundaries[1][0] . $rangeBoundaries[1][1]; } unset($rangeSet); return implode(' ', $rangeBlocks); } /** * Get tab color. * * @return Color */ public function getTabColor() { if ($this->tabColor === null) { $this->tabColor = new Color(); } return $this->tabColor; } /** * Reset tab color. * * @return $this */ public function resetTabColor() { $this->tabColor = null; return $this; } /** * Tab color set? * * @return bool */ public function isTabColorSet() { return $this->tabColor !== null; } /** * Copy worksheet (!= clone!). * * @return static */ public function copy() { return clone $this; } /** * Returns a boolean true if the specified row contains no cells. By default, this means that no cell records * exist in the collection for this row. false will be returned otherwise. * This rule can be modified by passing a $definitionOfEmptyFlags value: * 1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value * cells, then the row will be considered empty. * 2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty * string value cells, then the row will be considered empty. * 3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * If the only cells in the collection are null value or empty string value cells, then the row * will be considered empty. * * @param int $definitionOfEmptyFlags * Possible Flag Values are: * CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL * CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL */ public function isEmptyRow(int $rowId, int $definitionOfEmptyFlags = 0): bool { try { $iterator = new RowIterator($this, $rowId, $rowId); $iterator->seek($rowId); $row = $iterator->current(); } catch (Exception $e) { return true; } return $row->isEmpty($definitionOfEmptyFlags); } /** * Returns a boolean true if the specified column contains no cells. By default, this means that no cell records * exist in the collection for this column. false will be returned otherwise. * This rule can be modified by passing a $definitionOfEmptyFlags value: * 1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value * cells, then the column will be considered empty. * 2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty * string value cells, then the column will be considered empty. * 3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * If the only cells in the collection are null value or empty string value cells, then the column * will be considered empty. * * @param int $definitionOfEmptyFlags * Possible Flag Values are: * CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL * CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL */ public function isEmptyColumn(string $columnId, int $definitionOfEmptyFlags = 0): bool { try { $iterator = new ColumnIterator($this, $columnId, $columnId); $iterator->seek($columnId); $column = $iterator->current(); } catch (Exception $e) { return true; } return $column->isEmpty($definitionOfEmptyFlags); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { // @phpstan-ignore-next-line foreach ($this as $key => $val) { if ($key == 'parent') { continue; } if (is_object($val) || (is_array($val))) { if ($key == 'cellCollection') { $newCollection = $this->cellCollection->cloneCellCollection($this); $this->cellCollection = $newCollection; } elseif ($key == 'drawingCollection') { $currentCollection = $this->drawingCollection; $this->drawingCollection = new ArrayObject(); foreach ($currentCollection as $item) { if (is_object($item)) { $newDrawing = clone $item; $newDrawing->setWorksheet($this); } } } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof AutoFilter)) { $newAutoFilter = clone $this->autoFilter; $this->autoFilter = $newAutoFilter; $this->autoFilter->setParent($this); } else { $this->{$key} = unserialize(serialize($val)); } } } } /** * Define the code name of the sheet. * * @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change * silently space to underscore) * @param bool $validate False to skip validation of new title. WARNING: This should only be set * at parse time (by Readers), where titles can be assumed to be valid. * * @return $this */ public function setCodeName($codeName, $validate = true) { // Is this a 'rename' or not? if ($this->getCodeName() == $codeName) { return $this; } if ($validate) { $codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same // Syntax check // throw an exception if not valid self::checkSheetCodeName($codeName); // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_' if ($this->parent !== null) { // Is there already such sheet name? if ($this->parent->sheetCodeNameExists($codeName)) { // Use name, but append with lowest possible integer if (Shared\StringHelper::countCharacters($codeName) > 29) { $codeName = Shared\StringHelper::substring($codeName, 0, 29); } $i = 1; while ($this->getParentOrThrow()->sheetCodeNameExists($codeName . '_' . $i)) { ++$i; if ($i == 10) { if (Shared\StringHelper::countCharacters($codeName) > 28) { $codeName = Shared\StringHelper::substring($codeName, 0, 28); } } elseif ($i == 100) { if (Shared\StringHelper::countCharacters($codeName) > 27) { $codeName = Shared\StringHelper::substring($codeName, 0, 27); } } } $codeName .= '_' . $i; // ok, we have a valid name } } } $this->codeName = $codeName; return $this; } /** * Return the code name of the sheet. * * @return null|string */ public function getCodeName() { return $this->codeName; } /** * Sheet has a code name ? * * @return bool */ public function hasCodeName() { return $this->codeName !== null; } public static function nameRequiresQuotes(string $sheetName): bool { return preg_match(self::SHEET_NAME_REQUIRES_NO_QUOTES, $sheetName) !== 1; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php 0000644 00000011343 15002227416 0020576 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\Style\Color; class Shadow implements IComparable { // Shadow alignment const SHADOW_BOTTOM = 'b'; const SHADOW_BOTTOM_LEFT = 'bl'; const SHADOW_BOTTOM_RIGHT = 'br'; const SHADOW_CENTER = 'ctr'; const SHADOW_LEFT = 'l'; const SHADOW_TOP = 't'; const SHADOW_TOP_LEFT = 'tl'; const SHADOW_TOP_RIGHT = 'tr'; /** * Visible. * * @var bool */ private $visible; /** * Blur radius. * * Defaults to 6 * * @var int */ private $blurRadius; /** * Shadow distance. * * Defaults to 2 * * @var int */ private $distance; /** * Shadow direction (in degrees). * * @var int */ private $direction; /** * Shadow alignment. * * @var string */ private $alignment; /** * Color. * * @var Color */ private $color; /** * Alpha. * * @var int */ private $alpha; /** * Create a new Shadow. */ public function __construct() { // Initialise values $this->visible = false; $this->blurRadius = 6; $this->distance = 2; $this->direction = 0; $this->alignment = self::SHADOW_BOTTOM_RIGHT; $this->color = new Color(Color::COLOR_BLACK); $this->alpha = 50; } /** * Get Visible. * * @return bool */ public function getVisible() { return $this->visible; } /** * Set Visible. * * @param bool $visible * * @return $this */ public function setVisible($visible) { $this->visible = $visible; return $this; } /** * Get Blur radius. * * @return int */ public function getBlurRadius() { return $this->blurRadius; } /** * Set Blur radius. * * @param int $blurRadius * * @return $this */ public function setBlurRadius($blurRadius) { $this->blurRadius = $blurRadius; return $this; } /** * Get Shadow distance. * * @return int */ public function getDistance() { return $this->distance; } /** * Set Shadow distance. * * @param int $distance * * @return $this */ public function setDistance($distance) { $this->distance = $distance; return $this; } /** * Get Shadow direction (in degrees). * * @return int */ public function getDirection() { return $this->direction; } /** * Set Shadow direction (in degrees). * * @param int $direction * * @return $this */ public function setDirection($direction) { $this->direction = $direction; return $this; } /** * Get Shadow alignment. * * @return string */ public function getAlignment() { return $this->alignment; } /** * Set Shadow alignment. * * @param string $alignment * * @return $this */ public function setAlignment($alignment) { $this->alignment = $alignment; return $this; } /** * Get Color. * * @return Color */ public function getColor() { return $this->color; } /** * Set Color. * * @return $this */ public function setColor(Color $color) { $this->color = $color; return $this; } /** * Get Alpha. * * @return int */ public function getAlpha() { return $this->alpha; } /** * Set Alpha. * * @param int $alpha * * @return $this */ public function setAlpha($alpha) { $this->alpha = $alpha; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( ($this->visible ? 't' : 'f') . $this->blurRadius . $this->distance . $this->direction . $this->alignment . $this->color->getHashCode() . $this->alpha . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFit.php 0000644 00000003267 15002227416 0017337 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\CellAddress; use PhpOffice\PhpSpreadsheet\Cell\CellRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; class AutoFit { protected Worksheet $worksheet; public function __construct(Worksheet $worksheet) { $this->worksheet = $worksheet; } public function getAutoFilterIndentRanges(): array { $autoFilterIndentRanges = []; $autoFilterIndentRanges[] = $this->getAutoFilterIndentRange($this->worksheet->getAutoFilter()); foreach ($this->worksheet->getTableCollection() as $table) { /** @var Table $table */ if ($table->getShowHeaderRow() === true && $table->getAllowFilter() === true) { $autoFilter = $table->getAutoFilter(); if ($autoFilter !== null) { $autoFilterIndentRanges[] = $this->getAutoFilterIndentRange($autoFilter); } } } return array_filter($autoFilterIndentRanges); } private function getAutoFilterIndentRange(AutoFilter $autoFilter): ?string { $autoFilterRange = $autoFilter->getRange(); $autoFilterIndentRange = null; if (!empty($autoFilterRange)) { $autoFilterRangeBoundaries = Coordinate::rangeBoundaries($autoFilterRange); $autoFilterIndentRange = (string) new CellRange( CellAddress::fromColumnAndRow($autoFilterRangeBoundaries[0][0], $autoFilterRangeBoundaries[0][1]), CellAddress::fromColumnAndRow($autoFilterRangeBoundaries[1][0], $autoFilterRangeBoundaries[0][1]) ); } return $autoFilterIndentRange; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php 0000644 00000006341 15002227416 0020155 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class PageMargins { /** * Left. * * @var float */ private $left = 0.7; /** * Right. * * @var float */ private $right = 0.7; /** * Top. * * @var float */ private $top = 0.75; /** * Bottom. * * @var float */ private $bottom = 0.75; /** * Header. * * @var float */ private $header = 0.3; /** * Footer. * * @var float */ private $footer = 0.3; /** * Create a new PageMargins. */ public function __construct() { } /** * Get Left. * * @return float */ public function getLeft() { return $this->left; } /** * Set Left. * * @param float $left * * @return $this */ public function setLeft($left) { $this->left = $left; return $this; } /** * Get Right. * * @return float */ public function getRight() { return $this->right; } /** * Set Right. * * @param float $right * * @return $this */ public function setRight($right) { $this->right = $right; return $this; } /** * Get Top. * * @return float */ public function getTop() { return $this->top; } /** * Set Top. * * @param float $top * * @return $this */ public function setTop($top) { $this->top = $top; return $this; } /** * Get Bottom. * * @return float */ public function getBottom() { return $this->bottom; } /** * Set Bottom. * * @param float $bottom * * @return $this */ public function setBottom($bottom) { $this->bottom = $bottom; return $this; } /** * Get Header. * * @return float */ public function getHeader() { return $this->header; } /** * Set Header. * * @param float $header * * @return $this */ public function setHeader($header) { $this->header = $header; return $this; } /** * Get Footer. * * @return float */ public function getFooter() { return $this->footer; } /** * Set Footer. * * @param float $footer * * @return $this */ public function setFooter($footer) { $this->footer = $footer; return $this; } public static function fromCentimeters(float $value): float { return $value / 2.54; } public static function toCentimeters(float $value): float { return $value * 2.54; } public static function fromMillimeters(float $value): float { return $value / 25.4; } public static function toMillimeters(float $value): float { return $value * 25.4; } public static function fromPoints(float $value): float { return $value / 72; } public static function toPoints(float $value): float { return $value * 72; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageBreak.php 0000644 00000002535 15002227416 0017602 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\CellAddress; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; class PageBreak { /** @var int */ private $breakType; /** @var string */ private $coordinate; /** @var int */ private $maxColOrRow; /** @param array|CellAddress|string $coordinate */ public function __construct(int $breakType, $coordinate, int $maxColOrRow = -1) { $coordinate = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); $this->breakType = $breakType; $this->coordinate = $coordinate; $this->maxColOrRow = $maxColOrRow; } public function getBreakType(): int { return $this->breakType; } public function getCoordinate(): string { return $this->coordinate; } public function getMaxColOrRow(): int { return $this->maxColOrRow; } public function getColumnInt(): int { return Coordinate::indexesFromString($this->coordinate)[0]; } public function getRow(): int { return Coordinate::indexesFromString($this->coordinate)[1]; } public function getColumnString(): string { return Coordinate::indexesFromString($this->coordinate)[2]; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php 0000644 00000007741 15002227416 0017222 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; class Column { /** * \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet. * * @var Worksheet */ private $worksheet; /** * Column index. * * @var string */ private $columnIndex; /** * Create a new column. * * @param string $columnIndex */ public function __construct(Worksheet $worksheet, $columnIndex = 'A') { // Set parent and column index $this->worksheet = $worksheet; $this->columnIndex = $columnIndex; } /** * Destructor. */ public function __destruct() { // @phpstan-ignore-next-line $this->worksheet = null; } /** * Get column index as string eg: 'A'. */ public function getColumnIndex(): string { return $this->columnIndex; } /** * Get cell iterator. * * @param int $startRow The row number at which to start iterating * @param int $endRow Optionally, the row number at which to stop iterating */ public function getCellIterator($startRow = 1, $endRow = null): ColumnCellIterator { return new ColumnCellIterator($this->worksheet, $this->columnIndex, $startRow, $endRow); } /** * Get row iterator. Synonym for getCellIterator(). * * @param int $startRow The row number at which to start iterating * @param int $endRow Optionally, the row number at which to stop iterating */ public function getRowIterator($startRow = 1, $endRow = null): ColumnCellIterator { return $this->getCellIterator($startRow, $endRow); } /** * Returns a boolean true if the column contains no cells. By default, this means that no cell records exist in the * collection for this column. false will be returned otherwise. * This rule can be modified by passing a $definitionOfEmptyFlags value: * 1 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL If the only cells in the collection are null value * cells, then the column will be considered empty. * 2 - CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL If the only cells in the collection are empty * string value cells, then the column will be considered empty. * 3 - CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL | CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * If the only cells in the collection are null value or empty string value cells, then the column * will be considered empty. * * @param int $definitionOfEmptyFlags * Possible Flag Values are: * CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL * CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL * @param int $startRow The row number at which to start checking if cells are empty * @param int $endRow Optionally, the row number at which to stop checking if cells are empty */ public function isEmpty(int $definitionOfEmptyFlags = 0, $startRow = 1, $endRow = null): bool { $nullValueCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL); $emptyStringCellIsEmpty = (bool) ($definitionOfEmptyFlags & CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL); $cellIterator = $this->getCellIterator($startRow, $endRow); $cellIterator->setIterateOnlyExistingCells(true); foreach ($cellIterator as $cell) { /** @scrutinizer ignore-call */ $value = $cell->getValue(); if ($value === null && $nullValueCellIsEmpty === true) { continue; } if ($value === '' && $emptyStringCellIsEmpty === true) { continue; } return false; } return true; } /** * Returns bound worksheet. */ public function getWorksheet(): Worksheet { return $this->worksheet; } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php 0000644 00000012650 15002227416 0021527 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; /** * @extends CellIterator<int> */ class ColumnCellIterator extends CellIterator { /** * Current iterator position. * * @var int */ private $currentRow; /** * Column index. * * @var int */ private $columnIndex; /** * Start position. * * @var int */ private $startRow = 1; /** * End position. * * @var int */ private $endRow = 1; /** * Create a new row iterator. * * @param Worksheet $worksheet The worksheet to iterate over * @param string $columnIndex The column that we want to iterate * @param int $startRow The row number at which to start iterating * @param int $endRow Optionally, the row number at which to stop iterating */ public function __construct(Worksheet $worksheet, $columnIndex = 'A', $startRow = 1, $endRow = null) { // Set subject $this->worksheet = $worksheet; $this->cellCollection = $worksheet->getCellCollection(); $this->columnIndex = Coordinate::columnIndexFromString($columnIndex); $this->resetEnd($endRow); $this->resetStart($startRow); } /** * (Re)Set the start row and the current row pointer. * * @param int $startRow The row number at which to start iterating * * @return $this */ public function resetStart(int $startRow = 1) { $this->startRow = $startRow; $this->adjustForExistingOnlyRange(); $this->seek($startRow); return $this; } /** * (Re)Set the end row. * * @param int $endRow The row number at which to stop iterating * * @return $this */ public function resetEnd($endRow = null) { $this->endRow = $endRow ?: $this->worksheet->getHighestRow(); $this->adjustForExistingOnlyRange(); return $this; } /** * Set the row pointer to the selected row. * * @param int $row The row number to set the current pointer at * * @return $this */ public function seek(int $row = 1) { if ( $this->onlyExistingCells && (!$this->cellCollection->has(Coordinate::stringFromColumnIndex($this->columnIndex) . $row)) ) { throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist'); } if (($row < $this->startRow) || ($row > $this->endRow)) { throw new PhpSpreadsheetException("Row $row is out of range ({$this->startRow} - {$this->endRow})"); } $this->currentRow = $row; return $this; } /** * Rewind the iterator to the starting row. */ public function rewind(): void { $this->currentRow = $this->startRow; } /** * Return the current cell in this worksheet column. */ public function current(): ?Cell { $cellAddress = Coordinate::stringFromColumnIndex($this->columnIndex) . $this->currentRow; return $this->cellCollection->has($cellAddress) ? $this->cellCollection->get($cellAddress) : ( $this->ifNotExists === self::IF_NOT_EXISTS_CREATE_NEW ? $this->worksheet->createNewCell($cellAddress) : null ); } /** * Return the current iterator key. */ public function key(): int { return $this->currentRow; } /** * Set the iterator to its next value. */ public function next(): void { $columnAddress = Coordinate::stringFromColumnIndex($this->columnIndex); do { ++$this->currentRow; } while ( ($this->onlyExistingCells) && ($this->currentRow <= $this->endRow) && (!$this->cellCollection->has($columnAddress . $this->currentRow)) ); } /** * Set the iterator to its previous value. */ public function prev(): void { $columnAddress = Coordinate::stringFromColumnIndex($this->columnIndex); do { --$this->currentRow; } while ( ($this->onlyExistingCells) && ($this->currentRow >= $this->startRow) && (!$this->cellCollection->has($columnAddress . $this->currentRow)) ); } /** * Indicate if more rows exist in the worksheet range of rows that we're iterating. */ public function valid(): bool { return $this->currentRow <= $this->endRow && $this->currentRow >= $this->startRow; } /** * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary. */ protected function adjustForExistingOnlyRange(): void { if ($this->onlyExistingCells) { $columnAddress = Coordinate::stringFromColumnIndex($this->columnIndex); while ( (!$this->cellCollection->has($columnAddress . $this->startRow)) && ($this->startRow <= $this->endRow) ) { ++$this->startRow; } while ( (!$this->cellCollection->has($columnAddress . $this->endRow)) && ($this->endRow >= $this->startRow) ) { --$this->endRow; } } } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php 0000644 00000004100 15002227416 0020340 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use Iterator as NativeIterator; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Collection\Cells; /** * @template TKey * * @implements NativeIterator<TKey, Cell> */ abstract class CellIterator implements NativeIterator { public const TREAT_NULL_VALUE_AS_EMPTY_CELL = 1; public const TREAT_EMPTY_STRING_AS_EMPTY_CELL = 2; public const IF_NOT_EXISTS_RETURN_NULL = false; public const IF_NOT_EXISTS_CREATE_NEW = true; /** * Worksheet to iterate. * * @var Worksheet */ protected $worksheet; /** * Cell Collection to iterate. * * @var Cells */ protected $cellCollection; /** * Iterate only existing cells. * * @var bool */ protected $onlyExistingCells = false; /** * If iterating all cells, and a cell doesn't exist, identifies whether a new cell should be created, * or if the iterator should return a null value. * * @var bool */ protected $ifNotExists = self::IF_NOT_EXISTS_CREATE_NEW; /** * Destructor. */ public function __destruct() { // @phpstan-ignore-next-line $this->worksheet = $this->cellCollection = null; } public function getIfNotExists(): bool { return $this->ifNotExists; } public function setIfNotExists(bool $ifNotExists = self::IF_NOT_EXISTS_CREATE_NEW): void { $this->ifNotExists = $ifNotExists; } /** * Get loop only existing cells. */ public function getIterateOnlyExistingCells(): bool { return $this->onlyExistingCells; } /** * Validate start/end values for 'IterateOnlyExistingCells' mode, and adjust if necessary. */ abstract protected function adjustForExistingOnlyRange(): void; /** * Set the iterator to loop only existing cells. */ public function setIterateOnlyExistingCells(bool $value): void { $this->onlyExistingCells = (bool) $value; $this->adjustForExistingOnlyRange(); } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php 0000644 00000024647 15002227416 0020117 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Shared\PasswordHasher; class Protection { const ALGORITHM_MD2 = 'MD2'; const ALGORITHM_MD4 = 'MD4'; const ALGORITHM_MD5 = 'MD5'; const ALGORITHM_SHA_1 = 'SHA-1'; const ALGORITHM_SHA_256 = 'SHA-256'; const ALGORITHM_SHA_384 = 'SHA-384'; const ALGORITHM_SHA_512 = 'SHA-512'; const ALGORITHM_RIPEMD_128 = 'RIPEMD-128'; const ALGORITHM_RIPEMD_160 = 'RIPEMD-160'; const ALGORITHM_WHIRLPOOL = 'WHIRLPOOL'; /** * Autofilters are locked when sheet is protected, default true. * * @var ?bool */ private $autoFilter; /** * Deleting columns is locked when sheet is protected, default true. * * @var ?bool */ private $deleteColumns; /** * Deleting rows is locked when sheet is protected, default true. * * @var ?bool */ private $deleteRows; /** * Formatting cells is locked when sheet is protected, default true. * * @var ?bool */ private $formatCells; /** * Formatting columns is locked when sheet is protected, default true. * * @var ?bool */ private $formatColumns; /** * Formatting rows is locked when sheet is protected, default true. * * @var ?bool */ private $formatRows; /** * Inserting columns is locked when sheet is protected, default true. * * @var ?bool */ private $insertColumns; /** * Inserting hyperlinks is locked when sheet is protected, default true. * * @var ?bool */ private $insertHyperlinks; /** * Inserting rows is locked when sheet is protected, default true. * * @var ?bool */ private $insertRows; /** * Objects are locked when sheet is protected, default false. * * @var ?bool */ private $objects; /** * Pivot tables are locked when the sheet is protected, default true. * * @var ?bool */ private $pivotTables; /** * Scenarios are locked when sheet is protected, default false. * * @var ?bool */ private $scenarios; /** * Selection of locked cells is locked when sheet is protected, default false. * * @var ?bool */ private $selectLockedCells; /** * Selection of unlocked cells is locked when sheet is protected, default false. * * @var ?bool */ private $selectUnlockedCells; /** * Sheet is locked when sheet is protected, default false. * * @var ?bool */ private $sheet; /** * Sorting is locked when sheet is protected, default true. * * @var ?bool */ private $sort; /** * Hashed password. * * @var string */ private $password = ''; /** * Algorithm name. * * @var string */ private $algorithm = ''; /** * Salt value. * * @var string */ private $salt = ''; /** * Spin count. * * @var int */ private $spinCount = 10000; /** * Create a new Protection. */ public function __construct() { } /** * Is some sort of protection enabled? */ public function isProtectionEnabled(): bool { return $this->password !== '' || isset($this->sheet) || isset($this->objects) || isset($this->scenarios) || isset($this->formatCells) || isset($this->formatColumns) || isset($this->formatRows) || isset($this->insertColumns) || isset($this->insertRows) || isset($this->insertHyperlinks) || isset($this->deleteColumns) || isset($this->deleteRows) || isset($this->selectLockedCells) || isset($this->sort) || isset($this->autoFilter) || isset($this->pivotTables) || isset($this->selectUnlockedCells); } public function getSheet(): ?bool { return $this->sheet; } public function setSheet(?bool $sheet): self { $this->sheet = $sheet; return $this; } public function getObjects(): ?bool { return $this->objects; } public function setObjects(?bool $objects): self { $this->objects = $objects; return $this; } public function getScenarios(): ?bool { return $this->scenarios; } public function setScenarios(?bool $scenarios): self { $this->scenarios = $scenarios; return $this; } public function getFormatCells(): ?bool { return $this->formatCells; } public function setFormatCells(?bool $formatCells): self { $this->formatCells = $formatCells; return $this; } public function getFormatColumns(): ?bool { return $this->formatColumns; } public function setFormatColumns(?bool $formatColumns): self { $this->formatColumns = $formatColumns; return $this; } public function getFormatRows(): ?bool { return $this->formatRows; } public function setFormatRows(?bool $formatRows): self { $this->formatRows = $formatRows; return $this; } public function getInsertColumns(): ?bool { return $this->insertColumns; } public function setInsertColumns(?bool $insertColumns): self { $this->insertColumns = $insertColumns; return $this; } public function getInsertRows(): ?bool { return $this->insertRows; } public function setInsertRows(?bool $insertRows): self { $this->insertRows = $insertRows; return $this; } public function getInsertHyperlinks(): ?bool { return $this->insertHyperlinks; } public function setInsertHyperlinks(?bool $insertHyperLinks): self { $this->insertHyperlinks = $insertHyperLinks; return $this; } public function getDeleteColumns(): ?bool { return $this->deleteColumns; } public function setDeleteColumns(?bool $deleteColumns): self { $this->deleteColumns = $deleteColumns; return $this; } public function getDeleteRows(): ?bool { return $this->deleteRows; } public function setDeleteRows(?bool $deleteRows): self { $this->deleteRows = $deleteRows; return $this; } public function getSelectLockedCells(): ?bool { return $this->selectLockedCells; } public function setSelectLockedCells(?bool $selectLockedCells): self { $this->selectLockedCells = $selectLockedCells; return $this; } public function getSort(): ?bool { return $this->sort; } public function setSort(?bool $sort): self { $this->sort = $sort; return $this; } public function getAutoFilter(): ?bool { return $this->autoFilter; } public function setAutoFilter(?bool $autoFilter): self { $this->autoFilter = $autoFilter; return $this; } public function getPivotTables(): ?bool { return $this->pivotTables; } public function setPivotTables(?bool $pivotTables): self { $this->pivotTables = $pivotTables; return $this; } public function getSelectUnlockedCells(): ?bool { return $this->selectUnlockedCells; } public function setSelectUnlockedCells(?bool $selectUnlockedCells): self { $this->selectUnlockedCells = $selectUnlockedCells; return $this; } /** * Get hashed password. * * @return string */ public function getPassword() { return $this->password; } /** * Set Password. * * @param string $password * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ public function setPassword($password, $alreadyHashed = false) { if (!$alreadyHashed) { $salt = $this->generateSalt(); $this->setSalt($salt); $password = PasswordHasher::hashPassword($password, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount()); } $this->password = $password; return $this; } public function setHashValue(string $password): self { return $this->setPassword($password, true); } /** * Create a pseudorandom string. */ private function generateSalt(): string { return base64_encode(random_bytes(16)); } /** * Get algorithm name. */ public function getAlgorithm(): string { return $this->algorithm; } /** * Set algorithm name. */ public function setAlgorithm(string $algorithm): self { return $this->setAlgorithmName($algorithm); } /** * Set algorithm name. */ public function setAlgorithmName(string $algorithm): self { $this->algorithm = $algorithm; return $this; } public function getSalt(): string { return $this->salt; } public function setSalt(string $salt): self { return $this->setSaltValue($salt); } public function setSaltValue(string $salt): self { $this->salt = $salt; return $this; } /** * Get spin count. */ public function getSpinCount(): int { return $this->spinCount; } /** * Set spin count. */ public function setSpinCount(int $spinCount): self { $this->spinCount = $spinCount; return $this; } /** * Verify that the given non-hashed password can "unlock" the protection. */ public function verify(string $password): bool { if ($this->password === '') { return true; } $hash = PasswordHasher::hashPassword($password, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount()); return $this->getPassword() === $hash; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } } phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php 0000644 00000026512 15002227416 0020150 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Cell\Hyperlink; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\IComparable; class BaseDrawing implements IComparable { const EDIT_AS_ABSOLUTE = 'absolute'; const EDIT_AS_ONECELL = 'oneCell'; const EDIT_AS_TWOCELL = 'twoCell'; private const VALID_EDIT_AS = [ self::EDIT_AS_ABSOLUTE, self::EDIT_AS_ONECELL, self::EDIT_AS_TWOCELL, ]; /** * The editAs attribute, used only with two cell anchor. * * @var string */ protected $editAs = ''; /** * Image counter. * * @var int */ private static $imageCounter = 0; /** * Image index. * * @var int */ private $imageIndex = 0; /** * Name. * * @var string */ protected $name = ''; /** * Description. * * @var string */ protected $description = ''; /** * Worksheet. * * @var null|Worksheet */ protected $worksheet; /** * Coordinates. * * @var string */ protected $coordinates = 'A1'; /** * Offset X. * * @var int */ protected $offsetX = 0; /** * Offset Y. * * @var int */ protected $offsetY = 0; /** * Coordinates2. * * @var string */ protected $coordinates2 = ''; /** * Offset X2. * * @var int */ protected $offsetX2 = 0; /** * Offset Y2. * * @var int */ protected $offsetY2 = 0; /** * Width. * * @var int */ protected $width = 0; /** * Height. * * @var int */ protected $height = 0; /** * Pixel width of image. See $width for the size the Drawing will be in the sheet. * * @var int */ protected $imageWidth = 0; /** * Pixel width of image. See $height for the size the Drawing will be in the sheet. * * @var int */ protected $imageHeight = 0; /** * Proportional resize. * * @var bool */ protected $resizeProportional = true; /** * Rotation. * * @var int */ protected $rotation = 0; /** * Shadow. * * @var Drawing\Shadow */ protected $shadow; /** * Image hyperlink. * * @var null|Hyperlink */ private $hyperlink; /** * Image type. * * @var int */ protected $type = IMAGETYPE_UNKNOWN; /** * Create a new BaseDrawing. */ public function __construct() { // Initialise values $this->setShadow(); // Set image index ++self::$imageCounter; $this->imageIndex = self::$imageCounter; } public function getImageIndex(): int { return $this->imageIndex; } public function getName(): string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getDescription(): string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function getWorksheet(): ?Worksheet { return $this->worksheet; } /** * Set Worksheet. * * @param bool $overrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet? */ public function setWorksheet(?Worksheet $worksheet = null, bool $overrideOld = false): self { if ($this->worksheet === null) { // Add drawing to \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet if ($worksheet !== null) { $this->worksheet = $worksheet; $this->worksheet->getCell($this->coordinates); $this->worksheet->getDrawingCollection()->append($this); } } else { if ($overrideOld) { // Remove drawing from old \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $iterator = $this->worksheet->getDrawingCollection()->getIterator(); while ($iterator->valid()) { if ($iterator->current()->getHashCode() === $this->getHashCode()) { $this->worksheet->getDrawingCollection()->offsetUnset(/** @scrutinizer ignore-type */ $iterator->key()); $this->worksheet = null; break; } } // Set new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $this->setWorksheet($worksheet); } else { throw new PhpSpreadsheetException('A Worksheet has already been assigned. Drawings can only exist on one \\PhpOffice\\PhpSpreadsheet\\Worksheet.'); } } return $this; } public function getCoordinates(): string { return $this->coordinates; } public function setCoordinates(string $coordinates): self { $this->coordinates = $coordinates; return $this; } public function getOffsetX(): int { return $this->offsetX; } public function setOffsetX(int $offsetX): self { $this->offsetX = $offsetX; return $this; } public function getOffsetY(): int { return $this->offsetY; } public function setOffsetY(int $offsetY): self { $this->offsetY = $offsetY; return $this; } public function getCoordinates2(): string { return $this->coordinates2; } public function setCoordinates2(string $coordinates2): self { $this->coordinates2 = $coordinates2; return $this; } public function getOffsetX2(): int { return $this->offsetX2; } public function setOffsetX2(int $offsetX2): self { $this->offsetX2 = $offsetX2; return $this; } public function getOffsetY2(): int { return $this->offsetY2; } public function setOffsetY2(int $offsetY2): self { $this->offsetY2 = $offsetY2; return $this; } public function getWidth(): int { return $this->width; } public function setWidth(int $width): self { // Resize proportional? if ($this->resizeProportional && $width != 0) { $ratio = $this->height / ($this->width != 0 ? $this->width : 1); $this->height = (int) round($ratio * $width); } // Set width $this->width = $width; return $this; } public function getHeight(): int { return $this->height; } public function setHeight(int $height): self { // Resize proportional? if ($this->resizeProportional && $height != 0) { $ratio = $this->width / ($this->height != 0 ? $this->height : 1); $this->width = (int) round($ratio * $height); } // Set height $this->height = $height; return $this; } /** * Set width and height with proportional resize. * * Example: * <code> * $objDrawing->setResizeProportional(true); * $objDrawing->setWidthAndHeight(160,120); * </code> * * @author Vincent@luo MSN:kele_100@hotmail.com */ public function setWidthAndHeight(int $width, int $height): self { $xratio = $width / ($this->width != 0 ? $this->width : 1); $yratio = $height / ($this->height != 0 ? $this->height : 1); if ($this->resizeProportional && !($width == 0 || $height == 0)) { if (($xratio * $this->height) < $height) { $this->height = (int) ceil($xratio * $this->height); $this->width = $width; } else { $this->width = (int) ceil($yratio * $this->width); $this->height = $height; } } else { $this->width = $width; $this->height = $height; } return $this; } public function getResizeProportional(): bool { return $this->resizeProportional; } public function setResizeProportional(bool $resizeProportional): self { $this->resizeProportional = $resizeProportional; return $this; } public function getRotation(): int { return $this->rotation; } public function setRotation(int $rotation): self { $this->rotation = $rotation; return $this; } public function getShadow(): Drawing\Shadow { return $this->shadow; } public function setShadow(?Drawing\Shadow $shadow = null): self { $this->shadow = $shadow ?? new Drawing\Shadow(); return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->name . $this->description . (($this->worksheet === null) ? '' : $this->worksheet->getHashCode()) . $this->coordinates . $this->offsetX . $this->offsetY . $this->coordinates2 . $this->offsetX2 . $this->offsetY2 . $this->width . $this->height . $this->rotation . $this->shadow->getHashCode() . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if ($key == 'worksheet') { $this->worksheet = null; } elseif (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } public function setHyperlink(?Hyperlink $hyperlink = null): void { $this->hyperlink = $hyperlink; } public function getHyperlink(): ?Hyperlink { return $this->hyperlink; } /** * Set Fact Sizes and Type of Image. */ protected function setSizesAndType(string $path): void { if ($this->imageWidth === 0 && $this->imageHeight === 0 && $this->type === IMAGETYPE_UNKNOWN) { $imageData = getimagesize($path); if (!empty($imageData)) { $this->imageWidth = $imageData[0]; $this->imageHeight = $imageData[1]; $this->type = $imageData[2]; } } if ($this->width === 0 && $this->height === 0) { $this->width = $this->imageWidth; $this->height = $this->imageHeight; } } /** * Get Image Type. */ public function getType(): int { return $this->type; } public function getImageWidth(): int { return $this->imageWidth; } public function getImageHeight(): int { return $this->imageHeight; } public function getEditAs(): string { return $this->editAs; } public function setEditAs(string $editAs): self { $this->editAs = $editAs; return $this; } public function validEditAs(): bool { return in_array($this->editAs, self::VALID_EDIT_AS, true); } } phpspreadsheet/src/PhpSpreadsheet/IComparable.php 0000644 00000000266 15002227416 0016163 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet; interface IComparable { /** * Get hash code. * * @return string Hash code */ public function getHashCode(); } phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php 0000644 00000154046 15002227416 0017051 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; use PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class ReferenceHelper { /** Constants */ /** Regular Expressions */ const REFHELPER_REGEXP_CELLREF = '((\w*|\'[^!]*\')!)?(?<![:a-z\$])(\$?[a-z]{1,3}\$?\d+)(?=[^:!\d\'])'; const REFHELPER_REGEXP_CELLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}\$?\d+):(\$?[a-z]{1,3}\$?\d+)'; const REFHELPER_REGEXP_ROWRANGE = '((\w*|\'[^!]*\')!)?(\$?\d+):(\$?\d+)'; const REFHELPER_REGEXP_COLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; /** * Instance of this class. * * @var ?ReferenceHelper */ private static $instance; /** * @var CellReferenceHelper */ private $cellReferenceHelper; /** * Get an instance of this class. * * @return ReferenceHelper */ public static function getInstance() { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } /** * Create a new ReferenceHelper. */ protected function __construct() { } /** * Compare two column addresses * Intended for use as a Callback function for sorting column addresses by column. * * @param string $a First column to test (e.g. 'AA') * @param string $b Second column to test (e.g. 'Z') * * @return int */ public static function columnSort($a, $b) { return strcasecmp(strlen($a) . $a, strlen($b) . $b); } /** * Compare two column addresses * Intended for use as a Callback function for reverse sorting column addresses by column. * * @param string $a First column to test (e.g. 'AA') * @param string $b Second column to test (e.g. 'Z') * * @return int */ public static function columnReverseSort(string $a, string $b) { return -strcasecmp(strlen($a) . $a, strlen($b) . $b); } /** * Compare two cell addresses * Intended for use as a Callback function for sorting cell addresses by column and row. * * @param string $a First cell to test (e.g. 'AA1') * @param string $b Second cell to test (e.g. 'Z1') * * @return int */ public static function cellSort(string $a, string $b) { /** @scrutinizer be-damned */ sscanf($a, '%[A-Z]%d', $ac, $ar); /** @var int $ar */ /** @var string $ac */ /** @scrutinizer be-damned */ sscanf($b, '%[A-Z]%d', $bc, $br); /** @var int $br */ /** @var string $bc */ if ($ar === $br) { return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); } return ($ar < $br) ? -1 : 1; } /** * Compare two cell addresses * Intended for use as a Callback function for sorting cell addresses by column and row. * * @param string $a First cell to test (e.g. 'AA1') * @param string $b Second cell to test (e.g. 'Z1') * * @return int */ public static function cellReverseSort(string $a, string $b) { /** @scrutinizer be-damned */ sscanf($a, '%[A-Z]%d', $ac, $ar); /** @var int $ar */ /** @var string $ac */ /** @scrutinizer be-damned */ sscanf($b, '%[A-Z]%d', $bc, $br); /** @var int $br */ /** @var string $bc */ if ($ar === $br) { return -strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); } return ($ar < $br) ? 1 : -1; } /** * Update page breaks when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustPageBreaks(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aBreaks = $worksheet->getBreaks(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aBreaks, [self::class, 'cellReverseSort']) : uksort($aBreaks, [self::class, 'cellSort']); foreach ($aBreaks as $cellAddress => $value) { if ($this->cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) { // If we're deleting, then clear any defined breaks that are within the range // of rows/columns that we're deleting $worksheet->setBreak($cellAddress, Worksheet::BREAK_NONE); } else { // Otherwise update any affected breaks by inserting a new break at the appropriate point // and removing the old affected break $newReference = $this->updateCellReference($cellAddress); if ($cellAddress !== $newReference) { $worksheet->setBreak($newReference, $value) ->setBreak($cellAddress, Worksheet::BREAK_NONE); } } } } /** * Update cell comments when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing */ protected function adjustComments(Worksheet $worksheet): void { $aComments = $worksheet->getComments(); $aNewComments = []; // the new array of all comments foreach ($aComments as $cellAddress => &$value) { // Any comments inside a deleted range will be ignored if ($this->cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === false) { // Otherwise build a new array of comments indexed by the adjusted cell reference $newReference = $this->updateCellReference($cellAddress); $aNewComments[$newReference] = $value; } } // Replace the comments array with the new set of comments $worksheet->setComments($aNewComments); } /** * Update hyperlinks when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustHyperlinks(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aHyperlinkCollection = $worksheet->getHyperlinkCollection(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aHyperlinkCollection, [self::class, 'cellReverseSort']) : uksort($aHyperlinkCollection, [self::class, 'cellSort']); foreach ($aHyperlinkCollection as $cellAddress => $value) { $newReference = $this->updateCellReference($cellAddress); if ($this->cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) { $worksheet->setHyperlink($cellAddress, null); } elseif ($cellAddress !== $newReference) { $worksheet->setHyperlink($newReference, $value); $worksheet->setHyperlink($cellAddress, null); } } } /** * Update conditional formatting styles when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustConditionalFormatting(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aStyles = $worksheet->getConditionalStylesCollection(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aStyles, [self::class, 'cellReverseSort']) : uksort($aStyles, [self::class, 'cellSort']); foreach ($aStyles as $cellAddress => $cfRules) { $worksheet->removeConditionalStyles($cellAddress); $newReference = $this->updateCellReference($cellAddress); foreach ($cfRules as &$cfRule) { /** @var Conditional $cfRule */ $conditions = $cfRule->getConditions(); foreach ($conditions as &$condition) { if (is_string($condition)) { $condition = $this->updateFormulaReferences( $condition, $this->cellReferenceHelper->beforeCellAddress(), $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true ); } } $cfRule->setConditions($conditions); } $worksheet->setConditionalStyles($newReference, $cfRules); } } /** * Update data validations when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustDataValidations(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aDataValidationCollection = $worksheet->getDataValidationCollection(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aDataValidationCollection, [self::class, 'cellReverseSort']) : uksort($aDataValidationCollection, [self::class, 'cellSort']); foreach ($aDataValidationCollection as $cellAddress => $dataValidation) { $newReference = $this->updateCellReference($cellAddress); if ($cellAddress !== $newReference) { $dataValidation->setSqref($newReference); $worksheet->setDataValidation($newReference, $dataValidation); $worksheet->setDataValidation($cellAddress, null); } } } /** * Update merged cells when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing */ protected function adjustMergeCells(Worksheet $worksheet): void { $aMergeCells = $worksheet->getMergeCells(); $aNewMergeCells = []; // the new array of all merge cells foreach ($aMergeCells as $cellAddress => &$value) { $newReference = $this->updateCellReference($cellAddress); $aNewMergeCells[$newReference] = $newReference; } $worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array } /** * Update protected cells when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustProtectedCells(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void { $aProtectedCells = $worksheet->getProtectedCells(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aProtectedCells, [self::class, 'cellReverseSort']) : uksort($aProtectedCells, [self::class, 'cellSort']); foreach ($aProtectedCells as $cellAddress => $value) { $newReference = $this->updateCellReference($cellAddress); if ($cellAddress !== $newReference) { $worksheet->protectCells($newReference, $value, true); $worksheet->unprotectCells($cellAddress); } } } /** * Update column dimensions when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing */ protected function adjustColumnDimensions(Worksheet $worksheet): void { $aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true); if (!empty($aColumnDimensions)) { foreach ($aColumnDimensions as $objColumnDimension) { $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1'); [$newReference] = Coordinate::coordinateFromString($newReference); if ($objColumnDimension->getColumnIndex() !== $newReference) { $objColumnDimension->setColumnIndex($newReference); } } $worksheet->refreshColumnDimensions(); } } /** * Update row dimensions when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param int $beforeRow Number of the row we're inserting/deleting before * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustRowDimensions(Worksheet $worksheet, $beforeRow, $numberOfRows): void { $aRowDimensions = array_reverse($worksheet->getRowDimensions(), true); if (!empty($aRowDimensions)) { foreach ($aRowDimensions as $objRowDimension) { $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex()); [, $newReference] = Coordinate::coordinateFromString($newReference); $newRoweference = (int) $newReference; if ($objRowDimension->getRowIndex() !== $newRoweference) { $objRowDimension->setRowIndex($newRoweference); } } $worksheet->refreshRowDimensions(); $copyDimension = $worksheet->getRowDimension($beforeRow - 1); for ($i = $beforeRow; $i <= $beforeRow - 1 + $numberOfRows; ++$i) { $newDimension = $worksheet->getRowDimension($i); $newDimension->setRowHeight($copyDimension->getRowHeight()); $newDimension->setVisible($copyDimension->getVisible()); $newDimension->setOutlineLevel($copyDimension->getOutlineLevel()); $newDimension->setCollapsed($copyDimension->getCollapsed()); } } } /** * Insert a new column or row, updating all possible related data. * * @param string $beforeCellAddress Insert before this cell address (e.g. 'A1') * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) * @param Worksheet $worksheet The worksheet that we're editing */ public function insertNewBefore( string $beforeCellAddress, int $numberOfColumns, int $numberOfRows, Worksheet $worksheet ): void { $remove = ($numberOfColumns < 0 || $numberOfRows < 0); if ( $this->cellReferenceHelper === null || $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows) ) { $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows); } // Get coordinate of $beforeCellAddress [$beforeColumn, $beforeRow] = Coordinate::indexesFromString($beforeCellAddress); // Clear cells if we are removing columns or rows $highestColumn = $worksheet->getHighestColumn(); $highestRow = $worksheet->getHighestRow(); // 1. Clear column strips if we are removing columns if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) { $this->clearColumnStrips($highestRow, $beforeColumn, $numberOfColumns, $worksheet); } // 2. Clear row strips if we are removing rows if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) { $this->clearRowStrips($highestColumn, $beforeColumn, $beforeRow, $numberOfRows, $worksheet); } // Find missing coordinates. This is important when inserting column before the last column $cellCollection = $worksheet->getCellCollection(); $missingCoordinates = array_filter( array_map(function ($row) use ($highestColumn) { return "{$highestColumn}{$row}"; }, range(1, $highestRow)), function ($coordinate) use ($cellCollection) { return $cellCollection->has($coordinate) === false; } ); // Create missing cells with null values if (!empty($missingCoordinates)) { foreach ($missingCoordinates as $coordinate) { $worksheet->createNewCell($coordinate); } } $allCoordinates = $worksheet->getCoordinates(); if ($remove) { // It's faster to reverse and pop than to use unshift, especially with large cell collections $allCoordinates = array_reverse($allCoordinates); } // Loop through cells, bottom-up, and change cell coordinate while ($coordinate = array_pop($allCoordinates)) { $cell = $worksheet->getCell($coordinate); $cellIndex = Coordinate::columnIndexFromString($cell->getColumn()); if ($cellIndex - 1 + $numberOfColumns < 0) { continue; } // New coordinate $newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $numberOfColumns) . ($cell->getRow() + $numberOfRows); // Should the cell be updated? Move value and cellXf index from one cell to another. if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) { // Update cell styles $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex()); // Insert this cell at its new location if ($cell->getDataType() === DataType::TYPE_FORMULA) { // Formula should be adjusted $worksheet->getCell($newCoordinate) ->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true)); } else { // Cell value should not be adjusted $worksheet->getCell($newCoordinate)->setValueExplicit($cell->getValue(), $cell->getDataType()); } // Clear the original cell $worksheet->getCellCollection()->delete($coordinate); } else { /* We don't need to update styles for rows/columns before our insertion position, but we do still need to adjust any formulae in those cells */ if ($cell->getDataType() === DataType::TYPE_FORMULA) { // Formula should be adjusted $cell->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true)); } } } // Duplicate styles for the newly inserted cells $highestColumn = $worksheet->getHighestColumn(); $highestRow = $worksheet->getHighestRow(); if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) { $this->duplicateStylesByColumn($worksheet, $beforeColumn, $beforeRow, $highestRow, $numberOfColumns); } if ($numberOfRows > 0 && $beforeRow - 1 > 0) { $this->duplicateStylesByRow($worksheet, $beforeColumn, $beforeRow, $highestColumn, $numberOfRows); } // Update worksheet: column dimensions $this->adjustColumnDimensions($worksheet); // Update worksheet: row dimensions $this->adjustRowDimensions($worksheet, $beforeRow, $numberOfRows); // Update worksheet: page breaks $this->adjustPageBreaks($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: comments $this->adjustComments($worksheet); // Update worksheet: hyperlinks $this->adjustHyperlinks($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: conditional formatting styles $this->adjustConditionalFormatting($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: data validations $this->adjustDataValidations($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: merge cells $this->adjustMergeCells($worksheet); // Update worksheet: protected cells $this->adjustProtectedCells($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: autofilter $this->adjustAutoFilter($worksheet, $beforeCellAddress, $numberOfColumns); // Update worksheet: table $this->adjustTable($worksheet, $beforeCellAddress, $numberOfColumns); // Update worksheet: freeze pane if ($worksheet->getFreezePane()) { $splitCell = $worksheet->getFreezePane(); $topLeftCell = $worksheet->getTopLeftCell() ?? ''; $splitCell = $this->updateCellReference($splitCell); $topLeftCell = $this->updateCellReference($topLeftCell); $worksheet->freezePane($splitCell, $topLeftCell); } // Page setup if ($worksheet->getPageSetup()->isPrintAreaSet()) { $worksheet->getPageSetup()->setPrintArea( $this->updateCellReference($worksheet->getPageSetup()->getPrintArea()) ); } // Update worksheet: drawings $aDrawings = $worksheet->getDrawingCollection(); foreach ($aDrawings as $objDrawing) { $newReference = $this->updateCellReference($objDrawing->getCoordinates()); if ($objDrawing->getCoordinates() != $newReference) { $objDrawing->setCoordinates($newReference); } if ($objDrawing->getCoordinates2() !== '') { $newReference = $this->updateCellReference($objDrawing->getCoordinates2()); if ($objDrawing->getCoordinates2() != $newReference) { $objDrawing->setCoordinates2($newReference); } } } // Update workbook: define names if (count($worksheet->getParentOrThrow()->getDefinedNames()) > 0) { $this->updateDefinedNames($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); } // Garbage collect $worksheet->garbageCollect(); } /** * Update references within formulas. * * @param string $formula Formula to update * @param string $beforeCellAddress Insert before this one * @param int $numberOfColumns Number of columns to insert * @param int $numberOfRows Number of rows to insert * @param string $worksheetName Worksheet name/title * * @return string Updated formula */ public function updateFormulaReferences( $formula = '', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0, $worksheetName = '', bool $includeAbsoluteReferences = false ) { if ( $this->cellReferenceHelper === null || $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows) ) { $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows); } // Update cell references in the formula $formulaBlocks = explode('"', $formula); $i = false; foreach ($formulaBlocks as &$formulaBlock) { // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode) $i = $i === false; if ($i) { $adjustCount = 0; $newCellTokens = $cellTokens = []; // Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5) $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_ROWRANGE . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3] . ':' . $match[4]; $modified3 = substr($this->updateCellReference('$A' . $match[3], $includeAbsoluteReferences), 2); $modified4 = substr($this->updateCellReference('$A' . $match[4], $includeAbsoluteReferences), 2); if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) { if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) { $toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString .= $modified3 . ':' . $modified4; // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = 100000; $row = 10000000 + (int) trim($match[3], '$'); $cellIndex = "{$column}{$row}"; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(?<!\d\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i'; ++$adjustCount; } } } } // Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E) $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_COLRANGE . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3] . ':' . $match[4]; $modified3 = substr($this->updateCellReference($match[3] . '$1', $includeAbsoluteReferences), 0, -2); $modified4 = substr($this->updateCellReference($match[4] . '$1', $includeAbsoluteReferences), 0, -2); if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) { if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) { $toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString .= $modified3 . ':' . $modified4; // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($match[3], '$')) + 100000; $row = 10000000; $cellIndex = "{$column}{$row}"; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?![A-Z])/i'; ++$adjustCount; } } } } // Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5) $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLRANGE . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3] . ':' . $match[4]; $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences); $modified4 = $this->updateCellReference($match[4], $includeAbsoluteReferences); if ($match[3] . $match[4] !== $modified3 . $modified4) { if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) { $toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString .= $modified3 . ':' . $modified4; [$column, $row] = Coordinate::coordinateFromString($match[3]); // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000; $row = (int) trim($row, '$') + 10000000; $cellIndex = "{$column}{$row}"; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(?<![A-Z]\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i'; ++$adjustCount; } } } } // Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5) $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLREF . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3]; $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences); if ($match[3] !== $modified3) { if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) { $toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString .= $modified3; [$column, $row] = Coordinate::coordinateFromString($match[3]); $columnAdditionalIndex = $column[0] === '$' ? 1 : 0; $rowAdditionalIndex = $row[0] === '$' ? 1 : 0; // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000; $row = (int) trim($row, '$') + 10000000; $cellIndex = $row . $rowAdditionalIndex . $column . $columnAdditionalIndex; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?!\d)/i'; ++$adjustCount; } } } } if ($adjustCount > 0) { if ($numberOfColumns > 0 || $numberOfRows > 0) { krsort($cellTokens); krsort($newCellTokens); } else { ksort($cellTokens); ksort($newCellTokens); } // Update cell references in the formula $formulaBlock = str_replace('\\', '', (string) preg_replace($cellTokens, $newCellTokens, $formulaBlock)); } } } unset($formulaBlock); // Then rebuild the formula string return implode('"', $formulaBlocks); } /** * Update all cell references within a formula, irrespective of worksheet. */ public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string { $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows); if ($numberOfColumns !== 0) { $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns); } if ($numberOfRows !== 0) { $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows); } return $formula; } private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $columnLengths = array_map('strlen', array_column($splitRanges[6], 0)); $rowLengths = array_map('strlen', array_column($splitRanges[7], 0)); $columnOffsets = array_column($splitRanges[6], 1); $rowOffsets = array_column($splitRanges[7], 1); $columns = $splitRanges[6]; $rows = $splitRanges[7]; while ($splitCount > 0) { --$splitCount; $columnLength = $columnLengths[$splitCount]; $rowLength = $rowLengths[$splitCount]; $columnOffset = $columnOffsets[$splitCount]; $rowOffset = $rowOffsets[$splitCount]; $column = $columns[$splitCount][0]; $row = $rows[$splitCount][0]; if (!empty($column) && $column[0] !== '$') { $column = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($column) + $numberOfColumns); $formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength); } if (!empty($row) && $row[0] !== '$') { $row = (int) $row + $numberOfRows; $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength); } } return $formula; } private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $fromColumnLengths = array_map('strlen', array_column($splitRanges[1], 0)); $fromColumnOffsets = array_column($splitRanges[1], 1); $toColumnLengths = array_map('strlen', array_column($splitRanges[2], 0)); $toColumnOffsets = array_column($splitRanges[2], 1); $fromColumns = $splitRanges[1]; $toColumns = $splitRanges[2]; while ($splitCount > 0) { --$splitCount; $fromColumnLength = $fromColumnLengths[$splitCount]; $toColumnLength = $toColumnLengths[$splitCount]; $fromColumnOffset = $fromColumnOffsets[$splitCount]; $toColumnOffset = $toColumnOffsets[$splitCount]; $fromColumn = $fromColumns[$splitCount][0]; $toColumn = $toColumns[$splitCount][0]; if (!empty($fromColumn) && $fromColumn[0] !== '$') { $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $numberOfColumns); $formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength); } if (!empty($toColumn) && $toColumn[0] !== '$') { $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns); $formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength); } } return $formula; } private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string { $splitCount = preg_match_all( '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui', $formula, $splitRanges, PREG_OFFSET_CAPTURE ); $fromRowLengths = array_map('strlen', array_column($splitRanges[1], 0)); $fromRowOffsets = array_column($splitRanges[1], 1); $toRowLengths = array_map('strlen', array_column($splitRanges[2], 0)); $toRowOffsets = array_column($splitRanges[2], 1); $fromRows = $splitRanges[1]; $toRows = $splitRanges[2]; while ($splitCount > 0) { --$splitCount; $fromRowLength = $fromRowLengths[$splitCount]; $toRowLength = $toRowLengths[$splitCount]; $fromRowOffset = $fromRowOffsets[$splitCount]; $toRowOffset = $toRowOffsets[$splitCount]; $fromRow = $fromRows[$splitCount][0]; $toRow = $toRows[$splitCount][0]; if (!empty($fromRow) && $fromRow[0] !== '$') { $fromRow = (int) $fromRow + $numberOfRows; $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength); } if (!empty($toRow) && $toRow[0] !== '$') { $toRow = (int) $toRow + $numberOfRows; $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength); } } return $formula; } /** * Update cell reference. * * @param string $cellReference Cell address or range of addresses * * @return string Updated cell range */ private function updateCellReference($cellReference = 'A1', bool $includeAbsoluteReferences = false) { // Is it in another worksheet? Will not have to update anything. if (strpos($cellReference, '!') !== false) { return $cellReference; } // Is it a range or a single cell? if (!Coordinate::coordinateIsRange($cellReference)) { // Single cell return $this->cellReferenceHelper->updateCellReference($cellReference, $includeAbsoluteReferences); } // Range return $this->updateCellRange($cellReference, $includeAbsoluteReferences); } /** * Update named formulae (i.e. containing worksheet references / named ranges). * * @param Spreadsheet $spreadsheet Object to update * @param string $oldName Old name (name to replace) * @param string $newName New name */ public function updateNamedFormulae(Spreadsheet $spreadsheet, $oldName = '', $newName = ''): void { if ($oldName == '') { return; } foreach ($spreadsheet->getWorksheetIterator() as $sheet) { foreach ($sheet->getCoordinates(false) as $coordinate) { $cell = $sheet->getCell($coordinate); if ($cell->getDataType() === DataType::TYPE_FORMULA) { $formula = $cell->getValue(); if (strpos($formula, $oldName) !== false) { $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula); $formula = str_replace($oldName . '!', $newName . '!', $formula); $cell->setValueExplicit($formula, DataType::TYPE_FORMULA); } } } } } private function updateDefinedNames(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void { foreach ($worksheet->getParentOrThrow()->getDefinedNames() as $definedName) { if ($definedName->isFormula() === false) { $this->updateNamedRange($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); } else { $this->updateNamedFormula($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); } } } private function updateNamedRange(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void { $cellAddress = $definedName->getValue(); $asFormula = ($cellAddress[0] === '='); if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) { /** * If we delete the entire range that is referenced by a Named Range, MS Excel sets the value to #REF! * PhpSpreadsheet still only does a basic adjustment, so the Named Range will still reference Cells. * Note that this applies only when deleting columns/rows; subsequent insertion won't fix the #REF! * TODO Can we work out a method to identify Named Ranges that cease to be valid, so that we can replace * them with a #REF! */ if ($asFormula === true) { $formula = $this->updateFormulaReferences($cellAddress, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true); $definedName->setValue($formula); } else { $definedName->setValue($this->updateCellReference(ltrim($cellAddress, '='), true)); } } } private function updateNamedFormula(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void { if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) { /** * If we delete the entire range that is referenced by a Named Formula, MS Excel sets the value to #REF! * PhpSpreadsheet still only does a basic adjustment, so the Named Formula will still reference Cells. * Note that this applies only when deleting columns/rows; subsequent insertion won't fix the #REF! * TODO Can we work out a method to identify Named Ranges that cease to be valid, so that we can replace * them with a #REF! */ $formula = $definedName->getValue(); $formula = $this->updateFormulaReferences($formula, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true); $definedName->setValue($formula); } } /** * Update cell range. * * @param string $cellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3') * * @return string Updated cell range */ private function updateCellRange(string $cellRange = 'A1:A1', bool $includeAbsoluteReferences = false): string { if (!Coordinate::coordinateIsRange($cellRange)) { throw new Exception('Only cell ranges may be passed to this method.'); } // Update range $range = Coordinate::splitRange($cellRange); $ic = count($range); for ($i = 0; $i < $ic; ++$i) { $jc = count($range[$i]); for ($j = 0; $j < $jc; ++$j) { if (ctype_alpha($range[$i][$j])) { $range[$i][$j] = Coordinate::coordinateFromString( $this->cellReferenceHelper->updateCellReference($range[$i][$j] . '1', $includeAbsoluteReferences) )[0]; } elseif (ctype_digit($range[$i][$j])) { $range[$i][$j] = Coordinate::coordinateFromString( $this->cellReferenceHelper->updateCellReference('A' . $range[$i][$j], $includeAbsoluteReferences) )[1]; } else { $range[$i][$j] = $this->cellReferenceHelper->updateCellReference($range[$i][$j], $includeAbsoluteReferences); } } } // Recreate range string return Coordinate::buildRange($range); } private function clearColumnStrips(int $highestRow, int $beforeColumn, int $numberOfColumns, Worksheet $worksheet): void { $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn + $numberOfColumns); $endColumnId = Coordinate::stringFromColumnIndex($beforeColumn); for ($row = 1; $row <= $highestRow - 1; ++$row) { for ($column = $startColumnId; $column !== $endColumnId; ++$column) { $coordinate = $column . $row; $this->clearStripCell($worksheet, $coordinate); } } } private function clearRowStrips(string $highestColumn, int $beforeColumn, int $beforeRow, int $numberOfRows, Worksheet $worksheet): void { $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn); ++$highestColumn; for ($column = $startColumnId; $column !== $highestColumn; ++$column) { for ($row = $beforeRow + $numberOfRows; $row <= $beforeRow - 1; ++$row) { $coordinate = $column . $row; $this->clearStripCell($worksheet, $coordinate); } } } private function clearStripCell(Worksheet $worksheet, string $coordinate): void { $worksheet->removeConditionalStyles($coordinate); $worksheet->setHyperlink($coordinate); $worksheet->setDataValidation($coordinate); $worksheet->removeComment($coordinate); if ($worksheet->cellExists($coordinate)) { $worksheet->getCell($coordinate)->setValueExplicit(null, DataType::TYPE_NULL); $worksheet->getCell($coordinate)->setXfIndex(0); } } private function adjustAutoFilter(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void { $autoFilter = $worksheet->getAutoFilter(); $autoFilterRange = $autoFilter->getRange(); if (!empty($autoFilterRange)) { if ($numberOfColumns !== 0) { $autoFilterColumns = $autoFilter->getColumns(); if (count($autoFilterColumns) > 0) { $column = ''; $row = 0; sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row); $columnIndex = Coordinate::columnIndexFromString((string) $column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange); if ($columnIndex <= $rangeEnd[0]) { if ($numberOfColumns < 0) { $this->adjustAutoFilterDeleteRules($columnIndex, $numberOfColumns, $autoFilterColumns, $autoFilter); } $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; // Shuffle columns in autofilter range if ($numberOfColumns > 0) { $this->adjustAutoFilterInsert($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter); } else { $this->adjustAutoFilterDelete($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter); } } } } $worksheet->setAutoFilter( $this->updateCellReference($autoFilterRange) ); } } private function adjustAutoFilterDeleteRules(int $columnIndex, int $numberOfColumns, array $autoFilterColumns, AutoFilter $autoFilter): void { // If we're actually deleting any columns that fall within the autofilter range, // then we delete any rules for those columns $deleteColumn = $columnIndex + $numberOfColumns - 1; $deleteCount = abs($numberOfColumns); for ($i = 1; $i <= $deleteCount; ++$i) { $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1); if (isset($autoFilterColumns[$columnName])) { $autoFilter->clearColumn($columnName); } ++$deleteColumn; } } private function adjustAutoFilterInsert(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void { $startColRef = $startCol; $endColRef = $rangeEnd; $toColRef = $rangeEnd + $numberOfColumns; do { $autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef)); --$endColRef; --$toColRef; } while ($startColRef <= $endColRef); } private function adjustAutoFilterDelete(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void { // For delete, we shuffle from beginning to end to avoid overwriting $startColID = Coordinate::stringFromColumnIndex($startCol); $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns); $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1); do { $autoFilter->shiftColumn($startColID, $toColID); ++$startColID; ++$toColID; } while ($startColID !== $endColID); } private function adjustTable(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void { $tableCollection = $worksheet->getTableCollection(); foreach ($tableCollection as $table) { $tableRange = $table->getRange(); if (!empty($tableRange)) { if ($numberOfColumns !== 0) { $tableColumns = $table->getColumns(); if (count($tableColumns) > 0) { $column = ''; $row = 0; sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row); $columnIndex = Coordinate::columnIndexFromString((string) $column); [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($tableRange); if ($columnIndex <= $rangeEnd[0]) { if ($numberOfColumns < 0) { $this->adjustTableDeleteRules($columnIndex, $numberOfColumns, $tableColumns, $table); } $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; // Shuffle columns in table range if ($numberOfColumns > 0) { $this->adjustTableInsert($startCol, $numberOfColumns, $rangeEnd[0], $table); } else { $this->adjustTableDelete($startCol, $numberOfColumns, $rangeEnd[0], $table); } } } } $table->setRange($this->updateCellReference($tableRange)); } } } private function adjustTableDeleteRules(int $columnIndex, int $numberOfColumns, array $tableColumns, Table $table): void { // If we're actually deleting any columns that fall within the table range, // then we delete any rules for those columns $deleteColumn = $columnIndex + $numberOfColumns - 1; $deleteCount = abs($numberOfColumns); for ($i = 1; $i <= $deleteCount; ++$i) { $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1); if (isset($tableColumns[$columnName])) { $table->clearColumn($columnName); } ++$deleteColumn; } } private function adjustTableInsert(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void { $startColRef = $startCol; $endColRef = $rangeEnd; $toColRef = $rangeEnd + $numberOfColumns; do { $table->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef)); --$endColRef; --$toColRef; } while ($startColRef <= $endColRef); } private function adjustTableDelete(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void { // For delete, we shuffle from beginning to end to avoid overwriting $startColID = Coordinate::stringFromColumnIndex($startCol); $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns); $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1); do { $table->shiftColumn($startColID, $toColID); ++$startColID; ++$toColID; } while ($startColID !== $endColID); } private function duplicateStylesByColumn(Worksheet $worksheet, int $beforeColumn, int $beforeRow, int $highestRow, int $numberOfColumns): void { $beforeColumnName = Coordinate::stringFromColumnIndex($beforeColumn - 1); for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { // Style $coordinate = $beforeColumnName . $i; if ($worksheet->cellExists($coordinate)) { $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) { $worksheet->getCell([$j, $i])->setXfIndex($xfIndex); } } } } private function duplicateStylesByRow(Worksheet $worksheet, int $beforeColumn, int $beforeRow, string $highestColumn, int $numberOfRows): void { $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn); for ($i = $beforeColumn; $i <= $highestColumnIndex; ++$i) { // Style $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1); if ($worksheet->cellExists($coordinate)) { $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) { $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); } } } } /** * __clone implementation. Cloning should not be allowed in a Singleton! */ final public function __clone() { throw new Exception('Cloning a Singleton is not allowed!'); } } phpspreadsheet/src/PhpSpreadsheet/Theme.php 0000644 00000016003 15002227416 0015043 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet; class Theme { /** @var string */ private $themeColorName = 'Office'; /** @var string */ private $themeFontName = 'Office'; public const COLOR_SCHEME_2013_PLUS_NAME = 'Office 2013+'; public const COLOR_SCHEME_2013_PLUS = [ 'dk1' => '000000', 'lt1' => 'FFFFFF', 'dk2' => '44546A', 'lt2' => 'E7E6E6', 'accent1' => '4472C4', 'accent2' => 'ED7D31', 'accent3' => 'A5A5A5', 'accent4' => 'FFC000', 'accent5' => '5B9BD5', 'accent6' => '70AD47', 'hlink' => '0563C1', 'folHlink' => '954F72', ]; public const COLOR_SCHEME_2007_2010_NAME = 'Office 2007-2010'; public const COLOR_SCHEME_2007_2010 = [ 'dk1' => '000000', 'lt1' => 'FFFFFF', 'dk2' => '1F497D', 'lt2' => 'EEECE1', 'accent1' => '4F81BD', 'accent2' => 'C0504D', 'accent3' => '9BBB59', 'accent4' => '8064A2', 'accent5' => '4BACC6', 'accent6' => 'F79646', 'hlink' => '0000FF', 'folHlink' => '800080', ]; /** @var string[] */ private $themeColors = self::COLOR_SCHEME_2007_2010; /** @var string */ private $majorFontLatin = 'Cambria'; /** @var string */ private $majorFontEastAsian = ''; /** @var string */ private $majorFontComplexScript = ''; /** @var string */ private $minorFontLatin = 'Calibri'; /** @var string */ private $minorFontEastAsian = ''; /** @var string */ private $minorFontComplexScript = ''; /** * Map of Major (header) fonts to write. * * @var string[] */ private $majorFontSubstitutions = self::FONTS_TIMES_SUBSTITUTIONS; /** * Map of Minor (body) fonts to write. * * @var string[] */ private $minorFontSubstitutions = self::FONTS_ARIAL_SUBSTITUTIONS; public const FONTS_TIMES_SUBSTITUTIONS = [ 'Jpan' => 'MS Pゴシック', 'Hang' => '맑은 고딕', 'Hans' => '宋体', 'Hant' => '新細明體', 'Arab' => 'Times New Roman', 'Hebr' => 'Times New Roman', 'Thai' => 'Tahoma', 'Ethi' => 'Nyala', 'Beng' => 'Vrinda', 'Gujr' => 'Shruti', 'Khmr' => 'MoolBoran', 'Knda' => 'Tunga', 'Guru' => 'Raavi', 'Cans' => 'Euphemia', 'Cher' => 'Plantagenet Cherokee', 'Yiii' => 'Microsoft Yi Baiti', 'Tibt' => 'Microsoft Himalaya', 'Thaa' => 'MV Boli', 'Deva' => 'Mangal', 'Telu' => 'Gautami', 'Taml' => 'Latha', 'Syrc' => 'Estrangelo Edessa', 'Orya' => 'Kalinga', 'Mlym' => 'Kartika', 'Laoo' => 'DokChampa', 'Sinh' => 'Iskoola Pota', 'Mong' => 'Mongolian Baiti', 'Viet' => 'Times New Roman', 'Uigh' => 'Microsoft Uighur', 'Geor' => 'Sylfaen', ]; public const FONTS_ARIAL_SUBSTITUTIONS = [ 'Jpan' => 'MS Pゴシック', 'Hang' => '맑은 고딕', 'Hans' => '宋体', 'Hant' => '新細明體', 'Arab' => 'Arial', 'Hebr' => 'Arial', 'Thai' => 'Tahoma', 'Ethi' => 'Nyala', 'Beng' => 'Vrinda', 'Gujr' => 'Shruti', 'Khmr' => 'DaunPenh', 'Knda' => 'Tunga', 'Guru' => 'Raavi', 'Cans' => 'Euphemia', 'Cher' => 'Plantagenet Cherokee', 'Yiii' => 'Microsoft Yi Baiti', 'Tibt' => 'Microsoft Himalaya', 'Thaa' => 'MV Boli', 'Deva' => 'Mangal', 'Telu' => 'Gautami', 'Taml' => 'Latha', 'Syrc' => 'Estrangelo Edessa', 'Orya' => 'Kalinga', 'Mlym' => 'Kartika', 'Laoo' => 'DokChampa', 'Sinh' => 'Iskoola Pota', 'Mong' => 'Mongolian Baiti', 'Viet' => 'Arial', 'Uigh' => 'Microsoft Uighur', 'Geor' => 'Sylfaen', ]; public function getThemeColors(): array { return $this->themeColors; } public function setThemeColor(string $key, string $value): self { $this->themeColors[$key] = $value; return $this; } public function getThemeColorName(): string { return $this->themeColorName; } public function setThemeColorName(string $name, ?array $themeColors = null): self { $this->themeColorName = $name; if ($name === self::COLOR_SCHEME_2007_2010_NAME) { $themeColors = $themeColors ?? self::COLOR_SCHEME_2007_2010; } elseif ($name === self::COLOR_SCHEME_2013_PLUS_NAME) { $themeColors = $themeColors ?? self::COLOR_SCHEME_2013_PLUS; } if ($themeColors !== null) { $this->themeColors = $themeColors; } return $this; } public function getMajorFontLatin(): string { return $this->majorFontLatin; } public function getMajorFontEastAsian(): string { return $this->majorFontEastAsian; } public function getMajorFontComplexScript(): string { return $this->majorFontComplexScript; } public function getMajorFontSubstitutions(): array { return $this->majorFontSubstitutions; } /** @param null|array $substitutions */ public function setMajorFontValues(?string $latin, ?string $eastAsian, ?string $complexScript, $substitutions): self { if (!empty($latin)) { $this->majorFontLatin = $latin; } if ($eastAsian !== null) { $this->majorFontEastAsian = $eastAsian; } if ($complexScript !== null) { $this->majorFontComplexScript = $complexScript; } if ($substitutions !== null) { $this->majorFontSubstitutions = $substitutions; } return $this; } public function getMinorFontLatin(): string { return $this->minorFontLatin; } public function getMinorFontEastAsian(): string { return $this->minorFontEastAsian; } public function getMinorFontComplexScript(): string { return $this->minorFontComplexScript; } public function getMinorFontSubstitutions(): array { return $this->minorFontSubstitutions; } /** @param null|array $substitutions */ public function setMinorFontValues(?string $latin, ?string $eastAsian, ?string $complexScript, $substitutions): self { if (!empty($latin)) { $this->minorFontLatin = $latin; } if ($eastAsian !== null) { $this->minorFontEastAsian = $eastAsian; } if ($complexScript !== null) { $this->minorFontComplexScript = $complexScript; } if ($substitutions !== null) { $this->minorFontSubstitutions = $substitutions; } return $this; } public function getThemeFontName(): string { return $this->themeFontName; } public function setThemeFontName(?string $name): self { if (!empty($name)) { $this->themeFontName = $name; } return $this; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php 0000644 00000002117 15002227416 0022671 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; class Constants { // Constants currently used by WeekNum; will eventually be used by WEEKDAY const STARTWEEK_SUNDAY = 1; const STARTWEEK_MONDAY = 2; const STARTWEEK_MONDAY_ALT = 11; const STARTWEEK_TUESDAY = 12; const STARTWEEK_WEDNESDAY = 13; const STARTWEEK_THURSDAY = 14; const STARTWEEK_FRIDAY = 15; const STARTWEEK_SATURDAY = 16; const STARTWEEK_SUNDAY_ALT = 17; const DOW_SUNDAY = 1; const DOW_MONDAY = 2; const DOW_TUESDAY = 3; const DOW_WEDNESDAY = 4; const DOW_THURSDAY = 5; const DOW_FRIDAY = 6; const DOW_SATURDAY = 7; const STARTWEEK_MONDAY_ISO = 21; const METHODARR = [ self::STARTWEEK_SUNDAY => self::DOW_SUNDAY, self::DOW_MONDAY, self::STARTWEEK_MONDAY_ALT => self::DOW_MONDAY, self::DOW_TUESDAY, self::DOW_WEDNESDAY, self::DOW_THURSDAY, self::DOW_FRIDAY, self::DOW_SATURDAY, self::DOW_SUNDAY, self::STARTWEEK_MONDAY_ISO => self::STARTWEEK_MONDAY_ISO, ]; } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php 0000644 00000006764 15002227416 0022624 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use Datetime; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class TimeValue { use ArrayEnabled; /** * TIMEVALUE. * * Returns a value that represents a particular time. * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp * value. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * TIMEVALUE(timeValue) * * @param null|array|string $timeValue A text string that represents a time in any one of the Microsoft * Excel time formats; for example, "6:45 PM" and "18:45" text strings * within quotation marks that represent time. * Date information in time_text is ignored. * Or can be an array of date/time values * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromString($timeValue) { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } // try to parse as time iff there is at least one digit if (is_string($timeValue) && preg_match('/\\d/', $timeValue) !== 1) { return ExcelError::VALUE(); } $timeValue = trim($timeValue ?? '', '"'); $timeValue = str_replace(['/', '.'], '-', $timeValue); $arraySplit = preg_split('/[\/:\-\s]/', $timeValue) ?: []; if ((count($arraySplit) == 2 || count($arraySplit) == 3) && $arraySplit[0] > 24) { $arraySplit[0] = ($arraySplit[0] % 24); $timeValue = implode(':', $arraySplit); } $PHPDateArray = Helpers::dateParse($timeValue); $retValue = ExcelError::VALUE(); if (Helpers::dateParseSucceeded($PHPDateArray)) { /** @var int */ $hour = $PHPDateArray['hour']; /** @var int */ $minute = $PHPDateArray['minute']; /** @var int */ $second = $PHPDateArray['second']; // OpenOffice-specific code removed - it works just like Excel $excelDateValue = SharedDateHelper::formattedPHPToExcel(1900, 1, 1, $hour, $minute, $second) - 1; $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_EXCEL) { $retValue = (float) $excelDateValue; } elseif ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { $retValue = (int) SharedDateHelper::excelToTimestamp($excelDateValue + 25569) - 3600; } else { $retValue = new DateTime('1900-01-01 ' . $PHPDateArray['hour'] . ':' . $PHPDateArray['minute'] . ':' . $PHPDateArray['second']); } } return $retValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php 0000644 00000010763 15002227416 0022010 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Month { use ArrayEnabled; /** * EDATE. * * Returns the serial number that represents the date that is the indicated number of months * before or after a specified date (the start_date). * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month * as the date of issue. * * Excel Function: * EDATE(dateValue,adjustmentMonths) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|int $adjustmentMonths The number of months before or after start_date. * A positive value for months yields a future date; * a negative value yields a past date. * Or can be an array of adjustment values * * @return array|mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function adjust($dateValue, $adjustmentMonths) { if (is_array($dateValue) || is_array($adjustmentMonths)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $adjustmentMonths); } try { $dateValue = Helpers::getDateValue($dateValue, false); $adjustmentMonths = Helpers::validateNumericNull($adjustmentMonths); } catch (Exception $e) { return $e->getMessage(); } $dateValue = floor($dateValue); $adjustmentMonths = floor($adjustmentMonths); // Execute function $PHPDateObject = Helpers::adjustDateByMonths($dateValue, $adjustmentMonths); return Helpers::returnIn3FormatsObject($PHPDateObject); } /** * EOMONTH. * * Returns the date value for the last day of the month that is the indicated number of months * before or after start_date. * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month. * * Excel Function: * EOMONTH(dateValue,adjustmentMonths) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|int $adjustmentMonths The number of months before or after start_date. * A positive value for months yields a future date; * a negative value yields a past date. * Or can be an array of adjustment values * * @return array|mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function lastDay($dateValue, $adjustmentMonths) { if (is_array($dateValue) || is_array($adjustmentMonths)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $adjustmentMonths); } try { $dateValue = Helpers::getDateValue($dateValue, false); $adjustmentMonths = Helpers::validateNumericNull($adjustmentMonths); } catch (Exception $e) { return $e->getMessage(); } $dateValue = floor($dateValue); $adjustmentMonths = floor($adjustmentMonths); // Execute function $PHPDateObject = Helpers::adjustDateByMonths($dateValue, $adjustmentMonths + 1); $adjustDays = (int) $PHPDateObject->format('d'); $adjustDaysString = '-' . $adjustDays . ' days'; $PHPDateObject->modify($adjustDaysString); return Helpers::returnIn3FormatsObject($PHPDateObject); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php 0000644 00000012245 15002227416 0022051 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Days360 { use ArrayEnabled; /** * DAYS360. * * Returns the number of days between two dates based on a 360-day year (twelve 30-day months), * which is used in some accounting calculations. Use this function to help compute payments if * your accounting system is based on twelve 30-day months. * * Excel Function: * DAYS360(startDate,endDate[,method]) * * @param array|mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|mixed $method US or European Method as a bool * FALSE or omitted: U.S. (NASD) method. If the starting date is * the last day of a month, it becomes equal to the 30th of the * same month. If the ending date is the last day of a month and * the starting date is earlier than the 30th of a month, the * ending date becomes equal to the 1st of the next month; * otherwise the ending date becomes equal to the 30th of the * same month. * TRUE: European method. Starting dates and ending dates that * occur on the 31st of a month become equal to the 30th of the * same month. * Or can be an array of methods * * @return array|int|string Number of days between start date and end date * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function between($startDate = 0, $endDate = 0, $method = false) { if (is_array($startDate) || is_array($endDate) || is_array($method)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $startDate, $endDate, $method); } try { $startDate = Helpers::getDateValue($startDate); $endDate = Helpers::getDateValue($endDate); } catch (Exception $e) { return $e->getMessage(); } if (!is_bool($method)) { return ExcelError::VALUE(); } // Execute function $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); $startDay = $PHPStartDateObject->format('j'); $startMonth = $PHPStartDateObject->format('n'); $startYear = $PHPStartDateObject->format('Y'); $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); $endDay = $PHPEndDateObject->format('j'); $endMonth = $PHPEndDateObject->format('n'); $endYear = $PHPEndDateObject->format('Y'); return self::dateDiff360((int) $startDay, (int) $startMonth, (int) $startYear, (int) $endDay, (int) $endMonth, (int) $endYear, !$method); } /** * Return the number of days between two dates based on a 360 day calendar. */ private static function dateDiff360(int $startDay, int $startMonth, int $startYear, int $endDay, int $endMonth, int $endYear, bool $methodUS): int { $startDay = self::getStartDay($startDay, $startMonth, $startYear, $methodUS); $endDay = self::getEndDay($endDay, $endMonth, $endYear, $startDay, $methodUS); return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360; } private static function getStartDay(int $startDay, int $startMonth, int $startYear, bool $methodUS): int { if ($startDay == 31) { --$startDay; } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !Helpers::isLeapYear($startYear))))) { $startDay = 30; } return $startDay; } private static function getEndDay(int $endDay, int &$endMonth, int &$endYear, int $startDay, bool $methodUS): int { if ($endDay == 31) { if ($methodUS && $startDay != 30) { $endDay = 1; if ($endMonth == 12) { ++$endYear; $endMonth = 1; } else { ++$endMonth; } } else { $endDay = 30; } } return $endDay; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php 0000644 00000004335 15002227416 0022343 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTimeImmutable; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Current { /** * DATENOW. * * Returns the current date. * The NOW function is useful when you need to display the current date and time on a worksheet or * calculate a value based on the current date and time, and have that value updated each time you * open the worksheet. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * and time format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * TODAY() * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function today() { $dti = new DateTimeImmutable(); $dateArray = Helpers::dateParse($dti->format('c')); return Helpers::dateParseSucceeded($dateArray) ? Helpers::returnIn3FormatsArray($dateArray, true) : ExcelError::VALUE(); } /** * DATETIMENOW. * * Returns the current date and time. * The NOW function is useful when you need to display the current date and time on a worksheet or * calculate a value based on the current date and time, and have that value updated each time you * open the worksheet. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * and time format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * NOW() * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function now() { $dti = new DateTimeImmutable(); $dateArray = Helpers::dateParse($dti->format('c')); return Helpers::dateParseSucceeded($dateArray) ? Helpers::returnIn3FormatsArray($dateArray) : ExcelError::VALUE(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php 0000644 00000013727 15002227416 0022760 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateInterval; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Difference { use ArrayEnabled; /** * DATEDIF. * * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object * or a standard date string * Or can be an array of date values * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object * or a standard date string * Or can be an array of date values * @param array|string $unit * Or can be an array of unit values * * @return array|int|string Interval between the dates * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function interval($startDate, $endDate, $unit = 'D') { if (is_array($startDate) || is_array($endDate) || is_array($unit)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $startDate, $endDate, $unit); } try { $startDate = Helpers::getDateValue($startDate); $endDate = Helpers::getDateValue($endDate); $difference = self::initialDiff($startDate, $endDate); $unit = strtoupper($unit); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); $startDays = (int) $PHPStartDateObject->format('j'); //$startMonths = (int) $PHPStartDateObject->format('n'); $startYears = (int) $PHPStartDateObject->format('Y'); $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); $endDays = (int) $PHPEndDateObject->format('j'); //$endMonths = (int) $PHPEndDateObject->format('n'); $endYears = (int) $PHPEndDateObject->format('Y'); $PHPDiffDateObject = $PHPEndDateObject->diff($PHPStartDateObject); $retVal = false; $retVal = self::replaceRetValue($retVal, $unit, 'D') ?? self::datedifD($difference); $retVal = self::replaceRetValue($retVal, $unit, 'M') ?? self::datedifM($PHPDiffDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'MD') ?? self::datedifMD($startDays, $endDays, $PHPEndDateObject, $PHPDiffDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'Y') ?? self::datedifY($PHPDiffDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'YD') ?? self::datedifYD($difference, $startYears, $endYears, $PHPStartDateObject, $PHPEndDateObject); $retVal = self::replaceRetValue($retVal, $unit, 'YM') ?? self::datedifYM($PHPDiffDateObject); return is_bool($retVal) ? ExcelError::VALUE() : $retVal; } private static function initialDiff(float $startDate, float $endDate): float { // Validate parameters if ($startDate > $endDate) { throw new Exception(ExcelError::NAN()); } return $endDate - $startDate; } /** * Decide whether it's time to set retVal. * * @param bool|int $retVal * * @return null|bool|int */ private static function replaceRetValue($retVal, string $unit, string $compare) { if ($retVal !== false || $unit !== $compare) { return $retVal; } return null; } private static function datedifD(float $difference): int { return (int) $difference; } private static function datedifM(DateInterval $PHPDiffDateObject): int { return 12 * (int) $PHPDiffDateObject->format('%y') + (int) $PHPDiffDateObject->format('%m'); } private static function datedifMD(int $startDays, int $endDays, DateTime $PHPEndDateObject, DateInterval $PHPDiffDateObject): int { if ($endDays < $startDays) { $retVal = $endDays; $PHPEndDateObject->modify('-' . $endDays . ' days'); $adjustDays = (int) $PHPEndDateObject->format('j'); $retVal += ($adjustDays - $startDays); } else { $retVal = (int) $PHPDiffDateObject->format('%d'); } return $retVal; } private static function datedifY(DateInterval $PHPDiffDateObject): int { return (int) $PHPDiffDateObject->format('%y'); } private static function datedifYD(float $difference, int $startYears, int $endYears, DateTime $PHPStartDateObject, DateTime $PHPEndDateObject): int { $retVal = (int) $difference; if ($endYears > $startYears) { $isLeapStartYear = $PHPStartDateObject->format('L'); $wasLeapEndYear = $PHPEndDateObject->format('L'); // Adjust end year to be as close as possible as start year while ($PHPEndDateObject >= $PHPStartDateObject) { $PHPEndDateObject->modify('-1 year'); //$endYears = $PHPEndDateObject->format('Y'); } $PHPEndDateObject->modify('+1 year'); // Get the result $retVal = (int) $PHPEndDateObject->diff($PHPStartDateObject)->days; // Adjust for leap years cases $isLeapEndYear = $PHPEndDateObject->format('L'); $limit = new DateTime($PHPEndDateObject->format('Y-02-29')); if (!$isLeapStartYear && !$wasLeapEndYear && $isLeapEndYear && $PHPEndDateObject >= $limit) { --$retVal; } } return (int) $retVal; } private static function datedifYM(DateInterval $PHPDiffDateObject): int { return (int) $PHPDiffDateObject->format('%m'); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php 0000644 00000010555 15002227416 0022632 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class TimeParts { use ArrayEnabled; /** * HOUROFDAY. * * Returns the hour of a time value. * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.). * * Excel Function: * HOUR(timeValue) * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * Or can be an array of date/time values * * @return array|int|string Hour * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function hour($timeValue) { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } try { Helpers::nullFalseTrueToNumber($timeValue); if (!is_numeric($timeValue)) { $timeValue = Helpers::getTimeValue($timeValue); } Helpers::validateNotNegative($timeValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $timeValue = fmod($timeValue, 1); $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); return (int) $timeValue->format('H'); } /** * MINUTE. * * Returns the minutes of a time value. * The minute is given as an integer, ranging from 0 to 59. * * Excel Function: * MINUTE(timeValue) * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * Or can be an array of date/time values * * @return array|int|string Minute * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function minute($timeValue) { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } try { Helpers::nullFalseTrueToNumber($timeValue); if (!is_numeric($timeValue)) { $timeValue = Helpers::getTimeValue($timeValue); } Helpers::validateNotNegative($timeValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $timeValue = fmod($timeValue, 1); $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); return (int) $timeValue->format('i'); } /** * SECOND. * * Returns the seconds of a time value. * The minute is given as an integer, ranging from 0 to 59. * * Excel Function: * SECOND(timeValue) * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * Or can be an array of date/time values * * @return array|int|string Second * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function second($timeValue) { if (is_array($timeValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); } try { Helpers::nullFalseTrueToNumber($timeValue); if (!is_numeric($timeValue)) { $timeValue = Helpers::getTimeValue($timeValue); } Helpers::validateNotNegative($timeValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $timeValue = fmod($timeValue, 1); $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); return (int) $timeValue->format('s'); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php 0000644 00000010301 15002227416 0023161 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class NetworkDays { use ArrayEnabled; /** * NETWORKDAYS. * * Returns the number of whole working days between start_date and end_date. Working days * exclude weekends and any dates identified in holidays. * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days * worked during a specific term. * * Excel Function: * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]]) * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param mixed $dateArgs An array of dates (such as holidays) to exclude from the calculation * * @return array|int|string Interval between the dates * If an array of values is passed for the $startDate or $endDate arguments, then the returned result * will also be an array with matching dimensions */ public static function count($startDate, $endDate, ...$dateArgs) { if (is_array($startDate) || is_array($endDate)) { return self::evaluateArrayArgumentsSubset( [self::class, __FUNCTION__], 2, $startDate, $endDate, ...$dateArgs ); } try { // Retrieve the mandatory start and end date that are referenced in the function definition $sDate = Helpers::getDateValue($startDate); $eDate = Helpers::getDateValue($endDate); $startDate = min($sDate, $eDate); $endDate = max($sDate, $eDate); // Get the optional days $dateArgs = Functions::flattenArray($dateArgs); // Test any extra holiday parameters $holidayArray = []; foreach ($dateArgs as $holidayDate) { $holidayArray[] = Helpers::getDateValue($holidayDate); } } catch (Exception $e) { return $e->getMessage(); } // Execute function $startDow = self::calcStartDow($startDate); $endDow = self::calcEndDow($endDate); $wholeWeekDays = (int) floor(($endDate - $startDate) / 7) * 5; $partWeekDays = self::calcPartWeekDays($startDow, $endDow); // Test any extra holiday parameters $holidayCountedArray = []; foreach ($holidayArray as $holidayDate) { if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { if ((Week::day($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) { --$partWeekDays; $holidayCountedArray[] = $holidayDate; } } } return self::applySign($wholeWeekDays + $partWeekDays, $sDate, $eDate); } private static function calcStartDow(float $startDate): int { $startDow = 6 - (int) Week::day($startDate, 2); if ($startDow < 0) { $startDow = 5; } return $startDow; } private static function calcEndDow(float $endDate): int { $endDow = (int) Week::day($endDate, 2); if ($endDow >= 6) { $endDow = 0; } return $endDow; } private static function calcPartWeekDays(int $startDow, int $endDow): int { $partWeekDays = $endDow + $startDow; if ($partWeekDays > 5) { $partWeekDays -= 5; } return $partWeekDays; } private static function applySign(int $result, float $sDate, float $eDate): int { return ($sDate > $eDate) ? -$result : $result; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php 0000644 00000024076 15002227416 0021620 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Week { use ArrayEnabled; /** * WEEKNUM. * * Returns the week of the year for a specified date. * The WEEKNUM function considers the week containing January 1 to be the first week of the year. * However, there is a European standard that defines the first week as the one with the majority * of days (four or more) falling in the new year. This means that for years in which there are * three days or less in the first week of January, the WEEKNUM function returns week numbers * that are incorrect according to the European standard. * * Excel Function: * WEEKNUM(dateValue[,style]) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|int $method Week begins on Sunday or Monday * 1 or omitted Week begins on Sunday. * 2 Week begins on Monday. * 11 Week begins on Monday. * 12 Week begins on Tuesday. * 13 Week begins on Wednesday. * 14 Week begins on Thursday. * 15 Week begins on Friday. * 16 Week begins on Saturday. * 17 Week begins on Sunday. * 21 ISO (Jan. 4 is week 1, begins on Monday). * Or can be an array of methods * * @return array|int|string Week Number * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function number($dateValue, $method = Constants::STARTWEEK_SUNDAY) { if (is_array($dateValue) || is_array($method)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $method); } $origDateValueNull = empty($dateValue); try { $method = self::validateMethod($method); if ($dateValue === null) { // boolean not allowed $dateValue = (SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904 || $method === Constants::DOW_SUNDAY) ? 0 : 1; } $dateValue = self::validateDateValue($dateValue); if (!$dateValue && self::buggyWeekNum1900($method)) { // This seems to be an additional Excel bug. return 0; } } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); if ($method == Constants::STARTWEEK_MONDAY_ISO) { Helpers::silly1900($PHPDateObject); return (int) $PHPDateObject->format('W'); } if (self::buggyWeekNum1904($method, $origDateValueNull, $PHPDateObject)) { return 0; } Helpers::silly1900($PHPDateObject, '+ 5 years'); // 1905 calendar matches $dayOfYear = (int) $PHPDateObject->format('z'); $PHPDateObject->modify('-' . $dayOfYear . ' days'); $firstDayOfFirstWeek = (int) $PHPDateObject->format('w'); $daysInFirstWeek = (6 - $firstDayOfFirstWeek + $method) % 7; $daysInFirstWeek += 7 * !$daysInFirstWeek; $endFirstWeek = $daysInFirstWeek - 1; $weekOfYear = floor(($dayOfYear - $endFirstWeek + 13) / 7); return (int) $weekOfYear; } /** * ISOWEEKNUM. * * Returns the ISO 8601 week number of the year for a specified date. * * Excel Function: * ISOWEEKNUM(dateValue) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Week Number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function isoWeekNumber($dateValue) { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } if (self::apparentBug($dateValue)) { return 52; } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); Helpers::silly1900($PHPDateObject); return (int) $PHPDateObject->format('W'); } /** * WEEKDAY. * * Returns the day of the week for a specified date. The day is given as an integer * ranging from 0 to 7 (dependent on the requested style). * * Excel Function: * WEEKDAY(dateValue[,style]) * * @param null|array|float|int|string $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param mixed $style A number that determines the type of return value * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday). * 2 Numbers 1 (Monday) through 7 (Sunday). * 3 Numbers 0 (Monday) through 6 (Sunday). * Or can be an array of styles * * @return array|int|string Day of the week value * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function day($dateValue, $style = 1) { if (is_array($dateValue) || is_array($style)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $style); } try { $dateValue = Helpers::getDateValue($dateValue); $style = self::validateStyle($style); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); Helpers::silly1900($PHPDateObject); $DoW = (int) $PHPDateObject->format('w'); switch ($style) { case 1: ++$DoW; break; case 2: $DoW = self::dow0Becomes7($DoW); break; case 3: $DoW = self::dow0Becomes7($DoW) - 1; break; } return $DoW; } /** * @param mixed $style expect int */ private static function validateStyle($style): int { if (!is_numeric($style)) { throw new Exception(ExcelError::VALUE()); } $style = (int) $style; if (($style < 1) || ($style > 3)) { throw new Exception(ExcelError::NAN()); } return $style; } private static function dow0Becomes7(int $DoW): int { return ($DoW === 0) ? 7 : $DoW; } /** * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string */ private static function apparentBug($dateValue): bool { if (SharedDateHelper::getExcelCalendar() !== SharedDateHelper::CALENDAR_MAC_1904) { if (is_bool($dateValue)) { return true; } if (is_numeric($dateValue) && !((int) $dateValue)) { return true; } } return false; } /** * Validate dateValue parameter. * * @param mixed $dateValue */ private static function validateDateValue($dateValue): float { if (is_bool($dateValue)) { throw new Exception(ExcelError::VALUE()); } return Helpers::getDateValue($dateValue); } /** * Validate method parameter. * * @param mixed $method */ private static function validateMethod($method): int { if ($method === null) { $method = Constants::STARTWEEK_SUNDAY; } if (!is_numeric($method)) { throw new Exception(ExcelError::VALUE()); } $method = (int) $method; if (!array_key_exists($method, Constants::METHODARR)) { throw new Exception(ExcelError::NAN()); } $method = Constants::METHODARR[$method]; return $method; } private static function buggyWeekNum1900(int $method): bool { return $method === Constants::DOW_SUNDAY && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900; } private static function buggyWeekNum1904(int $method, bool $origNull, DateTime $dateObject): bool { // This appears to be another Excel bug. return $method === Constants::DOW_SUNDAY && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904 && !$origNull && $dateObject->format('Y-m-d') === '1904-01-01'; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php 0000644 00000004325 15002227416 0021620 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; 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 { use ArrayEnabled; /** * DAYS. * * Returns the number of days between two dates * * Excel Function: * DAYS(endDate, startDate) * * @param array|DateTimeInterface|float|int|string $endDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|DateTimeInterface|float|int|string $startDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Number of days between start date and end date or an error * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function between($endDate, $startDate) { if (is_array($endDate) || is_array($startDate)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $endDate, $startDate); } try { $startDate = Helpers::getDateValue($startDate); $endDate = Helpers::getDateValue($endDate); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); $days = ExcelError::VALUE(); $diff = $PHPStartDateObject->diff($PHPEndDateObject); if ($diff !== false && !is_bool($diff->days)) { $days = $diff->days; if ($diff->invert) { $days = -$days; } } return $days; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php 0000644 00000013310 15002227416 0022406 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class YearFrac { use ArrayEnabled; /** * YEARFRAC. * * Calculates the fraction of the year represented by the number of whole days between two dates * (the start_date and the end_date). * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or * obligations to assign to a specific term. * * Excel Function: * YEARFRAC(startDate,endDate[,method]) * See https://lists.oasis-open.org/archives/office-formula/200806/msg00039.html * for description of algorithm used in Excel * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of values * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of methods * @param array|int $method Method used for the calculation * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * Or can be an array of methods * * @return array|float|string fraction of the year, or a string containing an error * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function fraction($startDate, $endDate, $method = 0) { if (is_array($startDate) || is_array($endDate) || is_array($method)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $startDate, $endDate, $method); } try { $method = (int) Helpers::validateNumericNull($method); $sDate = Helpers::getDateValue($startDate); $eDate = Helpers::getDateValue($endDate); $sDate = self::excelBug($sDate, $startDate, $endDate, $method); $eDate = self::excelBug($eDate, $endDate, $startDate, $method); $startDate = min($sDate, $eDate); $endDate = max($sDate, $eDate); } catch (Exception $e) { return $e->getMessage(); } switch ($method) { case 0: return Functions::scalar(Days360::between($startDate, $endDate)) / 360; case 1: return self::method1($startDate, $endDate); case 2: return Functions::scalar(Difference::interval($startDate, $endDate)) / 360; case 3: return Functions::scalar(Difference::interval($startDate, $endDate)) / 365; case 4: return Functions::scalar(Days360::between($startDate, $endDate, true)) / 360; } return ExcelError::NAN(); } /** * Excel 1900 calendar treats date argument of null as 1900-01-00. Really. * * @param mixed $startDate * @param mixed $endDate */ private static function excelBug(float $sDate, $startDate, $endDate, int $method): float { if (Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE && SharedDateHelper::getExcelCalendar() !== SharedDateHelper::CALENDAR_MAC_1904) { if ($endDate === null && $startDate !== null) { if (DateParts::month($sDate) == 12 && DateParts::day($sDate) === 31 && $method === 0) { $sDate += 2; } else { ++$sDate; } } } return $sDate; } private static function method1(float $startDate, float $endDate): float { $days = Functions::scalar(Difference::interval($startDate, $endDate)); $startYear = (int) DateParts::year($startDate); $endYear = (int) DateParts::year($endDate); $years = $endYear - $startYear + 1; $startMonth = (int) DateParts::month($startDate); $startDay = (int) DateParts::day($startDate); $endMonth = (int) DateParts::month($endDate); $endDay = (int) DateParts::day($endDate); $startMonthDay = 100 * $startMonth + $startDay; $endMonthDay = 100 * $endMonth + $endDay; if ($years == 1) { $tmpCalcAnnualBasis = 365 + (int) Helpers::isLeapYear($endYear); } elseif ($years == 2 && $startMonthDay >= $endMonthDay) { if (Helpers::isLeapYear($startYear)) { $tmpCalcAnnualBasis = 365 + (int) ($startMonthDay <= 229); } elseif (Helpers::isLeapYear($endYear)) { $tmpCalcAnnualBasis = 365 + (int) ($endMonthDay >= 229); } else { $tmpCalcAnnualBasis = 365; } } else { $tmpCalcAnnualBasis = 0; for ($year = $startYear; $year <= $endYear; ++$year) { $tmpCalcAnnualBasis += 365 + (int) Helpers::isLeapYear($year); } $tmpCalcAnnualBasis /= $years; } return $days / $tmpCalcAnnualBasis; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php 0000644 00000015262 15002227416 0022574 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTimeImmutable; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class DateValue { use ArrayEnabled; /** * DATEVALUE. * * Returns a value that represents a particular date. * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp * value. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * DATEVALUE(dateValue) * * @param null|array|string $dateValue Text that represents a date in a Microsoft Excel date format. * For example, "1/30/2008" or "30-Jan-2008" are text strings within * quotation marks that represent dates. Using the default date * system in Excel for Windows, date_text must represent a date from * January 1, 1900, to December 31, 9999. Using the default date * system in Excel for the Macintosh, date_text must represent a date * from January 1, 1904, to December 31, 9999. DATEVALUE returns the * #VALUE! error value if date_text is out of this range. * Or can be an array of date values * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromString($dateValue) { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } // try to parse as date iff there is at least one digit if (is_string($dateValue) && preg_match('/\\d/', $dateValue) !== 1) { return ExcelError::VALUE(); } $dti = new DateTimeImmutable(); $baseYear = SharedDateHelper::getExcelCalendar(); $dateValue = trim($dateValue ?? '', '"'); // Strip any ordinals because they're allowed in Excel (English only) $dateValue = (string) preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue); // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany) $dateValue = str_replace(['/', '.', '-', ' '], ' ', $dateValue); $yearFound = false; $t1 = explode(' ', $dateValue); $t = ''; foreach ($t1 as &$t) { if ((is_numeric($t)) && ($t > 31)) { if ($yearFound) { return ExcelError::VALUE(); } if ($t < 100) { $t += 1900; } $yearFound = true; } } if (count($t1) === 1) { // We've been fed a time value without any date return ((strpos((string) $t, ':') === false)) ? ExcelError::Value() : 0.0; } unset($t); $dateValue = self::t1ToString($t1, $dti, $yearFound); $PHPDateArray = self::setUpArray($dateValue, $dti); return self::finalResults($PHPDateArray, $dti, $baseYear); } private static function t1ToString(array $t1, DateTimeImmutable $dti, bool $yearFound): string { if (count($t1) == 2) { // We only have two parts of the date: either day/month or month/year if ($yearFound) { array_unshift($t1, 1); } else { if (is_numeric($t1[1]) && $t1[1] > 29) { $t1[1] += 1900; array_unshift($t1, 1); } else { $t1[] = $dti->format('Y'); } } } $dateValue = implode(' ', $t1); return $dateValue; } /** * Parse date. */ private static function setUpArray(string $dateValue, DateTimeImmutable $dti): array { $PHPDateArray = Helpers::dateParse($dateValue); if (!Helpers::dateParseSucceeded($PHPDateArray)) { // If original count was 1, we've already returned. // If it was 2, we added another. // Therefore, neither of the first 2 stroks below can fail. $testVal1 = strtok($dateValue, '- '); $testVal2 = strtok('- '); $testVal3 = strtok('- ') ?: $dti->format('Y'); Helpers::adjustYear((string) $testVal1, (string) $testVal2, $testVal3); $PHPDateArray = Helpers::dateParse($testVal1 . '-' . $testVal2 . '-' . $testVal3); if (!Helpers::dateParseSucceeded($PHPDateArray)) { $PHPDateArray = Helpers::dateParse($testVal2 . '-' . $testVal1 . '-' . $testVal3); } } return $PHPDateArray; } /** * Final results. * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ private static function finalResults(array $PHPDateArray, DateTimeImmutable $dti, int $baseYear) { $retValue = ExcelError::Value(); if (Helpers::dateParseSucceeded($PHPDateArray)) { // Execute function Helpers::replaceIfEmpty($PHPDateArray['year'], $dti->format('Y')); if ($PHPDateArray['year'] < $baseYear) { return ExcelError::VALUE(); } Helpers::replaceIfEmpty($PHPDateArray['month'], $dti->format('m')); Helpers::replaceIfEmpty($PHPDateArray['day'], $dti->format('d')); $PHPDateArray['hour'] = 0; $PHPDateArray['minute'] = 0; $PHPDateArray['second'] = 0; $month = (int) $PHPDateArray['month']; $day = (int) $PHPDateArray['day']; $year = (int) $PHPDateArray['year']; if (!checkdate($month, $day, $year)) { return ($year === 1900 && $month === 2 && $day === 29) ? Helpers::returnIn3FormatsFloat(60.0) : ExcelError::VALUE(); } $retValue = Helpers::returnIn3FormatsArray($PHPDateArray, true); } return $retValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php 0000644 00000016343 15002227416 0022303 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class WorkDay { use ArrayEnabled; /** * WORKDAY. * * Returns the date that is the indicated number of working days before or after a date (the * starting date). Working days exclude weekends and any dates identified as holidays. * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected * delivery times, or the number of days of work performed. * * Excel Function: * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]]) * * @param array|mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * @param array|int $endDays The number of nonweekend and nonholiday days before or after * startDate. A positive value for days yields a future date; a * negative value yields a past date. * Or can be an array of int values * @param null|mixed $dateArgs An array of dates (such as holidays) to exclude from the calculation * * @return array|mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of values is passed for the $startDate or $endDays,arguments, then the returned result * will also be an array with matching dimensions */ public static function date($startDate, $endDays, ...$dateArgs) { if (is_array($startDate) || is_array($endDays)) { return self::evaluateArrayArgumentsSubset( [self::class, __FUNCTION__], 2, $startDate, $endDays, ...$dateArgs ); } // Retrieve the mandatory start date and days that are referenced in the function definition try { $startDate = Helpers::getDateValue($startDate); $endDays = Helpers::validateNumericNull($endDays); $holidayArray = array_map([Helpers::class, 'getDateValue'], Functions::flattenArray($dateArgs)); } catch (Exception $e) { return $e->getMessage(); } $startDate = (float) floor($startDate); $endDays = (int) floor($endDays); // If endDays is 0, we always return startDate if ($endDays == 0) { return $startDate; } if ($endDays < 0) { return self::decrementing($startDate, $endDays, $holidayArray); } return self::incrementing($startDate, $endDays, $holidayArray); } /** * Use incrementing logic to determine Workday. * * @return mixed */ private static function incrementing(float $startDate, int $endDays, array $holidayArray) { // Adjust the start date if it falls over a weekend $startDoW = self::getWeekDay($startDate, 3); if ($startDoW >= 5) { $startDate += 7 - $startDoW; --$endDays; } // Add endDays $endDate = (float) $startDate + ((int) ($endDays / 5) * 7); $endDays = $endDays % 5; while ($endDays > 0) { ++$endDate; // Adjust the calculated end date if it falls over a weekend $endDow = self::getWeekDay($endDate, 3); if ($endDow >= 5) { $endDate += 7 - $endDow; } --$endDays; } // Test any extra holiday parameters if (!empty($holidayArray)) { $endDate = self::incrementingArray($startDate, $endDate, $holidayArray); } return Helpers::returnIn3FormatsFloat($endDate); } private static function incrementingArray(float $startDate, float $endDate, array $holidayArray): float { $holidayCountedArray = $holidayDates = []; foreach ($holidayArray as $holidayDate) { if (self::getWeekDay($holidayDate, 3) < 5) { $holidayDates[] = $holidayDate; } } sort($holidayDates, SORT_NUMERIC); foreach ($holidayDates as $holidayDate) { if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { if (!in_array($holidayDate, $holidayCountedArray)) { ++$endDate; $holidayCountedArray[] = $holidayDate; } } // Adjust the calculated end date if it falls over a weekend $endDoW = self::getWeekDay($endDate, 3); if ($endDoW >= 5) { $endDate += 7 - $endDoW; } } return $endDate; } /** * Use decrementing logic to determine Workday. * * @return mixed */ private static function decrementing(float $startDate, int $endDays, array $holidayArray) { // Adjust the start date if it falls over a weekend $startDoW = self::getWeekDay($startDate, 3); if ($startDoW >= 5) { $startDate += -$startDoW + 4; ++$endDays; } // Add endDays $endDate = (float) $startDate + ((int) ($endDays / 5) * 7); $endDays = $endDays % 5; while ($endDays < 0) { --$endDate; // Adjust the calculated end date if it falls over a weekend $endDow = self::getWeekDay($endDate, 3); if ($endDow >= 5) { $endDate += 4 - $endDow; } ++$endDays; } // Test any extra holiday parameters if (!empty($holidayArray)) { $endDate = self::decrementingArray($startDate, $endDate, $holidayArray); } return Helpers::returnIn3FormatsFloat($endDate); } private static function decrementingArray(float $startDate, float $endDate, array $holidayArray): float { $holidayCountedArray = $holidayDates = []; foreach ($holidayArray as $holidayDate) { if (self::getWeekDay($holidayDate, 3) < 5) { $holidayDates[] = $holidayDate; } } rsort($holidayDates, SORT_NUMERIC); foreach ($holidayDates as $holidayDate) { if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) { if (!in_array($holidayDate, $holidayCountedArray)) { --$endDate; $holidayCountedArray[] = $holidayDate; } } // Adjust the calculated end date if it falls over a weekend $endDoW = self::getWeekDay($endDate, 3); /** int $endDoW */ if ($endDoW >= 5) { $endDate += -$endDoW + 4; } } return $endDate; } private static function getWeekDay(float $date, int $wd): int { $result = Functions::scalar(Week::day($date, $wd)); return is_int($result) ? $result : -1; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php 0000644 00000022115 15002227416 0022317 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Helpers { /** * Identify if a year is a leap year or not. * * @param int|string $year The year to test * * @return bool TRUE if the year is a leap year, otherwise FALSE */ public static function isLeapYear($year): bool { return (($year % 4) === 0) && (($year % 100) !== 0) || (($year % 400) === 0); } /** * getDateValue. * * @param mixed $dateValue * * @return float Excel date/time serial value */ public static function getDateValue($dateValue, bool $allowBool = true): float { if (is_object($dateValue)) { $retval = SharedDateHelper::PHPToExcel($dateValue); if (is_bool($retval)) { throw new Exception(ExcelError::VALUE()); } return $retval; } self::nullFalseTrueToNumber($dateValue, $allowBool); if (!is_numeric($dateValue)) { $saveReturnDateType = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); $dateValue = DateValue::fromString($dateValue); Functions::setReturnDateType($saveReturnDateType); if (!is_numeric($dateValue)) { throw new Exception(ExcelError::VALUE()); } } if ($dateValue < 0 && Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE) { throw new Exception(ExcelError::NAN()); } return (float) $dateValue; } /** * getTimeValue. * * @param string $timeValue * * @return mixed Excel date/time serial value, or string if error */ public static function getTimeValue($timeValue) { $saveReturnDateType = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); $timeValue = TimeValue::fromString($timeValue); Functions::setReturnDateType($saveReturnDateType); return $timeValue; } /** * Adjust date by given months. * * @param mixed $dateValue */ public static function adjustDateByMonths($dateValue = 0, float $adjustmentMonths = 0): DateTime { // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); $oMonth = (int) $PHPDateObject->format('m'); $oYear = (int) $PHPDateObject->format('Y'); $adjustmentMonthsString = (string) $adjustmentMonths; if ($adjustmentMonths > 0) { $adjustmentMonthsString = '+' . $adjustmentMonths; } if ($adjustmentMonths != 0) { $PHPDateObject->modify($adjustmentMonthsString . ' months'); } $nMonth = (int) $PHPDateObject->format('m'); $nYear = (int) $PHPDateObject->format('Y'); $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12); if ($monthDiff != $adjustmentMonths) { $adjustDays = (int) $PHPDateObject->format('d'); $adjustDaysString = '-' . $adjustDays . ' days'; $PHPDateObject->modify($adjustDaysString); } return $PHPDateObject; } /** * Help reduce perceived complexity of some tests. * * @param mixed $value * @param mixed $altValue */ public static function replaceIfEmpty(&$value, $altValue): void { $value = $value ?: $altValue; } /** * Adjust year in ambiguous situations. */ public static function adjustYear(string $testVal1, string $testVal2, string &$testVal3): void { if (!is_numeric($testVal1) || $testVal1 < 31) { if (!is_numeric($testVal2) || $testVal2 < 12) { if (is_numeric($testVal3) && $testVal3 < 12) { $testVal3 += 2000; } } } } /** * Return result in one of three formats. * * @return mixed */ public static function returnIn3FormatsArray(array $dateArray, bool $noFrac = false) { $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_PHP_DATETIME_OBJECT) { return new DateTime( $dateArray['year'] . '-' . $dateArray['month'] . '-' . $dateArray['day'] . ' ' . $dateArray['hour'] . ':' . $dateArray['minute'] . ':' . $dateArray['second'] ); } $excelDateValue = SharedDateHelper::formattedPHPToExcel( $dateArray['year'], $dateArray['month'], $dateArray['day'], $dateArray['hour'], $dateArray['minute'], $dateArray['second'] ); if ($retType === Functions::RETURNDATE_EXCEL) { return $noFrac ? floor($excelDateValue) : (float) $excelDateValue; } // RETURNDATE_UNIX_TIMESTAMP) return (int) SharedDateHelper::excelToTimestamp($excelDateValue); } /** * Return result in one of three formats. * * @return mixed */ public static function returnIn3FormatsFloat(float $excelDateValue) { $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_EXCEL) { return $excelDateValue; } if ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { return (int) SharedDateHelper::excelToTimestamp($excelDateValue); } // RETURNDATE_PHP_DATETIME_OBJECT return SharedDateHelper::excelToDateTimeObject($excelDateValue); } /** * Return result in one of three formats. * * @return mixed */ public static function returnIn3FormatsObject(DateTime $PHPDateObject) { $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_PHP_DATETIME_OBJECT) { return $PHPDateObject; } if ($retType === Functions::RETURNDATE_EXCEL) { return (float) SharedDateHelper::PHPToExcel($PHPDateObject); } // RETURNDATE_UNIX_TIMESTAMP $stamp = SharedDateHelper::PHPToExcel($PHPDateObject); $stamp = is_bool($stamp) ? ((int) $stamp) : $stamp; return (int) SharedDateHelper::excelToTimestamp($stamp); } private static function baseDate(): int { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { return 0; } if (SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904) { return 0; } return 1; } /** * Many functions accept null/false/true argument treated as 0/0/1. * * @param mixed $number */ public static function nullFalseTrueToNumber(&$number, bool $allowBool = true): void { $number = Functions::flattenSingleValue($number); $nullVal = self::baseDate(); if ($number === null) { $number = $nullVal; } elseif ($allowBool && is_bool($number)) { $number = $nullVal + (int) $number; } } /** * Many functions accept null argument treated as 0. * * @param mixed $number * * @return float|int */ public static function validateNumericNull($number) { $number = Functions::flattenSingleValue($number); if ($number === null) { return 0; } if (is_int($number)) { return $number; } if (is_numeric($number)) { return (float) $number; } throw new Exception(ExcelError::VALUE()); } /** * Many functions accept null/false/true argument treated as 0/0/1. * * @param mixed $number * * @return float */ public static function validateNotNegative($number) { if (!is_numeric($number)) { throw new Exception(ExcelError::VALUE()); } if ($number >= 0) { return (float) $number; } throw new Exception(ExcelError::NAN()); } public static function silly1900(DateTime $PHPDateObject, string $mod = '-1 day'): void { $isoDate = $PHPDateObject->format('c'); if ($isoDate < '1900-03-01') { $PHPDateObject->modify($mod); } } public static function dateParse(string $string): array { return self::forceArray(date_parse($string)); } public static function dateParseSucceeded(array $dateArray): bool { return $dateArray['error_count'] === 0; } /** * Despite documentation, date_parse probably never returns false. * Just in case, this routine helps guarantee it. * * @param array|false $dateArray */ private static function forceArray($dateArray): array { return is_array($dateArray) ? $dateArray : ['error_count' => 1]; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php 0000644 00000016470 15002227416 0021601 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Date { use ArrayEnabled; /** * DATE. * * The DATE function returns a value that represents a particular date. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * DATE(year,month,day) * * PhpSpreadsheet is a lot more forgiving than MS Excel when passing non numeric values to this function. * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted, * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language. * * @param array|int $year The value of the year argument can include one to four digits. * Excel interprets the year argument according to the configured * date system: 1900 or 1904. * If year is between 0 (zero) and 1899 (inclusive), Excel adds that * value to 1900 to calculate the year. For example, DATE(108,1,2) * returns January 2, 2008 (1900+108). * If year is between 1900 and 9999 (inclusive), Excel uses that * value as the year. For example, DATE(2008,1,2) returns January 2, * 2008. * If year is less than 0 or is 10000 or greater, Excel returns the * #NUM! error value. * @param array|int $month A positive or negative integer representing the month of the year * from 1 to 12 (January to December). * If month is greater than 12, month adds that number of months to * the first month in the year specified. For example, DATE(2008,14,2) * returns the serial number representing February 2, 2009. * If month is less than 1, month subtracts the magnitude of that * number of months, plus 1, from the first month in the year * specified. For example, DATE(2008,-3,2) returns the serial number * representing September 2, 2007. * @param array|int $day A positive or negative integer representing the day of the month * from 1 to 31. * If day is greater than the number of days in the month specified, * day adds that number of days to the first day in the month. For * example, DATE(2008,1,35) returns the serial number representing * February 4, 2008. * If day is less than 1, day subtracts the magnitude that number of * days, plus one, from the first day of the month specified. For * example, DATE(2008,1,-15) returns the serial number representing * December 16, 2007. * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromYMD($year, $month, $day) { if (is_array($year) || is_array($month) || is_array($day)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $year, $month, $day); } $baseYear = SharedDateHelper::getExcelCalendar(); try { $year = self::getYear($year, $baseYear); // must be int - Scrutinizer is wrong $month = self::getMonth($month); $day = self::getDay($day); self::adjustYearMonth(/** @scrutinizer ignore-type */ $year, $month, $baseYear); } catch (Exception $e) { return $e->getMessage(); } // Execute function $excelDateValue = SharedDateHelper::formattedPHPToExcel(/** @scrutinizer ignore-type */ $year, $month, $day); return Helpers::returnIn3FormatsFloat($excelDateValue); } /** * Convert year from multiple formats to int. * * @param mixed $year */ private static function getYear($year, int $baseYear): int { $year = ($year !== null) ? StringHelper::testStringAsNumeric((string) $year) : 0; if (!is_numeric($year)) { throw new Exception(ExcelError::VALUE()); } $year = (int) $year; if ($year < ($baseYear - 1900)) { throw new Exception(ExcelError::NAN()); } if ((($baseYear - 1900) !== 0) && ($year < $baseYear) && ($year >= 1900)) { throw new Exception(ExcelError::NAN()); } if (($year < $baseYear) && ($year >= ($baseYear - 1900))) { $year += 1900; } return (int) $year; } /** * Convert month from multiple formats to int. * * @param mixed $month */ private static function getMonth($month): int { if (($month !== null) && (!is_numeric($month))) { $month = SharedDateHelper::monthStringToNumber($month); } $month = ($month !== null) ? StringHelper::testStringAsNumeric((string) $month) : 0; if (!is_numeric($month)) { throw new Exception(ExcelError::VALUE()); } return (int) $month; } /** * Convert day from multiple formats to int. * * @param mixed $day */ private static function getDay($day): int { if (($day !== null) && (!is_numeric($day))) { $day = SharedDateHelper::dayStringToNumber($day); } $day = ($day !== null) ? StringHelper::testStringAsNumeric((string) $day) : 0; if (!is_numeric($day)) { throw new Exception(ExcelError::VALUE()); } return (int) $day; } private static function adjustYearMonth(int &$year, int &$month, int $baseYear): void { if ($month < 1) { // Handle year/month adjustment if month < 1 --$month; $year += ceil($month / 12) - 1; $month = 13 - abs($month % 12); } elseif ($month > 12) { // Handle year/month adjustment if month > 12 $year += floor($month / 12); $month = ($month % 12); } // Re-validate the year parameter after adjustments if (($year < $baseYear) || ($year >= 10000)) { throw new Exception(ExcelError::NAN()); } } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php 0000644 00000012013 15002227416 0021607 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class Time { use ArrayEnabled; /** * TIME. * * The TIME function returns a value that represents a particular time. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * TIME(hour,minute,second) * * @param array|int $hour A number from 0 (zero) to 32767 representing the hour. * Any value greater than 23 will be divided by 24 and the remainder * will be treated as the hour value. For example, TIME(27,0,0) = * TIME(3,0,0) = .125 or 3:00 AM. * @param array|int $minute A number from 0 to 32767 representing the minute. * Any value greater than 59 will be converted to hours and minutes. * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM. * @param array|int $second A number from 0 to 32767 representing the second. * Any value greater than 59 will be converted to hours, minutes, * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148 * or 12:33:20 AM * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions * * @return array|mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fromHMS($hour, $minute, $second) { if (is_array($hour) || is_array($minute) || is_array($second)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $hour, $minute, $second); } try { $hour = self::toIntWithNullBool($hour); $minute = self::toIntWithNullBool($minute); $second = self::toIntWithNullBool($second); } catch (Exception $e) { return $e->getMessage(); } self::adjustSecond($second, $minute); self::adjustMinute($minute, $hour); if ($hour > 23) { $hour = $hour % 24; } elseif ($hour < 0) { return ExcelError::NAN(); } // Execute function $retType = Functions::getReturnDateType(); if ($retType === Functions::RETURNDATE_EXCEL) { $calendar = SharedDateHelper::getExcelCalendar(); $date = (int) ($calendar !== SharedDateHelper::CALENDAR_WINDOWS_1900); return (float) SharedDateHelper::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second); } if ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { return (int) SharedDateHelper::excelToTimestamp(SharedDateHelper::formattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600 } // RETURNDATE_PHP_DATETIME_OBJECT // Hour has already been normalized (0-23) above $phpDateObject = new DateTime('1900-01-01 ' . $hour . ':' . $minute . ':' . $second); return $phpDateObject; } private static function adjustSecond(int &$second, int &$minute): void { if ($second < 0) { $minute += floor($second / 60); $second = 60 - abs($second % 60); if ($second == 60) { $second = 0; } } elseif ($second >= 60) { $minute += floor($second / 60); $second = $second % 60; } } private static function adjustMinute(int &$minute, int &$hour): void { if ($minute < 0) { $hour += floor($minute / 60); $minute = 60 - abs($minute % 60); if ($minute == 60) { $minute = 0; } } elseif ($minute >= 60) { $hour += floor($minute / 60); $minute = $minute % 60; } } /** * @param mixed $value expect int */ private static function toIntWithNullBool($value): int { $value = $value ?? 0; if (is_bool($value)) { $value = (int) $value; } if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (int) $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php 0000644 00000012125 15002227416 0022604 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDateHelper; class DateParts { use ArrayEnabled; /** * DAYOFMONTH. * * Returns the day of the month, for a specified date. The day is given as an integer * ranging from 1 to 31. * * Excel Function: * DAY(dateValue) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Day of the month * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function day($dateValue) { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } $weirdResult = self::weirdCondition($dateValue); if ($weirdResult >= 0) { return $weirdResult; } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); return (int) $PHPDateObject->format('j'); } /** * MONTHOFYEAR. * * Returns the month of a date represented by a serial number. * The month is given as an integer, ranging from 1 (January) to 12 (December). * * Excel Function: * MONTH(dateValue) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Month of the year * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function month($dateValue) { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } if ($dateValue < 1 && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900) { return 1; } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); return (int) $PHPDateObject->format('n'); } /** * YEAR. * * Returns the year corresponding to a date. * The year is returned as an integer in the range 1900-9999. * * Excel Function: * YEAR(dateValue) * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * Or can be an array of date values * * @return array|int|string Year * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function year($dateValue) { if (is_array($dateValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); } try { $dateValue = Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } if ($dateValue < 1 && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900) { return 1900; } // Execute function $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); return (int) $PHPDateObject->format('Y'); } /** * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string */ private static function weirdCondition($dateValue): int { // Excel does not treat 0 consistently for DAY vs. (MONTH or YEAR) if (SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900 && Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { if (is_bool($dateValue)) { return (int) $dateValue; } if ($dateValue === null) { return 0; } if (is_numeric($dateValue) && $dateValue < 1 && $dateValue >= 0) { return 0; } } return -1; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Category.php 0000644 00000001321 15002227416 0020011 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; abstract class Category { // Function categories const CATEGORY_CUBE = 'Cube'; const CATEGORY_DATABASE = 'Database'; const CATEGORY_DATE_AND_TIME = 'Date and Time'; const CATEGORY_ENGINEERING = 'Engineering'; const CATEGORY_FINANCIAL = 'Financial'; const CATEGORY_INFORMATION = 'Information'; const CATEGORY_LOGICAL = 'Logical'; const CATEGORY_LOOKUP_AND_REFERENCE = 'Lookup and Reference'; const CATEGORY_MATH_AND_TRIG = 'Math and Trig'; const CATEGORY_STATISTICAL = 'Statistical'; const CATEGORY_TEXT_AND_DATA = 'Text and Data'; const CATEGORY_WEB = 'Web'; const CATEGORY_UNCATEGORISED = 'Uncategorised'; } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Exp.php 0000644 00000001743 15002227416 0020517 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Exp { use ArrayEnabled; /** * EXP. * * Returns the result of builtin function exp after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return exp($number); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Roman.php 0000644 00000064117 15002227416 0021043 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Roman { use ArrayEnabled; private const VALUES = [ 45 => ['VL'], 46 => ['VLI'], 47 => ['VLII'], 48 => ['VLIII'], 49 => ['VLIV', 'IL'], 95 => ['VC'], 96 => ['VCI'], 97 => ['VCII'], 98 => ['VCIII'], 99 => ['VCIV', 'IC'], 145 => ['CVL'], 146 => ['CVLI'], 147 => ['CVLII'], 148 => ['CVLIII'], 149 => ['CVLIV', 'CIL'], 195 => ['CVC'], 196 => ['CVCI'], 197 => ['CVCII'], 198 => ['CVCIII'], 199 => ['CVCIV', 'CIC'], 245 => ['CCVL'], 246 => ['CCVLI'], 247 => ['CCVLII'], 248 => ['CCVLIII'], 249 => ['CCVLIV', 'CCIL'], 295 => ['CCVC'], 296 => ['CCVCI'], 297 => ['CCVCII'], 298 => ['CCVCIII'], 299 => ['CCVCIV', 'CCIC'], 345 => ['CCCVL'], 346 => ['CCCVLI'], 347 => ['CCCVLII'], 348 => ['CCCVLIII'], 349 => ['CCCVLIV', 'CCCIL'], 395 => ['CCCVC'], 396 => ['CCCVCI'], 397 => ['CCCVCII'], 398 => ['CCCVCIII'], 399 => ['CCCVCIV', 'CCCIC'], 445 => ['CDVL'], 446 => ['CDVLI'], 447 => ['CDVLII'], 448 => ['CDVLIII'], 449 => ['CDVLIV', 'CDIL'], 450 => ['LD'], 451 => ['LDI'], 452 => ['LDII'], 453 => ['LDIII'], 454 => ['LDIV'], 455 => ['LDV'], 456 => ['LDVI'], 457 => ['LDVII'], 458 => ['LDVIII'], 459 => ['LDIX'], 460 => ['LDX'], 461 => ['LDXI'], 462 => ['LDXII'], 463 => ['LDXIII'], 464 => ['LDXIV'], 465 => ['LDXV'], 466 => ['LDXVI'], 467 => ['LDXVII'], 468 => ['LDXVIII'], 469 => ['LDXIX'], 470 => ['LDXX'], 471 => ['LDXXI'], 472 => ['LDXXII'], 473 => ['LDXXIII'], 474 => ['LDXXIV'], 475 => ['LDXXV'], 476 => ['LDXXVI'], 477 => ['LDXXVII'], 478 => ['LDXXVIII'], 479 => ['LDXXIX'], 480 => ['LDXXX'], 481 => ['LDXXXI'], 482 => ['LDXXXII'], 483 => ['LDXXXIII'], 484 => ['LDXXXIV'], 485 => ['LDXXXV'], 486 => ['LDXXXVI'], 487 => ['LDXXXVII'], 488 => ['LDXXXVIII'], 489 => ['LDXXXIX'], 490 => ['LDXL', 'XD'], 491 => ['LDXLI', 'XDI'], 492 => ['LDXLII', 'XDII'], 493 => ['LDXLIII', 'XDIII'], 494 => ['LDXLIV', 'XDIV'], 495 => ['LDVL', 'XDV', 'VD'], 496 => ['LDVLI', 'XDVI', 'VDI'], 497 => ['LDVLII', 'XDVII', 'VDII'], 498 => ['LDVLIII', 'XDVIII', 'VDIII'], 499 => ['LDVLIV', 'XDIX', 'VDIV', 'ID'], 545 => ['DVL'], 546 => ['DVLI'], 547 => ['DVLII'], 548 => ['DVLIII'], 549 => ['DVLIV', 'DIL'], 595 => ['DVC'], 596 => ['DVCI'], 597 => ['DVCII'], 598 => ['DVCIII'], 599 => ['DVCIV', 'DIC'], 645 => ['DCVL'], 646 => ['DCVLI'], 647 => ['DCVLII'], 648 => ['DCVLIII'], 649 => ['DCVLIV', 'DCIL'], 695 => ['DCVC'], 696 => ['DCVCI'], 697 => ['DCVCII'], 698 => ['DCVCIII'], 699 => ['DCVCIV', 'DCIC'], 745 => ['DCCVL'], 746 => ['DCCVLI'], 747 => ['DCCVLII'], 748 => ['DCCVLIII'], 749 => ['DCCVLIV', 'DCCIL'], 795 => ['DCCVC'], 796 => ['DCCVCI'], 797 => ['DCCVCII'], 798 => ['DCCVCIII'], 799 => ['DCCVCIV', 'DCCIC'], 845 => ['DCCCVL'], 846 => ['DCCCVLI'], 847 => ['DCCCVLII'], 848 => ['DCCCVLIII'], 849 => ['DCCCVLIV', 'DCCCIL'], 895 => ['DCCCVC'], 896 => ['DCCCVCI'], 897 => ['DCCCVCII'], 898 => ['DCCCVCIII'], 899 => ['DCCCVCIV', 'DCCCIC'], 945 => ['CMVL'], 946 => ['CMVLI'], 947 => ['CMVLII'], 948 => ['CMVLIII'], 949 => ['CMVLIV', 'CMIL'], 950 => ['LM'], 951 => ['LMI'], 952 => ['LMII'], 953 => ['LMIII'], 954 => ['LMIV'], 955 => ['LMV'], 956 => ['LMVI'], 957 => ['LMVII'], 958 => ['LMVIII'], 959 => ['LMIX'], 960 => ['LMX'], 961 => ['LMXI'], 962 => ['LMXII'], 963 => ['LMXIII'], 964 => ['LMXIV'], 965 => ['LMXV'], 966 => ['LMXVI'], 967 => ['LMXVII'], 968 => ['LMXVIII'], 969 => ['LMXIX'], 970 => ['LMXX'], 971 => ['LMXXI'], 972 => ['LMXXII'], 973 => ['LMXXIII'], 974 => ['LMXXIV'], 975 => ['LMXXV'], 976 => ['LMXXVI'], 977 => ['LMXXVII'], 978 => ['LMXXVIII'], 979 => ['LMXXIX'], 980 => ['LMXXX'], 981 => ['LMXXXI'], 982 => ['LMXXXII'], 983 => ['LMXXXIII'], 984 => ['LMXXXIV'], 985 => ['LMXXXV'], 986 => ['LMXXXVI'], 987 => ['LMXXXVII'], 988 => ['LMXXXVIII'], 989 => ['LMXXXIX'], 990 => ['LMXL', 'XM'], 991 => ['LMXLI', 'XMI'], 992 => ['LMXLII', 'XMII'], 993 => ['LMXLIII', 'XMIII'], 994 => ['LMXLIV', 'XMIV'], 995 => ['LMVL', 'XMV', 'VM'], 996 => ['LMVLI', 'XMVI', 'VMI'], 997 => ['LMVLII', 'XMVII', 'VMII'], 998 => ['LMVLIII', 'XMVIII', 'VMIII'], 999 => ['LMVLIV', 'XMIX', 'VMIV', 'IM'], 1045 => ['MVL'], 1046 => ['MVLI'], 1047 => ['MVLII'], 1048 => ['MVLIII'], 1049 => ['MVLIV', 'MIL'], 1095 => ['MVC'], 1096 => ['MVCI'], 1097 => ['MVCII'], 1098 => ['MVCIII'], 1099 => ['MVCIV', 'MIC'], 1145 => ['MCVL'], 1146 => ['MCVLI'], 1147 => ['MCVLII'], 1148 => ['MCVLIII'], 1149 => ['MCVLIV', 'MCIL'], 1195 => ['MCVC'], 1196 => ['MCVCI'], 1197 => ['MCVCII'], 1198 => ['MCVCIII'], 1199 => ['MCVCIV', 'MCIC'], 1245 => ['MCCVL'], 1246 => ['MCCVLI'], 1247 => ['MCCVLII'], 1248 => ['MCCVLIII'], 1249 => ['MCCVLIV', 'MCCIL'], 1295 => ['MCCVC'], 1296 => ['MCCVCI'], 1297 => ['MCCVCII'], 1298 => ['MCCVCIII'], 1299 => ['MCCVCIV', 'MCCIC'], 1345 => ['MCCCVL'], 1346 => ['MCCCVLI'], 1347 => ['MCCCVLII'], 1348 => ['MCCCVLIII'], 1349 => ['MCCCVLIV', 'MCCCIL'], 1395 => ['MCCCVC'], 1396 => ['MCCCVCI'], 1397 => ['MCCCVCII'], 1398 => ['MCCCVCIII'], 1399 => ['MCCCVCIV', 'MCCCIC'], 1445 => ['MCDVL'], 1446 => ['MCDVLI'], 1447 => ['MCDVLII'], 1448 => ['MCDVLIII'], 1449 => ['MCDVLIV', 'MCDIL'], 1450 => ['MLD'], 1451 => ['MLDI'], 1452 => ['MLDII'], 1453 => ['MLDIII'], 1454 => ['MLDIV'], 1455 => ['MLDV'], 1456 => ['MLDVI'], 1457 => ['MLDVII'], 1458 => ['MLDVIII'], 1459 => ['MLDIX'], 1460 => ['MLDX'], 1461 => ['MLDXI'], 1462 => ['MLDXII'], 1463 => ['MLDXIII'], 1464 => ['MLDXIV'], 1465 => ['MLDXV'], 1466 => ['MLDXVI'], 1467 => ['MLDXVII'], 1468 => ['MLDXVIII'], 1469 => ['MLDXIX'], 1470 => ['MLDXX'], 1471 => ['MLDXXI'], 1472 => ['MLDXXII'], 1473 => ['MLDXXIII'], 1474 => ['MLDXXIV'], 1475 => ['MLDXXV'], 1476 => ['MLDXXVI'], 1477 => ['MLDXXVII'], 1478 => ['MLDXXVIII'], 1479 => ['MLDXXIX'], 1480 => ['MLDXXX'], 1481 => ['MLDXXXI'], 1482 => ['MLDXXXII'], 1483 => ['MLDXXXIII'], 1484 => ['MLDXXXIV'], 1485 => ['MLDXXXV'], 1486 => ['MLDXXXVI'], 1487 => ['MLDXXXVII'], 1488 => ['MLDXXXVIII'], 1489 => ['MLDXXXIX'], 1490 => ['MLDXL', 'MXD'], 1491 => ['MLDXLI', 'MXDI'], 1492 => ['MLDXLII', 'MXDII'], 1493 => ['MLDXLIII', 'MXDIII'], 1494 => ['MLDXLIV', 'MXDIV'], 1495 => ['MLDVL', 'MXDV', 'MVD'], 1496 => ['MLDVLI', 'MXDVI', 'MVDI'], 1497 => ['MLDVLII', 'MXDVII', 'MVDII'], 1498 => ['MLDVLIII', 'MXDVIII', 'MVDIII'], 1499 => ['MLDVLIV', 'MXDIX', 'MVDIV', 'MID'], 1545 => ['MDVL'], 1546 => ['MDVLI'], 1547 => ['MDVLII'], 1548 => ['MDVLIII'], 1549 => ['MDVLIV', 'MDIL'], 1595 => ['MDVC'], 1596 => ['MDVCI'], 1597 => ['MDVCII'], 1598 => ['MDVCIII'], 1599 => ['MDVCIV', 'MDIC'], 1645 => ['MDCVL'], 1646 => ['MDCVLI'], 1647 => ['MDCVLII'], 1648 => ['MDCVLIII'], 1649 => ['MDCVLIV', 'MDCIL'], 1695 => ['MDCVC'], 1696 => ['MDCVCI'], 1697 => ['MDCVCII'], 1698 => ['MDCVCIII'], 1699 => ['MDCVCIV', 'MDCIC'], 1745 => ['MDCCVL'], 1746 => ['MDCCVLI'], 1747 => ['MDCCVLII'], 1748 => ['MDCCVLIII'], 1749 => ['MDCCVLIV', 'MDCCIL'], 1795 => ['MDCCVC'], 1796 => ['MDCCVCI'], 1797 => ['MDCCVCII'], 1798 => ['MDCCVCIII'], 1799 => ['MDCCVCIV', 'MDCCIC'], 1845 => ['MDCCCVL'], 1846 => ['MDCCCVLI'], 1847 => ['MDCCCVLII'], 1848 => ['MDCCCVLIII'], 1849 => ['MDCCCVLIV', 'MDCCCIL'], 1895 => ['MDCCCVC'], 1896 => ['MDCCCVCI'], 1897 => ['MDCCCVCII'], 1898 => ['MDCCCVCIII'], 1899 => ['MDCCCVCIV', 'MDCCCIC'], 1945 => ['MCMVL'], 1946 => ['MCMVLI'], 1947 => ['MCMVLII'], 1948 => ['MCMVLIII'], 1949 => ['MCMVLIV', 'MCMIL'], 1950 => ['MLM'], 1951 => ['MLMI'], 1952 => ['MLMII'], 1953 => ['MLMIII'], 1954 => ['MLMIV'], 1955 => ['MLMV'], 1956 => ['MLMVI'], 1957 => ['MLMVII'], 1958 => ['MLMVIII'], 1959 => ['MLMIX'], 1960 => ['MLMX'], 1961 => ['MLMXI'], 1962 => ['MLMXII'], 1963 => ['MLMXIII'], 1964 => ['MLMXIV'], 1965 => ['MLMXV'], 1966 => ['MLMXVI'], 1967 => ['MLMXVII'], 1968 => ['MLMXVIII'], 1969 => ['MLMXIX'], 1970 => ['MLMXX'], 1971 => ['MLMXXI'], 1972 => ['MLMXXII'], 1973 => ['MLMXXIII'], 1974 => ['MLMXXIV'], 1975 => ['MLMXXV'], 1976 => ['MLMXXVI'], 1977 => ['MLMXXVII'], 1978 => ['MLMXXVIII'], 1979 => ['MLMXXIX'], 1980 => ['MLMXXX'], 1981 => ['MLMXXXI'], 1982 => ['MLMXXXII'], 1983 => ['MLMXXXIII'], 1984 => ['MLMXXXIV'], 1985 => ['MLMXXXV'], 1986 => ['MLMXXXVI'], 1987 => ['MLMXXXVII'], 1988 => ['MLMXXXVIII'], 1989 => ['MLMXXXIX'], 1990 => ['MLMXL', 'MXM'], 1991 => ['MLMXLI', 'MXMI'], 1992 => ['MLMXLII', 'MXMII'], 1993 => ['MLMXLIII', 'MXMIII'], 1994 => ['MLMXLIV', 'MXMIV'], 1995 => ['MLMVL', 'MXMV', 'MVM'], 1996 => ['MLMVLI', 'MXMVI', 'MVMI'], 1997 => ['MLMVLII', 'MXMVII', 'MVMII'], 1998 => ['MLMVLIII', 'MXMVIII', 'MVMIII'], 1999 => ['MLMVLIV', 'MXMIX', 'MVMIV', 'MIM'], 2045 => ['MMVL'], 2046 => ['MMVLI'], 2047 => ['MMVLII'], 2048 => ['MMVLIII'], 2049 => ['MMVLIV', 'MMIL'], 2095 => ['MMVC'], 2096 => ['MMVCI'], 2097 => ['MMVCII'], 2098 => ['MMVCIII'], 2099 => ['MMVCIV', 'MMIC'], 2145 => ['MMCVL'], 2146 => ['MMCVLI'], 2147 => ['MMCVLII'], 2148 => ['MMCVLIII'], 2149 => ['MMCVLIV', 'MMCIL'], 2195 => ['MMCVC'], 2196 => ['MMCVCI'], 2197 => ['MMCVCII'], 2198 => ['MMCVCIII'], 2199 => ['MMCVCIV', 'MMCIC'], 2245 => ['MMCCVL'], 2246 => ['MMCCVLI'], 2247 => ['MMCCVLII'], 2248 => ['MMCCVLIII'], 2249 => ['MMCCVLIV', 'MMCCIL'], 2295 => ['MMCCVC'], 2296 => ['MMCCVCI'], 2297 => ['MMCCVCII'], 2298 => ['MMCCVCIII'], 2299 => ['MMCCVCIV', 'MMCCIC'], 2345 => ['MMCCCVL'], 2346 => ['MMCCCVLI'], 2347 => ['MMCCCVLII'], 2348 => ['MMCCCVLIII'], 2349 => ['MMCCCVLIV', 'MMCCCIL'], 2395 => ['MMCCCVC'], 2396 => ['MMCCCVCI'], 2397 => ['MMCCCVCII'], 2398 => ['MMCCCVCIII'], 2399 => ['MMCCCVCIV', 'MMCCCIC'], 2445 => ['MMCDVL'], 2446 => ['MMCDVLI'], 2447 => ['MMCDVLII'], 2448 => ['MMCDVLIII'], 2449 => ['MMCDVLIV', 'MMCDIL'], 2450 => ['MMLD'], 2451 => ['MMLDI'], 2452 => ['MMLDII'], 2453 => ['MMLDIII'], 2454 => ['MMLDIV'], 2455 => ['MMLDV'], 2456 => ['MMLDVI'], 2457 => ['MMLDVII'], 2458 => ['MMLDVIII'], 2459 => ['MMLDIX'], 2460 => ['MMLDX'], 2461 => ['MMLDXI'], 2462 => ['MMLDXII'], 2463 => ['MMLDXIII'], 2464 => ['MMLDXIV'], 2465 => ['MMLDXV'], 2466 => ['MMLDXVI'], 2467 => ['MMLDXVII'], 2468 => ['MMLDXVIII'], 2469 => ['MMLDXIX'], 2470 => ['MMLDXX'], 2471 => ['MMLDXXI'], 2472 => ['MMLDXXII'], 2473 => ['MMLDXXIII'], 2474 => ['MMLDXXIV'], 2475 => ['MMLDXXV'], 2476 => ['MMLDXXVI'], 2477 => ['MMLDXXVII'], 2478 => ['MMLDXXVIII'], 2479 => ['MMLDXXIX'], 2480 => ['MMLDXXX'], 2481 => ['MMLDXXXI'], 2482 => ['MMLDXXXII'], 2483 => ['MMLDXXXIII'], 2484 => ['MMLDXXXIV'], 2485 => ['MMLDXXXV'], 2486 => ['MMLDXXXVI'], 2487 => ['MMLDXXXVII'], 2488 => ['MMLDXXXVIII'], 2489 => ['MMLDXXXIX'], 2490 => ['MMLDXL', 'MMXD'], 2491 => ['MMLDXLI', 'MMXDI'], 2492 => ['MMLDXLII', 'MMXDII'], 2493 => ['MMLDXLIII', 'MMXDIII'], 2494 => ['MMLDXLIV', 'MMXDIV'], 2495 => ['MMLDVL', 'MMXDV', 'MMVD'], 2496 => ['MMLDVLI', 'MMXDVI', 'MMVDI'], 2497 => ['MMLDVLII', 'MMXDVII', 'MMVDII'], 2498 => ['MMLDVLIII', 'MMXDVIII', 'MMVDIII'], 2499 => ['MMLDVLIV', 'MMXDIX', 'MMVDIV', 'MMID'], 2545 => ['MMDVL'], 2546 => ['MMDVLI'], 2547 => ['MMDVLII'], 2548 => ['MMDVLIII'], 2549 => ['MMDVLIV', 'MMDIL'], 2595 => ['MMDVC'], 2596 => ['MMDVCI'], 2597 => ['MMDVCII'], 2598 => ['MMDVCIII'], 2599 => ['MMDVCIV', 'MMDIC'], 2645 => ['MMDCVL'], 2646 => ['MMDCVLI'], 2647 => ['MMDCVLII'], 2648 => ['MMDCVLIII'], 2649 => ['MMDCVLIV', 'MMDCIL'], 2695 => ['MMDCVC'], 2696 => ['MMDCVCI'], 2697 => ['MMDCVCII'], 2698 => ['MMDCVCIII'], 2699 => ['MMDCVCIV', 'MMDCIC'], 2745 => ['MMDCCVL'], 2746 => ['MMDCCVLI'], 2747 => ['MMDCCVLII'], 2748 => ['MMDCCVLIII'], 2749 => ['MMDCCVLIV', 'MMDCCIL'], 2795 => ['MMDCCVC'], 2796 => ['MMDCCVCI'], 2797 => ['MMDCCVCII'], 2798 => ['MMDCCVCIII'], 2799 => ['MMDCCVCIV', 'MMDCCIC'], 2845 => ['MMDCCCVL'], 2846 => ['MMDCCCVLI'], 2847 => ['MMDCCCVLII'], 2848 => ['MMDCCCVLIII'], 2849 => ['MMDCCCVLIV', 'MMDCCCIL'], 2895 => ['MMDCCCVC'], 2896 => ['MMDCCCVCI'], 2897 => ['MMDCCCVCII'], 2898 => ['MMDCCCVCIII'], 2899 => ['MMDCCCVCIV', 'MMDCCCIC'], 2945 => ['MMCMVL'], 2946 => ['MMCMVLI'], 2947 => ['MMCMVLII'], 2948 => ['MMCMVLIII'], 2949 => ['MMCMVLIV', 'MMCMIL'], 2950 => ['MMLM'], 2951 => ['MMLMI'], 2952 => ['MMLMII'], 2953 => ['MMLMIII'], 2954 => ['MMLMIV'], 2955 => ['MMLMV'], 2956 => ['MMLMVI'], 2957 => ['MMLMVII'], 2958 => ['MMLMVIII'], 2959 => ['MMLMIX'], 2960 => ['MMLMX'], 2961 => ['MMLMXI'], 2962 => ['MMLMXII'], 2963 => ['MMLMXIII'], 2964 => ['MMLMXIV'], 2965 => ['MMLMXV'], 2966 => ['MMLMXVI'], 2967 => ['MMLMXVII'], 2968 => ['MMLMXVIII'], 2969 => ['MMLMXIX'], 2970 => ['MMLMXX'], 2971 => ['MMLMXXI'], 2972 => ['MMLMXXII'], 2973 => ['MMLMXXIII'], 2974 => ['MMLMXXIV'], 2975 => ['MMLMXXV'], 2976 => ['MMLMXXVI'], 2977 => ['MMLMXXVII'], 2978 => ['MMLMXXVIII'], 2979 => ['MMLMXXIX'], 2980 => ['MMLMXXX'], 2981 => ['MMLMXXXI'], 2982 => ['MMLMXXXII'], 2983 => ['MMLMXXXIII'], 2984 => ['MMLMXXXIV'], 2985 => ['MMLMXXXV'], 2986 => ['MMLMXXXVI'], 2987 => ['MMLMXXXVII'], 2988 => ['MMLMXXXVIII'], 2989 => ['MMLMXXXIX'], 2990 => ['MMLMXL', 'MMXM'], 2991 => ['MMLMXLI', 'MMXMI'], 2992 => ['MMLMXLII', 'MMXMII'], 2993 => ['MMLMXLIII', 'MMXMIII'], 2994 => ['MMLMXLIV', 'MMXMIV'], 2995 => ['MMLMVL', 'MMXMV', 'MMVM'], 2996 => ['MMLMVLI', 'MMXMVI', 'MMVMI'], 2997 => ['MMLMVLII', 'MMXMVII', 'MMVMII'], 2998 => ['MMLMVLIII', 'MMXMVIII', 'MMVMIII'], 2999 => ['MMLMVLIV', 'MMXMIX', 'MMVMIV', 'MMIM'], 3045 => ['MMMVL'], 3046 => ['MMMVLI'], 3047 => ['MMMVLII'], 3048 => ['MMMVLIII'], 3049 => ['MMMVLIV', 'MMMIL'], 3095 => ['MMMVC'], 3096 => ['MMMVCI'], 3097 => ['MMMVCII'], 3098 => ['MMMVCIII'], 3099 => ['MMMVCIV', 'MMMIC'], 3145 => ['MMMCVL'], 3146 => ['MMMCVLI'], 3147 => ['MMMCVLII'], 3148 => ['MMMCVLIII'], 3149 => ['MMMCVLIV', 'MMMCIL'], 3195 => ['MMMCVC'], 3196 => ['MMMCVCI'], 3197 => ['MMMCVCII'], 3198 => ['MMMCVCIII'], 3199 => ['MMMCVCIV', 'MMMCIC'], 3245 => ['MMMCCVL'], 3246 => ['MMMCCVLI'], 3247 => ['MMMCCVLII'], 3248 => ['MMMCCVLIII'], 3249 => ['MMMCCVLIV', 'MMMCCIL'], 3295 => ['MMMCCVC'], 3296 => ['MMMCCVCI'], 3297 => ['MMMCCVCII'], 3298 => ['MMMCCVCIII'], 3299 => ['MMMCCVCIV', 'MMMCCIC'], 3345 => ['MMMCCCVL'], 3346 => ['MMMCCCVLI'], 3347 => ['MMMCCCVLII'], 3348 => ['MMMCCCVLIII'], 3349 => ['MMMCCCVLIV', 'MMMCCCIL'], 3395 => ['MMMCCCVC'], 3396 => ['MMMCCCVCI'], 3397 => ['MMMCCCVCII'], 3398 => ['MMMCCCVCIII'], 3399 => ['MMMCCCVCIV', 'MMMCCCIC'], 3445 => ['MMMCDVL'], 3446 => ['MMMCDVLI'], 3447 => ['MMMCDVLII'], 3448 => ['MMMCDVLIII'], 3449 => ['MMMCDVLIV', 'MMMCDIL'], 3450 => ['MMMLD'], 3451 => ['MMMLDI'], 3452 => ['MMMLDII'], 3453 => ['MMMLDIII'], 3454 => ['MMMLDIV'], 3455 => ['MMMLDV'], 3456 => ['MMMLDVI'], 3457 => ['MMMLDVII'], 3458 => ['MMMLDVIII'], 3459 => ['MMMLDIX'], 3460 => ['MMMLDX'], 3461 => ['MMMLDXI'], 3462 => ['MMMLDXII'], 3463 => ['MMMLDXIII'], 3464 => ['MMMLDXIV'], 3465 => ['MMMLDXV'], 3466 => ['MMMLDXVI'], 3467 => ['MMMLDXVII'], 3468 => ['MMMLDXVIII'], 3469 => ['MMMLDXIX'], 3470 => ['MMMLDXX'], 3471 => ['MMMLDXXI'], 3472 => ['MMMLDXXII'], 3473 => ['MMMLDXXIII'], 3474 => ['MMMLDXXIV'], 3475 => ['MMMLDXXV'], 3476 => ['MMMLDXXVI'], 3477 => ['MMMLDXXVII'], 3478 => ['MMMLDXXVIII'], 3479 => ['MMMLDXXIX'], 3480 => ['MMMLDXXX'], 3481 => ['MMMLDXXXI'], 3482 => ['MMMLDXXXII'], 3483 => ['MMMLDXXXIII'], 3484 => ['MMMLDXXXIV'], 3485 => ['MMMLDXXXV'], 3486 => ['MMMLDXXXVI'], 3487 => ['MMMLDXXXVII'], 3488 => ['MMMLDXXXVIII'], 3489 => ['MMMLDXXXIX'], 3490 => ['MMMLDXL', 'MMMXD'], 3491 => ['MMMLDXLI', 'MMMXDI'], 3492 => ['MMMLDXLII', 'MMMXDII'], 3493 => ['MMMLDXLIII', 'MMMXDIII'], 3494 => ['MMMLDXLIV', 'MMMXDIV'], 3495 => ['MMMLDVL', 'MMMXDV', 'MMMVD'], 3496 => ['MMMLDVLI', 'MMMXDVI', 'MMMVDI'], 3497 => ['MMMLDVLII', 'MMMXDVII', 'MMMVDII'], 3498 => ['MMMLDVLIII', 'MMMXDVIII', 'MMMVDIII'], 3499 => ['MMMLDVLIV', 'MMMXDIX', 'MMMVDIV', 'MMMID'], 3545 => ['MMMDVL'], 3546 => ['MMMDVLI'], 3547 => ['MMMDVLII'], 3548 => ['MMMDVLIII'], 3549 => ['MMMDVLIV', 'MMMDIL'], 3595 => ['MMMDVC'], 3596 => ['MMMDVCI'], 3597 => ['MMMDVCII'], 3598 => ['MMMDVCIII'], 3599 => ['MMMDVCIV', 'MMMDIC'], 3645 => ['MMMDCVL'], 3646 => ['MMMDCVLI'], 3647 => ['MMMDCVLII'], 3648 => ['MMMDCVLIII'], 3649 => ['MMMDCVLIV', 'MMMDCIL'], 3695 => ['MMMDCVC'], 3696 => ['MMMDCVCI'], 3697 => ['MMMDCVCII'], 3698 => ['MMMDCVCIII'], 3699 => ['MMMDCVCIV', 'MMMDCIC'], 3745 => ['MMMDCCVL'], 3746 => ['MMMDCCVLI'], 3747 => ['MMMDCCVLII'], 3748 => ['MMMDCCVLIII'], 3749 => ['MMMDCCVLIV', 'MMMDCCIL'], 3795 => ['MMMDCCVC'], 3796 => ['MMMDCCVCI'], 3797 => ['MMMDCCVCII'], 3798 => ['MMMDCCVCIII'], 3799 => ['MMMDCCVCIV', 'MMMDCCIC'], 3845 => ['MMMDCCCVL'], 3846 => ['MMMDCCCVLI'], 3847 => ['MMMDCCCVLII'], 3848 => ['MMMDCCCVLIII'], 3849 => ['MMMDCCCVLIV', 'MMMDCCCIL'], 3895 => ['MMMDCCCVC'], 3896 => ['MMMDCCCVCI'], 3897 => ['MMMDCCCVCII'], 3898 => ['MMMDCCCVCIII'], 3899 => ['MMMDCCCVCIV', 'MMMDCCCIC'], 3945 => ['MMMCMVL'], 3946 => ['MMMCMVLI'], 3947 => ['MMMCMVLII'], 3948 => ['MMMCMVLIII'], 3949 => ['MMMCMVLIV', 'MMMCMIL'], 3950 => ['MMMLM'], 3951 => ['MMMLMI'], 3952 => ['MMMLMII'], 3953 => ['MMMLMIII'], 3954 => ['MMMLMIV'], 3955 => ['MMMLMV'], 3956 => ['MMMLMVI'], 3957 => ['MMMLMVII'], 3958 => ['MMMLMVIII'], 3959 => ['MMMLMIX'], 3960 => ['MMMLMX'], 3961 => ['MMMLMXI'], 3962 => ['MMMLMXII'], 3963 => ['MMMLMXIII'], 3964 => ['MMMLMXIV'], 3965 => ['MMMLMXV'], 3966 => ['MMMLMXVI'], 3967 => ['MMMLMXVII'], 3968 => ['MMMLMXVIII'], 3969 => ['MMMLMXIX'], 3970 => ['MMMLMXX'], 3971 => ['MMMLMXXI'], 3972 => ['MMMLMXXII'], 3973 => ['MMMLMXXIII'], 3974 => ['MMMLMXXIV'], 3975 => ['MMMLMXXV'], 3976 => ['MMMLMXXVI'], 3977 => ['MMMLMXXVII'], 3978 => ['MMMLMXXVIII'], 3979 => ['MMMLMXXIX'], 3980 => ['MMMLMXXX'], 3981 => ['MMMLMXXXI'], 3982 => ['MMMLMXXXII'], 3983 => ['MMMLMXXXIII'], 3984 => ['MMMLMXXXIV'], 3985 => ['MMMLMXXXV'], 3986 => ['MMMLMXXXVI'], 3987 => ['MMMLMXXXVII'], 3988 => ['MMMLMXXXVIII'], 3989 => ['MMMLMXXXIX'], 3990 => ['MMMLMXL', 'MMMXM'], 3991 => ['MMMLMXLI', 'MMMXMI'], 3992 => ['MMMLMXLII', 'MMMXMII'], 3993 => ['MMMLMXLIII', 'MMMXMIII'], 3994 => ['MMMLMXLIV', 'MMMXMIV'], 3995 => ['MMMLMVL', 'MMMXMV', 'MMMVM'], 3996 => ['MMMLMVLI', 'MMMXMVI', 'MMMVMI'], 3997 => ['MMMLMVLII', 'MMMXMVII', 'MMMVMII'], 3998 => ['MMMLMVLIII', 'MMMXMVIII', 'MMMVMIII'], 3999 => ['MMMLMVLIV', 'MMMXMIX', 'MMMVMIV', 'MMMIM'], ]; private const THOUSANDS = ['', 'M', 'MM', 'MMM']; private const HUNDREDS = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']; private const TENS = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']; private const ONES = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; const MAX_ROMAN_VALUE = 3999; const MAX_ROMAN_STYLE = 4; private static function valueOk(int $aValue, int $style): string { $origValue = $aValue; $m = \intdiv($aValue, 1000); $aValue %= 1000; $c = \intdiv($aValue, 100); $aValue %= 100; $t = \intdiv($aValue, 10); $aValue %= 10; $result = self::THOUSANDS[$m] . self::HUNDREDS[$c] . self::TENS[$t] . self::ONES[$aValue]; if ($style > 0) { if (array_key_exists($origValue, self::VALUES)) { $arr = self::VALUES[$origValue]; $idx = min($style, count($arr)) - 1; $result = $arr[$idx]; } } return $result; } private static function styleOk(int $aValue, int $style): string { return ($aValue < 0 || $aValue > self::MAX_ROMAN_VALUE) ? ExcelError::VALUE() : self::valueOk($aValue, $style); } public static function calculateRoman(int $aValue, int $style): string { return ($style < 0 || $style > self::MAX_ROMAN_STYLE) ? ExcelError::VALUE() : self::styleOk($aValue, $style); } /** * ROMAN. * * Converts a number to Roman numeral * * @param mixed $aValue Number to convert * Or can be an array of numbers * @param mixed $style Number indicating one of five possible forms * Or can be an array of styles * * @return array|string Roman numeral, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($aValue, $style = 0) { if (is_array($aValue) || is_array($style)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $aValue, $style); } try { $aValue = Helpers::validateNumericNullBool($aValue); if (is_bool($style)) { $style = $style ? 0 : 4; } $style = Helpers::validateNumericNullSubstitution($style, null); } catch (Exception $e) { return $e->getMessage(); } return self::calculateRoman((int) $aValue, (int) $style); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php 0000644 00000006254 15002227416 0022076 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Logarithms { use ArrayEnabled; /** * LOG_BASE. * * Returns the logarithm of a number to a specified base. The default base is 10. * * Excel Function: * LOG(number[,base]) * * @param mixed $number The positive real number for which you want the logarithm * Or can be an array of values * @param mixed $base The base of the logarithm. If base is omitted, it is assumed to be 10. * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function withBase($number, $base = 10) { if (is_array($number) || is_array($base)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $base); } try { $number = Helpers::validateNumericNullBool($number); Helpers::validatePositive($number); $base = Helpers::validateNumericNullBool($base); Helpers::validatePositive($base); } catch (Exception $e) { return $e->getMessage(); } return log($number, $base); } /** * LOG10. * * Returns the result of builtin function log after validating args. * * @param mixed $number Should be numeric * Or can be an array of values * * @return array|float|string Rounded number * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function base10($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); Helpers::validatePositive($number); } catch (Exception $e) { return $e->getMessage(); } return log10($number); } /** * LN. * * Returns the result of builtin function log after validating args. * * @param mixed $number Should be numeric * Or can be an array of values * * @return array|float|string Rounded number * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function natural($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); Helpers::validatePositive($number); } catch (Exception $e) { return $e->getMessage(); } return log($number); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Operations.php 0000644 00000011604 15002227416 0022103 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Operations { use ArrayEnabled; /** * MOD. * * @param mixed $dividend Dividend * Or can be an array of values * @param mixed $divisor Divisor * Or can be an array of values * * @return array|float|int|string Remainder, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function mod($dividend, $divisor) { if (is_array($dividend) || is_array($divisor)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $dividend, $divisor); } try { $dividend = Helpers::validateNumericNullBool($dividend); $divisor = Helpers::validateNumericNullBool($divisor); Helpers::validateNotZero($divisor); } catch (Exception $e) { return $e->getMessage(); } if (($dividend < 0.0) && ($divisor > 0.0)) { return $divisor - fmod(abs($dividend), $divisor); } if (($dividend > 0.0) && ($divisor < 0.0)) { return $divisor + fmod($dividend, abs($divisor)); } return fmod($dividend, $divisor); } /** * POWER. * * Computes x raised to the power y. * * @param array|float|int $x * Or can be an array of values * @param array|float|int $y * Or can be an array of values * * @return array|float|int|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function power($x, $y) { if (is_array($x) || is_array($y)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $y); } try { $x = Helpers::validateNumericNullBool($x); $y = Helpers::validateNumericNullBool($y); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if (!$x && !$y) { return ExcelError::NAN(); } if (!$x && $y < 0.0) { return ExcelError::DIV0(); } // Return $result = $x ** $y; return Helpers::numberOrNan($result); } /** * PRODUCT. * * PRODUCT returns the product of all the values and cells referenced in the argument list. * * Excel Function: * PRODUCT(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function product(...$args) { $args = array_filter( Functions::flattenArray($args), function ($value) { return $value !== null; } ); // Return value $returnValue = (count($args) === 0) ? 0.0 : 1.0; // Loop through arguments foreach ($args as $arg) { // Is it a numeric value? if (is_numeric($arg)) { $returnValue *= $arg; } else { return ExcelError::throwError($arg); } } return (float) $returnValue; } /** * QUOTIENT. * * QUOTIENT function returns the integer portion of a division. Numerator is the divided number * and denominator is the divisor. * * Excel Function: * QUOTIENT(value1,value2) * * @param mixed $numerator Expect float|int * Or can be an array of values * @param mixed $denominator Expect float|int * Or can be an array of values * * @return array|int|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function quotient($numerator, $denominator) { if (is_array($numerator) || is_array($denominator)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numerator, $denominator); } try { $numerator = Helpers::validateNumericNullSubstitution($numerator, 0); $denominator = Helpers::validateNumericNullSubstitution($denominator, 0); Helpers::validateNotZero($denominator); } catch (Exception $e) { return $e->getMessage(); } return (int) ($numerator / $denominator); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php 0000644 00000002766 15002227416 0021064 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Trunc { use ArrayEnabled; /** * TRUNC. * * Truncates value to the number of fractional digits by number_digits. * * @param array|float $value * Or can be an array of values * @param array|int $digits * Or can be an array of values * * @return array|float|string Truncated value, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($value = 0, $digits = 0) { if (is_array($value) || is_array($digits)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $digits); } try { $value = Helpers::validateNumericNullBool($value); $digits = Helpers::validateNumericNullSubstitution($digits, null); } catch (Exception $e) { return $e->getMessage(); } $digits = floor($digits); // Truncate $adjust = 10 ** $digits; if (($digits > 0) && (rtrim((string) (int) ((abs($value) - abs((int) $value)) * $adjust), '0') < $adjust / 10)) { return $value; } return ((int) ($value * $adjust)) / $adjust; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sign.php 0000644 00000002145 15002227416 0020660 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Sign { use ArrayEnabled; /** * SIGN. * * Determines the sign of a number. Returns 1 if the number is positive, zero (0) * if the number is 0, and -1 if the number is negative. * * @param array|float $number Number to round, or can be an array of numbers * * @return array|int|string sign value, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::returnSign($number); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php 0000644 00000011213 15002227416 0021551 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical; class Subtotal { /** * @param mixed $cellReference * @param mixed $args */ protected static function filterHiddenArgs($cellReference, $args): array { return array_filter( $args, function ($index) use ($cellReference) { $explodeArray = explode('.', $index); $row = $explodeArray[1] ?? ''; if (!is_numeric($row)) { return true; } return $cellReference->getWorksheet()->getRowDimension($row)->getVisible(); }, ARRAY_FILTER_USE_KEY ); } /** * @param mixed $cellReference * @param mixed $args */ protected static function filterFormulaArgs($cellReference, $args): array { return array_filter( $args, function ($index) use ($cellReference) { $explodeArray = explode('.', $index); $row = $explodeArray[1] ?? ''; $column = $explodeArray[2] ?? ''; $retVal = true; if ($cellReference->getWorksheet()->cellExists($column . $row)) { //take this cell out if it contains the SUBTOTAL or AGGREGATE functions in a formula $isFormula = $cellReference->getWorksheet()->getCell($column . $row)->isFormula(); $cellFormula = !preg_match( '/^=.*\b(SUBTOTAL|AGGREGATE)\s*\(/i', $cellReference->getWorksheet()->getCell($column . $row)->getValue() ?? '' ); $retVal = !$isFormula || $cellFormula; } return $retVal; }, ARRAY_FILTER_USE_KEY ); } private const CALL_FUNCTIONS = [ 1 => [Statistical\Averages::class, 'average'], // 1 and 101 [Statistical\Counts::class, 'COUNT'], // 2 and 102 [Statistical\Counts::class, 'COUNTA'], // 3 and 103 [Statistical\Maximum::class, 'max'], // 4 and 104 [Statistical\Minimum::class, 'min'], // 5 and 105 [Operations::class, 'product'], // 6 and 106 [Statistical\StandardDeviations::class, 'STDEV'], // 7 and 107 [Statistical\StandardDeviations::class, 'STDEVP'], // 8 and 108 [Sum::class, 'sumIgnoringStrings'], // 9 and 109 [Statistical\Variances::class, 'VAR'], // 10 and 110 [Statistical\Variances::class, 'VARP'], // 111 and 111 ]; /** * SUBTOTAL. * * Returns a subtotal in a list or database. * * @param mixed $functionType * A number 1 to 11 that specifies which function to * use in calculating subtotals within a range * list * Numbers 101 to 111 shadow the functions of 1 to 11 * but ignore any values in the range that are * in hidden rows * @param mixed[] $args A mixed data series of values * * @return float|string */ public static function evaluate($functionType, ...$args) { $cellReference = array_pop($args); $bArgs = Functions::flattenArrayIndexed($args); $aArgs = []; // int keys must come before string keys for PHP 8.0+ // Otherwise, PHP thinks positional args follow keyword // in the subsequent call to call_user_func_array. // Fortunately, order of args is unimportant to Subtotal. foreach ($bArgs as $key => $value) { if (is_int($key)) { $aArgs[$key] = $value; } } foreach ($bArgs as $key => $value) { if (!is_int($key)) { $aArgs[$key] = $value; } } try { $subtotal = (int) Helpers::validateNumericNullBool($functionType); } catch (Exception $e) { return $e->getMessage(); } // Calculate if ($subtotal > 100) { $aArgs = self::filterHiddenArgs($cellReference, $aArgs); $subtotal -= 100; } $aArgs = self::filterFormulaArgs($cellReference, $aArgs); if (array_key_exists($subtotal, self::CALL_FUNCTIONS)) { /** @var callable */ $call = self::CALL_FUNCTIONS[$subtotal]; return call_user_func_array($call, $aArgs); } return ExcelError::VALUE(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php 0000644 00000005641 15002227416 0021145 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Arabic { use ArrayEnabled; private const ROMAN_LOOKUP = [ 'M' => 1000, 'D' => 500, 'C' => 100, 'L' => 50, 'X' => 10, 'V' => 5, 'I' => 1, ]; /** * Recursively calculate the arabic value of a roman numeral. * * @param int $sum * @param int $subtract * * @return int */ private static function calculateArabic(array $roman, &$sum = 0, $subtract = 0) { $numeral = array_shift($roman); if (!isset(self::ROMAN_LOOKUP[$numeral])) { throw new Exception('Invalid character detected'); } $arabic = self::ROMAN_LOOKUP[$numeral]; if (count($roman) > 0 && isset(self::ROMAN_LOOKUP[$roman[0]]) && $arabic < self::ROMAN_LOOKUP[$roman[0]]) { $subtract += $arabic; } else { $sum += ($arabic - $subtract); $subtract = 0; } if (count($roman) > 0) { self::calculateArabic($roman, $sum, $subtract); } return $sum; } /** * @param mixed $value */ private static function mollifyScrutinizer($value): array { return is_array($value) ? $value : []; } private static function strSplit(string $roman): array { $rslt = str_split($roman); return self::mollifyScrutinizer($rslt); } /** * ARABIC. * * Converts a Roman numeral to an Arabic numeral. * * Excel Function: * ARABIC(text) * * @param mixed $roman Should be a string, or can be an array of strings * * @return array|int|string the arabic numberal contrived from the roman numeral * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($roman) { if (is_array($roman)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $roman); } // An empty string should return 0 $roman = substr(trim(strtoupper((string) $roman)), 0, 255); if ($roman === '') { return 0; } // Convert the roman numeral to an arabic number $negativeNumber = $roman[0] === '-'; if ($negativeNumber) { $roman = substr($roman, 1); } try { $arabic = self::calculateArabic(self::strSplit($roman)); } catch (Exception $e) { return ExcelError::VALUE(); // Invalid character detected } if ($negativeNumber) { $arabic *= -1; // The number should be negative } return $arabic; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php 0000644 00000013725 15002227416 0021340 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Ceiling { use ArrayEnabled; /** * CEILING. * * Returns number rounded up, away from zero, to the nearest multiple of significance. * For example, if you want to avoid using pennies in your prices and your product is * priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the * nearest nickel. * * Excel Function: * CEILING(number[,significance]) * * @param array|float $number the number you want the ceiling * Or can be an array of values * @param array|float $significance the multiple to which you want to round * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ceiling($number, $significance = null) { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } if ($significance === null) { self::floorCheck1Arg(); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); } catch (Exception $e) { return $e->getMessage(); } return self::argumentsOk((float) $number, (float) $significance); } /** * CEILING.MATH. * * Round a number down to the nearest integer or to the nearest multiple of significance. * * Excel Function: * CEILING.MATH(number[,significance[,mode]]) * * @param mixed $number Number to round * Or can be an array of values * @param mixed $significance Significance * Or can be an array of values * @param array|int $mode direction to round negative numbers * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function math($number, $significance = null, $mode = 0) { if (is_array($number) || is_array($significance) || is_array($mode)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance, $mode); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); $mode = Helpers::validateNumericNullSubstitution($mode, null); } catch (Exception $e) { return $e->getMessage(); } if (empty($significance * $number)) { return 0.0; } if (self::ceilingMathTest((float) $significance, (float) $number, (int) $mode)) { return floor($number / $significance) * $significance; } return ceil($number / $significance) * $significance; } /** * CEILING.PRECISE. * * Rounds number up, away from zero, to the nearest multiple of significance. * * Excel Function: * CEILING.PRECISE(number[,significance]) * * @param mixed $number the number you want to round * Or can be an array of values * @param array|float $significance the multiple to which you want to round * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function precise($number, $significance = 1) { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, null); } catch (Exception $e) { return $e->getMessage(); } if (!$significance) { return 0.0; } $result = $number / abs($significance); return ceil($result) * $significance * (($significance < 0) ? -1 : 1); } /** * Let CEILINGMATH complexity pass Scrutinizer. */ private static function ceilingMathTest(float $significance, float $number, int $mode): bool { return ((float) $significance < 0) || ((float) $number < 0 && !empty($mode)); } /** * Avoid Scrutinizer problems concerning complexity. * * @return float|string */ private static function argumentsOk(float $number, float $significance) { if (empty($number * $significance)) { return 0.0; } if (Helpers::returnSign($number) == Helpers::returnSign($significance)) { return ceil($number / $significance) * $significance; } return ExcelError::NAN(); } private static function floorCheck1Arg(): void { $compatibility = Functions::getCompatibilityMode(); if ($compatibility === Functions::COMPATIBILITY_EXCEL) { throw new Exception('Excel requires 2 arguments for CEILING'); } } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php 0000644 00000006522 15002227416 0021566 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Sine { use ArrayEnabled; /** * SIN. * * Returns the result of builtin function sin after validating args. * * @param mixed $angle Should be numeric, or can be an array of numbers * * @return array|float|string sine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sin($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return sin($angle); } /** * SINH. * * Returns the result of builtin function sinh after validating args. * * @param mixed $angle Should be numeric, or can be an array of numbers * * @return array|float|string hyperbolic sine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sinh($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return sinh($angle); } /** * ASIN. * * Returns the arcsine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arcsine of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function asin($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(asin($number)); } /** * ASINH. * * Returns the inverse hyperbolic sine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The inverse hyperbolic sine of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function asinh($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(asinh($number)); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php 0000644 00000003505 15002227416 0022103 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Secant { use ArrayEnabled; /** * SEC. * * Returns the secant of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The secant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sec($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, cos($angle)); } /** * SECH. * * Returns the hyperbolic secant of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The hyperbolic secant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sech($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, cosh($angle)); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php 0000644 00000012667 15002227416 0022277 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Tangent { use ArrayEnabled; /** * TAN. * * Returns the result of builtin function tan after validating args. * * @param mixed $angle Should be numeric, or can be an array of numbers * * @return array|float|string tangent * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function tan($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(sin($angle), cos($angle)); } /** * TANH. * * Returns the result of builtin function sinh after validating args. * * @param mixed $angle Should be numeric, or can be an array of numbers * * @return array|float|string hyperbolic tangent * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function tanh($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return tanh($angle); } /** * ATAN. * * Returns the arctangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arctangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function atan($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(atan($number)); } /** * ATANH. * * Returns the inverse hyperbolic tangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The inverse hyperbolic tangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function atanh($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(atanh($number)); } /** * ATAN2. * * This function calculates the arc tangent of the two variables x and y. It is similar to * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used * to determine the quadrant of the result. * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between * -pi and pi, excluding -pi. * * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function. * * Excel Function: * ATAN2(xCoordinate,yCoordinate) * * @param mixed $xCoordinate should be float, the x-coordinate of the point, or can be an array of numbers * @param mixed $yCoordinate should be float, the y-coordinate of the point, or can be an array of numbers * * @return array|float|string * The inverse tangent of the specified x- and y-coordinates, or a string containing an error * If an array of numbers is passed as one of the arguments, then the returned result will also be an array * with the same dimensions */ public static function atan2($xCoordinate, $yCoordinate) { if (is_array($xCoordinate) || is_array($yCoordinate)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $xCoordinate, $yCoordinate); } try { $xCoordinate = Helpers::validateNumericNullBool($xCoordinate); $yCoordinate = Helpers::validateNumericNullBool($yCoordinate); } catch (Exception $e) { return $e->getMessage(); } if (($xCoordinate == 0) && ($yCoordinate == 0)) { return ExcelError::DIV0(); } return atan2($yCoordinate, $xCoordinate); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php 0000644 00000006606 15002227416 0022113 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Cosine { use ArrayEnabled; /** * COS. * * Returns the result of builtin function cos after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string cosine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function cos($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return cos($number); } /** * COSH. * * Returns the result of builtin function cosh after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string hyperbolic cosine * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function cosh($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return cosh($number); } /** * ACOS. * * Returns the arccosine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arccosine of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acos($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(acos($number)); } /** * ACOSH. * * Returns the arc inverse hyperbolic cosine of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The inverse hyperbolic cosine of the number, or an error string * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acosh($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(acosh($number)); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php 0000644 00000006744 15002227416 0022620 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Cotangent { use ArrayEnabled; /** * COT. * * Returns the cotangent of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The cotangent of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function cot($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(cos($angle), sin($angle)); } /** * COTH. * * Returns the hyperbolic cotangent of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The hyperbolic cotangent of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function coth($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, tanh($angle)); } /** * ACOT. * * Returns the arccotangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The arccotangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acot($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return (M_PI / 2) - atan($number); } /** * ACOTH. * * Returns the hyperbolic arccotangent of a number. * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string The hyperbolic arccotangent of the number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function acoth($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } $result = ($number === 1) ? NAN : (log(($number + 1) / ($number - 1)) / 2); return Helpers::numberOrNan($result); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php 0000644 00000003517 15002227416 0022430 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Trig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers; class Cosecant { use ArrayEnabled; /** * CSC. * * Returns the cosecant of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The cosecant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function csc($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, sin($angle)); } /** * CSCH. * * Returns the hyperbolic cosecant of an angle. * * @param array|float $angle Number, or can be an array of numbers * * @return array|float|string The hyperbolic cosecant of the angle * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function csch($angle) { if (is_array($angle)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); } try { $angle = Helpers::validateNumericNullBool($angle); } catch (Exception $e) { return $e->getMessage(); } return Helpers::verySmallDenominator(1.0, sinh($angle)); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Round.php 0000644 00000016457 15002227416 0021062 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Round { use ArrayEnabled; /** * ROUND. * * Returns the result of builtin function round after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * @param mixed $precision Should be int, or can be an array of numbers * * @return array|float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function round($number, $precision) { if (is_array($number) || is_array($precision)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $precision); } try { $number = Helpers::validateNumericNullBool($number); $precision = Helpers::validateNumericNullBool($precision); } catch (Exception $e) { return $e->getMessage(); } return round($number, (int) $precision); } /** * ROUNDUP. * * Rounds a number up to a specified number of decimal places * * @param array|float $number Number to round, or can be an array of numbers * @param array|int $digits Number of digits to which you want to round $number, or can be an array of numbers * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function up($number, $digits) { if (is_array($number) || is_array($digits)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $digits); } try { $number = Helpers::validateNumericNullBool($number); $digits = (int) Helpers::validateNumericNullSubstitution($digits, null); } catch (Exception $e) { return $e->getMessage(); } if ($number == 0.0) { return 0.0; } if ($number < 0.0) { return round($number - 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN); } return round($number + 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN); } /** * ROUNDDOWN. * * Rounds a number down to a specified number of decimal places * * @param array|float $number Number to round, or can be an array of numbers * @param array|int $digits Number of digits to which you want to round $number, or can be an array of numbers * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function down($number, $digits) { if (is_array($number) || is_array($digits)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $digits); } try { $number = Helpers::validateNumericNullBool($number); $digits = (int) Helpers::validateNumericNullSubstitution($digits, null); } catch (Exception $e) { return $e->getMessage(); } if ($number == 0.0) { return 0.0; } if ($number < 0.0) { return round($number + 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_UP); } return round($number - 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_UP); } /** * MROUND. * * Rounds a number to the nearest multiple of a specified value * * @param mixed $number Expect float. Number to round, or can be an array of numbers * @param mixed $multiple Expect int. Multiple to which you want to round, or can be an array of numbers. * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function multiple($number, $multiple) { if (is_array($number) || is_array($multiple)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $multiple); } try { $number = Helpers::validateNumericNullSubstitution($number, 0); $multiple = Helpers::validateNumericNullSubstitution($multiple, null); } catch (Exception $e) { return $e->getMessage(); } if ($number == 0 || $multiple == 0) { return 0; } if ((Helpers::returnSign($number)) == (Helpers::returnSign($multiple))) { $multiplier = 1 / $multiple; return round($number * $multiplier) / $multiplier; } return ExcelError::NAN(); } /** * EVEN. * * Returns number rounded up to the nearest even integer. * You can use this function for processing items that come in twos. For example, * a packing crate accepts rows of one or two items. The crate is full when * the number of items, rounded up to the nearest two, matches the crate's * capacity. * * Excel Function: * EVEN(number) * * @param array|float $number Number to round, or can be an array of numbers * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function even($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::getEven($number); } /** * ODD. * * Returns number rounded up to the nearest odd integer. * * @param array|float $number Number to round, or can be an array of numbers * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function odd($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } $significance = Helpers::returnSign($number); if ($significance == 0) { return 1; } $result = ceil($number / $significance) * $significance; if ($result == Helpers::getEven($result)) { $result += $significance; } return $result; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php 0000644 00000012271 15002227416 0023116 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use Matrix\Builder; use Matrix\Div0Exception as MatrixDiv0Exception; use Matrix\Exception as MatrixException; use Matrix\Matrix; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class MatrixFunctions { /** * Convert parameter to Matrix. * * @param mixed $matrixValues A matrix of values */ private static function getMatrix($matrixValues): Matrix { $matrixData = []; if (!is_array($matrixValues)) { $matrixValues = [[$matrixValues]]; } $row = 0; foreach ($matrixValues as $matrixRow) { if (!is_array($matrixRow)) { $matrixRow = [$matrixRow]; } $column = 0; foreach ($matrixRow as $matrixCell) { if ((is_string($matrixCell)) || ($matrixCell === null)) { throw new Exception(ExcelError::VALUE()); } $matrixData[$row][$column] = $matrixCell; ++$column; } ++$row; } return new Matrix($matrixData); } /** * SEQUENCE. * * Generates a list of sequential numbers in an array. * * Excel Function: * SEQUENCE(rows,[columns],[start],[step]) * * @param mixed $rows the number of rows to return, defaults to 1 * @param mixed $columns the number of columns to return, defaults to 1 * @param mixed $start the first number in the sequence, defaults to 1 * @param mixed $step the amount to increment each subsequent value in the array, defaults to 1 * * @return array|string The resulting array, or a string containing an error */ public static function sequence($rows = 1, $columns = 1, $start = 1, $step = 1) { try { $rows = (int) Helpers::validateNumericNullSubstitution($rows, 1); Helpers::validatePositive($rows); $columns = (int) Helpers::validateNumericNullSubstitution($columns, 1); Helpers::validatePositive($columns); $start = Helpers::validateNumericNullSubstitution($start, 1); $step = Helpers::validateNumericNullSubstitution($step, 1); } catch (Exception $e) { return $e->getMessage(); } if ($step === 0) { return array_chunk( array_fill(0, $rows * $columns, $start), max($columns, 1) ); } return array_chunk( range($start, $start + (($rows * $columns - 1) * $step), $step), max($columns, 1) ); } /** * MDETERM. * * Returns the matrix determinant of an array. * * Excel Function: * MDETERM(array) * * @param mixed $matrixValues A matrix of values * * @return float|string The result, or a string containing an error */ public static function determinant($matrixValues) { try { $matrix = self::getMatrix($matrixValues); return $matrix->determinant(); } catch (MatrixException $ex) { return ExcelError::VALUE(); } catch (Exception $e) { return $e->getMessage(); } } /** * MINVERSE. * * Returns the inverse matrix for the matrix stored in an array. * * Excel Function: * MINVERSE(array) * * @param mixed $matrixValues A matrix of values * * @return array|string The result, or a string containing an error */ public static function inverse($matrixValues) { try { $matrix = self::getMatrix($matrixValues); return $matrix->inverse()->toArray(); } catch (MatrixDiv0Exception $e) { return ExcelError::NAN(); } catch (MatrixException $e) { return ExcelError::VALUE(); } catch (Exception $e) { return $e->getMessage(); } } /** * MMULT. * * @param mixed $matrixData1 A matrix of values * @param mixed $matrixData2 A matrix of values * * @return array|string The result, or a string containing an error */ public static function multiply($matrixData1, $matrixData2) { try { $matrixA = self::getMatrix($matrixData1); $matrixB = self::getMatrix($matrixData2); return $matrixA->multiply($matrixB)->toArray(); } catch (MatrixException $ex) { return ExcelError::VALUE(); } catch (Exception $e) { return $e->getMessage(); } } /** * MUnit. * * @param mixed $dimension Number of rows and columns * * @return array|string The result, or a string containing an error */ public static function identity($dimension) { try { $dimension = (int) Helpers::validateNumericNullBool($dimension); Helpers::validatePositive($dimension, ExcelError::VALUE()); $matrix = Builder::createIdentityMatrix($dimension, 0)->toArray(); return $matrix; } catch (Exception $e) { return $e->getMessage(); } } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php 0000644 00000002100 15002227416 0021467 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class IntClass { use ArrayEnabled; /** * INT. * * Casts a floating point value to an integer * * Excel Function: * INT(number) * * @param array|float $number Number to cast to an integer, or can be an array of numbers * * @return array|int|string Integer value, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return (int) floor($number); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php 0000644 00000001754 15002227416 0021543 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Absolute { use ArrayEnabled; /** * ABS. * * Returns the result of builtin function abs after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|int|string rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return abs($number); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Floor.php 0000644 00000015050 15002227416 0021040 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Floor { use ArrayEnabled; private static function floorCheck1Arg(): void { $compatibility = Functions::getCompatibilityMode(); if ($compatibility === Functions::COMPATIBILITY_EXCEL) { throw new Exception('Excel requires 2 arguments for FLOOR'); } } /** * FLOOR. * * Rounds number down, toward zero, to the nearest multiple of significance. * * Excel Function: * FLOOR(number[,significance]) * * @param mixed $number Expect float. Number to round * Or can be an array of values * @param mixed $significance Expect float. Significance * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function floor($number, $significance = null) { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } if ($significance === null) { self::floorCheck1Arg(); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); } catch (Exception $e) { return $e->getMessage(); } return self::argumentsOk((float) $number, (float) $significance); } /** * FLOOR.MATH. * * Round a number down to the nearest integer or to the nearest multiple of significance. * * Excel Function: * FLOOR.MATH(number[,significance[,mode]]) * * @param mixed $number Number to round * Or can be an array of values * @param mixed $significance Significance * Or can be an array of values * @param mixed $mode direction to round negative numbers * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function math($number, $significance = null, $mode = 0) { if (is_array($number) || is_array($significance) || is_array($mode)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance, $mode); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); $mode = Helpers::validateNumericNullSubstitution($mode, null); } catch (Exception $e) { return $e->getMessage(); } return self::argsOk((float) $number, (float) $significance, (int) $mode); } /** * FLOOR.PRECISE. * * Rounds number down, toward zero, to the nearest multiple of significance. * * Excel Function: * FLOOR.PRECISE(number[,significance]) * * @param array|float $number Number to round * Or can be an array of values * @param array|float $significance Significance * Or can be an array of values * * @return array|float|string Rounded Number, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function precise($number, $significance = 1) { if (is_array($number) || is_array($significance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); } try { $number = Helpers::validateNumericNullBool($number); $significance = Helpers::validateNumericNullSubstitution($significance, null); } catch (Exception $e) { return $e->getMessage(); } return self::argumentsOkPrecise((float) $number, (float) $significance); } /** * Avoid Scrutinizer problems concerning complexity. * * @return float|string */ private static function argumentsOkPrecise(float $number, float $significance) { if ($significance == 0.0) { return ExcelError::DIV0(); } if ($number == 0.0) { return 0.0; } return floor($number / abs($significance)) * abs($significance); } /** * Avoid Scrutinizer complexity problems. * * @return float|string Rounded Number, or a string containing an error */ private static function argsOk(float $number, float $significance, int $mode) { if (!$significance) { return ExcelError::DIV0(); } if (!$number) { return 0.0; } if (self::floorMathTest($number, $significance, $mode)) { return ceil($number / $significance) * $significance; } return floor($number / $significance) * $significance; } /** * Let FLOORMATH complexity pass Scrutinizer. */ private static function floorMathTest(float $number, float $significance, int $mode): bool { return Helpers::returnSign($significance) == -1 || (Helpers::returnSign($number) == -1 && !empty($mode)); } /** * Avoid Scrutinizer problems concerning complexity. * * @return float|string */ private static function argumentsOk(float $number, float $significance) { if ($significance == 0.0) { return ExcelError::DIV0(); } if ($number == 0.0) { return 0.0; } if (Helpers::returnSign($significance) == 1) { return floor($number / $significance) * $significance; } if (Helpers::returnSign($number) == -1 && Helpers::returnSign($significance) == -1) { return floor($number / $significance) * $significance; } return ExcelError::NAN(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php 0000644 00000003754 15002227416 0020464 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Gcd { /** * Recursively determine GCD. * * Returns the greatest common divisor of a series of numbers. * The greatest common divisor is the largest integer that divides both * number1 and number2 without a remainder. * * Excel Function: * GCD(number1[,number2[, ...]]) * * @param float|int $a * @param float|int $b * * @return float|int */ private static function evaluateGCD($a, $b) { return $b ? self::evaluateGCD($b, $a % $b) : $a; } /** * GCD. * * Returns the greatest common divisor of a series of numbers. * The greatest common divisor is the largest integer that divides both * number1 and number2 without a remainder. * * Excel Function: * GCD(number1[,number2[, ...]]) * * @param mixed ...$args Data values * * @return float|int|string Greatest Common Divisor, or a string containing an error */ public static function evaluate(...$args) { try { $arrayArgs = []; foreach (Functions::flattenArray($args) as $value1) { if ($value1 !== null) { $value = Helpers::validateNumericNullSubstitution($value1, 1); Helpers::validateNotNegative($value); $arrayArgs[] = (int) $value; } } } catch (Exception $e) { return $e->getMessage(); } if (count($arrayArgs) <= 0) { return ExcelError::VALUE(); } $gcd = (int) array_pop($arrayArgs); do { $gcd = self::evaluateGCD($gcd, (int) array_pop($arrayArgs)); } while (!empty($arrayArgs)); return $gcd; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php 0000644 00000007642 15002227416 0022077 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class SumSquares { /** * SUMSQ. * * SUMSQ returns the sum of the squares of the arguments * * Excel Function: * SUMSQ(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function sumSquare(...$args) { try { $returnValue = 0; // Loop through arguments foreach (Functions::flattenArray($args) as $arg) { $arg1 = Helpers::validateNumericNullSubstitution($arg, 0); $returnValue += ($arg1 * $arg1); } } catch (Exception $e) { return $e->getMessage(); } return $returnValue; } private static function getCount(array $array1, array $array2): int { $count = count($array1); if ($count !== count($array2)) { throw new Exception(ExcelError::NA()); } return $count; } /** * These functions accept only numeric arguments, not even strings which are numeric. * * @param mixed $item */ private static function numericNotString($item): bool { return is_numeric($item) && !is_string($item); } /** * SUMX2MY2. * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * * @return float|string */ public static function sumXSquaredMinusYSquared($matrixData1, $matrixData2) { try { $array1 = Functions::flattenArray($matrixData1); $array2 = Functions::flattenArray($matrixData2); $count = self::getCount($array1, $array2); $result = 0; for ($i = 0; $i < $count; ++$i) { if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]); } } } catch (Exception $e) { return $e->getMessage(); } return $result; } /** * SUMX2PY2. * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * * @return float|string */ public static function sumXSquaredPlusYSquared($matrixData1, $matrixData2) { try { $array1 = Functions::flattenArray($matrixData1); $array2 = Functions::flattenArray($matrixData2); $count = self::getCount($array1, $array2); $result = 0; for ($i = 0; $i < $count; ++$i) { if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]); } } } catch (Exception $e) { return $e->getMessage(); } return $result; } /** * SUMXMY2. * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * * @return float|string */ public static function sumXMinusYSquared($matrixData1, $matrixData2) { try { $array1 = Functions::flattenArray($matrixData1); $array2 = Functions::flattenArray($matrixData2); $count = self::getCount($array1, $array2); $result = 0; for ($i = 0; $i < $count; ++$i) { if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]); } } } catch (Exception $e) { return $e->getMessage(); } return $result; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php 0000644 00000007351 15002227416 0021670 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical; class Factorial { use ArrayEnabled; /** * FACT. * * Returns the factorial of a number. * The factorial of a number is equal to 1*2*3*...* number. * * Excel Function: * FACT(factVal) * * @param array|float $factVal Factorial Value, or can be an array of numbers * * @return array|float|int|string Factorial, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function fact($factVal) { if (is_array($factVal)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $factVal); } try { $factVal = Helpers::validateNumericNullBool($factVal); Helpers::validateNotNegative($factVal); } catch (Exception $e) { return $e->getMessage(); } $factLoop = floor($factVal); if ($factVal > $factLoop) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return Statistical\Distributions\Gamma::gammaValue($factVal + 1); } } $factorial = 1; while ($factLoop > 1) { $factorial *= $factLoop--; } return $factorial; } /** * FACTDOUBLE. * * Returns the double factorial of a number. * * Excel Function: * FACTDOUBLE(factVal) * * @param array|float $factVal Factorial Value, or can be an array of numbers * * @return array|float|int|string Double Factorial, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function factDouble($factVal) { if (is_array($factVal)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $factVal); } try { $factVal = Helpers::validateNumericNullSubstitution($factVal, 0); Helpers::validateNotNegative($factVal); } catch (Exception $e) { return $e->getMessage(); } $factLoop = floor($factVal); $factorial = 1; while ($factLoop > 1) { $factorial *= $factLoop; $factLoop -= 2; } return $factorial; } /** * MULTINOMIAL. * * Returns the ratio of the factorial of a sum of values to the product of factorials. * * @param mixed[] $args An array of mixed values for the Data Series * * @return float|string The result, or a string containing an error */ public static function multinomial(...$args) { $summer = 0; $divisor = 1; try { // Loop through arguments foreach (Functions::flattenArray($args) as $argx) { $arg = Helpers::validateNumericNullSubstitution($argx, null); Helpers::validateNotNegative($arg); $arg = (int) $arg; $summer += $arg; $divisor *= self::fact($arg); } } catch (Exception $e) { return $e->getMessage(); } $summer = self::fact($summer); return is_numeric($summer) ? ($summer / $divisor) : ExcelError::VALUE(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php 0000644 00000007054 15002227416 0022411 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Combinations { use ArrayEnabled; /** * COMBIN. * * Returns the number of combinations for a given number of items. Use COMBIN to * determine the total possible number of groups for a given number of items. * * Excel Function: * COMBIN(numObjs,numInSet) * * @param mixed $numObjs Number of different objects, or can be an array of numbers * @param mixed $numInSet Number of objects in each combination, or can be an array of numbers * * @return array|float|int|string Number of combinations, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function withoutRepetition($numObjs, $numInSet) { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = Helpers::validateNumericNullSubstitution($numObjs, null); $numInSet = Helpers::validateNumericNullSubstitution($numInSet, null); Helpers::validateNotNegative($numInSet); Helpers::validateNotNegative($numObjs - $numInSet); } catch (Exception $e) { return $e->getMessage(); } return round(Factorial::fact($numObjs) / Factorial::fact($numObjs - $numInSet)) / Factorial::fact($numInSet); // @phpstan-ignore-line } /** * COMBINA. * * Returns the number of combinations for a given number of items. Use COMBIN to * determine the total possible number of groups for a given number of items. * * Excel Function: * COMBINA(numObjs,numInSet) * * @param mixed $numObjs Number of different objects, or can be an array of numbers * @param mixed $numInSet Number of objects in each combination, or can be an array of numbers * * @return array|float|int|string Number of combinations, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function withRepetition($numObjs, $numInSet) { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = Helpers::validateNumericNullSubstitution($numObjs, null); $numInSet = Helpers::validateNumericNullSubstitution($numInSet, null); Helpers::validateNotNegative($numInSet); Helpers::validateNotNegative($numObjs); $numObjs = (int) $numObjs; $numInSet = (int) $numInSet; // Microsoft documentation says following is true, but Excel // does not enforce this restriction. //Helpers::validateNotNegative($numObjs - $numInSet); if ($numObjs === 0) { Helpers::validateNotNegative(-$numInSet); return 1; } } catch (Exception $e) { return $e->getMessage(); } return round( Factorial::fact($numObjs + $numInSet - 1) / Factorial::fact($numObjs - 1) // @phpstan-ignore-line ) / Factorial::fact($numInSet); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Random.php 0000644 00000006404 15002227416 0021202 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Random { use ArrayEnabled; /** * RAND. * * @return float Random number */ public static function rand() { return mt_rand(0, 10000000) / 10000000; } /** * RANDBETWEEN. * * @param mixed $min Minimal value * Or can be an array of values * @param mixed $max Maximal value * Or can be an array of values * * @return array|float|int|string Random number * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function randBetween($min, $max) { if (is_array($min) || is_array($max)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $min, $max); } try { $min = (int) Helpers::validateNumericNullBool($min); $max = (int) Helpers::validateNumericNullBool($max); Helpers::validateNotNegative($max - $min); } catch (Exception $e) { return $e->getMessage(); } return mt_rand($min, $max); } /** * RANDARRAY. * * Generates a list of sequential numbers in an array. * * Excel Function: * RANDARRAY([rows],[columns],[start],[step]) * * @param mixed $rows the number of rows to return, defaults to 1 * @param mixed $columns the number of columns to return, defaults to 1 * @param mixed $min the minimum number to be returned, defaults to 0 * @param mixed $max the maximum number to be returned, defaults to 1 * @param bool $wholeNumber the type of numbers to return: * False - Decimal numbers to 15 decimal places. (default) * True - Whole (integer) numbers * * @return array|string The resulting array, or a string containing an error */ public static function randArray($rows = 1, $columns = 1, $min = 0, $max = 1, $wholeNumber = false) { try { $rows = (int) Helpers::validateNumericNullSubstitution($rows, 1); Helpers::validatePositive($rows); $columns = (int) Helpers::validateNumericNullSubstitution($columns, 1); Helpers::validatePositive($columns); $min = Helpers::validateNumericNullSubstitution($min, 1); $max = Helpers::validateNumericNullSubstitution($max, 1); if ($max <= $min) { return ExcelError::VALUE(); } } catch (Exception $e) { return $e->getMessage(); } return array_chunk( array_map( function () use ($min, $max, $wholeNumber) { return $wholeNumber ? mt_rand((int) $min, (int) $max) : (mt_rand() / mt_getrandmax()) * ($max - $min) + $min; }, array_fill(0, $rows * $columns, $min) ), max($columns, 1) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php 0000644 00000006206 15002227416 0021364 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Helpers { /** * Many functions accept null/false/true argument treated as 0/0/1. * * @return float|string quotient or DIV0 if denominator is too small */ public static function verySmallDenominator(float $numerator, float $denominator) { return (abs($denominator) < 1.0E-12) ? ExcelError::DIV0() : ($numerator / $denominator); } /** * Many functions accept null/false/true argument treated as 0/0/1. * * @param mixed $number * * @return float|int */ public static function validateNumericNullBool($number) { $number = Functions::flattenSingleValue($number); if ($number === null) { return 0; } if (is_bool($number)) { return (int) $number; } if (is_numeric($number)) { return 0 + $number; } throw new Exception(ExcelError::throwError($number)); } /** * Validate numeric, but allow substitute for null. * * @param mixed $number * @param null|float|int $substitute * * @return float|int */ public static function validateNumericNullSubstitution($number, $substitute) { $number = Functions::flattenSingleValue($number); if ($number === null && $substitute !== null) { return $substitute; } if (is_numeric($number)) { return 0 + $number; } throw new Exception(ExcelError::throwError($number)); } /** * Confirm number >= 0. * * @param float|int $number */ public static function validateNotNegative($number, ?string $except = null): void { if ($number >= 0) { return; } throw new Exception($except ?? ExcelError::NAN()); } /** * Confirm number > 0. * * @param float|int $number */ public static function validatePositive($number, ?string $except = null): void { if ($number > 0) { return; } throw new Exception($except ?? ExcelError::NAN()); } /** * Confirm number != 0. * * @param float|int $number */ public static function validateNotZero($number): void { if ($number) { return; } throw new Exception(ExcelError::DIV0()); } public static function returnSign(float $number): int { return $number ? (($number > 0) ? 1 : -1) : 0; } public static function getEven(float $number): float { $significance = 2 * self::returnSign($number); return $significance ? (ceil($number / $significance) * $significance) : 0; } /** * Return NAN or value depending on argument. * * @param float $result Number * * @return float|string */ public static function numberOrNan($result) { return is_nan($result) ? ExcelError::NAN() : $result; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Base.php 0000644 00000004362 15002227416 0020635 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Base { use ArrayEnabled; /** * BASE. * * Converts a number into a text representation with the given radix (base). * * Excel Function: * BASE(Number, Radix [Min_length]) * * @param mixed $number expect float * Or can be an array of values * @param mixed $radix expect float * Or can be an array of values * @param mixed $minLength expect int or null * Or can be an array of values * * @return array|string the text representation with the given radix (base) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function evaluate($number, $radix, $minLength = null) { if (is_array($number) || is_array($radix) || is_array($minLength)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $radix, $minLength); } try { $number = (float) floor(Helpers::validateNumericNullBool($number)); $radix = (int) Helpers::validateNumericNullBool($radix); } catch (Exception $e) { return $e->getMessage(); } return self::calculate($number, $radix, $minLength); } /** * @param mixed $minLength */ private static function calculate(float $number, int $radix, $minLength): string { if ($minLength === null || is_numeric($minLength)) { if ($number < 0 || $number >= 2 ** 53 || $radix < 2 || $radix > 36) { return ExcelError::NAN(); // Numeric range constraints } $outcome = strtoupper((string) base_convert("$number", 10, $radix)); if ($minLength !== null) { $outcome = str_pad($outcome, (int) $minLength, '0', STR_PAD_LEFT); // String padding } return $outcome; } return ExcelError::VALUE(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php 0000644 00000003113 15002227416 0021673 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class SeriesSum { use ArrayEnabled; /** * SERIESSUM. * * Returns the sum of a power series * * @param mixed $x Input value * @param mixed $n Initial power * @param mixed $m Step * @param mixed[] $args An array of coefficients for the Data Series * * @return array|float|string The result, or a string containing an error */ public static function evaluate($x, $n, $m, ...$args) { if (is_array($x) || is_array($n) || is_array($m)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 3, $x, $n, $m, ...$args); } try { $x = Helpers::validateNumericNullSubstitution($x, 0); $n = Helpers::validateNumericNullSubstitution($n, 0); $m = Helpers::validateNumericNullSubstitution($m, 0); // Loop through arguments $aArgs = Functions::flattenArray($args); $returnValue = 0; $i = 0; foreach ($aArgs as $argx) { if ($argx !== null) { $arg = Helpers::validateNumericNullSubstitution($argx, 0); $returnValue += $arg * $x ** ($n + ($m * $i)); ++$i; } } } catch (Exception $e) { return $e->getMessage(); } return $returnValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Angle.php 0000644 00000003421 15002227416 0021004 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Angle { use ArrayEnabled; /** * DEGREES. * * Returns the result of builtin function rad2deg after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function toDegrees($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return rad2deg($number); } /** * RADIANS. * * Returns the result of builtin function deg2rad after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string Rounded number * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function toRadians($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return deg2rad($number); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php 0000644 00000003533 15002227416 0020713 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Sqrt { use ArrayEnabled; /** * SQRT. * * Returns the result of builtin function sqrt after validating args. * * @param mixed $number Should be numeric, or can be an array of numbers * * @return array|float|string square root * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function sqrt($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullBool($number); } catch (Exception $e) { return $e->getMessage(); } return Helpers::numberOrNan(sqrt($number)); } /** * SQRTPI. * * Returns the square root of (number * pi). * * @param array|float $number Number, or can be an array of numbers * * @return array|float|string Square Root of Number * Pi, or a string containing an error * If an array of numbers is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function pi($number) { if (is_array($number)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); } try { $number = Helpers::validateNumericNullSubstitution($number, 0); Helpers::validateNotNegative($number); } catch (Exception $e) { return $e->getMessage(); } return sqrt($number * M_PI); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sum.php 0000644 00000006616 15002227416 0020533 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Information\Value; class Sum { /** * SUM, ignoring non-numeric non-error strings. This is eventually used by SUMIF. * * SUM computes the sum of all the values and cells referenced in the argument list. * * Excel Function: * SUM(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function sumIgnoringStrings(...$args) { $returnValue = 0; // Loop through the arguments foreach (Functions::flattenArray($args) as $arg) { // Is it a numeric value? if (is_numeric($arg)) { $returnValue += $arg; } elseif (ErrorValue::isError($arg)) { return $arg; } } return $returnValue; } /** * SUM, returning error for non-numeric strings. This is used by Excel SUM function. * * SUM computes the sum of all the values and cells referenced in the argument list. * * Excel Function: * SUM(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function sumErroringStrings(...$args) { $returnValue = 0; // Loop through the arguments $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { // Is it a numeric value? if (is_numeric($arg) || empty($arg)) { if (is_string($arg)) { $arg = (int) $arg; } $returnValue += $arg; } elseif (is_bool($arg)) { $returnValue += (int) $arg; } elseif (ErrorValue::isError($arg)) { return $arg; } elseif ($arg !== null && !Functions::isCellValue($k)) { // ignore non-numerics from cell, but fail as literals (except null) return ExcelError::VALUE(); } } return $returnValue; } /** * SUMPRODUCT. * * Excel Function: * SUMPRODUCT(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function product(...$args) { $arrayList = $args; $wrkArray = Functions::flattenArray(array_shift($arrayList)); $wrkCellCount = count($wrkArray); for ($i = 0; $i < $wrkCellCount; ++$i) { if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) { $wrkArray[$i] = 0; } } foreach ($arrayList as $matrixData) { $array2 = Functions::flattenArray($matrixData); $count = count($array2); if ($wrkCellCount != $count) { return ExcelError::VALUE(); } foreach ($array2 as $i => $val) { if ((!is_numeric($val)) || (is_string($val))) { $val = 0; } $wrkArray[$i] *= $val; } } return array_sum($wrkArray); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php 0000644 00000007122 15002227416 0020473 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Lcm { // // Private method to return an array of the factors of the input value // private static function factors(float $value): array { $startVal = floor(sqrt($value)); $factorArray = []; for ($i = $startVal; $i > 1; --$i) { if (($value % $i) == 0) { $factorArray = array_merge($factorArray, self::factors($value / $i)); $factorArray = array_merge($factorArray, self::factors($i)); if ($i <= sqrt($value)) { break; } } } if (!empty($factorArray)) { rsort($factorArray); return $factorArray; } return [(int) $value]; } /** * LCM. * * Returns the lowest common multiplier of a series of numbers * The least common multiple is the smallest positive integer that is a multiple * of all integer arguments number1, number2, and so on. Use LCM to add fractions * with different denominators. * * Excel Function: * LCM(number1[,number2[, ...]]) * * @param mixed ...$args Data values * * @return int|string Lowest Common Multiplier, or a string containing an error */ public static function evaluate(...$args) { try { $arrayArgs = []; $anyZeros = 0; $anyNonNulls = 0; foreach (Functions::flattenArray($args) as $value1) { $anyNonNulls += (int) ($value1 !== null); $value = Helpers::validateNumericNullSubstitution($value1, 1); Helpers::validateNotNegative($value); $arrayArgs[] = (int) $value; $anyZeros += (int) !((bool) $value); } self::testNonNulls($anyNonNulls); if ($anyZeros) { return 0; } } catch (Exception $e) { return $e->getMessage(); } $returnValue = 1; $allPoweredFactors = []; // Loop through arguments foreach ($arrayArgs as $value) { $myFactors = self::factors(floor($value)); $myCountedFactors = array_count_values($myFactors); $myPoweredFactors = []; foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) { $myPoweredFactors[$myCountedFactor] = $myCountedFactor ** $myCountedPower; } self::processPoweredFactors($allPoweredFactors, $myPoweredFactors); } foreach ($allPoweredFactors as $allPoweredFactor) { $returnValue *= (int) $allPoweredFactor; } return $returnValue; } private static function processPoweredFactors(array &$allPoweredFactors, array &$myPoweredFactors): void { foreach ($myPoweredFactors as $myPoweredValue => $myPoweredFactor) { if (isset($allPoweredFactors[$myPoweredValue])) { if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) { $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; } } else { $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; } } } private static function testNonNulls(int $anyNonNulls): void { if (!$anyNonNulls) { throw new Exception(ExcelError::VALUE()); } } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Web/Service.php 0000644 00000003661 15002227416 0020362 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Web; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Settings; use Psr\Http\Client\ClientExceptionInterface; class Service { /** * WEBSERVICE. * * Returns data from a web service on the Internet or Intranet. * * Excel Function: * Webservice(url) * * @return string the output resulting from a call to the webservice */ public static function webService(string $url) { $url = trim($url); if (strlen($url) > 2048) { return ExcelError::VALUE(); // Invalid URL length } if (!preg_match('/^http[s]?:\/\//', $url)) { return ExcelError::VALUE(); // Invalid protocol } // Get results from the the webservice $client = Settings::getHttpClient(); $requestFactory = Settings::getRequestFactory(); $request = $requestFactory->createRequest('GET', $url); try { $response = $client->sendRequest($request); } catch (ClientExceptionInterface $e) { return ExcelError::VALUE(); // cURL error } if ($response->getStatusCode() != 200) { return ExcelError::VALUE(); // cURL error } $output = $response->getBody()->getContents(); if (strlen($output) > 32767) { return ExcelError::VALUE(); // Output not a string or too long } return $output; } /** * URLENCODE. * * Returns data from a web service on the Internet or Intranet. * * Excel Function: * urlEncode(text) * * @param mixed $text * * @return string the url encoded output */ public static function urlEncode($text) { if (!is_string($text)) { return ExcelError::VALUE(); } return str_replace('+', '%20', urlencode($text)); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaParser.php 0000644 00000054142 15002227416 0021027 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; /** * PARTLY BASED ON: * Copyright (c) 2007 E. W. Bachtal, Inc. * * 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. * * https://ewbi.blogs.com/develops/2007/03/excel_formula_p.html * https://ewbi.blogs.com/develops/2004/12/excel_formula_p.html */ class FormulaParser { // Character constants const QUOTE_DOUBLE = '"'; const QUOTE_SINGLE = '\''; const BRACKET_CLOSE = ']'; const BRACKET_OPEN = '['; const BRACE_OPEN = '{'; const BRACE_CLOSE = '}'; const PAREN_OPEN = '('; const PAREN_CLOSE = ')'; const SEMICOLON = ';'; const WHITESPACE = ' '; const COMMA = ','; const ERROR_START = '#'; const OPERATORS_SN = '+-'; const OPERATORS_INFIX = '+-*/^&=><'; const OPERATORS_POSTFIX = '%'; /** * Formula. * * @var string */ private $formula; /** * Tokens. * * @var FormulaToken[] */ private $tokens = []; /** * Create a new FormulaParser. * * @param ?string $formula Formula to parse */ public function __construct($formula = '') { // Check parameters if ($formula === null) { throw new Exception('Invalid parameter passed: formula'); } // Initialise values $this->formula = trim($formula); // Parse! $this->parseToTokens(); } /** * Get Formula. * * @return string */ public function getFormula() { return $this->formula; } /** * Get Token. * * @param int $id Token id */ public function getToken(int $id = 0): FormulaToken { if (isset($this->tokens[$id])) { return $this->tokens[$id]; } throw new Exception("Token with id $id does not exist."); } /** * Get Token count. * * @return int */ public function getTokenCount() { return count($this->tokens); } /** * Get Tokens. * * @return FormulaToken[] */ public function getTokens() { return $this->tokens; } /** * Parse to tokens. */ private function parseToTokens(): void { // No attempt is made to verify formulas; assumes formulas are derived from Excel, where // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions. // Check if the formula has a valid starting = $formulaLength = strlen($this->formula); if ($formulaLength < 2 || $this->formula[0] != '=') { return; } // Helper variables $tokens1 = $tokens2 = $stack = []; $inString = $inPath = $inRange = $inError = false; $nextToken = null; //$token = $previousToken = null; $index = 1; $value = ''; $ERRORS = ['#NULL!', '#DIV/0!', '#VALUE!', '#REF!', '#NAME?', '#NUM!', '#N/A']; $COMPARATORS_MULTI = ['>=', '<=', '<>']; while ($index < $formulaLength) { // state-dependent character evaluation (order is important) // double-quoted strings // embeds are doubled // end marks token if ($inString) { if ($this->formula[$index] == self::QUOTE_DOUBLE) { if ((($index + 2) <= $formulaLength) && ($this->formula[$index + 1] == self::QUOTE_DOUBLE)) { $value .= self::QUOTE_DOUBLE; ++$index; } else { $inString = false; $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_TEXT); $value = ''; } } else { $value .= $this->formula[$index]; } ++$index; continue; } // single-quoted strings (links) // embeds are double // end does not mark a token if ($inPath) { if ($this->formula[$index] == self::QUOTE_SINGLE) { if ((($index + 2) <= $formulaLength) && ($this->formula[$index + 1] == self::QUOTE_SINGLE)) { $value .= self::QUOTE_SINGLE; ++$index; } else { $inPath = false; } } else { $value .= $this->formula[$index]; } ++$index; continue; } // bracked strings (R1C1 range index or linked workbook name) // no embeds (changed to "()" by Excel) // end does not mark a token if ($inRange) { if ($this->formula[$index] == self::BRACKET_CLOSE) { $inRange = false; } $value .= $this->formula[$index]; ++$index; continue; } // error values // end marks a token, determined from absolute list of values if ($inError) { $value .= $this->formula[$index]; ++$index; if (in_array($value, $ERRORS)) { $inError = false; $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_ERROR); $value = ''; } continue; } // scientific notation check if (strpos(self::OPERATORS_SN, $this->formula[$index]) !== false) { if (strlen($value) > 1) { if (preg_match('/^[1-9]{1}(\\.\\d+)?E{1}$/', $this->formula[$index]) != 0) { $value .= $this->formula[$index]; ++$index; continue; } } } // independent character evaluation (order not important) // establish state-dependent character evaluations if ($this->formula[$index] == self::QUOTE_DOUBLE) { if (strlen($value) > 0) { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inString = true; ++$index; continue; } if ($this->formula[$index] == self::QUOTE_SINGLE) { if (strlen($value) > 0) { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inPath = true; ++$index; continue; } if ($this->formula[$index] == self::BRACKET_OPEN) { $inRange = true; $value .= self::BRACKET_OPEN; ++$index; continue; } if ($this->formula[$index] == self::ERROR_START) { if (strlen($value) > 0) { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inError = true; $value .= self::ERROR_START; ++$index; continue; } // mark start and end of arrays and array rows if ($this->formula[$index] == self::BRACE_OPEN) { if (strlen($value) > 0) { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $tmp = new FormulaToken('ARRAY', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; $tmp = new FormulaToken('ARRAYROW', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; ++$index; continue; } if ($this->formula[$index] == self::SEMICOLON) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; $tmp = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT); $tokens1[] = $tmp; $tmp = new FormulaToken('ARRAYROW', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; ++$index; continue; } if ($this->formula[$index] == self::BRACE_CLOSE) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; ++$index; continue; } // trim white-space if ($this->formula[$index] == self::WHITESPACE) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken('', FormulaToken::TOKEN_TYPE_WHITESPACE); ++$index; while (($this->formula[$index] == self::WHITESPACE) && ($index < $formulaLength)) { ++$index; } continue; } // multi-character comparators if (($index + 2) <= $formulaLength) { if (in_array(substr($this->formula, $index, 2), $COMPARATORS_MULTI)) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken(substr($this->formula, $index, 2), FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_LOGICAL); $index += 2; continue; } } // standard infix operators if (strpos(self::OPERATORS_INFIX, $this->formula[$index]) !== false) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken($this->formula[$index], FormulaToken::TOKEN_TYPE_OPERATORINFIX); ++$index; continue; } // standard postfix operators (only one) if (strpos(self::OPERATORS_POSTFIX, $this->formula[$index]) !== false) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken($this->formula[$index], FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX); ++$index; continue; } // start subexpression or function if ($this->formula[$index] == self::PAREN_OPEN) { if (strlen($value) > 0) { $tmp = new FormulaToken($value, FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; $value = ''; } else { $tmp = new FormulaToken('', FormulaToken::TOKEN_TYPE_SUBEXPRESSION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; } ++$index; continue; } // function, subexpression, or array parameters, or operand unions if ($this->formula[$index] == self::COMMA) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $stack[] = $tmp; if ($tmp->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) { $tokens1[] = new FormulaToken(',', FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_UNION); } else { $tokens1[] = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT); } ++$index; continue; } // stop subexpression if ($this->formula[$index] == self::PAREN_CLOSE) { if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; ++$index; continue; } // token accumulation $value .= $this->formula[$index]; ++$index; } // dump remaining accumulation if (strlen($value) > 0) { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); } // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections $tokenCount = count($tokens1); for ($i = 0; $i < $tokenCount; ++$i) { $token = $tokens1[$i]; if (isset($tokens1[$i - 1])) { $previousToken = $tokens1[$i - 1]; } else { $previousToken = null; } if (isset($tokens1[$i + 1])) { $nextToken = $tokens1[$i + 1]; } else { $nextToken = null; } if ($token === null) { continue; } if ($token->getTokenType() != FormulaToken::TOKEN_TYPE_WHITESPACE) { $tokens2[] = $token; continue; } if ($previousToken === null) { continue; } if ( !( (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) ) { continue; } if ($nextToken === null) { continue; } if ( !( (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || ($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) ) { continue; } $tokens2[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_INTERSECTION); } // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names $this->tokens = []; $tokenCount = count($tokens2); for ($i = 0; $i < $tokenCount; ++$i) { $token = $tokens2[$i]; if (isset($tokens2[$i - 1])) { $previousToken = $tokens2[$i - 1]; } else { $previousToken = null; } //if (isset($tokens2[$i + 1])) { // $nextToken = $tokens2[$i + 1]; //} else { // $nextToken = null; //} if ($token === null) { continue; } if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '-') { if ($i == 0) { $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); } elseif ( (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } else { $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); } $this->tokens[] = $token; continue; } if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '+') { if ($i == 0) { continue; } elseif ( (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } else { continue; } $this->tokens[] = $token; continue; } if ( $token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING ) { if (strpos('<>=', substr($token->getValue(), 0, 1)) !== false) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); } elseif ($token->getValue() == '&') { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_CONCATENATION); } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } $this->tokens[] = $token; continue; } if ( $token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND && $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING ) { if (!is_numeric($token->getValue())) { if (strtoupper($token->getValue()) == 'TRUE' || strtoupper($token->getValue()) == 'FALSE') { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_RANGE); } } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_NUMBER); } $this->tokens[] = $token; continue; } if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) { if (strlen($token->getValue()) > 0) { if (substr($token->getValue(), 0, 1) == '@') { $token->setValue(substr($token->getValue(), 1)); } } } $this->tokens[] = $token; } } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php 0000644 00000015115 15002227416 0021376 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Offset { /** * OFFSET. * * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells. * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and * the number of columns to be returned. * * Excel Function: * =OFFSET(cellAddress, rows, cols, [height], [width]) * * @param null|string $cellAddress The reference from which you want to base the offset. * Reference must refer to a cell or range of adjacent cells; * otherwise, OFFSET returns the #VALUE! error value. * @param mixed $rows The number of rows, up or down, that you want the upper-left cell to refer to. * Using 5 as the rows argument specifies that the upper-left cell in the * reference is five rows below reference. Rows can be positive (which means * below the starting reference) or negative (which means above the starting * reference). * @param mixed $columns The number of columns, to the left or right, that you want the upper-left cell * of the result to refer to. Using 5 as the cols argument specifies that the * upper-left cell in the reference is five columns to the right of reference. * Cols can be positive (which means to the right of the starting reference) * or negative (which means to the left of the starting reference). * @param mixed $height The height, in number of rows, that you want the returned reference to be. * Height must be a positive number. * @param mixed $width The width, in number of columns, that you want the returned reference to be. * Width must be a positive number. * * @return array|int|string An array containing a cell or range of cells, or a string on error */ public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null, ?Cell $cell = null) { $rows = Functions::flattenSingleValue($rows); $columns = Functions::flattenSingleValue($columns); $height = Functions::flattenSingleValue($height); $width = Functions::flattenSingleValue($width); if ($cellAddress === null || $cellAddress === '') { return ExcelError::VALUE(); } if (!is_object($cell)) { return ExcelError::REF(); } [$cellAddress, $worksheet] = self::extractWorksheet($cellAddress, $cell); $startCell = $endCell = $cellAddress; if (strpos($cellAddress, ':')) { [$startCell, $endCell] = explode(':', $cellAddress); } [$startCellColumn, $startCellRow] = Coordinate::coordinateFromString($startCell); [$endCellColumn, $endCellRow] = Coordinate::coordinateFromString($endCell); $startCellRow += $rows; $startCellColumn = Coordinate::columnIndexFromString($startCellColumn) - 1; $startCellColumn += $columns; if (($startCellRow <= 0) || ($startCellColumn < 0)) { return ExcelError::REF(); } $endCellColumn = self::adjustEndCellColumnForWidth($endCellColumn, $width, $startCellColumn, $columns); $startCellColumn = Coordinate::stringFromColumnIndex($startCellColumn + 1); $endCellRow = self::adustEndCellRowForHeight($height, $startCellRow, $rows, $endCellRow); if (($endCellRow <= 0) || ($endCellColumn < 0)) { return ExcelError::REF(); } $endCellColumn = Coordinate::stringFromColumnIndex($endCellColumn + 1); $cellAddress = "{$startCellColumn}{$startCellRow}"; if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) { $cellAddress .= ":{$endCellColumn}{$endCellRow}"; } return self::extractRequiredCells($worksheet, $cellAddress); } /** @return mixed */ private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress) { return Calculation::getInstance($worksheet !== null ? $worksheet->getParent() : null) ->extractCellRange($cellAddress, $worksheet, false); } private static function extractWorksheet(?string $cellAddress, Cell $cell): array { $cellAddress = self::assessCellAddress($cellAddress ?? '', $cell); $sheetName = ''; if (strpos($cellAddress, '!') !== false) { [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); $sheetName = trim($sheetName, "'"); } $worksheet = ($sheetName !== '') ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($sheetName) : $cell->getWorksheet(); return [$cellAddress, $worksheet]; } private static function assessCellAddress(string $cellAddress, Cell $cell): string { if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $cellAddress) !== false) { $cellAddress = Functions::expandDefinedName($cellAddress, $cell); } return $cellAddress; } /** * @param mixed $width * @param mixed $columns */ private static function adjustEndCellColumnForWidth(string $endCellColumn, $width, int $startCellColumn, $columns): int { $endCellColumn = Coordinate::columnIndexFromString($endCellColumn) - 1; if (($width !== null) && (!is_object($width))) { $endCellColumn = $startCellColumn + (int) $width - 1; } else { $endCellColumn += (int) $columns; } return $endCellColumn; } /** * @param mixed $height * @param mixed $rows * @param mixed $endCellRow */ private static function adustEndCellRowForHeight($height, int $startCellRow, $rows, $endCellRow): int { if (($height !== null) && (!is_object($height))) { $endCellRow = $startCellRow + (int) $height - 1; } else { $endCellRow += (int) $rows; } return $endCellRow; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php 0000644 00000010536 15002227416 0021533 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class HLookup extends LookupBase { use ArrayEnabled; /** * HLOOKUP * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value * in the same column based on the index_number. * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupArray The range of cells being searched * @param mixed $indexNumber The row number in table_array from which the matching value must be returned. * The first row is 1. * @param mixed $notExactMatch determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function lookup($lookupValue, $lookupArray, $indexNumber, $notExactMatch = true) { if (is_array($lookupValue) || is_array($indexNumber)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $indexNumber, $notExactMatch); } $notExactMatch = (bool) ($notExactMatch ?? true); try { self::validateLookupArray($lookupArray); $lookupArray = self::convertLiteralArray($lookupArray); $indexNumber = self::validateIndexLookup($lookupArray, $indexNumber); } catch (Exception $e) { return $e->getMessage(); } $f = array_keys($lookupArray); $firstRow = reset($f); if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray))) { return ExcelError::REF(); } $firstkey = $f[0] - 1; $returnColumn = $firstkey + $indexNumber; $firstColumn = array_shift($f) ?? 1; $rowNumber = self::hLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); if ($rowNumber !== null) { // otherwise return the appropriate value return $lookupArray[$returnColumn][Coordinate::stringFromColumnIndex($rowNumber)]; } return ExcelError::NA(); } /** * @param mixed $lookupValue The value that you want to match in lookup_array * @param int|string $column */ private static function hLookupSearch($lookupValue, array $lookupArray, $column, bool $notExactMatch): ?int { $lookupLower = StringHelper::strToLower((string) $lookupValue); $rowNumber = null; foreach ($lookupArray[$column] as $rowKey => $rowData) { // break if we have passed possible keys $bothNumeric = is_numeric($lookupValue) && is_numeric($rowData); $bothNotNumeric = !is_numeric($lookupValue) && !is_numeric($rowData); $cellDataLower = StringHelper::strToLower((string) $rowData); if ( $notExactMatch && (($bothNumeric && $rowData > $lookupValue) || ($bothNotNumeric && $cellDataLower > $lookupLower)) ) { break; } $rowNumber = self::checkMatch( $bothNumeric, $bothNotNumeric, $notExactMatch, Coordinate::columnIndexFromString($rowKey), $cellDataLower, $lookupLower, $rowNumber ); } return $rowNumber; } private static function convertLiteralArray(array $lookupArray): array { if (array_key_exists(0, $lookupArray)) { $lookupArray2 = []; $row = 0; foreach ($lookupArray as $arrayVal) { ++$row; if (!is_array($arrayVal)) { $arrayVal = [$arrayVal]; } $arrayVal2 = []; foreach ($arrayVal as $key2 => $val2) { $index = Coordinate::stringFromColumnIndex($key2 + 1); $arrayVal2[$index] = $val2; } $lookupArray2[$row] = $arrayVal2; } $lookupArray = $lookupArray2; } return $lookupArray; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php 0000644 00000002527 15002227416 0022120 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; class Hyperlink { /** * HYPERLINK. * * Excel Function: * =HYPERLINK(linkURL, [displayName]) * * @param mixed $linkURL Expect string. Value to check, is also the value returned when no error * @param mixed $displayName Expect string. Value to return when testValue is an error condition * @param Cell $cell The cell to set the hyperlink in * * @return mixed The value of $displayName (or $linkURL if $displayName was blank) */ public static function set($linkURL = '', $displayName = null, ?Cell $cell = null) { $linkURL = ($linkURL === null) ? '' : Functions::flattenSingleValue($linkURL); $displayName = ($displayName === null) ? '' : Functions::flattenSingleValue($displayName); if ((!is_object($cell)) || (trim($linkURL) == '')) { return ExcelError::REF(); } if ((is_object($displayName)) || trim($displayName) == '') { $displayName = $linkURL; } $cell->getHyperlink()->setUrl($linkURL); $cell->getHyperlink()->setTooltip($displayName); return $displayName; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php 0000644 00000011723 15002227416 0021712 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use Exception; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Indirect { /** * Determine whether cell address is in A1 (true) or R1C1 (false) format. * * @param mixed $a1fmt Expect bool Helpers::CELLADDRESS_USE_A1 or CELLADDRESS_USE_R1C1, * but can be provided as numeric which is cast to bool */ private static function a1Format($a1fmt): bool { $a1fmt = Functions::flattenSingleValue($a1fmt); if ($a1fmt === null) { return Helpers::CELLADDRESS_USE_A1; } if (is_string($a1fmt)) { throw new Exception(ExcelError::VALUE()); } return (bool) $a1fmt; } /** * Convert cellAddress to string, verify not null string. * * @param array|string $cellAddress */ private static function validateAddress($cellAddress): string { $cellAddress = Functions::flattenSingleValue($cellAddress); if (!is_string($cellAddress) || !$cellAddress) { throw new Exception(ExcelError::REF()); } return $cellAddress; } /** * INDIRECT. * * Returns the reference specified by a text string. * References are immediately evaluated to display their contents. * * Excel Function: * =INDIRECT(cellAddress, bool) where the bool argument is optional * * @param array|string $cellAddress $cellAddress The cell address of the current cell (containing this formula) * @param mixed $a1fmt Expect bool Helpers::CELLADDRESS_USE_A1 or CELLADDRESS_USE_R1C1, * but can be provided as numeric which is cast to bool * @param Cell $cell The current cell (containing this formula) * * @return array|string An array containing a cell or range of cells, or a string on error */ public static function INDIRECT($cellAddress, $a1fmt, Cell $cell) { [$baseCol, $baseRow] = Coordinate::indexesFromString($cell->getCoordinate()); try { $a1 = self::a1Format($a1fmt); $cellAddress = self::validateAddress($cellAddress); } catch (Exception $e) { return $e->getMessage(); } [$cellAddress, $worksheet, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); if (preg_match('/^' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) { $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress)); } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) { $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress)); } try { [$cellAddress1, $cellAddress2, $cellAddress] = Helpers::extractCellAddresses($cellAddress, $a1, $cell->getWorkSheet(), $sheetName, $baseRow, $baseCol); } catch (Exception $e) { return ExcelError::REF(); } if ( (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress1, $matches)) || (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress2, $matches))) ) { return ExcelError::REF(); } return self::extractRequiredCells($worksheet, $cellAddress); } /** * Extract range values. * * @return mixed Array of values in range if range contains more than one element. * Otherwise, a single value is returned. */ private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress) { return Calculation::getInstance($worksheet !== null ? $worksheet->getParent() : null) ->extractCellRange($cellAddress, $worksheet, false); } private static function handleRowColumnRanges(?Worksheet $worksheet, string $start, string $end): string { // Being lazy, we're only checking a single row/column to get the max if (ctype_digit($start) && $start <= 1048576) { // Max 16,384 columns for Excel2007 $endColRef = ($worksheet !== null) ? $worksheet->getHighestDataColumn((int) $start) : AddressRange::MAX_COLUMN; return "A{$start}:{$endColRef}{$end}"; } elseif (ctype_alpha($start) && strlen($start) <= 3) { // Max 1,048,576 rows for Excel2007 $endRowRef = ($worksheet !== null) ? $worksheet->getHighestDataRow($start) : AddressRange::MAX_ROW; return "{$start}1:{$end}{$endRowRef}"; } return "{$start}:{$end}"; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Unique.php 0000644 00000010513 15002227416 0021413 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Unique { /** * UNIQUE * The UNIQUE function searches for value either from a one-row or one-column range or from an array. * * @param mixed $lookupVector The range of cells being searched * @param mixed $byColumn Whether the uniqueness should be determined by row (the default) or by column * @param mixed $exactlyOnce Whether the function should return only entries that occur just once in the list * * @return mixed The unique values from the search range */ public static function unique($lookupVector, $byColumn = false, $exactlyOnce = false) { if (!is_array($lookupVector)) { // Scalars are always returned "as is" return $lookupVector; } $byColumn = (bool) $byColumn; $exactlyOnce = (bool) $exactlyOnce; return ($byColumn === true) ? self::uniqueByColumn($lookupVector, $exactlyOnce) : self::uniqueByRow($lookupVector, $exactlyOnce); } /** * @return mixed */ private static function uniqueByRow(array $lookupVector, bool $exactlyOnce) { // When not $byColumn, we count whole rows or values, not individual values // so implode each row into a single string value array_walk( $lookupVector, function (array &$value): void { $value = implode(chr(0x00), $value); } ); $result = self::countValuesCaseInsensitive($lookupVector); if ($exactlyOnce === true) { $result = self::exactlyOnceFilter($result); } if (count($result) === 0) { return ExcelError::CALC(); } $result = array_keys($result); // restore rows from their strings array_walk( $result, function (string &$value): void { $value = explode(chr(0x00), $value); } ); return (count($result) === 1) ? array_pop($result) : $result; } /** * @return mixed */ private static function uniqueByColumn(array $lookupVector, bool $exactlyOnce) { $flattenedLookupVector = Functions::flattenArray($lookupVector); if (count($lookupVector, COUNT_RECURSIVE) > count($flattenedLookupVector, COUNT_RECURSIVE) + 1) { // We're looking at a full column check (multiple rows) $transpose = Matrix::transpose($lookupVector); $result = self::uniqueByRow($transpose, $exactlyOnce); return (is_array($result)) ? Matrix::transpose($result) : $result; } $result = self::countValuesCaseInsensitive($flattenedLookupVector); if ($exactlyOnce === true) { $result = self::exactlyOnceFilter($result); } if (count($result) === 0) { return ExcelError::CALC(); } $result = array_keys($result); return $result; } private static function countValuesCaseInsensitive(array $caseSensitiveLookupValues): array { $caseInsensitiveCounts = array_count_values( array_map( function (string $value) { return StringHelper::strToUpper($value); }, $caseSensitiveLookupValues ) ); $caseSensitiveCounts = []; foreach ($caseInsensitiveCounts as $caseInsensitiveKey => $count) { if (is_numeric($caseInsensitiveKey)) { $caseSensitiveCounts[$caseInsensitiveKey] = $count; } else { foreach ($caseSensitiveLookupValues as $caseSensitiveValue) { if ($caseInsensitiveKey === StringHelper::strToUpper($caseSensitiveValue)) { $caseSensitiveCounts[$caseSensitiveValue] = $count; break; } } } } return $caseSensitiveCounts; } private static function exactlyOnceFilter(array $values): array { return array_filter( $values, function ($value) { return $value === 1; } ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php 0000644 00000016271 15002227416 0024307 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class RowColumnInformation { /** * Test if cellAddress is null or whitespace string. * * @param null|array|string $cellAddress A reference to a range of cells */ private static function cellAddressNullOrWhitespace($cellAddress): bool { return $cellAddress === null || (!is_array($cellAddress) && trim($cellAddress) === ''); } private static function cellColumn(?Cell $cell): int { return ($cell !== null) ? (int) Coordinate::columnIndexFromString($cell->getColumn()) : 1; } /** * COLUMN. * * Returns the column number of the given cell reference * If the cell reference is a range of cells, COLUMN returns the column numbers of each column * in the reference as a horizontal array. * If cell reference is omitted, and the function is being called through the calculation engine, * then it is assumed to be the reference of the cell in which the COLUMN function appears; * otherwise this function returns 1. * * Excel Function: * =COLUMN([cellAddress]) * * @param null|array|string $cellAddress A reference to a range of cells for which you want the column numbers * * @return int|int[] */ public static function COLUMN($cellAddress = null, ?Cell $cell = null) { if (self::cellAddressNullOrWhitespace($cellAddress)) { return self::cellColumn($cell); } if (is_array($cellAddress)) { foreach ($cellAddress as $columnKey => $value) { $columnKey = (string) preg_replace('/[^a-z]/i', '', $columnKey); return (int) Coordinate::columnIndexFromString($columnKey); } return self::cellColumn($cell); } $cellAddress = $cellAddress ?? ''; if ($cell != null) { [,, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); [,, $cellAddress] = Helpers::extractCellAddresses($cellAddress, true, $cell->getWorksheet(), $sheetName); } [, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if (strpos($cellAddress, ':') !== false) { [$startAddress, $endAddress] = explode(':', $cellAddress); $startAddress = (string) preg_replace('/[^a-z]/i', '', $startAddress); $endAddress = (string) preg_replace('/[^a-z]/i', '', $endAddress); return range( (int) Coordinate::columnIndexFromString($startAddress), (int) Coordinate::columnIndexFromString($endAddress) ); } $cellAddress = (string) preg_replace('/[^a-z]/i', '', $cellAddress); return (int) Coordinate::columnIndexFromString($cellAddress); } /** * COLUMNS. * * Returns the number of columns in an array or reference. * * Excel Function: * =COLUMNS(cellAddress) * * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells * for which you want the number of columns * * @return int|string The number of columns in cellAddress, or a string if arguments are invalid */ public static function COLUMNS($cellAddress = null) { if (self::cellAddressNullOrWhitespace($cellAddress)) { return 1; } if (!is_array($cellAddress)) { return ExcelError::VALUE(); } reset($cellAddress); $isMatrix = (is_numeric(key($cellAddress))); [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); if ($isMatrix) { return $rows; } return $columns; } private static function cellRow(?Cell $cell): int { return ($cell !== null) ? $cell->getRow() : 1; } /** * ROW. * * Returns the row number of the given cell reference * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference * as a vertical array. * If cell reference is omitted, and the function is being called through the calculation engine, * then it is assumed to be the reference of the cell in which the ROW function appears; * otherwise this function returns 1. * * Excel Function: * =ROW([cellAddress]) * * @param null|array|string $cellAddress A reference to a range of cells for which you want the row numbers * * @return int|mixed[]|string */ public static function ROW($cellAddress = null, ?Cell $cell = null) { if (self::cellAddressNullOrWhitespace($cellAddress)) { return self::cellRow($cell); } if (is_array($cellAddress)) { foreach ($cellAddress as $rowKey => $rowValue) { foreach ($rowValue as $columnKey => $cellValue) { return (int) preg_replace('/\D/', '', $rowKey); } } return self::cellRow($cell); } $cellAddress = $cellAddress ?? ''; if ($cell !== null) { [,, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); [,, $cellAddress] = Helpers::extractCellAddresses($cellAddress, true, $cell->getWorksheet(), $sheetName); } [, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if (strpos($cellAddress, ':') !== false) { [$startAddress, $endAddress] = explode(':', $cellAddress); $startAddress = (string) preg_replace('/\D/', '', $startAddress); $endAddress = (string) preg_replace('/\D/', '', $endAddress); return array_map( function ($value) { return [$value]; }, range($startAddress, $endAddress) ); } [$cellAddress] = explode(':', $cellAddress); return (int) preg_replace('/\D/', '', $cellAddress); } /** * ROWS. * * Returns the number of rows in an array or reference. * * Excel Function: * =ROWS(cellAddress) * * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells * for which you want the number of rows * * @return int|string The number of rows in cellAddress, or a string if arguments are invalid */ public static function ROWS($cellAddress = null) { if (self::cellAddressNullOrWhitespace($cellAddress)) { return 1; } if (!is_array($cellAddress)) { return ExcelError::VALUE(); } reset($cellAddress); $isMatrix = (is_numeric(key($cellAddress))); [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); if ($isMatrix) { return $columns; } return $rows; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php 0000644 00000023724 15002227416 0022172 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class ExcelMatch { use ArrayEnabled; public const MATCHTYPE_SMALLEST_VALUE = -1; public const MATCHTYPE_FIRST_VALUE = 0; public const MATCHTYPE_LARGEST_VALUE = 1; /** * MATCH. * * The MATCH function searches for a specified item in a range of cells * * Excel Function: * =MATCH(lookup_value, lookup_array, [match_type]) * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupArray The range of cells being searched * @param mixed $matchType The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. * If match_type is 1 or -1, the list has to be ordered. * * @return array|int|string The relative position of the found item */ public static function MATCH($lookupValue, $lookupArray, $matchType = self::MATCHTYPE_LARGEST_VALUE) { if (is_array($lookupValue)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $matchType); } $lookupArray = Functions::flattenArray($lookupArray); try { // Input validation self::validateLookupValue($lookupValue); $matchType = self::validateMatchType($matchType); self::validateLookupArray($lookupArray); $keySet = array_keys($lookupArray); if ($matchType == self::MATCHTYPE_LARGEST_VALUE) { // If match_type is 1 the list has to be processed from last to first $lookupArray = array_reverse($lookupArray); $keySet = array_reverse($keySet); } $lookupArray = self::prepareLookupArray($lookupArray, $matchType); } catch (Exception $e) { return $e->getMessage(); } // MATCH() is not case sensitive, so we convert lookup value to be lower cased if it's a string type. if (is_string($lookupValue)) { $lookupValue = StringHelper::strToLower($lookupValue); } $valueKey = null; switch ($matchType) { case self::MATCHTYPE_LARGEST_VALUE: $valueKey = self::matchLargestValue($lookupArray, $lookupValue, $keySet); break; case self::MATCHTYPE_FIRST_VALUE: $valueKey = self::matchFirstValue($lookupArray, $lookupValue); break; case self::MATCHTYPE_SMALLEST_VALUE: default: $valueKey = self::matchSmallestValue($lookupArray, $lookupValue); } if ($valueKey !== null) { return ++$valueKey; } // Unsuccessful in finding a match, return #N/A error value return ExcelError::NA(); } /** * @param mixed $lookupValue * * @return mixed */ private static function matchFirstValue(array $lookupArray, $lookupValue) { if (is_string($lookupValue)) { $valueIsString = true; $wildcard = WildcardMatch::wildcard($lookupValue); } else { $valueIsString = false; $wildcard = ''; } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if ( $valueIsString && is_string($lookupArrayValue) ) { if (WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; // wildcard match } } else { if ($lookupArrayValue === $lookupValue) { return $i; // exact match } if ( $valueIsNumeric && (is_float($lookupArrayValue) || is_int($lookupArrayValue)) && $lookupArrayValue == $lookupValue ) { return $i; // exact match } } } return null; } /** * @param mixed $lookupValue * * @return mixed */ private static function matchLargestValue(array $lookupArray, $lookupValue, array $keySet) { if (is_string($lookupValue)) { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $wildcard = WildcardMatch::wildcard($lookupValue); foreach (array_reverse($lookupArray) as $i => $lookupArrayValue) { if (is_string($lookupArrayValue) && WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; } } } else { foreach ($lookupArray as $i => $lookupArrayValue) { if ($lookupArrayValue === $lookupValue) { return $keySet[$i]; } } } } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if ($valueIsNumeric && (is_int($lookupArrayValue) || is_float($lookupArrayValue))) { if ($lookupArrayValue <= $lookupValue) { return array_search($i, $keySet); } } $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); if ($typeMatch && ($lookupArrayValue <= $lookupValue)) { return array_search($i, $keySet); } } return null; } /** * @param mixed $lookupValue * * @return mixed */ private static function matchSmallestValue(array $lookupArray, $lookupValue) { $valueKey = null; if (is_string($lookupValue)) { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $wildcard = WildcardMatch::wildcard($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if (is_string($lookupArrayValue) && WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; } } } } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); // The basic algorithm is: // Iterate and keep the highest match until the next element is smaller than the searched value. // Return immediately if perfect match is found foreach ($lookupArray as $i => $lookupArrayValue) { $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); $bothNumeric = $valueIsNumeric && (is_int($lookupArrayValue) || is_float($lookupArrayValue)); if ($lookupArrayValue === $lookupValue) { // Another "special" case. If a perfect match is found, // the algorithm gives up immediately return $i; } if ($bothNumeric && $lookupValue == $lookupArrayValue) { return $i; // exact match, as above } if (($typeMatch || $bothNumeric) && $lookupArrayValue >= $lookupValue) { $valueKey = $i; } elseif ($typeMatch && $lookupArrayValue < $lookupValue) { //Excel algorithm gives up immediately if the first element is smaller than the searched value break; } } return $valueKey; } /** * @param mixed $lookupValue */ private static function validateLookupValue($lookupValue): void { // Lookup_value type has to be number, text, or logical values if ((!is_numeric($lookupValue)) && (!is_string($lookupValue)) && (!is_bool($lookupValue))) { throw new Exception(ExcelError::NA()); } } /** * @param mixed $matchType */ private static function validateMatchType($matchType): int { // Match_type is 0, 1 or -1 // However Excel accepts other numeric values, // including numeric strings and floats. // It seems to just be interested in the sign. if (!is_numeric($matchType)) { throw new Exception(ExcelError::Value()); } if ($matchType > 0) { return self::MATCHTYPE_LARGEST_VALUE; } if ($matchType < 0) { return self::MATCHTYPE_SMALLEST_VALUE; } return self::MATCHTYPE_FIRST_VALUE; } private static function validateLookupArray(array $lookupArray): void { // Lookup_array should not be empty $lookupArraySize = count($lookupArray); if ($lookupArraySize <= 0) { throw new Exception(ExcelError::NA()); } } /** * @param mixed $matchType */ private static function prepareLookupArray(array $lookupArray, $matchType): array { // Lookup_array should contain only number, text, or logical values, or empty (null) cells foreach ($lookupArray as $i => $value) { // check the type of the value if ((!is_numeric($value)) && (!is_string($value)) && (!is_bool($value)) && ($value !== null)) { throw new Exception(ExcelError::NA()); } // Convert strings to lowercase for case-insensitive testing if (is_string($value)) { $lookupArray[$i] = StringHelper::strToLower($value); } if ( ($value === null) && (($matchType == self::MATCHTYPE_LARGEST_VALUE) || ($matchType == self::MATCHTYPE_SMALLEST_VALUE)) ) { unset($lookupArray[$i]); } } return $lookupArray; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Matrix.php 0000644 00000010507 15002227416 0021414 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Matrix { use ArrayEnabled; /** * Helper function; NOT an implementation of any Excel Function. */ public static function isColumnVector(array $values): bool { return count($values, COUNT_RECURSIVE) === (count($values, COUNT_NORMAL) * 2); } /** * Helper function; NOT an implementation of any Excel Function. */ public static function isRowVector(array $values): bool { return count($values, COUNT_RECURSIVE) > 1 && (count($values, COUNT_NORMAL) === 1 || count($values, COUNT_RECURSIVE) === count($values, COUNT_NORMAL)); } /** * TRANSPOSE. * * @param array|mixed $matrixData A matrix of values * * @return array */ public static function transpose($matrixData) { $returnMatrix = []; if (!is_array($matrixData)) { $matrixData = [[$matrixData]]; } $column = 0; foreach ($matrixData as $matrixRow) { $row = 0; foreach ($matrixRow as $matrixCell) { $returnMatrix[$row][$column] = $matrixCell; ++$row; } ++$column; } return $returnMatrix; } /** * INDEX. * * Uses an index to choose a value from a reference or array * * Excel Function: * =INDEX(range_array, row_num, [column_num], [area_num]) * * @param mixed $matrix A range of cells or an array constant * @param mixed $rowNum The row in the array or range from which to return a value. * If row_num is omitted, column_num is required. * Or can be an array of values * @param mixed $columnNum The column in the array or range from which to return a value. * If column_num is omitted, row_num is required. * Or can be an array of values * * TODO Provide support for area_num, currently not supported * * @return mixed the value of a specified cell or array of cells * If an array of values is passed as the $rowNum and/or $columnNum arguments, then the returned result * will also be an array with the same dimensions */ public static function index($matrix, $rowNum = 0, $columnNum = null) { if (is_array($rowNum) || is_array($columnNum)) { return self::evaluateArrayArgumentsSubsetFrom([self::class, __FUNCTION__], 1, $matrix, $rowNum, $columnNum); } $rowNum = $rowNum ?? 0; $originalColumnNum = $columnNum; $columnNum = $columnNum ?? 0; try { $rowNum = LookupRefValidations::validatePositiveInt($rowNum); $columnNum = LookupRefValidations::validatePositiveInt($columnNum); } catch (Exception $e) { return $e->getMessage(); } if (!is_array($matrix) || ($rowNum > count($matrix))) { return ExcelError::REF(); } $rowKeys = array_keys($matrix); $columnKeys = @array_keys($matrix[$rowKeys[0]]); if ($columnNum > count($columnKeys)) { return ExcelError::REF(); } if ($originalColumnNum === null && 1 < count($columnKeys)) { return ExcelError::REF(); } if ($columnNum === 0) { return self::extractRowValue($matrix, $rowKeys, $rowNum); } $columnNum = $columnKeys[--$columnNum]; if ($rowNum === 0) { return array_map( function ($value) { return [$value]; }, array_column($matrix, $columnNum) ); } $rowNum = $rowKeys[--$rowNum]; return $matrix[$rowNum][$columnNum]; } /** @return mixed */ private static function extractRowValue(array $matrix, array $rowKeys, int $rowNum) { if ($rowNum === 0) { return $matrix; } $rowNum = $rowKeys[--$rowNum]; $row = $matrix[$rowNum]; if (is_array($row)) { return [$rowNum => $row]; } return $row; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Filter.php 0000644 00000004122 15002227416 0021371 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Filter { /** * @param mixed $lookupArray * @param mixed $matchArray * @param mixed $ifEmpty * * @return mixed */ public static function filter($lookupArray, $matchArray, $ifEmpty = null) { if (!is_array($matchArray)) { return ExcelError::VALUE(); } $matchArray = self::enumerateArrayKeys($matchArray); $result = (Matrix::isColumnVector($matchArray)) ? self::filterByRow($lookupArray, $matchArray) : self::filterByColumn($lookupArray, $matchArray); if (empty($result)) { return $ifEmpty ?? ExcelError::CALC(); } return array_values(array_map('array_values', $result)); } private static function enumerateArrayKeys(array $sortArray): array { array_walk( $sortArray, function (&$columns): void { if (is_array($columns)) { $columns = array_values($columns); } } ); return array_values($sortArray); } private static function filterByRow(array $lookupArray, array $matchArray): array { $matchArray = array_values(array_column($matchArray, 0)); return array_filter( array_values($lookupArray), function ($index) use ($matchArray): bool { return (bool) $matchArray[$index]; }, ARRAY_FILTER_USE_KEY ); } private static function filterByColumn(array $lookupArray, array $matchArray): array { $lookupArray = Matrix::transpose($lookupArray); if (count($matchArray) === 1) { $matchArray = array_pop($matchArray); } array_walk( $matchArray, function (&$value): void { $value = [$value]; } ); $result = self::filterByRow($lookupArray, $matchArray); return Matrix::transpose($result); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php 0000644 00000002743 15002227416 0022100 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Selection { use ArrayEnabled; /** * CHOOSE. * * Uses lookup_value to return a value from the list of value arguments. * Use CHOOSE to select one of up to 254 values based on the lookup_value. * * Excel Function: * =CHOOSE(index_num, value1, [value2], ...) * * @param mixed $chosenEntry The entry to select from the list (indexed from 1) * @param mixed ...$chooseArgs Data values * * @return mixed The selected value */ public static function choose($chosenEntry, ...$chooseArgs) { if (is_array($chosenEntry)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $chosenEntry, ...$chooseArgs); } $entryCount = count($chooseArgs) - 1; if (is_numeric($chosenEntry)) { --$chosenEntry; } else { return ExcelError::VALUE(); } $chosenEntry = floor($chosenEntry); if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) { return ExcelError::VALUE(); } if (is_array($chooseArgs[$chosenEntry])) { return Functions::flattenArray($chooseArgs[$chosenEntry]); } return $chooseArgs[$chosenEntry]; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php 0000644 00000010112 15002227416 0021537 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class VLookup extends LookupBase { use ArrayEnabled; /** * VLOOKUP * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value * in the same row based on the index_number. * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupArray The range of cells being searched * @param mixed $indexNumber The column number in table_array from which the matching value must be returned. * The first column is 1. * @param mixed $notExactMatch determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function lookup($lookupValue, $lookupArray, $indexNumber, $notExactMatch = true) { if (is_array($lookupValue) || is_array($indexNumber)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $indexNumber, $notExactMatch); } $notExactMatch = (bool) ($notExactMatch ?? true); try { self::validateLookupArray($lookupArray); $indexNumber = self::validateIndexLookup($lookupArray, $indexNumber); } catch (Exception $e) { return $e->getMessage(); } $f = array_keys($lookupArray); $firstRow = array_pop($f); if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray[$firstRow]))) { return ExcelError::REF(); } $columnKeys = array_keys($lookupArray[$firstRow]); $returnColumn = $columnKeys[--$indexNumber]; $firstColumn = array_shift($columnKeys) ?? 1; if (!$notExactMatch) { /** @var callable */ $callable = [self::class, 'vlookupSort']; uasort($lookupArray, $callable); } $rowNumber = self::vLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); if ($rowNumber !== null) { // return the appropriate value return $lookupArray[$rowNumber][$returnColumn]; } return ExcelError::NA(); } private static function vlookupSort(array $a, array $b): int { reset($a); $firstColumn = key($a); $aLower = StringHelper::strToLower((string) $a[$firstColumn]); $bLower = StringHelper::strToLower((string) $b[$firstColumn]); if ($aLower == $bLower) { return 0; } return ($aLower < $bLower) ? -1 : 1; } /** * @param mixed $lookupValue The value that you want to match in lookup_array * @param int|string $column */ private static function vLookupSearch($lookupValue, array $lookupArray, $column, bool $notExactMatch): ?int { $lookupLower = StringHelper::strToLower((string) $lookupValue); $rowNumber = null; foreach ($lookupArray as $rowKey => $rowData) { $bothNumeric = is_numeric($lookupValue) && is_numeric($rowData[$column]); $bothNotNumeric = !is_numeric($lookupValue) && !is_numeric($rowData[$column]); $cellDataLower = StringHelper::strToLower((string) $rowData[$column]); // break if we have passed possible keys if ( $notExactMatch && (($bothNumeric && ($rowData[$column] > $lookupValue)) || ($bothNotNumeric && ($cellDataLower > $lookupLower))) ) { break; } $rowNumber = self::checkMatch( $bothNumeric, $bothNotNumeric, $notExactMatch, $rowKey, $cellDataLower, $lookupLower, $rowNumber ); } return $rowNumber; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php 0000644 00000005367 15002227416 0021562 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Cell\AddressHelper; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Helpers { public const CELLADDRESS_USE_A1 = true; public const CELLADDRESS_USE_R1C1 = false; private static function convertR1C1(string &$cellAddress1, ?string &$cellAddress2, bool $a1, ?int $baseRow = null, ?int $baseCol = null): string { if ($a1 === self::CELLADDRESS_USE_R1C1) { $cellAddress1 = AddressHelper::convertToA1($cellAddress1, $baseRow ?? 1, $baseCol ?? 1); if ($cellAddress2) { $cellAddress2 = AddressHelper::convertToA1($cellAddress2, $baseRow ?? 1, $baseCol ?? 1); } } return $cellAddress1 . ($cellAddress2 ? ":$cellAddress2" : ''); } private static function adjustSheetTitle(string &$sheetTitle, ?string $value): void { if ($sheetTitle) { $sheetTitle .= '!'; if (stripos($value ?? '', $sheetTitle) === 0) { $sheetTitle = ''; } } } public static function extractCellAddresses(string $cellAddress, bool $a1, Worksheet $sheet, string $sheetName = '', ?int $baseRow = null, ?int $baseCol = null): array { $cellAddress1 = $cellAddress; $cellAddress2 = null; $namedRange = DefinedName::resolveName($cellAddress1, $sheet, $sheetName); if ($namedRange !== null) { $workSheet = $namedRange->getWorkSheet(); $sheetTitle = ($workSheet === null) ? '' : $workSheet->getTitle(); $value = (string) preg_replace('/^=/', '', $namedRange->getValue()); self::adjustSheetTitle($sheetTitle, $value); $cellAddress1 = $sheetTitle . $value; $cellAddress = $cellAddress1; $a1 = self::CELLADDRESS_USE_A1; } if (strpos($cellAddress, ':') !== false) { [$cellAddress1, $cellAddress2] = explode(':', $cellAddress); } $cellAddress = self::convertR1C1($cellAddress1, $cellAddress2, $a1, $baseRow, $baseCol); return [$cellAddress1, $cellAddress2, $cellAddress]; } public static function extractWorksheet(string $cellAddress, Cell $cell): array { $sheetName = ''; if (strpos($cellAddress, '!') !== false) { [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); $sheetName = trim($sheetName, "'"); } $worksheet = ($sheetName !== '') ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($sheetName) : $cell->getWorksheet(); return [$cellAddress, $worksheet, $sheetName]; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Sort.php 0000644 00000030173 15002227416 0021100 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Sort extends LookupRefValidations { public const ORDER_ASCENDING = 1; public const ORDER_DESCENDING = -1; /** * SORT * The SORT function returns a sorted array of the elements in an array. * The returned array is the same shape as the provided array argument. * Both $sortIndex and $sortOrder can be arrays, to provide multi-level sorting. * * @param mixed $sortArray The range of cells being sorted * @param mixed $sortIndex The column or row number within the sortArray to sort on * @param mixed $sortOrder Flag indicating whether to sort ascending or descending * Ascending = 1 (self::ORDER_ASCENDING) * Descending = -1 (self::ORDER_DESCENDING) * @param mixed $byColumn Whether the sort should be determined by row (the default) or by column * * @return mixed The sorted values from the sort range */ public static function sort($sortArray, $sortIndex = 1, $sortOrder = self::ORDER_ASCENDING, $byColumn = false) { if (!is_array($sortArray)) { // Scalars are always returned "as is" return $sortArray; } $sortArray = self::enumerateArrayKeys($sortArray); $byColumn = (bool) $byColumn; $lookupIndexSize = $byColumn ? count($sortArray) : count($sortArray[0]); try { // If $sortIndex and $sortOrder are scalars, then convert them into arrays if (is_scalar($sortIndex)) { $sortIndex = [$sortIndex]; $sortOrder = is_scalar($sortOrder) ? [$sortOrder] : $sortOrder; } // but the values of those array arguments still need validation $sortOrder = (empty($sortOrder) ? [self::ORDER_ASCENDING] : $sortOrder); self::validateArrayArgumentsForSort($sortIndex, $sortOrder, $lookupIndexSize); } catch (Exception $e) { return $e->getMessage(); } // We want a simple, enumrated array of arrays where we can reference column by its index number. $sortArray = array_values(array_map('array_values', $sortArray)); return ($byColumn === true) ? self::sortByColumn($sortArray, $sortIndex, $sortOrder) : self::sortByRow($sortArray, $sortIndex, $sortOrder); } /** * SORTBY * The SORTBY function sorts the contents of a range or array based on the values in a corresponding range or array. * The returned array is the same shape as the provided array argument. * Both $sortIndex and $sortOrder can be arrays, to provide multi-level sorting. * * @param mixed $sortArray The range of cells being sorted * @param mixed $args * At least one additional argument must be provided, The vector or range to sort on * After that, arguments are passed as pairs: * sort order: ascending or descending * Ascending = 1 (self::ORDER_ASCENDING) * Descending = -1 (self::ORDER_DESCENDING) * additional arrays or ranges for multi-level sorting * * @return mixed The sorted values from the sort range */ public static function sortBy($sortArray, ...$args) { if (!is_array($sortArray)) { // Scalars are always returned "as is" return $sortArray; } $sortArray = self::enumerateArrayKeys($sortArray); $lookupArraySize = count($sortArray); $argumentCount = count($args); try { $sortBy = $sortOrder = []; for ($i = 0; $i < $argumentCount; $i += 2) { $sortBy[] = self::validateSortVector($args[$i], $lookupArraySize); $sortOrder[] = self::validateSortOrder($args[$i + 1] ?? self::ORDER_ASCENDING); } } catch (Exception $e) { return $e->getMessage(); } return self::processSortBy($sortArray, $sortBy, $sortOrder); } private static function enumerateArrayKeys(array $sortArray): array { array_walk( $sortArray, function (&$columns): void { if (is_array($columns)) { $columns = array_values($columns); } } ); return array_values($sortArray); } /** * @param mixed $sortIndex * @param mixed $sortOrder */ private static function validateScalarArgumentsForSort(&$sortIndex, &$sortOrder, int $sortArraySize): void { if (is_array($sortIndex) || is_array($sortOrder)) { throw new Exception(ExcelError::VALUE()); } $sortIndex = self::validatePositiveInt($sortIndex, false); if ($sortIndex > $sortArraySize) { throw new Exception(ExcelError::VALUE()); } $sortOrder = self::validateSortOrder($sortOrder); } /** * @param mixed $sortVector */ private static function validateSortVector($sortVector, int $sortArraySize): array { if (!is_array($sortVector)) { throw new Exception(ExcelError::VALUE()); } // It doesn't matter if it's a row or a column vectors, it works either way $sortVector = Functions::flattenArray($sortVector); if (count($sortVector) !== $sortArraySize) { throw new Exception(ExcelError::VALUE()); } return $sortVector; } /** * @param mixed $sortOrder */ private static function validateSortOrder($sortOrder): int { $sortOrder = self::validateInt($sortOrder); if (($sortOrder == self::ORDER_ASCENDING || $sortOrder === self::ORDER_DESCENDING) === false) { throw new Exception(ExcelError::VALUE()); } return $sortOrder; } /** * @param array $sortIndex * @param mixed $sortOrder */ private static function validateArrayArgumentsForSort(&$sortIndex, &$sortOrder, int $sortArraySize): void { // It doesn't matter if they're row or column vectors, it works either way $sortIndex = Functions::flattenArray($sortIndex); $sortOrder = Functions::flattenArray($sortOrder); if ( count($sortOrder) === 0 || count($sortOrder) > $sortArraySize || (count($sortOrder) > count($sortIndex)) ) { throw new Exception(ExcelError::VALUE()); } if (count($sortIndex) > count($sortOrder)) { // If $sortOrder has fewer elements than $sortIndex, then the last order element is repeated. $sortOrder = array_merge( $sortOrder, array_fill(0, count($sortIndex) - count($sortOrder), array_pop($sortOrder)) ); } foreach ($sortIndex as $key => &$value) { self::validateScalarArgumentsForSort($value, $sortOrder[$key], $sortArraySize); } } private static function prepareSortVectorValues(array $sortVector): array { // Strings should be sorted case-insensitive; with booleans converted to locale-strings return array_map( function ($value) { if (is_bool($value)) { return ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); } elseif (is_string($value)) { return StringHelper::strToLower($value); } return $value; }, $sortVector ); } /** * @param array[] $sortIndex * @param int[] $sortOrder */ private static function processSortBy(array $sortArray, array $sortIndex, $sortOrder): array { $sortArguments = []; $sortData = []; foreach ($sortIndex as $index => $sortValues) { $sortData[] = $sortValues; $sortArguments[] = self::prepareSortVectorValues($sortValues); $sortArguments[] = $sortOrder[$index] === self::ORDER_ASCENDING ? SORT_ASC : SORT_DESC; } $sortArguments = self::applyPHP7Patch($sortArray, $sortArguments); $sortVector = self::executeVectorSortQuery($sortData, $sortArguments); return self::sortLookupArrayFromVector($sortArray, $sortVector); } /** * @param int[] $sortIndex * @param int[] $sortOrder */ private static function sortByRow(array $sortArray, array $sortIndex, array $sortOrder): array { $sortVector = self::buildVectorForSort($sortArray, $sortIndex, $sortOrder); return self::sortLookupArrayFromVector($sortArray, $sortVector); } /** * @param int[] $sortIndex * @param int[] $sortOrder */ private static function sortByColumn(array $sortArray, array $sortIndex, array $sortOrder): array { $sortArray = Matrix::transpose($sortArray); $result = self::sortByRow($sortArray, $sortIndex, $sortOrder); return Matrix::transpose($result); } /** * @param int[] $sortIndex * @param int[] $sortOrder */ private static function buildVectorForSort(array $sortArray, array $sortIndex, array $sortOrder): array { $sortArguments = []; $sortData = []; foreach ($sortIndex as $index => $sortIndexValue) { $sortValues = array_column($sortArray, $sortIndexValue - 1); $sortData[] = $sortValues; $sortArguments[] = self::prepareSortVectorValues($sortValues); $sortArguments[] = $sortOrder[$index] === self::ORDER_ASCENDING ? SORT_ASC : SORT_DESC; } $sortArguments = self::applyPHP7Patch($sortArray, $sortArguments); $sortData = self::executeVectorSortQuery($sortData, $sortArguments); return $sortData; } private static function executeVectorSortQuery(array $sortData, array $sortArguments): array { $sortData = Matrix::transpose($sortData); // We need to set an index that can be retained, as array_multisort doesn't maintain numeric keys. $sortDataIndexed = []; foreach ($sortData as $key => $value) { $sortDataIndexed[Coordinate::stringFromColumnIndex($key + 1)] = $value; } unset($sortData); $sortArguments[] = &$sortDataIndexed; array_multisort(...$sortArguments); // After the sort, we restore the numeric keys that will now be in the correct, sorted order $sortedData = []; foreach (array_keys($sortDataIndexed) as $key) { $sortedData[] = Coordinate::columnIndexFromString($key) - 1; } return $sortedData; } private static function sortLookupArrayFromVector(array $sortArray, array $sortVector): array { // Building a new array in the correct (sorted) order works; but may be memory heavy for larger arrays $sortedArray = []; foreach ($sortVector as $index) { $sortedArray[] = $sortArray[$index]; } return $sortedArray; // uksort( // $lookupArray, // function (int $a, int $b) use (array $sortVector) { // return $sortVector[$a] <=> $sortVector[$b]; // } // ); // // return $lookupArray; } /** * Hack to handle PHP 7: * From PHP 8.0.0, If two members compare as equal in a sort, they retain their original order; * but prior to PHP 8.0.0, their relative order in the sorted array was undefined. * MS Excel replicates the PHP 8.0.0 behaviour, retaining the original order of matching elements. * To replicate that behaviour with PHP 7, we add an extra sort based on the row index. */ private static function applyPHP7Patch(array $sortArray, array $sortArguments): array { if (PHP_VERSION_ID < 80000) { $sortArguments[] = range(1, count($sortArray)); $sortArguments[] = SORT_ASC; } return $sortArguments; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/LookupRefValidations.php 0000644 00000001722 15002227416 0024253 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class LookupRefValidations { /** * @param mixed $value */ public static function validateInt($value): int { if (!is_numeric($value)) { if (ErrorValue::isError($value)) { throw new Exception($value); } throw new Exception(ExcelError::VALUE()); } return (int) floor((float) $value); } /** * @param mixed $value */ public static function validatePositiveInt($value, bool $allowZero = true): int { $value = self::validateInt($value); if (($allowZero === false && $value <= 0) || $value < 0) { throw new Exception(ExcelError::VALUE()); } return $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Address.php 0000644 00000011301 15002227416 0021526 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\AddressHelper; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; class Address { use ArrayEnabled; public const ADDRESS_ABSOLUTE = 1; public const ADDRESS_COLUMN_RELATIVE = 2; public const ADDRESS_ROW_RELATIVE = 3; public const ADDRESS_RELATIVE = 4; public const REFERENCE_STYLE_A1 = true; public const REFERENCE_STYLE_R1C1 = false; /** * ADDRESS. * * Creates a cell address as text, given specified row and column numbers. * * Excel Function: * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText]) * * @param mixed $row Row number (integer) to use in the cell reference * Or can be an array of values * @param mixed $column Column number (integer) to use in the cell reference * Or can be an array of values * @param mixed $relativity Integer flag indicating the type of reference to return * 1 or omitted Absolute * 2 Absolute row; relative column * 3 Relative row; absolute column * 4 Relative * Or can be an array of values * @param mixed $referenceStyle A logical (boolean) value that specifies the A1 or R1C1 reference style. * TRUE or omitted ADDRESS returns an A1-style reference * FALSE ADDRESS returns an R1C1-style reference * Or can be an array of values * @param mixed $sheetName Optional Name of worksheet to use * Or can be an array of values * * @return array|string * If an array of values is passed as the $testValue argument, then the returned result will also be * an array with the same dimensions */ public static function cell($row, $column, $relativity = 1, $referenceStyle = true, $sheetName = '') { if ( is_array($row) || is_array($column) || is_array($relativity) || is_array($referenceStyle) || is_array($sheetName) ) { return self::evaluateArrayArguments( [self::class, __FUNCTION__], $row, $column, $relativity, $referenceStyle, $sheetName ); } $relativity = $relativity ?? 1; $referenceStyle = $referenceStyle ?? true; if (($row < 1) || ($column < 1)) { return ExcelError::VALUE(); } $sheetName = self::sheetName($sheetName); if (is_int($referenceStyle)) { $referenceStyle = (bool) $referenceStyle; } if ((!is_bool($referenceStyle)) || $referenceStyle === self::REFERENCE_STYLE_A1) { return self::formatAsA1($row, $column, $relativity, $sheetName); } return self::formatAsR1C1($row, $column, $relativity, $sheetName); } private static function sheetName(string $sheetName): string { if ($sheetName > '') { if (strpos($sheetName, ' ') !== false || strpos($sheetName, '[') !== false) { $sheetName = "'{$sheetName}'"; } $sheetName .= '!'; } return $sheetName; } private static function formatAsA1(int $row, int $column, int $relativity, string $sheetName): string { $rowRelative = $columnRelative = '$'; if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $columnRelative = ''; } if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $rowRelative = ''; } $column = Coordinate::stringFromColumnIndex($column); return "{$sheetName}{$columnRelative}{$column}{$rowRelative}{$row}"; } private static function formatAsR1C1(int $row, int $column, int $relativity, string $sheetName): string { if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $column = "[{$column}]"; } if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $row = "[{$row}]"; } [$rowChar, $colChar] = AddressHelper::getRowAndColumnChars(); return "{$sheetName}$rowChar{$row}$colChar{$column}"; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Formula.php 0000644 00000002362 15002227416 0021555 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; class Formula { /** * FORMULATEXT. * * @param mixed $cellReference The cell to check * @param Cell $cell The current cell (containing this formula) * * @return string */ public static function text($cellReference = '', ?Cell $cell = null) { if ($cell === null) { return ExcelError::REF(); } preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellReference, $matches); $cellReference = $matches[6] . $matches[7]; $worksheetName = trim($matches[3], "'"); $worksheet = (!empty($worksheetName)) ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($worksheetName) : $cell->getWorksheet(); if ( $worksheet === null || !$worksheet->cellExists($cellReference) || !$worksheet->getCell($cellReference)->isFormula() ) { return ExcelError::NA(); } return $worksheet->getCell($cellReference)->getValue(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php 0000644 00000006755 15002227416 0021433 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\LookupRef; class Lookup { use ArrayEnabled; /** * LOOKUP * The LOOKUP function searches for value either from a one-row or one-column range or from an array. * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupVector The range of cells being searched * @param null|mixed $resultVector The column from which the matching value must be returned * * @return mixed The value of the found cell */ public static function lookup($lookupValue, $lookupVector, $resultVector = null) { if (is_array($lookupValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $lookupValue, $lookupVector, $resultVector); } if (!is_array($lookupVector)) { return ExcelError::NA(); } $hasResultVector = isset($resultVector); $lookupRows = self::rowCount($lookupVector); $lookupColumns = self::columnCount($lookupVector); // we correctly orient our results if (($lookupRows === 1 && $lookupColumns > 1) || (!$hasResultVector && $lookupRows === 2 && $lookupColumns !== 2)) { $lookupVector = LookupRef\Matrix::transpose($lookupVector); $lookupRows = self::rowCount($lookupVector); $lookupColumns = self::columnCount($lookupVector); } $resultVector = self::verifyResultVector($resultVector ?? $lookupVector); if ($lookupRows === 2 && !$hasResultVector) { $resultVector = array_pop($lookupVector); $lookupVector = array_shift($lookupVector); } if ($lookupColumns !== 2) { $lookupVector = self::verifyLookupValues($lookupVector, $resultVector); } return VLookup::lookup($lookupValue, $lookupVector, 2); } private static function verifyLookupValues(array $lookupVector, array $resultVector): array { foreach ($lookupVector as &$value) { if (is_array($value)) { $k = array_keys($value); $key1 = $key2 = array_shift($k); ++$key2; $dataValue1 = $value[$key1]; } else { $key1 = 0; $key2 = 1; $dataValue1 = $value; } $dataValue2 = array_shift($resultVector); if (is_array($dataValue2)) { $dataValue2 = array_shift($dataValue2); } $value = [$key1 => $dataValue1, $key2 => $dataValue2]; } unset($value); return $lookupVector; } private static function verifyResultVector(array $resultVector): array { $resultRows = self::rowCount($resultVector); $resultColumns = self::columnCount($resultVector); // we correctly orient our results if ($resultRows === 1 && $resultColumns > 1) { $resultVector = LookupRef\Matrix::transpose($resultVector); } return $resultVector; } private static function rowCount(array $dataArray): int { return count($dataArray); } private static function columnCount(array $dataArray): int { $rowKeys = array_keys($dataArray); $row = array_shift($rowKeys); return count($dataArray[$row]); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php 0000644 00000004366 15002227416 0022222 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; abstract class LookupBase { /** * @param mixed $lookup_array */ protected static function validateLookupArray($lookup_array): void { if (!is_array($lookup_array)) { throw new Exception(ExcelError::REF()); } } /** @param float|int|string $index_number */ protected static function validateIndexLookup(array $lookup_array, $index_number): int { // index_number must be a number greater than or equal to 1. // Excel results are inconsistent when index is non-numeric. // VLOOKUP(whatever, whatever, SQRT(-1)) yields NUM error, but // VLOOKUP(whatever, whatever, cellref) yields REF error // when cellref is '=SQRT(-1)'. So just try our best here. // Similar results if string (literal yields VALUE, cellRef REF). if (!is_numeric($index_number)) { throw new Exception(ExcelError::throwError($index_number)); } if ($index_number < 1) { throw new Exception(ExcelError::VALUE()); } // index_number must be less than or equal to the number of columns in lookup_array if (empty($lookup_array)) { throw new Exception(ExcelError::REF()); } return (int) $index_number; } protected static function checkMatch( bool $bothNumeric, bool $bothNotNumeric, bool $notExactMatch, int $rowKey, string $cellDataLower, string $lookupLower, ?int $rowNumber ): ?int { // remember the last key, but only if datatypes match if ($bothNumeric || $bothNotNumeric) { // Spreadsheets software returns first exact match, // we have sorted and we might have broken key orders // we want the first one (by its initial index) if ($notExactMatch) { $rowNumber = $rowKey; } elseif (($cellDataLower == $lookupLower) && (($rowNumber === null) || ($rowKey < $rowNumber))) { $rowNumber = $rowKey; } } return $rowNumber; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php 0000644 00000000307 15002227416 0022055 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Internal; class MakeMatrix { /** @param array $args */ public static function make(...$args): array { return $args; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Internal/WildcardMatch.php 0000644 00000002350 15002227416 0022521 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Internal; class WildcardMatch { private const SEARCH_SET = [ '~~', // convert double tilde to unprintable value '~\\*', // convert tilde backslash asterisk to [*] (matches literal asterisk in regexp) '\\*', // convert backslash asterisk to .* (matches string of any length in regexp) '~\\?', // convert tilde backslash question to [?] (matches literal question mark in regexp) '\\?', // convert backslash question to . (matches one character in regexp) "\x1c", // convert original double tilde to single tilde ]; private const REPLACEMENT_SET = [ "\x1c", '[*]', '.*', '[?]', '.', '~', ]; public static function wildcard(string $wildcard): string { // Preg Escape the wildcard, but protecting the Excel * and ? search characters return str_replace(self::SEARCH_SET, self::REPLACEMENT_SET, preg_quote($wildcard, '/')); } public static function compare(?string $value, string $wildcard): bool { if ($value === '' || $value === null) { return false; } return (bool) preg_match("/^{$wildcard}\$/mui", $value); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTime.php 0000644 00000106247 15002227416 0017745 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; use DateTimeInterface; /** * @deprecated 1.18.0 */ class DateTime { /** * Identify if a year is a leap year or not. * * @deprecated 1.18.0 * Use the isLeapYear method in the DateTimeExcel\Helpers class instead * @see DateTimeExcel\Helpers::isLeapYear() * * @param int|string $year The year to test * * @return bool TRUE if the year is a leap year, otherwise FALSE */ public static function isLeapYear($year) { return DateTimeExcel\Helpers::isLeapYear($year); } /** * getDateValue. * * @deprecated 1.18.0 * Use the getDateValue method in the DateTimeExcel\Helpers class instead * @see DateTimeExcel\Helpers::getDateValue() * * @param mixed $dateValue * * @return mixed Excel date/time serial value, or string if error */ public static function getDateValue($dateValue) { try { return DateTimeExcel\Helpers::getDateValue($dateValue); } catch (Exception $e) { return $e->getMessage(); } } /** * DATETIMENOW. * * Returns the current date and time. * The NOW function is useful when you need to display the current date and time on a worksheet or * calculate a value based on the current date and time, and have that value updated each time you * open the worksheet. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * and time format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * NOW() * * @deprecated 1.18.0 * Use the now method in the DateTimeExcel\Current class instead * @see DateTimeExcel\Current::now() * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function DATETIMENOW() { return DateTimeExcel\Current::now(); } /** * DATENOW. * * Returns the current date. * The NOW function is useful when you need to display the current date and time on a worksheet or * calculate a value based on the current date and time, and have that value updated each time you * open the worksheet. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * and time format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * TODAY() * * @deprecated 1.18.0 * Use the today method in the DateTimeExcel\Current class instead * @see DateTimeExcel\Current::today() * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function DATENOW() { return DateTimeExcel\Current::today(); } /** * DATE. * * The DATE function returns a value that represents a particular date. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * * Excel Function: * DATE(year,month,day) * * @deprecated 1.18.0 * Use the fromYMD method in the DateTimeExcel\Date class instead * @see DateTimeExcel\Date::fromYMD() * * PhpSpreadsheet is a lot more forgiving than MS Excel when passing non numeric values to this function. * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted, * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language. * * @param int $year The value of the year argument can include one to four digits. * Excel interprets the year argument according to the configured * date system: 1900 or 1904. * If year is between 0 (zero) and 1899 (inclusive), Excel adds that * value to 1900 to calculate the year. For example, DATE(108,1,2) * returns January 2, 2008 (1900+108). * If year is between 1900 and 9999 (inclusive), Excel uses that * value as the year. For example, DATE(2008,1,2) returns January 2, * 2008. * If year is less than 0 or is 10000 or greater, Excel returns the * #NUM! error value. * @param int $month A positive or negative integer representing the month of the year * from 1 to 12 (January to December). * If month is greater than 12, month adds that number of months to * the first month in the year specified. For example, DATE(2008,14,2) * returns the serial number representing February 2, 2009. * If month is less than 1, month subtracts the magnitude of that * number of months, plus 1, from the first month in the year * specified. For example, DATE(2008,-3,2) returns the serial number * representing September 2, 2007. * @param int $day A positive or negative integer representing the day of the month * from 1 to 31. * If day is greater than the number of days in the month specified, * day adds that number of days to the first day in the month. For * example, DATE(2008,1,35) returns the serial number representing * February 4, 2008. * If day is less than 1, day subtracts the magnitude that number of * days, plus one, from the first day of the month specified. For * example, DATE(2008,1,-15) returns the serial number representing * December 16, 2007. * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function DATE($year = 0, $month = 1, $day = 1) { return DateTimeExcel\Date::fromYMD($year, $month, $day); } /** * TIME. * * The TIME function returns a value that represents a particular time. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * TIME(hour,minute,second) * * @deprecated 1.18.0 * Use the fromHMS method in the DateTimeExcel\Time class instead * @see DateTimeExcel\Time::fromHMS() * * @param int $hour A number from 0 (zero) to 32767 representing the hour. * Any value greater than 23 will be divided by 24 and the remainder * will be treated as the hour value. For example, TIME(27,0,0) = * TIME(3,0,0) = .125 or 3:00 AM. * @param int $minute A number from 0 to 32767 representing the minute. * Any value greater than 59 will be converted to hours and minutes. * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM. * @param int $second A number from 0 to 32767 representing the second. * Any value greater than 59 will be converted to hours, minutes, * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148 * or 12:33:20 AM * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function TIME($hour = 0, $minute = 0, $second = 0) { return DateTimeExcel\Time::fromHMS($hour, $minute, $second); } /** * DATEVALUE. * * Returns a value that represents a particular date. * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp * value. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * DATEVALUE(dateValue) * * @deprecated 1.18.0 * Use the fromString method in the DateTimeExcel\DateValue class instead * @see DateTimeExcel\DateValue::fromString() * * @param string $dateValue Text that represents a date in a Microsoft Excel date format. * For example, "1/30/2008" or "30-Jan-2008" are text strings within * quotation marks that represent dates. Using the default date * system in Excel for Windows, date_text must represent a date from * January 1, 1900, to December 31, 9999. Using the default date * system in Excel for the Macintosh, date_text must represent a date * from January 1, 1904, to December 31, 9999. DATEVALUE returns the * #VALUE! error value if date_text is out of this range. * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function DATEVALUE($dateValue) { return DateTimeExcel\DateValue::fromString($dateValue); } /** * TIMEVALUE. * * Returns a value that represents a particular time. * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp * value. * * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * * Excel Function: * TIMEVALUE(timeValue) * * @deprecated 1.18.0 * Use the fromString method in the DateTimeExcel\TimeValue class instead * @see DateTimeExcel\TimeValue::fromString() * * @param string $timeValue A text string that represents a time in any one of the Microsoft * Excel time formats; for example, "6:45 PM" and "18:45" text strings * within quotation marks that represent time. * Date information in time_text is ignored. * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function TIMEVALUE($timeValue) { return DateTimeExcel\TimeValue::fromString($timeValue); } /** * DATEDIF. * * Excel Function: * DATEDIF(startdate, enddate, unit) * * @deprecated 1.18.0 * Use the interval method in the DateTimeExcel\Difference class instead * @see DateTimeExcel\Difference::interval() * * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object * or a standard date string * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object * or a standard date string * @param array|string $unit * * @return array|int|string Interval between the dates */ public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') { return DateTimeExcel\Difference::interval($startDate, $endDate, $unit); } /** * DAYS. * * Returns the number of days between two dates * * Excel Function: * DAYS(endDate, startDate) * * @deprecated 1.18.0 * Use the between method in the DateTimeExcel\Days class instead * @see DateTimeExcel\Days::between() * * @param array|DateTimeInterface|float|int|string $endDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string * @param array|DateTimeInterface|float|int|string $startDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string * * @return array|int|string Number of days between start date and end date or an error */ public static function DAYS($endDate = 0, $startDate = 0) { return DateTimeExcel\Days::between($endDate, $startDate); } /** * DAYS360. * * Returns the number of days between two dates based on a 360-day year (twelve 30-day months), * which is used in some accounting calculations. Use this function to help compute payments if * your accounting system is based on twelve 30-day months. * * Excel Function: * DAYS360(startDate,endDate[,method]) * * @deprecated 1.18.0 * Use the between method in the DateTimeExcel\Days360 class instead * @see DateTimeExcel\Days360::between() * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param array|bool $method US or European Method * FALSE or omitted: U.S. (NASD) method. If the starting date is * the last day of a month, it becomes equal to the 30th of the * same month. If the ending date is the last day of a month and * the starting date is earlier than the 30th of a month, the * ending date becomes equal to the 1st of the next month; * otherwise the ending date becomes equal to the 30th of the * same month. * TRUE: European method. Starting dates and ending dates that * occur on the 31st of a month become equal to the 30th of the * same month. * * @return array|int|string Number of days between start date and end date */ public static function DAYS360($startDate = 0, $endDate = 0, $method = false) { return DateTimeExcel\Days360::between($startDate, $endDate, $method); } /** * YEARFRAC. * * Calculates the fraction of the year represented by the number of whole days between two dates * (the start_date and the end_date). * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or * obligations to assign to a specific term. * * Excel Function: * YEARFRAC(startDate,endDate[,method]) * * @deprecated 1.18.0 * Use the fraction method in the DateTimeExcel\YearFrac class instead * @see DateTimeExcel\YearFrac::fraction() * * See https://lists.oasis-open.org/archives/office-formula/200806/msg00039.html * for description of algorithm used in Excel * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param array|int $method Method used for the calculation * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return array|float|string fraction of the year, or a string containing an error */ public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) { return DateTimeExcel\YearFrac::fraction($startDate, $endDate, $method); } /** * NETWORKDAYS. * * Returns the number of whole working days between start_date and end_date. Working days * exclude weekends and any dates identified in holidays. * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days * worked during a specific term. * * Excel Function: * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]]) * * @deprecated 1.18.0 * Use the count method in the DateTimeExcel\NetworkDays class instead * @see DateTimeExcel\NetworkDays::count() * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param mixed $dateArgs * * @return array|int|string Interval between the dates */ public static function NETWORKDAYS($startDate, $endDate, ...$dateArgs) { return DateTimeExcel\NetworkDays::count($startDate, $endDate, ...$dateArgs); } /** * WORKDAY. * * Returns the date that is the indicated number of working days before or after a date (the * starting date). Working days exclude weekends and any dates identified as holidays. * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected * delivery times, or the number of days of work performed. * * Excel Function: * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]]) * * @deprecated 1.18.0 * Use the date method in the DateTimeExcel\WorkDay class instead * @see DateTimeExcel\WorkDay::date() * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $endDays The number of nonweekend and nonholiday days before or after * startDate. A positive value for days yields a future date; a * negative value yields a past date. * @param mixed $dateArgs * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function WORKDAY($startDate, $endDays, ...$dateArgs) { return DateTimeExcel\WorkDay::date($startDate, $endDays, ...$dateArgs); } /** * DAYOFMONTH. * * Returns the day of the month, for a specified date. The day is given as an integer * ranging from 1 to 31. * * Excel Function: * DAY(dateValue) * * @deprecated 1.18.0 * Use the day method in the DateTimeExcel\DateParts class instead * @see DateTimeExcel\DateParts::day() * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * * @return array|int|string Day of the month */ public static function DAYOFMONTH($dateValue = 1) { return DateTimeExcel\DateParts::day($dateValue); } /** * WEEKDAY. * * Returns the day of the week for a specified date. The day is given as an integer * ranging from 0 to 7 (dependent on the requested style). * * Excel Function: * WEEKDAY(dateValue[,style]) * * @deprecated 1.18.0 * Use the day method in the DateTimeExcel\Week class instead * @see DateTimeExcel\Week::day() * * @param float|int|string $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $style A number that determines the type of return value * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday). * 2 Numbers 1 (Monday) through 7 (Sunday). * 3 Numbers 0 (Monday) through 6 (Sunday). * * @return array|int|string Day of the week value */ public static function WEEKDAY($dateValue = 1, $style = 1) { return DateTimeExcel\Week::day($dateValue, $style); } /** * STARTWEEK_SUNDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::STARTWEEK_SUNDAY * @see DateTimeExcel\Constants::STARTWEEK_SUNDAY */ const STARTWEEK_SUNDAY = 1; /** * STARTWEEK_MONDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::STARTWEEK_MONDAY * @see DateTimeExcel\Constants::STARTWEEK_MONDAY */ const STARTWEEK_MONDAY = 2; /** * STARTWEEK_MONDAY_ALT. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::STARTWEEK_MONDAY_ALT * @see DateTimeExcel\Constants::STARTWEEK_MONDAY_ALT */ const STARTWEEK_MONDAY_ALT = 11; /** * STARTWEEK_TUESDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::STARTWEEK_TUESDAY * @see DateTimeExcel\Constants::STARTWEEK_TUESDAY */ const STARTWEEK_TUESDAY = 12; /** * STARTWEEK_WEDNESDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::STARTWEEK_WEDNESDAY * @see DateTimeExcel\Constants::STARTWEEK_WEDNESDAY */ const STARTWEEK_WEDNESDAY = 13; /** * STARTWEEK_THURSDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::STARTWEEK_THURSDAY * @see DateTimeExcel\Constants::STARTWEEK_THURSDAY */ const STARTWEEK_THURSDAY = 14; /** * STARTWEEK_FRIDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::STARTWEEK_FRIDAY * @see DateTimeExcel\Constants::STARTWEEK_FRIDAY */ const STARTWEEK_FRIDAY = 15; /** * STARTWEEK_SATURDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::STARTWEEK_SATURDAY * @see DateTimeExcel\Constants::STARTWEEK_SATURDAY */ const STARTWEEK_SATURDAY = 16; /** * STARTWEEK_SUNDAY_ALT. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::STARTWEEK_SUNDAY_ALT * @see DateTimeExcel\Constants::STARTWEEK_SUNDAY_ALT */ const STARTWEEK_SUNDAY_ALT = 17; /** * DOW_SUNDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::DOW_SUNDAY * @see DateTimeExcel\Constants::DOW_SUNDAY */ const DOW_SUNDAY = 1; /** * DOW_MONDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::DOW_MONDAY * @see DateTimeExcel\Constants::DOW_MONDAY */ const DOW_MONDAY = 2; /** * DOW_TUESDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::DOW_TUESDAY * @see DateTimeExcel\Constants::DOW_TUESDAY */ const DOW_TUESDAY = 3; /** * DOW_WEDNESDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::DOW_WEDNESDAY * @see DateTimeExcel\Constants::DOW_WEDNESDAY */ const DOW_WEDNESDAY = 4; /** * DOW_THURSDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::DOW_THURSDAY * @see DateTimeExcel\Constants::DOW_THURSDAY */ const DOW_THURSDAY = 5; /** * DOW_FRIDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::DOW_FRIDAY * @see DateTimeExcel\Constants::DOW_FRIDAY */ const DOW_FRIDAY = 6; /** * DOW_SATURDAY. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::DOW_SATURDAY * @see DateTimeExcel\Constants::DOW_SATURDAY */ const DOW_SATURDAY = 7; /** * STARTWEEK_MONDAY_ISO. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::STARTWEEK_MONDAY_ISO * @see DateTimeExcel\Constants::STARTWEEK_MONDAY_ISO */ const STARTWEEK_MONDAY_ISO = 21; /** * METHODARR. * * @deprecated 1.18.0 * Use DateTimeExcel\Constants::METHODARR * @see DateTimeExcel\Constants::METHODARR */ const METHODARR = [ self::STARTWEEK_SUNDAY => self::DOW_SUNDAY, self::DOW_MONDAY, self::STARTWEEK_MONDAY_ALT => self::DOW_MONDAY, self::DOW_TUESDAY, self::DOW_WEDNESDAY, self::DOW_THURSDAY, self::DOW_FRIDAY, self::DOW_SATURDAY, self::DOW_SUNDAY, self::STARTWEEK_MONDAY_ISO => self::STARTWEEK_MONDAY_ISO, ]; /** * WEEKNUM. * * Returns the week of the year for a specified date. * The WEEKNUM function considers the week containing January 1 to be the first week of the year. * However, there is a European standard that defines the first week as the one with the majority * of days (four or more) falling in the new year. This means that for years in which there are * three days or less in the first week of January, the WEEKNUM function returns week numbers * that are incorrect according to the European standard. * * Excel Function: * WEEKNUM(dateValue[,style]) * * @deprecated 1.18.0 * Use the number method in the DateTimeExcel\Week class instead * @see DateTimeExcel\Week::number() * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $method Week begins on Sunday or Monday * 1 or omitted Week begins on Sunday. * 2 Week begins on Monday. * 11 Week begins on Monday. * 12 Week begins on Tuesday. * 13 Week begins on Wednesday. * 14 Week begins on Thursday. * 15 Week begins on Friday. * 16 Week begins on Saturday. * 17 Week begins on Sunday. * 21 ISO (Jan. 4 is week 1, begins on Monday). * * @return array|int|string Week Number */ public static function WEEKNUM($dateValue = 1, $method = /** @scrutinizer ignore-deprecated */ self::STARTWEEK_SUNDAY) { return DateTimeExcel\Week::number($dateValue, $method); } /** * ISOWEEKNUM. * * Returns the ISO 8601 week number of the year for a specified date. * * Excel Function: * ISOWEEKNUM(dateValue) * * @deprecated 1.18.0 * Use the isoWeekNumber method in the DateTimeExcel\Week class instead * @see DateTimeExcel\Week::isoWeekNumber() * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * * @return array|int|string Week Number */ public static function ISOWEEKNUM($dateValue = 1) { return DateTimeExcel\Week::isoWeekNumber($dateValue); } /** * MONTHOFYEAR. * * Returns the month of a date represented by a serial number. * The month is given as an integer, ranging from 1 (January) to 12 (December). * * Excel Function: * MONTH(dateValue) * * @deprecated 1.18.0 * Use the month method in the DateTimeExcel\DateParts class instead * @see DateTimeExcel\DateParts::month() * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * * @return array|int|string Month of the year */ public static function MONTHOFYEAR($dateValue = 1) { return DateTimeExcel\DateParts::month($dateValue); } /** * YEAR. * * Returns the year corresponding to a date. * The year is returned as an integer in the range 1900-9999. * * Excel Function: * YEAR(dateValue) * * @deprecated 1.18.0 * Use the ear method in the DateTimeExcel\DateParts class instead * @see DateTimeExcel\DateParts::year() * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * * @return array|int|string Year */ public static function YEAR($dateValue = 1) { return DateTimeExcel\DateParts::year($dateValue); } /** * HOUROFDAY. * * Returns the hour of a time value. * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.). * * Excel Function: * HOUR(timeValue) * * @deprecated 1.18.0 * Use the hour method in the DateTimeExcel\TimeParts class instead * @see DateTimeExcel\TimeParts::hour() * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * * @return array|int|string Hour */ public static function HOUROFDAY($timeValue = 0) { return DateTimeExcel\TimeParts::hour($timeValue); } /** * MINUTE. * * Returns the minutes of a time value. * The minute is given as an integer, ranging from 0 to 59. * * Excel Function: * MINUTE(timeValue) * * @deprecated 1.18.0 * Use the minute method in the DateTimeExcel\TimeParts class instead * @see DateTimeExcel\TimeParts::minute() * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * * @return array|int|string Minute */ public static function MINUTE($timeValue = 0) { return DateTimeExcel\TimeParts::minute($timeValue); } /** * SECOND. * * Returns the seconds of a time value. * The second is given as an integer in the range 0 (zero) to 59. * * Excel Function: * SECOND(timeValue) * * @deprecated 1.18.0 * Use the second method in the DateTimeExcel\TimeParts class instead * @see DateTimeExcel\TimeParts::second() * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * * @return array|int|string Second */ public static function SECOND($timeValue = 0) { return DateTimeExcel\TimeParts::second($timeValue); } /** * EDATE. * * Returns the serial number that represents the date that is the indicated number of months * before or after a specified date (the start_date). * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month * as the date of issue. * * Excel Function: * EDATE(dateValue,adjustmentMonths) * * @deprecated 1.18.0 * Use the adjust method in the DateTimeExcel\Edate class instead * @see DateTimeExcel\Month::adjust() * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $adjustmentMonths The number of months before or after start_date. * A positive value for months yields a future date; * a negative value yields a past date. * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function EDATE($dateValue = 1, $adjustmentMonths = 0) { return DateTimeExcel\Month::adjust($dateValue, $adjustmentMonths); } /** * EOMONTH. * * Returns the date value for the last day of the month that is the indicated number of months * before or after start_date. * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month. * * Excel Function: * EOMONTH(dateValue,adjustmentMonths) * * @deprecated 1.18.0 * Use the lastDay method in the DateTimeExcel\EoMonth class instead * @see DateTimeExcel\Month::lastDay() * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $adjustmentMonths The number of months before or after start_date. * A positive value for months yields a future date; * a negative value yields a past date. * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) { return DateTimeExcel\Month::lastDay($dateValue, $adjustmentMonths); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/BranchPruner.php 0000644 00000014252 15002227416 0022041 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class BranchPruner { /** * @var bool */ protected $branchPruningEnabled = true; /** * Used to generate unique store keys. * * @var int */ private $branchStoreKeyCounter = 0; /** * currently pending storeKey (last item of the storeKeysStack. * * @var ?string */ protected $pendingStoreKey; /** * @var string[] */ protected $storeKeysStack = []; /** * @var bool[] */ protected $conditionMap = []; /** * @var bool[] */ protected $thenMap = []; /** * @var bool[] */ protected $elseMap = []; /** * @var int[] */ protected $braceDepthMap = []; /** * @var null|string */ protected $currentCondition; /** * @var null|string */ protected $currentOnlyIf; /** * @var null|string */ protected $currentOnlyIfNot; /** * @var null|string */ protected $previousStoreKey; public function __construct(bool $branchPruningEnabled) { $this->branchPruningEnabled = $branchPruningEnabled; } public function clearBranchStore(): void { $this->branchStoreKeyCounter = 0; } public function initialiseForLoop(): void { $this->currentCondition = null; $this->currentOnlyIf = null; $this->currentOnlyIfNot = null; $this->previousStoreKey = null; $this->pendingStoreKey = empty($this->storeKeysStack) ? null : end($this->storeKeysStack); if ($this->branchPruningEnabled) { $this->initialiseCondition(); $this->initialiseThen(); $this->initialiseElse(); } } private function initialiseCondition(): void { if (isset($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]; } } } private function initialiseThen(): void { if (isset($this->thenMap[$this->pendingStoreKey]) && $this->thenMap[$this->pendingStoreKey]) { $this->currentOnlyIf = $this->pendingStoreKey; } elseif ( isset($this->previousStoreKey, $this->thenMap[$this->previousStoreKey]) && $this->thenMap[$this->previousStoreKey] ) { $this->currentOnlyIf = $this->previousStoreKey; } } private function initialiseElse(): void { if (isset($this->elseMap[$this->pendingStoreKey]) && $this->elseMap[$this->pendingStoreKey]) { $this->currentOnlyIfNot = $this->pendingStoreKey; } elseif ( isset($this->previousStoreKey, $this->elseMap[$this->previousStoreKey]) && $this->elseMap[$this->previousStoreKey] ) { $this->currentOnlyIfNot = $this->previousStoreKey; } } public function decrementDepth(): void { if (!empty($this->pendingStoreKey)) { --$this->braceDepthMap[$this->pendingStoreKey]; } } public function incrementDepth(): void { if (!empty($this->pendingStoreKey)) { ++$this->braceDepthMap[$this->pendingStoreKey]; } } public function functionCall(string $functionName): void { if ($this->branchPruningEnabled && ($functionName === 'IF(')) { // we handle a new if $this->pendingStoreKey = $this->getUnusedBranchStoreKey(); $this->storeKeysStack[] = $this->pendingStoreKey; $this->conditionMap[$this->pendingStoreKey] = true; $this->braceDepthMap[$this->pendingStoreKey] = 0; } elseif (!empty($this->pendingStoreKey) && array_key_exists($this->pendingStoreKey, $this->braceDepthMap)) { // this is not an if but we go deeper ++$this->braceDepthMap[$this->pendingStoreKey]; } } public function argumentSeparator(): void { if (!empty($this->pendingStoreKey) && $this->braceDepthMap[$this->pendingStoreKey] === 0) { // We must go to the IF next argument if ($this->conditionMap[$this->pendingStoreKey]) { $this->conditionMap[$this->pendingStoreKey] = false; $this->thenMap[$this->pendingStoreKey] = true; } elseif ($this->thenMap[$this->pendingStoreKey]) { $this->thenMap[$this->pendingStoreKey] = false; $this->elseMap[$this->pendingStoreKey] = true; } elseif ($this->elseMap[$this->pendingStoreKey]) { throw new Exception('Reaching fourth argument of an IF'); } } } /** * @param mixed $value */ public function closingBrace($value): void { if (!empty($this->pendingStoreKey) && $this->braceDepthMap[$this->pendingStoreKey] === -1) { // we are closing an IF( if ($value !== 'IF(') { throw new Exception('Parser bug we should be in an "IF("'); } if ($this->conditionMap[$this->pendingStoreKey]) { throw new Exception('We should not be expecting a condition'); } $this->thenMap[$this->pendingStoreKey] = false; $this->elseMap[$this->pendingStoreKey] = false; --$this->braceDepthMap[$this->pendingStoreKey]; array_pop($this->storeKeysStack); $this->pendingStoreKey = null; } } public function currentCondition(): ?string { return $this->currentCondition; } public function currentOnlyIf(): ?string { return $this->currentOnlyIf; } public function currentOnlyIfNot(): ?string { return $this->currentOnlyIfNot; } private function getUnusedBranchStoreKey(): string { $storeKeyValue = 'storeKey-' . $this->branchStoreKeyCounter; ++$this->branchStoreKeyCounter; return $storeKeyValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/FormattedNumber.php 0000644 00000013565 15002227416 0022554 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class FormattedNumber { /** Constants */ /** Regular Expressions */ private const STRING_REGEXP_FRACTION = '~^\s*(-?)((\d*)\s+)?(\d+\/\d+)\s*$~'; private const STRING_REGEXP_PERCENT = '~^(?:(?: *(?<PrefixedSign>[-+])? *\% *(?<PrefixedSign2>[-+])? *(?<PrefixedValue>[0-9]+\.?[0-9*]*(?:E[-+]?[0-9]*)?) *)|(?: *(?<PostfixedSign>[-+])? *(?<PostfixedValue>[0-9]+\.?[0-9]*(?:E[-+]?[0-9]*)?) *\% *))$~i'; // preg_quoted string for major currency symbols, with a %s for locale currency private const CURRENCY_CONVERSION_LIST = '\$€£¥%s'; private const STRING_CONVERSION_LIST = [ [self::class, 'convertToNumberIfNumeric'], [self::class, 'convertToNumberIfFraction'], [self::class, 'convertToNumberIfPercent'], [self::class, 'convertToNumberIfCurrency'], ]; /** * Identify whether a string contains a formatted numeric value, * and convert it to a numeric if it is. * * @param string $operand string value to test */ public static function convertToNumberIfFormatted(string &$operand): bool { foreach (self::STRING_CONVERSION_LIST as $conversionMethod) { if ($conversionMethod($operand) === true) { return true; } } return false; } /** * Identify whether a string contains a numeric value, * and convert it to a numeric if it is. * * @param string $operand string value to test */ public static function convertToNumberIfNumeric(string &$operand): bool { $thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/'); $value = preg_replace(['/(\d)' . $thousandsSeparator . '(\d)/u', '/([+-])\s+(\d)/u'], ['$1$2', '$1$2'], trim($operand)); $decimalSeparator = preg_quote(StringHelper::getDecimalSeparator(), '/'); $value = preg_replace(['/(\d)' . $decimalSeparator . '(\d)/u', '/([+-])\s+(\d)/u'], ['$1.$2', '$1$2'], $value ?? ''); if (is_numeric($value)) { $operand = (float) $value; return true; } return false; } /** * Identify whether a string contains a fractional numeric value, * and convert it to a numeric if it is. * * @param string $operand string value to test */ public static function convertToNumberIfFraction(string &$operand): bool { if (preg_match(self::STRING_REGEXP_FRACTION, $operand, $match)) { $sign = ($match[1] === '-') ? '-' : '+'; $wholePart = ($match[3] === '') ? '' : ($sign . $match[3]); $fractionFormula = '=' . $wholePart . $sign . $match[4]; $operand = Calculation::getInstance()->_calculateFormulaValue($fractionFormula); return true; } return false; } /** * Identify whether a string contains a percentage, and if so, * convert it to a numeric. * * @param string $operand string value to test */ public static function convertToNumberIfPercent(string &$operand): bool { $thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/'); $value = preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', trim($operand)); $decimalSeparator = preg_quote(StringHelper::getDecimalSeparator(), '/'); $value = preg_replace(['/(\d)' . $decimalSeparator . '(\d)/u', '/([+-])\s+(\d)/u'], ['$1.$2', '$1$2'], $value ?? ''); $match = []; if ($value !== null && preg_match(self::STRING_REGEXP_PERCENT, $value, $match, PREG_UNMATCHED_AS_NULL)) { //Calculate the percentage $sign = ($match['PrefixedSign'] ?? $match['PrefixedSign2'] ?? $match['PostfixedSign']) ?? ''; $operand = (float) ($sign . ($match['PostfixedValue'] ?? $match['PrefixedValue'])) / 100; return true; } return false; } /** * Identify whether a string contains a currency value, and if so, * convert it to a numeric. * * @param string $operand string value to test */ public static function convertToNumberIfCurrency(string &$operand): bool { $currencyRegexp = self::currencyMatcherRegexp(); $thousandsSeparator = preg_quote(StringHelper::getThousandsSeparator(), '/'); $value = preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $operand); $match = []; if ($value !== null && preg_match($currencyRegexp, $value, $match, PREG_UNMATCHED_AS_NULL)) { //Determine the sign $sign = ($match['PrefixedSign'] ?? $match['PrefixedSign2'] ?? $match['PostfixedSign']) ?? ''; $decimalSeparator = StringHelper::getDecimalSeparator(); //Cast to a float $intermediate = (string) ($match['PostfixedValue'] ?? $match['PrefixedValue']); $intermediate = str_replace($decimalSeparator, '.', $intermediate); if (is_numeric($intermediate)) { $operand = (float) ($sign . str_replace($decimalSeparator, '.', $intermediate)); return true; } } return false; } public static function currencyMatcherRegexp(): string { $currencyCodes = sprintf(self::CURRENCY_CONVERSION_LIST, preg_quote(StringHelper::getCurrencyCode(), '/')); $decimalSeparator = preg_quote(StringHelper::getDecimalSeparator(), '/'); return '~^(?:(?: *(?<PrefixedSign>[-+])? *(?<PrefixedCurrency>[' . $currencyCodes . ']) *(?<PrefixedSign2>[-+])? *(?<PrefixedValue>[0-9]+[' . $decimalSeparator . ']?[0-9*]*(?:E[-+]?[0-9]*)?) *)|(?: *(?<PostfixedSign>[-+])? *(?<PostfixedValue>[0-9]+' . $decimalSeparator . '?[0-9]*(?:E[-+]?[0-9]*)?) *(?<PostfixedCurrency>[' . $currencyCodes . ']) *))$~ui'; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/CyclicReferenceStack.php 0000644 00000002350 15002227416 0023457 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; class CyclicReferenceStack { /** * The call stack for calculated cells. * * @var mixed[] */ private $stack = []; /** * Return the number of entries on the stack. * * @return int */ public function count() { return count($this->stack); } /** * Push a new entry onto the stack. * * @param mixed $value */ public function push($value): void { $this->stack[$value] = $value; } /** * Pop the last entry from the stack. * * @return mixed */ public function pop() { return array_pop($this->stack); } /** * Test to see if a specified entry exists on the stack. * * @param mixed $value The value to test * * @return bool */ public function onStack($value) { return isset($this->stack[$value]); } /** * Clear the stack. */ public function clear(): void { $this->stack = []; } /** * Return an array of all entries on the stack. * * @return mixed[] */ public function showStack() { return $this->stack; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Operands/Operand.php 0000644 00000000336 15002227416 0022611 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands; interface Operand { public static function fromParser(string $formula, int $index, array $matches): self; public function value(): string; } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Operands/StructuredReference.php 0000644 00000027602 15002227416 0025211 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Table; final class StructuredReference implements Operand { public const NAME = 'Structured Reference'; private const OPEN_BRACE = '['; private const CLOSE_BRACE = ']'; private const ITEM_SPECIFIER_ALL = '#All'; private const ITEM_SPECIFIER_HEADERS = '#Headers'; private const ITEM_SPECIFIER_DATA = '#Data'; private const ITEM_SPECIFIER_TOTALS = '#Totals'; private const ITEM_SPECIFIER_THIS_ROW = '#This Row'; private const ITEM_SPECIFIER_ROWS_SET = [ self::ITEM_SPECIFIER_ALL, self::ITEM_SPECIFIER_HEADERS, self::ITEM_SPECIFIER_DATA, self::ITEM_SPECIFIER_TOTALS, ]; private const TABLE_REFERENCE = '/([\p{L}_\\\\][\p{L}\p{N}\._]+)?(\[(?:[^\]\[]+|(?R))*+\])/miu'; private string $value; private string $tableName; private Table $table; private string $reference; private ?int $headersRow; private int $firstDataRow; private int $lastDataRow; private ?int $totalsRow; private array $columns; public function __construct(string $structuredReference) { $this->value = $structuredReference; } public static function fromParser(string $formula, int $index, array $matches): self { $val = $matches[0]; $srCount = substr_count($val, self::OPEN_BRACE) - substr_count($val, self::CLOSE_BRACE); while ($srCount > 0) { $srIndex = strlen($val); $srStringRemainder = substr($formula, $index + $srIndex); $closingPos = strpos($srStringRemainder, self::CLOSE_BRACE); if ($closingPos === false) { throw new Exception("Formula Error: No closing ']' to match opening '['"); } $srStringRemainder = substr($srStringRemainder, 0, $closingPos + 1); --$srCount; if (strpos($srStringRemainder, self::OPEN_BRACE) !== false) { ++$srCount; } $val .= $srStringRemainder; } return new self($val); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ public function parse(Cell $cell): string { $this->getTableStructure($cell); $cellRange = ($this->isRowReference()) ? $this->getRowReference($cell) : $this->getColumnReference(); return $cellRange; } private function isRowReference(): bool { return strpos($this->value, '[@') !== false || strpos($this->value, '[' . self::ITEM_SPECIFIER_THIS_ROW . ']') !== false; } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getTableStructure(Cell $cell): void { preg_match(self::TABLE_REFERENCE, $this->value, $matches); $this->tableName = $matches[1]; $this->table = ($this->tableName === '') ? $this->getTableForCell($cell) : $this->getTableByName($cell); $this->reference = $matches[2]; $tableRange = Coordinate::getRangeBoundaries($this->table->getRange()); $this->headersRow = ($this->table->getShowHeaderRow()) ? (int) $tableRange[0][1] : null; $this->firstDataRow = ($this->table->getShowHeaderRow()) ? (int) $tableRange[0][1] + 1 : $tableRange[0][1]; $this->totalsRow = ($this->table->getShowTotalsRow()) ? (int) $tableRange[1][1] : null; $this->lastDataRow = ($this->table->getShowTotalsRow()) ? (int) $tableRange[1][1] - 1 : $tableRange[1][1]; $this->columns = $this->getColumns($cell, $tableRange); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getTableForCell(Cell $cell): Table { $tables = $cell->getWorksheet()->getTableCollection(); foreach ($tables as $table) { /** @var Table $table */ $range = $table->getRange(); if ($cell->isInRange($range) === true) { $this->tableName = $table->getName(); return $table; } } throw new Exception('Table for Structured Reference cannot be identified'); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getTableByName(Cell $cell): Table { $table = $cell->getWorksheet()->getTableByName($this->tableName); if ($table === null) { throw new Exception("Table {$this->tableName} for Structured Reference cannot be located"); } return $table; } private function getColumns(Cell $cell, array $tableRange): array { $worksheet = $cell->getWorksheet(); $cellReference = $cell->getCoordinate(); $columns = []; $lastColumn = ++$tableRange[1][0]; for ($column = $tableRange[0][0]; $column !== $lastColumn; ++$column) { $columns[$column] = $worksheet ->getCell($column . ($this->headersRow ?? ($this->firstDataRow - 1))) ->getCalculatedValue(); } $worksheet->getCell($cellReference); return $columns; } private function getRowReference(Cell $cell): string { $reference = str_replace("\u{a0}", ' ', $this->reference); /** @var string $reference */ $reference = str_replace('[' . self::ITEM_SPECIFIER_THIS_ROW . '],', '', $reference); foreach ($this->columns as $columnId => $columnName) { $columnName = str_replace("\u{a0}", ' ', $columnName); $reference = $this->adjustRowReference($columnName, $reference, $cell, $columnId); } /** @var string $reference */ return $this->validateParsedReference(trim($reference, '[]@, ')); } private function adjustRowReference(string $columnName, string $reference, Cell $cell, string $columnId): string { if ($columnName !== '') { $cellReference = $columnId . $cell->getRow(); $pattern1 = '/\[' . preg_quote($columnName, '/') . '\]/miu'; $pattern2 = '/@' . preg_quote($columnName, '/') . '/miu'; if (preg_match($pattern1, $reference) === 1) { $reference = preg_replace($pattern1, $cellReference, $reference); } elseif (preg_match($pattern2, $reference) === 1) { $reference = preg_replace($pattern2, $cellReference, $reference); } /** @var string $reference */ } return $reference; } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function getColumnReference(): string { $reference = str_replace("\u{a0}", ' ', $this->reference); $startRow = ($this->totalsRow === null) ? $this->lastDataRow : $this->totalsRow; $endRow = ($this->headersRow === null) ? $this->firstDataRow : $this->headersRow; [$startRow, $endRow] = $this->getRowsForColumnReference($reference, $startRow, $endRow); $reference = $this->getColumnsForColumnReference($reference, $startRow, $endRow); $reference = trim($reference, '[]@, '); if (substr_count($reference, ':') > 1) { $cells = explode(':', $reference); $firstCell = array_shift($cells); $lastCell = array_pop($cells); $reference = "{$firstCell}:{$lastCell}"; } return $this->validateParsedReference($reference); } /** * @throws Exception * @throws \PhpOffice\PhpSpreadsheet\Exception */ private function validateParsedReference(string $reference): string { if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . ':' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $reference) !== 1) { if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $reference) !== 1) { throw new Exception( "Invalid Structured Reference {$this->reference} {$reference}", Exception::CALCULATION_ENGINE_PUSH_TO_STACK ); } } return $reference; } private function fullData(int $startRow, int $endRow): string { $columns = array_keys($this->columns); $firstColumn = array_shift($columns); $lastColumn = (empty($columns)) ? $firstColumn : array_pop($columns); return "{$firstColumn}{$startRow}:{$lastColumn}{$endRow}"; } private function getMinimumRow(string $reference): int { switch ($reference) { case self::ITEM_SPECIFIER_ALL: case self::ITEM_SPECIFIER_HEADERS: return $this->headersRow ?? $this->firstDataRow; case self::ITEM_SPECIFIER_DATA: return $this->firstDataRow; case self::ITEM_SPECIFIER_TOTALS: return $this->totalsRow ?? $this->lastDataRow; } return $this->headersRow ?? $this->firstDataRow; } private function getMaximumRow(string $reference): int { switch ($reference) { case self::ITEM_SPECIFIER_HEADERS: return $this->headersRow ?? $this->firstDataRow; case self::ITEM_SPECIFIER_DATA: return $this->lastDataRow; case self::ITEM_SPECIFIER_ALL: case self::ITEM_SPECIFIER_TOTALS: return $this->totalsRow ?? $this->lastDataRow; } return $this->totalsRow ?? $this->lastDataRow; } public function value(): string { return $this->value; } /** * @return array<int, int> */ private function getRowsForColumnReference(string &$reference, int $startRow, int $endRow): array { $rowsSelected = false; foreach (self::ITEM_SPECIFIER_ROWS_SET as $rowReference) { $pattern = '/\[' . $rowReference . '\]/mui'; /** @var string $reference */ if (preg_match($pattern, $reference) === 1) { if (($rowReference === self::ITEM_SPECIFIER_HEADERS) && ($this->table->getShowHeaderRow() === false)) { throw new Exception( 'Table Headers are Hidden, and should not be Referenced', Exception::CALCULATION_ENGINE_PUSH_TO_STACK ); } $rowsSelected = true; $startRow = min($startRow, $this->getMinimumRow($rowReference)); $endRow = max($endRow, $this->getMaximumRow($rowReference)); $reference = preg_replace($pattern, '', $reference); } } if ($rowsSelected === false) { // If there isn't any Special Item Identifier specified, then the selection defaults to data rows only. $startRow = $this->firstDataRow; $endRow = $this->lastDataRow; } return [$startRow, $endRow]; } private function getColumnsForColumnReference(string $reference, int $startRow, int $endRow): string { $columnsSelected = false; foreach ($this->columns as $columnId => $columnName) { $columnName = str_replace("\u{a0}", ' ', $columnName); $cellFrom = "{$columnId}{$startRow}"; $cellTo = "{$columnId}{$endRow}"; $cellReference = ($cellFrom === $cellTo) ? $cellFrom : "{$cellFrom}:{$cellTo}"; $pattern = '/\[' . preg_quote($columnName, '/') . '\]/mui'; if (preg_match($pattern, $reference) === 1) { $columnsSelected = true; $reference = preg_replace($pattern, $cellReference, $reference); } /** @var string $reference */ } if ($columnsSelected === false) { return $this->fullData($startRow, $endRow); } return $reference; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentHelper.php 0000644 00000012325 15002227416 0023370 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class ArrayArgumentHelper { /** * @var int */ protected $indexStart = 0; /** * @var array */ protected $arguments; /** * @var int */ protected $argumentCount; /** * @var array */ protected $rows; /** * @var array */ protected $columns; public function initialise(array $arguments): void { $keys = array_keys($arguments); $this->indexStart = (int) array_shift($keys); $this->rows = $this->rows($arguments); $this->columns = $this->columns($arguments); $this->argumentCount = count($arguments); $this->arguments = $this->flattenSingleCellArrays($arguments, $this->rows, $this->columns); $this->rows = $this->rows($arguments); $this->columns = $this->columns($arguments); if ($this->arrayArguments() > 2) { throw new Exception('Formulae with more than two array arguments are not supported'); } } public function arguments(): array { return $this->arguments; } public function hasArrayArgument(): bool { return $this->arrayArguments() > 0; } public function getFirstArrayArgumentNumber(): int { $rowArrays = $this->filterArray($this->rows); $columnArrays = $this->filterArray($this->columns); for ($index = $this->indexStart; $index < $this->argumentCount; ++$index) { if (isset($rowArrays[$index]) || isset($columnArrays[$index])) { return ++$index; } } return 0; } public function getSingleRowVector(): ?int { $rowVectors = $this->getRowVectors(); return count($rowVectors) === 1 ? array_pop($rowVectors) : null; } private function getRowVectors(): array { $rowVectors = []; for ($index = $this->indexStart; $index < ($this->indexStart + $this->argumentCount); ++$index) { if ($this->rows[$index] === 1 && $this->columns[$index] > 1) { $rowVectors[] = $index; } } return $rowVectors; } public function getSingleColumnVector(): ?int { $columnVectors = $this->getColumnVectors(); return count($columnVectors) === 1 ? array_pop($columnVectors) : null; } private function getColumnVectors(): array { $columnVectors = []; for ($index = $this->indexStart; $index < ($this->indexStart + $this->argumentCount); ++$index) { if ($this->rows[$index] > 1 && $this->columns[$index] === 1) { $columnVectors[] = $index; } } return $columnVectors; } public function getMatrixPair(): array { for ($i = $this->indexStart; $i < ($this->indexStart + $this->argumentCount - 1); ++$i) { for ($j = $i + 1; $j < $this->argumentCount; ++$j) { if (isset($this->rows[$i], $this->rows[$j])) { return [$i, $j]; } } } return []; } public function isVector(int $argument): bool { return $this->rows[$argument] === 1 || $this->columns[$argument] === 1; } public function isRowVector(int $argument): bool { return $this->rows[$argument] === 1; } public function isColumnVector(int $argument): bool { return $this->columns[$argument] === 1; } public function rowCount(int $argument): int { return $this->rows[$argument]; } public function columnCount(int $argument): int { return $this->columns[$argument]; } private function rows(array $arguments): array { return array_map( function ($argument) { return is_countable($argument) ? count($argument) : 1; }, $arguments ); } private function columns(array $arguments): array { return array_map( function ($argument) { return is_array($argument) && is_array($argument[array_keys($argument)[0]]) ? count($argument[array_keys($argument)[0]]) : 1; }, $arguments ); } public function arrayArguments(): int { $count = 0; foreach (array_keys($this->arguments) as $argument) { if ($this->rows[$argument] > 1 || $this->columns[$argument] > 1) { ++$count; } } return $count; } private function flattenSingleCellArrays(array $arguments, array $rows, array $columns): array { foreach ($arguments as $index => $argument) { if ($rows[$index] === 1 && $columns[$index] === 1) { while (is_array($argument)) { $argument = array_pop($argument); } $arguments[$index] = $argument; } } return $arguments; } private function filterArray(array $array): array { return array_filter( $array, function ($value) { return $value > 1; } ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentProcessor.php 0000644 00000014605 15002227416 0024133 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class ArrayArgumentProcessor { /** * @var ArrayArgumentHelper */ private static $arrayArgumentHelper; /** * @param mixed ...$arguments */ public static function processArguments( ArrayArgumentHelper $arrayArgumentHelper, callable $method, ...$arguments ): array { self::$arrayArgumentHelper = $arrayArgumentHelper; if (self::$arrayArgumentHelper->hasArrayArgument() === false) { return [$method(...$arguments)]; } if (self::$arrayArgumentHelper->arrayArguments() === 1) { $nthArgument = self::$arrayArgumentHelper->getFirstArrayArgumentNumber(); return self::evaluateNthArgumentAsArray($method, $nthArgument, ...$arguments); } $singleRowVectorIndex = self::$arrayArgumentHelper->getSingleRowVector(); $singleColumnVectorIndex = self::$arrayArgumentHelper->getSingleColumnVector(); if ($singleRowVectorIndex !== null && $singleColumnVectorIndex !== null) { // Basic logic for a single row vector and a single column vector return self::evaluateVectorPair($method, $singleRowVectorIndex, $singleColumnVectorIndex, ...$arguments); } $matrixPair = self::$arrayArgumentHelper->getMatrixPair(); if ($matrixPair !== []) { if ( (self::$arrayArgumentHelper->isVector($matrixPair[0]) === true && self::$arrayArgumentHelper->isVector($matrixPair[1]) === false) || (self::$arrayArgumentHelper->isVector($matrixPair[0]) === false && self::$arrayArgumentHelper->isVector($matrixPair[1]) === true) ) { // Logic for a matrix and a vector (row or column) return self::evaluateVectorMatrixPair($method, $matrixPair, ...$arguments); } // Logic for matrix/matrix, column vector/column vector or row vector/row vector return self::evaluateMatrixPair($method, $matrixPair, ...$arguments); } // Still need to work out the logic for more than two array arguments, // For the moment, we're throwing an Exception when we initialise the ArrayArgumentHelper return ['#VALUE!']; } /** * @param mixed ...$arguments */ private static function evaluateVectorMatrixPair(callable $method, array $matrixIndexes, ...$arguments): array { $matrix2 = array_pop($matrixIndexes); /** @var array $matrixValues2 */ $matrixValues2 = $arguments[$matrix2]; $matrix1 = array_pop($matrixIndexes); /** @var array $matrixValues1 */ $matrixValues1 = $arguments[$matrix1]; $rows = min(array_map([self::$arrayArgumentHelper, 'rowCount'], [$matrix1, $matrix2])); $columns = min(array_map([self::$arrayArgumentHelper, 'columnCount'], [$matrix1, $matrix2])); if ($rows === 1) { $rows = max(array_map([self::$arrayArgumentHelper, 'rowCount'], [$matrix1, $matrix2])); } if ($columns === 1) { $columns = max(array_map([self::$arrayArgumentHelper, 'columnCount'], [$matrix1, $matrix2])); } $result = []; for ($rowIndex = 0; $rowIndex < $rows; ++$rowIndex) { for ($columnIndex = 0; $columnIndex < $columns; ++$columnIndex) { $rowIndex1 = self::$arrayArgumentHelper->isRowVector($matrix1) ? 0 : $rowIndex; $columnIndex1 = self::$arrayArgumentHelper->isColumnVector($matrix1) ? 0 : $columnIndex; $value1 = $matrixValues1[$rowIndex1][$columnIndex1]; $rowIndex2 = self::$arrayArgumentHelper->isRowVector($matrix2) ? 0 : $rowIndex; $columnIndex2 = self::$arrayArgumentHelper->isColumnVector($matrix2) ? 0 : $columnIndex; $value2 = $matrixValues2[$rowIndex2][$columnIndex2]; $arguments[$matrix1] = $value1; $arguments[$matrix2] = $value2; $result[$rowIndex][$columnIndex] = $method(...$arguments); } } return $result; } /** * @param mixed ...$arguments */ private static function evaluateMatrixPair(callable $method, array $matrixIndexes, ...$arguments): array { $matrix2 = array_pop($matrixIndexes); /** @var array $matrixValues2 */ $matrixValues2 = $arguments[$matrix2]; $matrix1 = array_pop($matrixIndexes); /** @var array $matrixValues1 */ $matrixValues1 = $arguments[$matrix1]; $result = []; foreach ($matrixValues1 as $rowIndex => $row) { foreach ($row as $columnIndex => $value1) { if (isset($matrixValues2[$rowIndex][$columnIndex]) === false) { continue; } $value2 = $matrixValues2[$rowIndex][$columnIndex]; $arguments[$matrix1] = $value1; $arguments[$matrix2] = $value2; $result[$rowIndex][$columnIndex] = $method(...$arguments); } } return $result; } /** * @param mixed ...$arguments */ private static function evaluateVectorPair(callable $method, int $rowIndex, int $columnIndex, ...$arguments): array { $rowVector = Functions::flattenArray($arguments[$rowIndex]); $columnVector = Functions::flattenArray($arguments[$columnIndex]); $result = []; foreach ($columnVector as $column) { $rowResults = []; foreach ($rowVector as $row) { $arguments[$rowIndex] = $row; $arguments[$columnIndex] = $column; $rowResults[] = $method(...$arguments); } $result[] = $rowResults; } return $result; } /** * Note, offset is from 1 (for the first argument) rather than from 0. * * @param mixed ...$arguments */ private static function evaluateNthArgumentAsArray(callable $method, int $nthArgument, ...$arguments): array { $values = array_slice($arguments, $nthArgument - 1, 1); /** @var array $values */ $values = array_pop($values); $result = []; foreach ($values as $value) { $arguments[$nthArgument - 1] = $value; $result[] = $method(...$arguments); } return $result; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Logger.php 0000644 00000006537 15002227416 0020676 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engine; class Logger { /** * Flag to determine whether a debug log should be generated by the calculation engine * If true, then a debug log will be generated * If false, then a debug log will not be generated. * * @var bool */ private $writeDebugLog = false; /** * Flag to determine whether a debug log should be echoed by the calculation engine * If true, then a debug log will be echoed * If false, then a debug log will not be echoed * A debug log can only be echoed if it is generated. * * @var bool */ private $echoDebugLog = false; /** * The debug log generated by the calculation engine. * * @var string[] */ private $debugLog = []; /** * The calculation engine cell reference stack. * * @var CyclicReferenceStack */ private $cellStack; /** * Instantiate a Calculation engine logger. */ public function __construct(CyclicReferenceStack $stack) { $this->cellStack = $stack; } /** * Enable/Disable Calculation engine logging. * * @param bool $writeDebugLog */ public function setWriteDebugLog($writeDebugLog): void { $this->writeDebugLog = $writeDebugLog; } /** * Return whether calculation engine logging is enabled or disabled. * * @return bool */ public function getWriteDebugLog() { return $this->writeDebugLog; } /** * Enable/Disable echoing of debug log information. * * @param bool $echoDebugLog */ public function setEchoDebugLog($echoDebugLog): void { $this->echoDebugLog = $echoDebugLog; } /** * Return whether echoing of debug log information is enabled or disabled. * * @return bool */ public function getEchoDebugLog() { return $this->echoDebugLog; } /** * Write an entry to the calculation engine debug log. * * @param mixed $args */ public function writeDebugLog(string $message, ...$args): void { // Only write the debug log if logging is enabled if ($this->writeDebugLog) { $message = sprintf($message, ...$args); $cellReference = implode(' -> ', $this->cellStack->showStack()); if ($this->echoDebugLog) { echo $cellReference, ($this->cellStack->count() > 0 ? ' => ' : ''), $message, PHP_EOL; } $this->debugLog[] = $cellReference . ($this->cellStack->count() > 0 ? ' => ' : '') . $message; } } /** * Write a series of entries to the calculation engine debug log. * * @param string[] $args */ public function mergeDebugLog(array $args): void { if ($this->writeDebugLog) { foreach ($args as $entry) { $this->writeDebugLog($entry); } } } /** * Clear the calculation engine debug log. */ public function clearLog(): void { $this->debugLog = []; } /** * Return the calculation engine debug log. * * @return string[] */ public function getLog() { return $this->debugLog; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Erf.php 0000644 00000006723 15002227416 0021215 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Erf { use ArrayEnabled; private const TWO_SQRT_PI = 1.128379167095512574; /** * ERF. * * Returns the error function integrated between the lower and upper bound arguments. * * Note: In Excel 2007 or earlier, if you input a negative value for the upper or lower bound arguments, * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was * improved, so that it can now calculate the function for both positive and negative ranges. * PhpSpreadsheet follows Excel 2010 behaviour, and accepts negative arguments. * * Excel Function: * ERF(lower[,upper]) * * @param mixed $lower Lower bound float for integrating ERF * Or can be an array of values * @param mixed $upper Upper bound float for integrating ERF. * If omitted, ERF integrates between zero and lower_limit * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ERF($lower, $upper = null) { if (is_array($lower) || is_array($upper)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $lower, $upper); } if (is_numeric($lower)) { if ($upper === null) { return self::erfValue($lower); } if (is_numeric($upper)) { return self::erfValue($upper) - self::erfValue($lower); } } return ExcelError::VALUE(); } /** * ERFPRECISE. * * Returns the error function integrated between the lower and upper bound arguments. * * Excel Function: * ERF.PRECISE(limit) * * @param mixed $limit Float bound for integrating ERF, other bound is zero * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ERFPRECISE($limit) { if (is_array($limit)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $limit); } return self::ERF($limit); } /** * Method to calculate the erf value. * * @param float|int|string $value * * @return float */ public static function erfValue($value) { $value = (float) $value; if (abs($value) > 2.2) { return 1 - ErfC::ERFC($value); } $sum = $term = $value; $xsqr = ($value * $value); $j = 1; do { $term *= $xsqr / $j; $sum -= $term / (2 * $j + 1); ++$j; $term *= $xsqr / $j; $sum += $term / (2 * $j + 1); ++$j; if ($sum == 0.0) { break; } } while (abs($term / $sum) > Functions::PRECISION); return self::TWO_SQRT_PI * $sum; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php 0000644 00000010511 15002227416 0024142 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use Complex\Complex as ComplexObject; use Complex\Exception as ComplexException; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ComplexOperations { use ArrayEnabled; /** * IMDIV. * * Returns the quotient of two complex numbers in x + yi or x + yj text format. * * Excel Function: * IMDIV(complexDividend,complexDivisor) * * @param array|string $complexDividend the complex numerator or dividend * Or can be an array of values * @param array|string $complexDivisor the complex denominator or divisor * Or can be an array of values * * @return array|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMDIV($complexDividend, $complexDivisor) { if (is_array($complexDividend) || is_array($complexDivisor)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $complexDividend, $complexDivisor); } try { return (string) (new ComplexObject($complexDividend))->divideby(new ComplexObject($complexDivisor)); } catch (ComplexException $e) { return ExcelError::NAN(); } } /** * IMSUB. * * Returns the difference of two complex numbers in x + yi or x + yj text format. * * Excel Function: * IMSUB(complexNumber1,complexNumber2) * * @param array|string $complexNumber1 the complex number from which to subtract complexNumber2 * Or can be an array of values * @param array|string $complexNumber2 the complex number to subtract from complexNumber1 * Or can be an array of values * * @return array|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSUB($complexNumber1, $complexNumber2) { if (is_array($complexNumber1) || is_array($complexNumber2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $complexNumber1, $complexNumber2); } try { return (string) (new ComplexObject($complexNumber1))->subtract(new ComplexObject($complexNumber2)); } catch (ComplexException $e) { return ExcelError::NAN(); } } /** * IMSUM. * * Returns the sum of two or more complex numbers in x + yi or x + yj text format. * * Excel Function: * IMSUM(complexNumber[,complexNumber[,...]]) * * @param string ...$complexNumbers Series of complex numbers to add * * @return string */ public static function IMSUM(...$complexNumbers) { // Return value $returnValue = new ComplexObject(0.0); $aArgs = Functions::flattenArray($complexNumbers); try { // Loop through the arguments foreach ($aArgs as $complex) { $returnValue = $returnValue->add(new ComplexObject($complex)); } } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $returnValue; } /** * IMPRODUCT. * * Returns the product of two or more complex numbers in x + yi or x + yj text format. * * Excel Function: * IMPRODUCT(complexNumber[,complexNumber[,...]]) * * @param string ...$complexNumbers Series of complex numbers to multiply * * @return string */ public static function IMPRODUCT(...$complexNumbers) { // Return value $returnValue = new ComplexObject(1.0); $aArgs = Functions::flattenArray($complexNumbers); try { // Loop through the arguments foreach ($aArgs as $complex) { $returnValue = $returnValue->multiply(new ComplexObject($complex)); } } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $returnValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Constants.php 0000644 00000000247 15002227416 0022450 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; class Constants { /** * EULER. */ public const EULER = 2.71828182845904523536; } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php 0000644 00000017056 15002227416 0022567 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ConvertHex extends ConvertBase { /** * toBinary. * * Return a hex value as binary. * * Excel Function: * HEX2BIN(x[,places]) * * @param array|string $value The hexadecimal number you want to convert. * Number cannot contain more than 10 characters. * The most significant bit of number is the sign bit (40th bit from the right). * The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is negative, HEX2BIN ignores places and returns a 10-character binary number. * If number is negative, it cannot be less than FFFFFFFE00, * and if number is positive, it cannot be greater than 1FF. * If number is not a valid hexadecimal number, HEX2BIN returns the #NUM! error value. * If HEX2BIN requires more than places characters, it returns the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, * HEX2BIN uses the minimum number of characters necessary. Places * is useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, HEX2BIN returns the #VALUE! error value. * If places is negative, HEX2BIN returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toBinary($value, $places = null) { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateHex($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $dec = self::toDecimal($value); return ConvertDecimal::toBinary($dec, $places); } /** * toDecimal. * * Return a hex value as decimal. * * Excel Function: * HEX2DEC(x) * * @param array|string $value The hexadecimal number you want to convert. This number cannot * contain more than 10 characters (40 bits). The most significant * bit of number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement * notation. * If number is not a valid hexadecimal number, HEX2DEC returns the * #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toDecimal($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::validateValue($value); $value = self::validateHex($value); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) > 10) { return ExcelError::NAN(); } $binX = ''; foreach (str_split($value) as $char) { $binX .= str_pad(base_convert($char, 16, 2), 4, '0', STR_PAD_LEFT); } if (strlen($binX) == 40 && $binX[0] == '1') { for ($i = 0; $i < 40; ++$i) { $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); } return (string) ((bindec($binX) + 1) * -1); } return (string) bindec($binX); } /** * toOctal. * * Return a hex value as octal. * * Excel Function: * HEX2OCT(x[,places]) * * @param array|string $value The hexadecimal number you want to convert. Number cannot * contain more than 10 characters. The most significant bit of * number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement * notation. * If number is negative, HEX2OCT ignores places and returns a * 10-character octal number. * If number is negative, it cannot be less than FFE0000000, and * if number is positive, it cannot be greater than 1FFFFFFF. * If number is not a valid hexadecimal number, HEX2OCT returns * the #NUM! error value. * If HEX2OCT requires more than places characters, it returns * the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, HEX2OCT * uses the minimum number of characters necessary. Places is * useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, HEX2OCT returns the #VALUE! error * value. * If places is negative, HEX2OCT returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toOctal($value, $places = null) { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateHex($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $decimal = self::toDecimal($value); return ConvertDecimal::toOctal($decimal, $places); } protected static function validateHex(string $value): string { if (strlen($value) > preg_match_all('/[0123456789ABCDEF]/', $value)) { throw new Exception(ExcelError::NAN()); } return $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php 0000644 00000013442 15002227416 0022024 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class BesselJ { use ArrayEnabled; /** * BESSELJ. * * Returns the Bessel function * * Excel Function: * BESSELJ(x,ord) * * NOTE: The MS Excel implementation of the BESSELJ function is still not accurate, particularly for higher order * values with x < -8 and x > 8. This code provides a more accurate calculation * * @param mixed $x A float value at which to evaluate the function. * If x is nonnumeric, BESSELJ returns the #VALUE! error value. * Or can be an array of values * @param mixed $ord The integer order of the Bessel function. * If ord is not an integer, it is truncated. * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value. * If $ord < 0, BESSELJ returns the #NUM! error value. * Or can be an array of values * * @return array|float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELJ($x, $ord) { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if ($ord < 0) { return ExcelError::NAN(); } $fResult = self::calculate($x, $ord); return (is_nan($fResult)) ? ExcelError::NAN() : $fResult; } private static function calculate(float $x, int $ord): float { // special cases switch ($ord) { case 0: return self::besselJ0($x); case 1: return self::besselJ1($x); } return self::besselJ2($x, $ord); } private static function besselJ0(float $x): float { $ax = abs($x); if ($ax < 8.0) { $y = $x * $x; $ans1 = 57568490574.0 + $y * (-13362590354.0 + $y * (651619640.7 + $y * (-11214424.18 + $y * (77392.33017 + $y * (-184.9052456))))); $ans2 = 57568490411.0 + $y * (1029532985.0 + $y * (9494680.718 + $y * (59272.64853 + $y * (267.8532712 + $y * 1.0)))); return $ans1 / $ans2; } $z = 8.0 / $ax; $y = $z * $z; $xx = $ax - 0.785398164; $ans1 = 1.0 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); $ans2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 - $y * 0.934935152e-7))); return sqrt(0.636619772 / $ax) * (cos($xx) * $ans1 - $z * sin($xx) * $ans2); } private static function besselJ1(float $x): float { $ax = abs($x); if ($ax < 8.0) { $y = $x * $x; $ans1 = $x * (72362614232.0 + $y * (-7895059235.0 + $y * (242396853.1 + $y * (-2972611.439 + $y * (15704.48260 + $y * (-30.16036606)))))); $ans2 = 144725228442.0 + $y * (2300535178.0 + $y * (18583304.74 + $y * (99447.43394 + $y * (376.9991397 + $y * 1.0)))); return $ans1 / $ans2; } $z = 8.0 / $ax; $y = $z * $z; $xx = $ax - 2.356194491; $ans1 = 1.0 + $y * (0.183105e-2 + $y * (-0.3516396496e-4 + $y * (0.2457520174e-5 + $y * (-0.240337019e-6)))); $ans2 = 0.04687499995 + $y * (-0.2002690873e-3 + $y * (0.8449199096e-5 + $y * (-0.88228987e-6 + $y * 0.105787412e-6))); $ans = sqrt(0.636619772 / $ax) * (cos($xx) * $ans1 - $z * sin($xx) * $ans2); return ($x < 0.0) ? -$ans : $ans; } private static function besselJ2(float $x, int $ord): float { $ax = abs($x); if ($ax === 0.0) { return 0.0; } if ($ax > $ord) { return self::besselj2a($ax, $ord, $x); } return self::besselj2b($ax, $ord, $x); } private static function besselj2a(float $ax, int $ord, float $x): float { $tox = 2.0 / $ax; $bjm = self::besselJ0($ax); $bj = self::besselJ1($ax); for ($j = 1; $j < $ord; ++$j) { $bjp = $j * $tox * $bj - $bjm; $bjm = $bj; $bj = $bjp; } $ans = $bj; return ($x < 0.0 && ($ord % 2) == 1) ? -$ans : $ans; } private static function besselj2b(float $ax, int $ord, float $x): float { $tox = 2.0 / $ax; $jsum = false; $bjp = $ans = $sum = 0.0; $bj = 1.0; for ($j = 2 * ($ord + (int) sqrt(40.0 * $ord)); $j > 0; --$j) { $bjm = $j * $tox * $bj - $bjp; $bjp = $bj; $bj = $bjm; if (abs($bj) > 1.0e+10) { $bj *= 1.0e-10; $bjp *= 1.0e-10; $ans *= 1.0e-10; $sum *= 1.0e-10; } if ($jsum === true) { $sum += $bj; } $jsum = $jsum === false; if ($j === $ord) { $ans = $bjp; } } $sum = 2.0 * $sum - $bj; $ans /= $sum; return ($x < 0.0 && ($ord % 2) === 1) ? -$ans : $ans; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselI.php 0000644 00000011243 15002227416 0022020 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class BesselI { use ArrayEnabled; /** * BESSELI. * * Returns the modified Bessel function In(x), which is equivalent to the Bessel function evaluated * for purely imaginary arguments * * Excel Function: * BESSELI(x,ord) * * NOTE: The MS Excel implementation of the BESSELI function is still not accurate. * This code provides a more accurate calculation * * @param mixed $x A float value at which to evaluate the function. * If x is nonnumeric, BESSELI returns the #VALUE! error value. * Or can be an array of values * @param mixed $ord The integer order of the Bessel function. * If ord is not an integer, it is truncated. * If $ord is nonnumeric, BESSELI returns the #VALUE! error value. * If $ord < 0, BESSELI returns the #NUM! error value. * Or can be an array of values * * @return array|float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELI($x, $ord) { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if ($ord < 0) { return ExcelError::NAN(); } $fResult = self::calculate($x, $ord); return (is_nan($fResult)) ? ExcelError::NAN() : $fResult; } private static function calculate(float $x, int $ord): float { // special cases switch ($ord) { case 0: return self::besselI0($x); case 1: return self::besselI1($x); } return self::besselI2($x, $ord); } private static function besselI0(float $x): float { $ax = abs($x); if ($ax < 3.75) { $y = $x / 3.75; $y = $y * $y; return 1.0 + $y * (3.5156229 + $y * (3.0899424 + $y * (1.2067492 + $y * (0.2659732 + $y * (0.360768e-1 + $y * 0.45813e-2))))); } $y = 3.75 / $ax; return (exp($ax) / sqrt($ax)) * (0.39894228 + $y * (0.1328592e-1 + $y * (0.225319e-2 + $y * (-0.157565e-2 + $y * (0.916281e-2 + $y * (-0.2057706e-1 + $y * (0.2635537e-1 + $y * (-0.1647633e-1 + $y * 0.392377e-2)))))))); } private static function besselI1(float $x): float { $ax = abs($x); if ($ax < 3.75) { $y = $x / 3.75; $y = $y * $y; $ans = $ax * (0.5 + $y * (0.87890594 + $y * (0.51498869 + $y * (0.15084934 + $y * (0.2658733e-1 + $y * (0.301532e-2 + $y * 0.32411e-3)))))); return ($x < 0.0) ? -$ans : $ans; } $y = 3.75 / $ax; $ans = 0.2282967e-1 + $y * (-0.2895312e-1 + $y * (0.1787654e-1 - $y * 0.420059e-2)); $ans = 0.39894228 + $y * (-0.3988024e-1 + $y * (-0.362018e-2 + $y * (0.163801e-2 + $y * (-0.1031555e-1 + $y * $ans)))); $ans *= exp($ax) / sqrt($ax); return ($x < 0.0) ? -$ans : $ans; } /** * Sop to Scrutinizer. * * @var float */ private static $zeroPointZero = 0.0; private static function besselI2(float $x, int $ord): float { if ($x === self::$zeroPointZero) { return 0.0; } $tox = 2.0 / abs($x); $bip = 0; $ans = 0.0; $bi = 1.0; for ($j = 2 * ($ord + (int) sqrt(40.0 * $ord)); $j > 0; --$j) { $bim = $bip + $j * $tox * $bi; $bip = $bi; $bi = $bim; if (abs($bi) > 1.0e+12) { $ans *= 1.0e-12; $bi *= 1.0e-12; $bip *= 1.0e-12; } if ($j === $ord) { $ans = $bip; } } $ans *= self::besselI0($x) / $bi; return ($x < 0.0 && (($ord % 2) === 1)) ? -$ans : $ans; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php 0000644 00000105716 15002227416 0022504 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ConvertUOM { use ArrayEnabled; public const CATEGORY_WEIGHT_AND_MASS = 'Weight and Mass'; public const CATEGORY_DISTANCE = 'Distance'; public const CATEGORY_TIME = 'Time'; public const CATEGORY_PRESSURE = 'Pressure'; public const CATEGORY_FORCE = 'Force'; public const CATEGORY_ENERGY = 'Energy'; public const CATEGORY_POWER = 'Power'; public const CATEGORY_MAGNETISM = 'Magnetism'; public const CATEGORY_TEMPERATURE = 'Temperature'; public const CATEGORY_VOLUME = 'Volume and Liquid Measure'; public const CATEGORY_AREA = 'Area'; public const CATEGORY_INFORMATION = 'Information'; public const CATEGORY_SPEED = 'Speed'; /** * Details of the Units of measure that can be used in CONVERTUOM(). * * @var mixed[] */ private static $conversionUnits = [ // Weight and Mass 'g' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Gram', 'AllowPrefix' => true], 'sg' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Slug', 'AllowPrefix' => false], 'lbm' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false], 'u' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => true], 'ozm' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false], 'grain' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Grain', 'AllowPrefix' => false], 'cwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'U.S. (short) hundredweight', 'AllowPrefix' => false], 'shweight' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'U.S. (short) hundredweight', 'AllowPrefix' => false], 'uk_cwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial hundredweight', 'AllowPrefix' => false], 'lcwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial hundredweight', 'AllowPrefix' => false], 'hweight' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial hundredweight', 'AllowPrefix' => false], 'stone' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Stone', 'AllowPrefix' => false], 'ton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Ton', 'AllowPrefix' => false], 'uk_ton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial ton', 'AllowPrefix' => false], 'LTON' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial ton', 'AllowPrefix' => false], 'brton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial ton', 'AllowPrefix' => false], // Distance 'm' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Meter', 'AllowPrefix' => true], 'mi' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Statute mile', 'AllowPrefix' => false], 'Nmi' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Nautical mile', 'AllowPrefix' => false], 'in' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Inch', 'AllowPrefix' => false], 'ft' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Foot', 'AllowPrefix' => false], 'yd' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Yard', 'AllowPrefix' => false], 'ang' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Angstrom', 'AllowPrefix' => true], 'ell' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Ell', 'AllowPrefix' => false], 'ly' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Light Year', 'AllowPrefix' => false], 'parsec' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Parsec', 'AllowPrefix' => false], 'pc' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Parsec', 'AllowPrefix' => false], 'Pica' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false], 'Picapt' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false], 'pica' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Pica (1/6 in)', 'AllowPrefix' => false], 'survey_mi' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'U.S survey mile (statute mile)', 'AllowPrefix' => false], // Time 'yr' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Year', 'AllowPrefix' => false], 'day' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Day', 'AllowPrefix' => false], 'd' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Day', 'AllowPrefix' => false], 'hr' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Hour', 'AllowPrefix' => false], 'mn' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Minute', 'AllowPrefix' => false], 'min' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Minute', 'AllowPrefix' => false], 'sec' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Second', 'AllowPrefix' => true], 's' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Second', 'AllowPrefix' => true], // Pressure 'Pa' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Pascal', 'AllowPrefix' => true], 'p' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Pascal', 'AllowPrefix' => true], 'atm' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], 'at' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], 'mmHg' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => true], 'psi' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'PSI', 'AllowPrefix' => true], 'Torr' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Torr', 'AllowPrefix' => true], // Force 'N' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Newton', 'AllowPrefix' => true], 'dyn' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Dyne', 'AllowPrefix' => true], 'dy' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Dyne', 'AllowPrefix' => true], 'lbf' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Pound force', 'AllowPrefix' => false], 'pond' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Pond', 'AllowPrefix' => true], // Energy 'J' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Joule', 'AllowPrefix' => true], 'e' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Erg', 'AllowPrefix' => true], 'c' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => true], 'cal' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'IT calorie', 'AllowPrefix' => true], 'eV' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], 'ev' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], 'HPh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], 'hh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], 'Wh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], 'wh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], 'flb' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Foot-pound', 'AllowPrefix' => false], 'BTU' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'BTU', 'AllowPrefix' => false], 'btu' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'BTU', 'AllowPrefix' => false], // Power 'HP' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], 'h' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], 'W' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Watt', 'AllowPrefix' => true], 'w' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Watt', 'AllowPrefix' => true], 'PS' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Pferdestärke', 'AllowPrefix' => false], // Magnetism 'T' => ['Group' => self::CATEGORY_MAGNETISM, 'Unit Name' => 'Tesla', 'AllowPrefix' => true], 'ga' => ['Group' => self::CATEGORY_MAGNETISM, 'Unit Name' => 'Gauss', 'AllowPrefix' => true], // Temperature 'C' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Celsius', 'AllowPrefix' => false], 'cel' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Celsius', 'AllowPrefix' => false], 'F' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Fahrenheit', 'AllowPrefix' => false], 'fah' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Fahrenheit', 'AllowPrefix' => false], 'K' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], 'kel' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], 'Rank' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Rankine', 'AllowPrefix' => false], 'Reau' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Réaumur', 'AllowPrefix' => false], // Volume 'l' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Litre', 'AllowPrefix' => true], 'L' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Litre', 'AllowPrefix' => true], 'lt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Litre', 'AllowPrefix' => true], 'tsp' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Teaspoon', 'AllowPrefix' => false], 'tspm' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Modern Teaspoon', 'AllowPrefix' => false], 'tbs' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Tablespoon', 'AllowPrefix' => false], 'oz' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => false], 'cup' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cup', 'AllowPrefix' => false], 'pt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], 'us_pt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], 'uk_pt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => false], 'qt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Quart', 'AllowPrefix' => false], 'uk_qt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Imperial Quart (UK)', 'AllowPrefix' => false], 'gal' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Gallon', 'AllowPrefix' => false], 'uk_gal' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Imperial Gallon (UK)', 'AllowPrefix' => false], 'ang3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Angstrom', 'AllowPrefix' => true], 'ang^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Angstrom', 'AllowPrefix' => true], 'barrel' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'US Oil Barrel', 'AllowPrefix' => false], 'bushel' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'US Bushel', 'AllowPrefix' => false], 'in3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Inch', 'AllowPrefix' => false], 'in^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Inch', 'AllowPrefix' => false], 'ft3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Foot', 'AllowPrefix' => false], 'ft^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Foot', 'AllowPrefix' => false], 'ly3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Light Year', 'AllowPrefix' => false], 'ly^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Light Year', 'AllowPrefix' => false], 'm3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Meter', 'AllowPrefix' => true], 'm^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Meter', 'AllowPrefix' => true], 'mi3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Mile', 'AllowPrefix' => false], 'mi^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Mile', 'AllowPrefix' => false], 'yd3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Yard', 'AllowPrefix' => false], 'yd^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Yard', 'AllowPrefix' => false], 'Nmi3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Nautical Mile', 'AllowPrefix' => false], 'Nmi^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Nautical Mile', 'AllowPrefix' => false], 'Pica3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], 'Pica^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], 'Picapt3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], 'Picapt^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], 'GRT' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Gross Registered Ton', 'AllowPrefix' => false], 'regton' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Gross Registered Ton', 'AllowPrefix' => false], 'MTON' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Measurement Ton (Freight Ton)', 'AllowPrefix' => false], // Area 'ha' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Hectare', 'AllowPrefix' => true], 'uk_acre' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'International Acre', 'AllowPrefix' => false], 'us_acre' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'US Survey/Statute Acre', 'AllowPrefix' => false], 'ang2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Angstrom', 'AllowPrefix' => true], 'ang^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Angstrom', 'AllowPrefix' => true], 'ar' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Are', 'AllowPrefix' => true], 'ft2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Feet', 'AllowPrefix' => false], 'ft^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Feet', 'AllowPrefix' => false], 'in2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Inches', 'AllowPrefix' => false], 'in^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Inches', 'AllowPrefix' => false], 'ly2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Light Years', 'AllowPrefix' => false], 'ly^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Light Years', 'AllowPrefix' => false], 'm2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Meters', 'AllowPrefix' => true], 'm^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Meters', 'AllowPrefix' => true], 'Morgen' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Morgen', 'AllowPrefix' => false], 'mi2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Miles', 'AllowPrefix' => false], 'mi^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Miles', 'AllowPrefix' => false], 'Nmi2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Nautical Miles', 'AllowPrefix' => false], 'Nmi^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Nautical Miles', 'AllowPrefix' => false], 'Pica2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], 'Pica^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], 'Picapt2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], 'Picapt^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], 'yd2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Yards', 'AllowPrefix' => false], 'yd^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Yards', 'AllowPrefix' => false], // Information 'byte' => ['Group' => self::CATEGORY_INFORMATION, 'Unit Name' => 'Byte', 'AllowPrefix' => true], 'bit' => ['Group' => self::CATEGORY_INFORMATION, 'Unit Name' => 'Bit', 'AllowPrefix' => true], // Speed 'm/s' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per second', 'AllowPrefix' => true], 'm/sec' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per second', 'AllowPrefix' => true], 'm/h' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per hour', 'AllowPrefix' => true], 'm/hr' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per hour', 'AllowPrefix' => true], 'mph' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Miles per hour', 'AllowPrefix' => false], 'admkn' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Admiralty Knot', 'AllowPrefix' => false], 'kn' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Knot', 'AllowPrefix' => false], ]; /** * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * * @var mixed[] */ private static $conversionMultipliers = [ 'Y' => ['multiplier' => 1E24, 'name' => 'yotta'], 'Z' => ['multiplier' => 1E21, 'name' => 'zetta'], 'E' => ['multiplier' => 1E18, 'name' => 'exa'], 'P' => ['multiplier' => 1E15, 'name' => 'peta'], 'T' => ['multiplier' => 1E12, 'name' => 'tera'], 'G' => ['multiplier' => 1E9, 'name' => 'giga'], 'M' => ['multiplier' => 1E6, 'name' => 'mega'], 'k' => ['multiplier' => 1E3, 'name' => 'kilo'], 'h' => ['multiplier' => 1E2, 'name' => 'hecto'], 'e' => ['multiplier' => 1E1, 'name' => 'dekao'], 'da' => ['multiplier' => 1E1, 'name' => 'dekao'], 'd' => ['multiplier' => 1E-1, 'name' => 'deci'], 'c' => ['multiplier' => 1E-2, 'name' => 'centi'], 'm' => ['multiplier' => 1E-3, 'name' => 'milli'], 'u' => ['multiplier' => 1E-6, 'name' => 'micro'], 'n' => ['multiplier' => 1E-9, 'name' => 'nano'], 'p' => ['multiplier' => 1E-12, 'name' => 'pico'], 'f' => ['multiplier' => 1E-15, 'name' => 'femto'], 'a' => ['multiplier' => 1E-18, 'name' => 'atto'], 'z' => ['multiplier' => 1E-21, 'name' => 'zepto'], 'y' => ['multiplier' => 1E-24, 'name' => 'yocto'], ]; /** * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * * @var mixed[] */ private static $binaryConversionMultipliers = [ 'Yi' => ['multiplier' => 2 ** 80, 'name' => 'yobi'], 'Zi' => ['multiplier' => 2 ** 70, 'name' => 'zebi'], 'Ei' => ['multiplier' => 2 ** 60, 'name' => 'exbi'], 'Pi' => ['multiplier' => 2 ** 50, 'name' => 'pebi'], 'Ti' => ['multiplier' => 2 ** 40, 'name' => 'tebi'], 'Gi' => ['multiplier' => 2 ** 30, 'name' => 'gibi'], 'Mi' => ['multiplier' => 2 ** 20, 'name' => 'mebi'], 'ki' => ['multiplier' => 2 ** 10, 'name' => 'kibi'], ]; /** * Details of the Units of measure conversion factors, organised by group. * * @var mixed[] */ private static $unitConversions = [ // Conversion uses gram (g) as an intermediate unit self::CATEGORY_WEIGHT_AND_MASS => [ 'g' => 1.0, 'sg' => 6.85217658567918E-05, 'lbm' => 2.20462262184878E-03, 'u' => 6.02214179421676E+23, 'ozm' => 3.52739619495804E-02, 'grain' => 1.54323583529414E+01, 'cwt' => 2.20462262184878E-05, 'shweight' => 2.20462262184878E-05, 'uk_cwt' => 1.96841305522212E-05, 'lcwt' => 1.96841305522212E-05, 'hweight' => 1.96841305522212E-05, 'stone' => 1.57473044417770E-04, 'ton' => 1.10231131092439E-06, 'uk_ton' => 9.84206527611061E-07, 'LTON' => 9.84206527611061E-07, 'brton' => 9.84206527611061E-07, ], // Conversion uses meter (m) as an intermediate unit self::CATEGORY_DISTANCE => [ 'm' => 1.0, 'mi' => 6.21371192237334E-04, 'Nmi' => 5.39956803455724E-04, 'in' => 3.93700787401575E+01, 'ft' => 3.28083989501312E+00, 'yd' => 1.09361329833771E+00, 'ang' => 1.0E+10, 'ell' => 8.74890638670166E-01, 'ly' => 1.05700083402462E-16, 'parsec' => 3.24077928966473E-17, 'pc' => 3.24077928966473E-17, 'Pica' => 2.83464566929134E+03, 'Picapt' => 2.83464566929134E+03, 'pica' => 2.36220472440945E+02, 'survey_mi' => 6.21369949494950E-04, ], // Conversion uses second (s) as an intermediate unit self::CATEGORY_TIME => [ 'yr' => 3.16880878140289E-08, 'day' => 1.15740740740741E-05, 'd' => 1.15740740740741E-05, 'hr' => 2.77777777777778E-04, 'mn' => 1.66666666666667E-02, 'min' => 1.66666666666667E-02, 'sec' => 1.0, 's' => 1.0, ], // Conversion uses Pascal (Pa) as an intermediate unit self::CATEGORY_PRESSURE => [ 'Pa' => 1.0, 'p' => 1.0, 'atm' => 9.86923266716013E-06, 'at' => 9.86923266716013E-06, 'mmHg' => 7.50063755419211E-03, 'psi' => 1.45037737730209E-04, 'Torr' => 7.50061682704170E-03, ], // Conversion uses Newton (N) as an intermediate unit self::CATEGORY_FORCE => [ 'N' => 1.0, 'dyn' => 1.0E+5, 'dy' => 1.0E+5, 'lbf' => 2.24808923655339E-01, 'pond' => 1.01971621297793E+02, ], // Conversion uses Joule (J) as an intermediate unit self::CATEGORY_ENERGY => [ 'J' => 1.0, 'e' => 9.99999519343231E+06, 'c' => 2.39006249473467E-01, 'cal' => 2.38846190642017E-01, 'eV' => 6.24145700000000E+18, 'ev' => 6.24145700000000E+18, 'HPh' => 3.72506430801000E-07, 'hh' => 3.72506430801000E-07, 'Wh' => 2.77777916238711E-04, 'wh' => 2.77777916238711E-04, 'flb' => 2.37304222192651E+01, 'BTU' => 9.47815067349015E-04, 'btu' => 9.47815067349015E-04, ], // Conversion uses Horsepower (HP) as an intermediate unit self::CATEGORY_POWER => [ 'HP' => 1.0, 'h' => 1.0, 'W' => 7.45699871582270E+02, 'w' => 7.45699871582270E+02, 'PS' => 1.01386966542400E+00, ], // Conversion uses Tesla (T) as an intermediate unit self::CATEGORY_MAGNETISM => [ 'T' => 1.0, 'ga' => 10000.0, ], // Conversion uses litre (l) as an intermediate unit self::CATEGORY_VOLUME => [ 'l' => 1.0, 'L' => 1.0, 'lt' => 1.0, 'tsp' => 2.02884136211058E+02, 'tspm' => 2.0E+02, 'tbs' => 6.76280454036860E+01, 'oz' => 3.38140227018430E+01, 'cup' => 4.22675283773038E+00, 'pt' => 2.11337641886519E+00, 'us_pt' => 2.11337641886519E+00, 'uk_pt' => 1.75975398639270E+00, 'qt' => 1.05668820943259E+00, 'uk_qt' => 8.79876993196351E-01, 'gal' => 2.64172052358148E-01, 'uk_gal' => 2.19969248299088E-01, 'ang3' => 1.0E+27, 'ang^3' => 1.0E+27, 'barrel' => 6.28981077043211E-03, 'bushel' => 2.83775932584017E-02, 'in3' => 6.10237440947323E+01, 'in^3' => 6.10237440947323E+01, 'ft3' => 3.53146667214886E-02, 'ft^3' => 3.53146667214886E-02, 'ly3' => 1.18093498844171E-51, 'ly^3' => 1.18093498844171E-51, 'm3' => 1.0E-03, 'm^3' => 1.0E-03, 'mi3' => 2.39912758578928E-13, 'mi^3' => 2.39912758578928E-13, 'yd3' => 1.30795061931439E-03, 'yd^3' => 1.30795061931439E-03, 'Nmi3' => 1.57426214685811E-13, 'Nmi^3' => 1.57426214685811E-13, 'Pica3' => 2.27769904358706E+07, 'Pica^3' => 2.27769904358706E+07, 'Picapt3' => 2.27769904358706E+07, 'Picapt^3' => 2.27769904358706E+07, 'GRT' => 3.53146667214886E-04, 'regton' => 3.53146667214886E-04, 'MTON' => 8.82866668037215E-04, ], // Conversion uses hectare (ha) as an intermediate unit self::CATEGORY_AREA => [ 'ha' => 1.0, 'uk_acre' => 2.47105381467165E+00, 'us_acre' => 2.47104393046628E+00, 'ang2' => 1.0E+24, 'ang^2' => 1.0E+24, 'ar' => 1.0E+02, 'ft2' => 1.07639104167097E+05, 'ft^2' => 1.07639104167097E+05, 'in2' => 1.55000310000620E+07, 'in^2' => 1.55000310000620E+07, 'ly2' => 1.11725076312873E-28, 'ly^2' => 1.11725076312873E-28, 'm2' => 1.0E+04, 'm^2' => 1.0E+04, 'Morgen' => 4.0E+00, 'mi2' => 3.86102158542446E-03, 'mi^2' => 3.86102158542446E-03, 'Nmi2' => 2.91553349598123E-03, 'Nmi^2' => 2.91553349598123E-03, 'Pica2' => 8.03521607043214E+10, 'Pica^2' => 8.03521607043214E+10, 'Picapt2' => 8.03521607043214E+10, 'Picapt^2' => 8.03521607043214E+10, 'yd2' => 1.19599004630108E+04, 'yd^2' => 1.19599004630108E+04, ], // Conversion uses bit (bit) as an intermediate unit self::CATEGORY_INFORMATION => [ 'bit' => 1.0, 'byte' => 0.125, ], // Conversion uses Meters per Second (m/s) as an intermediate unit self::CATEGORY_SPEED => [ 'm/s' => 1.0, 'm/sec' => 1.0, 'm/h' => 3.60E+03, 'm/hr' => 3.60E+03, 'mph' => 2.23693629205440E+00, 'admkn' => 1.94260256941567E+00, 'kn' => 1.94384449244060E+00, ], ]; /** * getConversionGroups * Returns a list of the different conversion groups for UOM conversions. * * @return array */ public static function getConversionCategories() { $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit) { $conversionGroups[] = $conversionUnit['Group']; } return array_merge(array_unique($conversionGroups)); } /** * getConversionGroupUnits * Returns an array of units of measure, for a specified conversion group, or for all groups. * * @param string $category The group whose units of measure you want to retrieve * * @return array */ public static function getConversionCategoryUnits($category = null) { $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { if (($category === null) || ($conversionGroup['Group'] == $category)) { $conversionGroups[$conversionGroup['Group']][] = $conversionUnit; } } return $conversionGroups; } /** * getConversionGroupUnitDetails. * * @param string $category The group whose units of measure you want to retrieve * * @return array */ public static function getConversionCategoryUnitDetails($category = null) { $conversionGroups = []; foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { if (($category === null) || ($conversionGroup['Group'] == $category)) { $conversionGroups[$conversionGroup['Group']][] = [ 'unit' => $conversionUnit, 'description' => $conversionGroup['Unit Name'], ]; } } return $conversionGroups; } /** * getConversionMultipliers * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * * @return mixed[] */ public static function getConversionMultipliers() { return self::$conversionMultipliers; } /** * getBinaryConversionMultipliers * Returns an array of the additional Multiplier prefixes that can be used with Information Units of Measure in CONVERTUOM(). * * @return mixed[] */ public static function getBinaryConversionMultipliers() { return self::$binaryConversionMultipliers; } /** * CONVERT. * * Converts a number from one measurement system to another. * For example, CONVERT can translate a table of distances in miles to a table of distances * in kilometers. * * Excel Function: * CONVERT(value,fromUOM,toUOM) * * @param array|float|int|string $value the value in fromUOM to convert * Or can be an array of values * @param array|string $fromUOM the units for value * Or can be an array of values * @param array|string $toUOM the units for the result * Or can be an array of values * * @return array|float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function CONVERT($value, $fromUOM, $toUOM) { if (is_array($value) || is_array($fromUOM) || is_array($toUOM)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $fromUOM, $toUOM); } if (!is_numeric($value)) { return ExcelError::VALUE(); } try { [$fromUOM, $fromCategory, $fromMultiplier] = self::getUOMDetails($fromUOM); [$toUOM, $toCategory, $toMultiplier] = self::getUOMDetails($toUOM); } catch (Exception $e) { return ExcelError::NA(); } if ($fromCategory !== $toCategory) { return ExcelError::NA(); } // @var float $value $value *= $fromMultiplier; if (($fromUOM === $toUOM) && ($fromMultiplier === $toMultiplier)) { // We've already factored $fromMultiplier into the value, so we need // to reverse it again return $value / $fromMultiplier; } elseif ($fromUOM === $toUOM) { return $value / $toMultiplier; } elseif ($fromCategory === self::CATEGORY_TEMPERATURE) { return self::convertTemperature($fromUOM, $toUOM, /** @scrutinizer ignore-type */ $value); } $baseValue = $value * (1.0 / self::$unitConversions[$fromCategory][$fromUOM]); return ($baseValue * self::$unitConversions[$fromCategory][$toUOM]) / $toMultiplier; } private static function getUOMDetails(string $uom): array { if (isset(self::$conversionUnits[$uom])) { $unitCategory = self::$conversionUnits[$uom]['Group']; return [$uom, $unitCategory, 1.0]; } // Check 1-character standard metric multiplier prefixes $multiplierType = substr($uom, 0, 1); $uom = substr($uom, 1); if (isset(self::$conversionUnits[$uom], self::$conversionMultipliers[$multiplierType])) { if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { throw new Exception('Prefix not allowed for UoM'); } $unitCategory = self::$conversionUnits[$uom]['Group']; return [$uom, $unitCategory, self::$conversionMultipliers[$multiplierType]['multiplier']]; } $multiplierType .= substr($uom, 0, 1); $uom = substr($uom, 1); // Check 2-character standard metric multiplier prefixes if (isset(self::$conversionUnits[$uom], self::$conversionMultipliers[$multiplierType])) { if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { throw new Exception('Prefix not allowed for UoM'); } $unitCategory = self::$conversionUnits[$uom]['Group']; return [$uom, $unitCategory, self::$conversionMultipliers[$multiplierType]['multiplier']]; } // Check 2-character binary multiplier prefixes if (isset(self::$conversionUnits[$uom], self::$binaryConversionMultipliers[$multiplierType])) { if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { throw new Exception('Prefix not allowed for UoM'); } $unitCategory = self::$conversionUnits[$uom]['Group']; if ($unitCategory !== 'Information') { throw new Exception('Binary Prefix is only allowed for Information UoM'); } return [$uom, $unitCategory, self::$binaryConversionMultipliers[$multiplierType]['multiplier']]; } throw new Exception('UoM Not Found'); } /** * @param float|int $value * * @return float|int */ protected static function convertTemperature(string $fromUOM, string $toUOM, $value) { $fromUOM = self::resolveTemperatureSynonyms($fromUOM); $toUOM = self::resolveTemperatureSynonyms($toUOM); if ($fromUOM === $toUOM) { return $value; } // Convert to Kelvin switch ($fromUOM) { case 'F': $value = ($value - 32) / 1.8 + 273.15; break; case 'C': $value += 273.15; break; case 'Rank': $value /= 1.8; break; case 'Reau': $value = $value * 1.25 + 273.15; break; } // Convert from Kelvin switch ($toUOM) { case 'F': $value = ($value - 273.15) * 1.8 + 32.00; break; case 'C': $value -= 273.15; break; case 'Rank': $value *= 1.8; break; case 'Reau': $value = ($value - 273.15) * 0.80000; break; } return $value; } private static function resolveTemperatureSynonyms(string $uom): string { switch ($uom) { case 'fah': return 'F'; case 'cel': return 'C'; case 'kel': return 'K'; } return $uom; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php 0000644 00000016615 15002227416 0023105 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ConvertOctal extends ConvertBase { /** * toBinary. * * Return an octal value as binary. * * Excel Function: * OCT2BIN(x[,places]) * * @param array|string $value The octal number you want to convert. Number may not * contain more than 10 characters. The most significant * bit of number is the sign bit. The remaining 29 bits * are magnitude bits. Negative numbers are represented * using two's-complement notation. * If number is negative, OCT2BIN ignores places and returns * a 10-character binary number. * If number is negative, it cannot be less than 7777777000, * and if number is positive, it cannot be greater than 777. * If number is not a valid octal number, OCT2BIN returns * the #NUM! error value. * If OCT2BIN requires more than places characters, it * returns the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, * OCT2BIN uses the minimum number of characters necessary. * Places is useful for padding the return value with * leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, OCT2BIN returns the #VALUE! * error value. * If places is negative, OCT2BIN returns the #NUM! error * value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toBinary($value, $places = null) { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateOctal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } return ConvertDecimal::toBinary(self::toDecimal($value), $places); } /** * toDecimal. * * Return an octal value as decimal. * * Excel Function: * OCT2DEC(x) * * @param array|string $value The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using * two's-complement notation. * If number is not a valid octal number, OCT2DEC returns the * #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toDecimal($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::validateValue($value); $value = self::validateOctal($value); } catch (Exception $e) { return $e->getMessage(); } $binX = ''; foreach (str_split($value) as $char) { $binX .= str_pad(decbin((int) $char), 3, '0', STR_PAD_LEFT); } if (strlen($binX) == 30 && $binX[0] == '1') { for ($i = 0; $i < 30; ++$i) { $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); } return (string) ((bindec($binX) + 1) * -1); } return (string) bindec($binX); } /** * toHex. * * Return an octal value as hex. * * Excel Function: * OCT2HEX(x[,places]) * * @param array|string $value The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using * two's-complement notation. * If number is negative, OCT2HEX ignores places and returns a * 10-character hexadecimal number. * If number is not a valid octal number, OCT2HEX returns the * #NUM! error value. * If OCT2HEX requires more than places characters, it returns * the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, OCT2HEX * uses the minimum number of characters necessary. Places is useful * for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, OCT2HEX returns the #VALUE! error value. * If places is negative, OCT2HEX returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toHex($value, $places = null) { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateOctal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $hexVal = strtoupper(dechex((int) self::toDecimal($value))); $hexVal = (PHP_INT_SIZE === 4 && strlen($value) === 10 && $value[0] >= '4') ? "FF{$hexVal}" : $hexVal; return self::nbrConversionFormat($hexVal, $places); } protected static function validateOctal(string $value): string { $numDigits = (int) preg_match_all('/[01234567]/', $value); if (strlen($value) > $numDigits || $numDigits > 10) { throw new Exception(ExcelError::NAN()); } return $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselY.php 0000644 00000011464 15002227416 0022045 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class BesselY { use ArrayEnabled; /** * BESSELY. * * Returns the Bessel function, which is also called the Weber function or the Neumann function. * * Excel Function: * BESSELY(x,ord) * * @param mixed $x A float value at which to evaluate the function. * If x is nonnumeric, BESSELY returns the #VALUE! error value. * Or can be an array of values * @param mixed $ord The integer order of the Bessel function. * If ord is not an integer, it is truncated. * If $ord is nonnumeric, BESSELY returns the #VALUE! error value. * If $ord < 0, BESSELY returns the #NUM! error value. * Or can be an array of values * * @return array|float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELY($x, $ord) { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if (($ord < 0) || ($x <= 0.0)) { return ExcelError::NAN(); } $fBy = self::calculate($x, $ord); return (is_nan($fBy)) ? ExcelError::NAN() : $fBy; } private static function calculate(float $x, int $ord): float { // special cases switch ($ord) { case 0: return self::besselY0($x); case 1: return self::besselY1($x); } return self::besselY2($x, $ord); } /** * Mollify Phpstan. * * @codeCoverageIgnore */ private static function callBesselJ(float $x, int $ord): float { $rslt = BesselJ::BESSELJ($x, $ord); if (!is_float($rslt)) { throw new Exception('Unexpected array or string'); } return $rslt; } private static function besselY0(float $x): float { if ($x < 8.0) { $y = ($x * $x); $ans1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733)))); $ans2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y)))); return $ans1 / $ans2 + 0.636619772 * self::callBesselJ($x, 0) * log($x); } $z = 8.0 / $x; $y = ($z * $z); $xx = $x - 0.785398164; $ans1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); $ans2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7)))); return sqrt(0.636619772 / $x) * (sin($xx) * $ans1 + $z * cos($xx) * $ans2); } private static function besselY1(float $x): float { if ($x < 8.0) { $y = ($x * $x); $ans1 = $x * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y * (-0.4237922726e7 + $y * 0.8511937935e4))))); $ans2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y * (0.1020426050e6 + $y * (0.3549632885e3 + $y))))); return ($ans1 / $ans2) + 0.636619772 * (self::callBesselJ($x, 1) * log($x) - 1 / $x); } $z = 8.0 / $x; $y = $z * $z; $xx = $x - 2.356194491; $ans1 = 1.0 + $y * (0.183105e-2 + $y * (-0.3516396496e-4 + $y * (0.2457520174e-5 + $y * (-0.240337019e-6)))); $ans2 = 0.04687499995 + $y * (-0.2002690873e-3 + $y * (0.8449199096e-5 + $y * (-0.88228987e-6 + $y * 0.105787412e-6))); return sqrt(0.636619772 / $x) * (sin($xx) * $ans1 + $z * cos($xx) * $ans2); } private static function besselY2(float $x, int $ord): float { $fTox = 2.0 / $x; $fBym = self::besselY0($x); $fBy = self::besselY1($x); for ($n = 1; $n < $ord; ++$n) { $fByp = $n * $fTox * $fBy - $fBym; $fBym = $fBy; $fBy = $fByp; } return $fBy; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php 0000644 00000016134 15002227416 0023263 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ConvertBinary extends ConvertBase { /** * toDecimal. * * Return a binary value as decimal. * * Excel Function: * BIN2DEC(x) * * @param array|string $value The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2DEC returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toDecimal($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::validateValue($value); $value = self::validateBinary($value); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) == 10 && $value[0] === '1') { // Two's Complement $value = substr($value, -9); return '-' . (512 - bindec($value)); } return (string) bindec($value); } /** * toHex. * * Return a binary value as hex. * * Excel Function: * BIN2HEX(x[,places]) * * @param array|string $value The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2HEX returns the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, BIN2HEX uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, BIN2HEX returns the #VALUE! error value. * If places is negative, BIN2HEX returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toHex($value, $places = null) { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateBinary($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) == 10 && $value[0] === '1') { $high2 = substr($value, 0, 2); $low8 = substr($value, 2); $xarr = ['00' => '00000000', '01' => '00000001', '10' => 'FFFFFFFE', '11' => 'FFFFFFFF']; return $xarr[$high2] . strtoupper(substr('0' . dechex((int) bindec($low8)), -2)); } $hexVal = (string) strtoupper(dechex((int) bindec($value))); return self::nbrConversionFormat($hexVal, $places); } /** * toOctal. * * Return a binary value as octal. * * Excel Function: * BIN2OCT(x[,places]) * * @param array|string $value The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2OCT returns the #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, BIN2OCT uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, BIN2OCT returns the #VALUE! error value. * If places is negative, BIN2OCT returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toOctal($value, $places = null) { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateBinary($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } if (strlen($value) == 10 && $value[0] === '1') { // Two's Complement return str_repeat('7', 6) . strtoupper(decoct((int) bindec("11$value"))); } $octVal = (string) decoct((int) bindec($value)); return self::nbrConversionFormat($octVal, $places); } protected static function validateBinary(string $value): string { if ((strlen($value) > preg_match_all('/[01]/', $value)) || (strlen($value) > 10)) { throw new Exception(ExcelError::NAN()); } return $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselK.php 0000644 00000010370 15002227416 0022022 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class BesselK { use ArrayEnabled; /** * BESSELK. * * Returns the modified Bessel function Kn(x), which is equivalent to the Bessel functions evaluated * for purely imaginary arguments. * * Excel Function: * BESSELK(x,ord) * * @param mixed $x A float value at which to evaluate the function. * If x is nonnumeric, BESSELK returns the #VALUE! error value. * Or can be an array of values * @param mixed $ord The integer order of the Bessel function. * If ord is not an integer, it is truncated. * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. * If $ord < 0, BESSELKI returns the #NUM! error value. * Or can be an array of values * * @return array|float|string Result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BESSELK($x, $ord) { if (is_array($x) || is_array($ord)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); } try { $x = EngineeringValidations::validateFloat($x); $ord = EngineeringValidations::validateInt($ord); } catch (Exception $e) { return $e->getMessage(); } if (($ord < 0) || ($x <= 0.0)) { return ExcelError::NAN(); } $fBk = self::calculate($x, $ord); return (is_nan($fBk)) ? ExcelError::NAN() : $fBk; } private static function calculate(float $x, int $ord): float { // special cases switch ($ord) { case 0: return self::besselK0($x); case 1: return self::besselK1($x); } return self::besselK2($x, $ord); } /** * Mollify Phpstan. * * @codeCoverageIgnore */ private static function callBesselI(float $x, int $ord): float { $rslt = BesselI::BESSELI($x, $ord); if (!is_float($rslt)) { throw new Exception('Unexpected array or string'); } return $rslt; } private static function besselK0(float $x): float { if ($x <= 2) { $fNum2 = $x * 0.5; $y = ($fNum2 * $fNum2); return -log($fNum2) * self::callBesselI($x, 0) + (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y * (0.10750e-3 + $y * 0.74e-5)))))); } $y = 2 / $x; return exp(-$x) / sqrt($x) * (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y * (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3)))))); } private static function besselK1(float $x): float { if ($x <= 2) { $fNum2 = $x * 0.5; $y = ($fNum2 * $fNum2); return log($fNum2) * self::callBesselI($x, 1) + (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y * (-0.110404e-2 + $y * (-0.4686e-4))))))) / $x; } $y = 2 / $x; return exp(-$x) / sqrt($x) * (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y * (0.325614e-2 + $y * (-0.68245e-3))))))); } private static function besselK2(float $x, int $ord): float { $fTox = 2 / $x; $fBkm = self::besselK0($x); $fBk = self::besselK1($x); for ($n = 1; $n < $ord; ++$n) { $fBkp = $fBkm + $n * $fTox * $fBk; $fBkm = $fBk; $fBk = $fBkp; } return $fBk; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertBase.php 0000644 00000003666 15002227416 0022717 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; abstract class ConvertBase { use ArrayEnabled; /** @param mixed $value */ protected static function validateValue($value): string { if (is_bool($value)) { if (Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE) { throw new Exception(ExcelError::VALUE()); } $value = (int) $value; } if (is_numeric($value)) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { $value = floor((float) $value); } } return strtoupper((string) $value); } /** @param mixed $places */ protected static function validatePlaces($places = null): ?int { if ($places === null) { return $places; } if (is_numeric($places)) { if ($places < 0 || $places > 10) { throw new Exception(ExcelError::NAN()); } return (int) $places; } throw new Exception(ExcelError::VALUE()); } /** * Formats a number base string value with leading zeroes. * * @param string $value The "number" to pad * @param ?int $places The length that we want to pad this value * * @return string The padded "number" */ protected static function nbrConversionFormat(string $value, ?int $places): string { if ($places !== null) { if (strlen($value) <= $places) { return substr(str_pad($value, $places, '0', STR_PAD_LEFT), -10); } return ExcelError::NAN(); } return substr($value, -10); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BitWise.php 0000644 00000020134 15002227416 0022037 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class BitWise { use ArrayEnabled; const SPLIT_DIVISOR = 2 ** 24; /** * Split a number into upper and lower portions for full 32-bit support. * * @param float|int $number * * @return int[] */ private static function splitNumber($number): array { return [(int) floor($number / self::SPLIT_DIVISOR), (int) fmod($number, self::SPLIT_DIVISOR)]; } /** * BITAND. * * Returns the bitwise AND of two integer values. * * Excel Function: * BITAND(number1, number2) * * @param array|int $number1 * Or can be an array of values * @param array|int $number2 * Or can be an array of values * * @return array|int|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITAND($number1, $number2) { if (is_array($number1) || is_array($number2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number1, $number2); } try { $number1 = self::validateBitwiseArgument($number1); $number2 = self::validateBitwiseArgument($number2); } catch (Exception $e) { return $e->getMessage(); } $split1 = self::splitNumber($number1); $split2 = self::splitNumber($number2); return self::SPLIT_DIVISOR * ($split1[0] & $split2[0]) + ($split1[1] & $split2[1]); } /** * BITOR. * * Returns the bitwise OR of two integer values. * * Excel Function: * BITOR(number1, number2) * * @param array|int $number1 * Or can be an array of values * @param array|int $number2 * Or can be an array of values * * @return array|int|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITOR($number1, $number2) { if (is_array($number1) || is_array($number2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number1, $number2); } try { $number1 = self::validateBitwiseArgument($number1); $number2 = self::validateBitwiseArgument($number2); } catch (Exception $e) { return $e->getMessage(); } $split1 = self::splitNumber($number1); $split2 = self::splitNumber($number2); return self::SPLIT_DIVISOR * ($split1[0] | $split2[0]) + ($split1[1] | $split2[1]); } /** * BITXOR. * * Returns the bitwise XOR of two integer values. * * Excel Function: * BITXOR(number1, number2) * * @param array|int $number1 * Or can be an array of values * @param array|int $number2 * Or can be an array of values * * @return array|int|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITXOR($number1, $number2) { if (is_array($number1) || is_array($number2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number1, $number2); } try { $number1 = self::validateBitwiseArgument($number1); $number2 = self::validateBitwiseArgument($number2); } catch (Exception $e) { return $e->getMessage(); } $split1 = self::splitNumber($number1); $split2 = self::splitNumber($number2); return self::SPLIT_DIVISOR * ($split1[0] ^ $split2[0]) + ($split1[1] ^ $split2[1]); } /** * BITLSHIFT. * * Returns the number value shifted left by shift_amount bits. * * Excel Function: * BITLSHIFT(number, shift_amount) * * @param array|int $number * Or can be an array of values * @param array|int $shiftAmount * Or can be an array of values * * @return array|float|int|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITLSHIFT($number, $shiftAmount) { if (is_array($number) || is_array($shiftAmount)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $shiftAmount); } try { $number = self::validateBitwiseArgument($number); $shiftAmount = self::validateShiftAmount($shiftAmount); } catch (Exception $e) { return $e->getMessage(); } $result = floor($number * (2 ** $shiftAmount)); if ($result > 2 ** 48 - 1) { return ExcelError::NAN(); } return $result; } /** * BITRSHIFT. * * Returns the number value shifted right by shift_amount bits. * * Excel Function: * BITRSHIFT(number, shift_amount) * * @param array|int $number * Or can be an array of values * @param array|int $shiftAmount * Or can be an array of values * * @return array|float|int|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function BITRSHIFT($number, $shiftAmount) { if (is_array($number) || is_array($shiftAmount)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $shiftAmount); } try { $number = self::validateBitwiseArgument($number); $shiftAmount = self::validateShiftAmount($shiftAmount); } catch (Exception $e) { return $e->getMessage(); } $result = floor($number / (2 ** $shiftAmount)); if ($result > 2 ** 48 - 1) { // possible because shiftAmount can be negative return ExcelError::NAN(); } return $result; } /** * Validate arguments passed to the bitwise functions. * * @param mixed $value * * @return float */ private static function validateBitwiseArgument($value) { $value = self::nullFalseTrueToNumber($value); if (is_numeric($value)) { $value = (float) $value; if ($value == floor($value)) { if (($value > 2 ** 48 - 1) || ($value < 0)) { throw new Exception(ExcelError::NAN()); } return floor($value); } throw new Exception(ExcelError::NAN()); } throw new Exception(ExcelError::VALUE()); } /** * Validate arguments passed to the bitwise functions. * * @param mixed $value * * @return int */ private static function validateShiftAmount($value) { $value = self::nullFalseTrueToNumber($value); if (is_numeric($value)) { if (abs($value) > 53) { throw new Exception(ExcelError::NAN()); } return (int) $value; } throw new Exception(ExcelError::VALUE()); } /** * Many functions accept null/false/true argument treated as 0/0/1. * * @param mixed $number * * @return mixed */ private static function nullFalseTrueToNumber(&$number) { if ($number === null) { $number = 0; } elseif (is_bool($number)) { $number = (int) $number; } return $number; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php 0000644 00000046176 15002227416 0024007 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use Complex\Complex as ComplexObject; use Complex\Exception as ComplexException; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ComplexFunctions { use ArrayEnabled; /** * IMABS. * * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format. * * Excel Function: * IMABS(complexNumber) * * @param array|string $complexNumber the complex number for which you want the absolute value * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMABS($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return $complex->abs(); } /** * IMARGUMENT. * * Returns the argument theta of a complex number, i.e. the angle in radians from the real * axis to the representation of the number in polar coordinates. * * Excel Function: * IMARGUMENT(complexNumber) * * @param array|string $complexNumber the complex number for which you want the argument theta * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMARGUMENT($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::DIV0(); } return $complex->argument(); } /** * IMCONJUGATE. * * Returns the complex conjugate of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCONJUGATE(complexNumber) * * @param array|string $complexNumber the complex number for which you want the conjugate * Or can be an array of values * * @return array|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCONJUGATE($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->conjugate(); } /** * IMCOS. * * Returns the cosine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOS(complexNumber) * * @param array|string $complexNumber the complex number for which you want the cosine * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCOS($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->cos(); } /** * IMCOSH. * * Returns the hyperbolic cosine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOSH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic cosine * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCOSH($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->cosh(); } /** * IMCOT. * * Returns the cotangent of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOT(complexNumber) * * @param array|string $complexNumber the complex number for which you want the cotangent * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCOT($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->cot(); } /** * IMCSC. * * Returns the cosecant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCSC(complexNumber) * * @param array|string $complexNumber the complex number for which you want the cosecant * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCSC($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->csc(); } /** * IMCSCH. * * Returns the hyperbolic cosecant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCSCH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic cosecant * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMCSCH($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->csch(); } /** * IMSIN. * * Returns the sine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSIN(complexNumber) * * @param array|string $complexNumber the complex number for which you want the sine * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSIN($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->sin(); } /** * IMSINH. * * Returns the hyperbolic sine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSINH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic sine * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSINH($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->sinh(); } /** * IMSEC. * * Returns the secant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSEC(complexNumber) * * @param array|string $complexNumber the complex number for which you want the secant * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSEC($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->sec(); } /** * IMSECH. * * Returns the hyperbolic secant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSECH(complexNumber) * * @param array|string $complexNumber the complex number for which you want the hyperbolic secant * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSECH($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->sech(); } /** * IMTAN. * * Returns the tangent of a complex number in x + yi or x + yj text format. * * Excel Function: * IMTAN(complexNumber) * * @param array|string $complexNumber the complex number for which you want the tangent * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMTAN($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->tan(); } /** * IMSQRT. * * Returns the square root of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSQRT(complexNumber) * * @param array|string $complexNumber the complex number for which you want the square root * Or can be an array of values * * @return array|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMSQRT($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } $theta = self::IMARGUMENT($complexNumber); if ($theta === ExcelError::DIV0()) { return '0'; } return (string) $complex->sqrt(); } /** * IMLN. * * Returns the natural logarithm of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLN(complexNumber) * * @param array|string $complexNumber the complex number for which you want the natural logarithm * Or can be an array of values * * @return array|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMLN($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::NAN(); } return (string) $complex->ln(); } /** * IMLOG10. * * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLOG10(complexNumber) * * @param array|string $complexNumber the complex number for which you want the common logarithm * Or can be an array of values * * @return array|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMLOG10($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::NAN(); } return (string) $complex->log10(); } /** * IMLOG2. * * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLOG2(complexNumber) * * @param array|string $complexNumber the complex number for which you want the base-2 logarithm * Or can be an array of values * * @return array|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMLOG2($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { return ExcelError::NAN(); } return (string) $complex->log2(); } /** * IMEXP. * * Returns the exponential of a complex number in x + yi or x + yj text format. * * Excel Function: * IMEXP(complexNumber) * * @param array|string $complexNumber the complex number for which you want the exponential * Or can be an array of values * * @return array|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMEXP($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return (string) $complex->exp(); } /** * IMPOWER. * * Returns a complex number in x + yi or x + yj text format raised to a power. * * Excel Function: * IMPOWER(complexNumber,realNumber) * * @param array|string $complexNumber the complex number you want to raise to a power * Or can be an array of values * @param array|float|int|string $realNumber the power to which you want to raise the complex number * Or can be an array of values * * @return array|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMPOWER($complexNumber, $realNumber) { if (is_array($complexNumber) || is_array($realNumber)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $complexNumber, $realNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } if (!is_numeric($realNumber)) { return ExcelError::VALUE(); } return (string) $complex->pow((float) $realNumber); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php 0000644 00000022401 15002227416 0023367 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ConvertDecimal extends ConvertBase { const LARGEST_OCTAL_IN_DECIMAL = 536870911; const SMALLEST_OCTAL_IN_DECIMAL = -536870912; const LARGEST_BINARY_IN_DECIMAL = 511; const SMALLEST_BINARY_IN_DECIMAL = -512; const LARGEST_HEX_IN_DECIMAL = 549755813887; const SMALLEST_HEX_IN_DECIMAL = -549755813888; /** * toBinary. * * Return a decimal value as binary. * * Excel Function: * DEC2BIN(x[,places]) * * @param array|string $value The decimal integer you want to convert. If number is negative, * valid place values are ignored and DEC2BIN returns a 10-character * (10-bit) binary number in which the most significant bit is the sign * bit. The remaining 9 bits are magnitude bits. Negative numbers are * represented using two's-complement notation. * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error * value. * If number is nonnumeric, DEC2BIN returns the #VALUE! error value. * If DEC2BIN requires more than places characters, it returns the #NUM! * error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, DEC2BIN uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2BIN returns the #VALUE! error value. * If places is zero or negative, DEC2BIN returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toBinary($value, $places = null) { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateDecimal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $value = (int) floor((float) $value); if ($value > self::LARGEST_BINARY_IN_DECIMAL || $value < self::SMALLEST_BINARY_IN_DECIMAL) { return ExcelError::NAN(); } $r = decbin($value); // Two's Complement $r = substr($r, -10); return self::nbrConversionFormat($r, $places); } /** * toHex. * * Return a decimal value as hex. * * Excel Function: * DEC2HEX(x[,places]) * * @param array|string $value The decimal integer you want to convert. If number is negative, * places is ignored and DEC2HEX returns a 10-character (40-bit) * hexadecimal number in which the most significant bit is the sign * bit. The remaining 39 bits are magnitude bits. Negative numbers * are represented using two's-complement notation. * If number < -549,755,813,888 or if number > 549,755,813,887, * DEC2HEX returns the #NUM! error value. * If number is nonnumeric, DEC2HEX returns the #VALUE! error value. * If DEC2HEX requires more than places characters, it returns the * #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, DEC2HEX uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2HEX returns the #VALUE! error value. * If places is zero or negative, DEC2HEX returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toHex($value, $places = null) { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateDecimal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $value = floor((float) $value); if ($value > self::LARGEST_HEX_IN_DECIMAL || $value < self::SMALLEST_HEX_IN_DECIMAL) { return ExcelError::NAN(); } $r = strtoupper(dechex((int) $value)); $r = self::hex32bit($value, $r); return self::nbrConversionFormat($r, $places); } public static function hex32bit(float $value, string $hexstr, bool $force = false): string { if (PHP_INT_SIZE === 4 || $force) { if ($value >= 2 ** 32) { $quotient = (int) ($value / (2 ** 32)); return strtoupper(substr('0' . dechex($quotient), -2) . $hexstr); } if ($value < -(2 ** 32)) { $quotient = 256 - (int) ceil((-$value) / (2 ** 32)); return strtoupper(substr('0' . dechex($quotient), -2) . substr("00000000$hexstr", -8)); } if ($value < 0) { return "FF$hexstr"; } } return $hexstr; } /** * toOctal. * * Return an decimal value as octal. * * Excel Function: * DEC2OCT(x[,places]) * * @param array|string $value The decimal integer you want to convert. If number is negative, * places is ignored and DEC2OCT returns a 10-character (30-bit) * octal number in which the most significant bit is the sign bit. * The remaining 29 bits are magnitude bits. Negative numbers are * represented using two's-complement notation. * If number < -536,870,912 or if number > 536,870,911, DEC2OCT * returns the #NUM! error value. * If number is nonnumeric, DEC2OCT returns the #VALUE! error value. * If DEC2OCT requires more than places characters, it returns the * #NUM! error value. * Or can be an array of values * @param array|int $places The number of characters to use. If places is omitted, DEC2OCT uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2OCT returns the #VALUE! error value. * If places is zero or negative, DEC2OCT returns the #NUM! error value. * Or can be an array of values * * @return array|string Result, or an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function toOctal($value, $places = null) { if (is_array($value) || is_array($places)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); } try { $value = self::validateValue($value); $value = self::validateDecimal($value); $places = self::validatePlaces($places); } catch (Exception $e) { return $e->getMessage(); } $value = (int) floor((float) $value); if ($value > self::LARGEST_OCTAL_IN_DECIMAL || $value < self::SMALLEST_OCTAL_IN_DECIMAL) { return ExcelError::NAN(); } $r = decoct($value); $r = substr($r, -10); return self::nbrConversionFormat($r, $places); } protected static function validateDecimal(string $value): string { if (strlen($value) > preg_match_all('/[-0123456789.]/', $value)) { throw new Exception(ExcelError::VALUE()); } return $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ErfC.php 0000644 00000004623 15002227416 0021315 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ErfC { use ArrayEnabled; /** * ERFC. * * Returns the complementary ERF function integrated between x and infinity * * Note: In Excel 2007 or earlier, if you input a negative value for the lower bound argument, * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was * improved, so that it can now calculate the function for both positive and negative x values. * PhpSpreadsheet follows Excel 2010 behaviour, and accepts nagative arguments. * * Excel Function: * ERFC(x) * * @param mixed $value The float lower bound for integrating ERFC * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ERFC($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (is_numeric($value)) { return self::erfcValue($value); } return ExcelError::VALUE(); } private const ONE_SQRT_PI = 0.564189583547756287; /** * Method to calculate the erfc value. * * @param float|int|string $value * * @return float */ private static function erfcValue($value) { $value = (float) $value; if (abs($value) < 2.2) { return 1 - Erf::erfValue($value); } if ($value < 0) { return 2 - self::erfcValue(-$value); } $a = $n = 1; $b = $c = $value; $d = ($value * $value) + 0.5; $q2 = $b / $d; do { $t = $a * $n + $b * $value; $a = $b; $b = $t; $t = $c * $n + $d * $value; $c = $d; $d = $t; $n += 0.5; $q1 = $q2; $q2 = $b / $d; } while ((abs($q1 - $q2) / $q2) > Functions::PRECISION); return self::ONE_SQRT_PI * exp(-$value * $value) * $q2; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Complex.php 0000644 00000010224 15002227416 0022077 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use Complex\Complex as ComplexObject; use Complex\Exception as ComplexException; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Complex { use ArrayEnabled; /** * COMPLEX. * * Converts real and imaginary coefficients into a complex number of the form x +/- yi or x +/- yj. * * Excel Function: * COMPLEX(realNumber,imaginary[,suffix]) * * @param mixed $realNumber the real float coefficient of the complex number * Or can be an array of values * @param mixed $imaginary the imaginary float coefficient of the complex number * Or can be an array of values * @param mixed $suffix The character suffix for the imaginary component of the complex number. * If omitted, the suffix is assumed to be "i". * Or can be an array of values * * @return array|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function COMPLEX($realNumber = 0.0, $imaginary = 0.0, $suffix = 'i') { if (is_array($realNumber) || is_array($imaginary) || is_array($suffix)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $realNumber, $imaginary, $suffix); } $realNumber = $realNumber ?? 0.0; $imaginary = $imaginary ?? 0.0; $suffix = $suffix ?? 'i'; try { $realNumber = EngineeringValidations::validateFloat($realNumber); $imaginary = EngineeringValidations::validateFloat($imaginary); } catch (Exception $e) { return $e->getMessage(); } if (($suffix === 'i') || ($suffix === 'j') || ($suffix === '')) { $complex = new ComplexObject($realNumber, $imaginary, $suffix); return (string) $complex; } return ExcelError::VALUE(); } /** * IMAGINARY. * * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format. * * Excel Function: * IMAGINARY(complexNumber) * * @param array|string $complexNumber the complex number for which you want the imaginary * coefficient * Or can be an array of values * * @return array|float|string (string if an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMAGINARY($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return $complex->getImaginary(); } /** * IMREAL. * * Returns the real coefficient of a complex number in x + yi or x + yj text format. * * Excel Function: * IMREAL(complexNumber) * * @param array|string $complexNumber the complex number for which you want the real coefficient * Or can be an array of values * * @return array|float|string (string if an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function IMREAL($complexNumber) { if (is_array($complexNumber)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); } try { $complex = new ComplexObject($complexNumber); } catch (ComplexException $e) { return ExcelError::NAN(); } return $complex->getReal(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php 0000644 00000001311 15002227416 0025115 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class EngineeringValidations { /** * @param mixed $value */ public static function validateFloat($value): float { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (float) $value; } /** * @param mixed $value */ public static function validateInt($value): int { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (int) floor((float) $value); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Compare.php 0000644 00000005620 15002227416 0022062 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; class Compare { use ArrayEnabled; /** * DELTA. * * Excel Function: * DELTA(a[,b]) * * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise. * Use this function to filter a set of values. For example, by summing several DELTA * functions you calculate the count of equal pairs. This function is also known as the * Kronecker Delta function. * * @param array|float $a the first number * Or can be an array of values * @param array|float $b The second number. If omitted, b is assumed to be zero. * Or can be an array of values * * @return array|int|string (string in the event of an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function DELTA($a, $b = 0.0) { if (is_array($a) || is_array($b)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $a, $b); } try { $a = EngineeringValidations::validateFloat($a); $b = EngineeringValidations::validateFloat($b); } catch (Exception $e) { return $e->getMessage(); } return (int) (abs($a - $b) < 1.0e-15); } /** * GESTEP. * * Excel Function: * GESTEP(number[,step]) * * Returns 1 if number >= step; returns 0 (zero) otherwise * Use this function to filter a set of values. For example, by summing several GESTEP * functions you calculate the count of values that exceed a threshold. * * @param array|float $number the value to test against step * Or can be an array of values * @param null|array|float $step The threshold value. If you omit a value for step, GESTEP uses zero. * Or can be an array of values * * @return array|int|string (string in the event of an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function GESTEP($number, $step = 0.0) { if (is_array($number) || is_array($step)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $step); } try { $number = EngineeringValidations::validateFloat($number); $step = EngineeringValidations::validateFloat($step ?? 0.0); } catch (Exception $e) { return $e->getMessage(); } return (int) ($number >= $step); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php 0000644 00000001425 15002227416 0023050 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; abstract class VarianceBase { /** * @param mixed $value * * @return mixed */ protected static function datatypeAdjustmentAllowStrings($value) { if (is_bool($value)) { return (int) $value; } elseif (is_string($value)) { return 0; } return $value; } /** * @param mixed $value * * @return mixed */ protected static function datatypeAdjustmentBooleans($value) { if (is_bool($value) && (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) { return (int) $value; } return $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Confidence.php 0000644 00000003403 15002227416 0022560 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Confidence { use ArrayEnabled; /** * CONFIDENCE. * * Returns the confidence interval for a population mean * * @param mixed $alpha As a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * @param mixed $size As an integer * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function CONFIDENCE($alpha, $stdDev, $size) { if (is_array($alpha) || is_array($stdDev) || is_array($size)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $alpha, $stdDev, $size); } try { $alpha = StatisticalValidations::validateFloat($alpha); $stdDev = StatisticalValidations::validateFloat($stdDev); $size = StatisticalValidations::validateInt($size); } catch (Exception $e) { return $e->getMessage(); } if (($alpha <= 0) || ($alpha >= 1) || ($stdDev <= 0) || ($size < 1)) { return ExcelError::NAN(); } /** @var float */ $temp = Distributions\StandardNormal::inverse(1 - $alpha / 2); return Functions::scalar($temp * $stdDev / sqrt($size)); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Maximum.php 0000644 00000004415 15002227416 0022144 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; class Maximum extends MaxMinBase { /** * MAX. * * MAX returns the value of the element of the values passed that has the highest value, * with negative numbers considered smaller than positive numbers. * * Excel Function: * MAX(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float */ public static function max(...$args) { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { if (($returnValue === null) || ($arg > $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } return $returnValue; } /** * MAXA. * * Returns the greatest value in a list of arguments, including numbers, text, and logical values * * Excel Function: * MAXA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float */ public static function maxA(...$args) { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); if (($returnValue === null) || ($arg > $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } return $returnValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Counts.php 0000644 00000005265 15002227416 0022006 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcException; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class Counts extends AggregateBase { /** * COUNT. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNT(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return int */ public static function COUNT(...$args) { $returnValue = 0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if (self::isAcceptedCountable($arg, $k, true)) { ++$returnValue; } } return $returnValue; } /** * COUNTA. * * Counts the number of cells that are not empty within the list of arguments * * Excel Function: * COUNTA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return int */ public static function COUNTA(...$args) { $returnValue = 0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { // Nulls are counted if literals, but not if cell values if ($arg !== null || (!Functions::isCellValue($k))) { ++$returnValue; } } return $returnValue; } /** * COUNTBLANK. * * Counts the number of empty cells within the list of arguments * * Excel Function: * COUNTBLANK(value1[,value2[, ...]]) * * @param mixed $range Data values * * @return int */ public static function COUNTBLANK($range) { if ($range === null) { return 1; } if (!is_array($range) || array_key_exists(0, $range)) { throw new CalcException('Must specify range of cells, not any kind of literal'); } $returnValue = 0; // Loop through arguments $aArgs = Functions::flattenArray($range); foreach ($aArgs as $arg) { // Is it a blank cell? if (($arg === null) || ((is_string($arg)) && ($arg == ''))) { ++$returnValue; } } return $returnValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php 0000644 00000004066 15002227416 0023212 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; abstract class AggregateBase { /** * MS Excel does not count Booleans if passed as cell values, but they are counted if passed as literals. * OpenOffice Calc always counts Booleans. * Gnumeric never counts Booleans. * * @param mixed $arg * @param mixed $k * * @return int|mixed */ protected static function testAcceptedBoolean($arg, $k) { if (!is_bool($arg)) { return $arg; } if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_GNUMERIC) { return $arg; } if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { return (int) $arg; } if (!Functions::isCellValue($k)) { return (int) $arg; } /*if ( (is_bool($arg)) && ((!Functions::isCellValue($k) && (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_EXCEL)) || (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE)) ) { $arg = (int) $arg; }*/ return $arg; } /** * @param mixed $arg * @param mixed $k * * @return bool */ protected static function isAcceptedCountable($arg, $k, bool $countNull = false) { if ($countNull && $arg === null && !Functions::isCellValue($k) && Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_GNUMERIC) { return true; } if (!is_numeric($arg)) { return false; } if (!is_string($arg)) { return true; } if (!Functions::isCellValue($k) && Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { return true; } if (!Functions::isCellValue($k) && Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_GNUMERIC) { return true; } return false; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Percentiles.php 0000644 00000014343 15002227416 0023005 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Percentiles { public const RANK_SORT_DESCENDING = 0; public const RANK_SORT_ASCENDING = 1; /** * PERCENTILE. * * Returns the nth percentile of values in a range.. * * Excel Function: * PERCENTILE(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function PERCENTILE(...$args) { $aArgs = Functions::flattenArray($args); // Calculate $entry = array_pop($aArgs); try { $entry = StatisticalValidations::validateFloat($entry); } catch (Exception $e) { return $e->getMessage(); } if (($entry < 0) || ($entry > 1)) { return ExcelError::NAN(); } $mArgs = self::percentileFilterValues($aArgs); $mValueCount = count($mArgs); if ($mValueCount > 0) { sort($mArgs); $count = Counts::COUNT($mArgs); $index = $entry * ($count - 1); $iBase = floor($index); if ($index == $iBase) { return $mArgs[$index]; } $iNext = $iBase + 1; $iProportion = $index - $iBase; return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion); } return ExcelError::NAN(); } /** * PERCENTRANK. * * Returns the rank of a value in a data set as a percentage of the data set. * Note that the returned rank is simply rounded to the appropriate significant digits, * rather than floored (as MS Excel), so value 3 for a value set of 1, 2, 3, 4 will return * 0.667 rather than 0.666 * * @param mixed $valueSet An array of (float) values, or a reference to, a list of numbers * @param mixed $value The number whose rank you want to find * @param mixed $significance The (integer) number of significant digits for the returned percentage value * * @return float|string (string if result is an error) */ public static function PERCENTRANK($valueSet, $value, $significance = 3) { $valueSet = Functions::flattenArray($valueSet); $value = Functions::flattenSingleValue($value); $significance = ($significance === null) ? 3 : Functions::flattenSingleValue($significance); try { $value = StatisticalValidations::validateFloat($value); $significance = StatisticalValidations::validateInt($significance); } catch (Exception $e) { return $e->getMessage(); } $valueSet = self::rankFilterValues($valueSet); $valueCount = count($valueSet); if ($valueCount == 0) { return ExcelError::NA(); } sort($valueSet, SORT_NUMERIC); $valueAdjustor = $valueCount - 1; if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) { return ExcelError::NA(); } $pos = array_search($value, $valueSet); if ($pos === false) { $pos = 0; $testValue = $valueSet[0]; while ($testValue < $value) { $testValue = $valueSet[++$pos]; } --$pos; $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos])); } return round(((float) $pos) / $valueAdjustor, $significance); } /** * QUARTILE. * * Returns the quartile of a data set. * * Excel Function: * QUARTILE(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function QUARTILE(...$args) { $aArgs = Functions::flattenArray($args); $entry = array_pop($aArgs); try { $entry = StatisticalValidations::validateFloat($entry); } catch (Exception $e) { return $e->getMessage(); } $entry = floor($entry); $entry /= 4; if (($entry < 0) || ($entry > 1)) { return ExcelError::NAN(); } return self::PERCENTILE($aArgs, $entry); } /** * RANK. * * Returns the rank of a number in a list of numbers. * * @param mixed $value The number whose rank you want to find * @param mixed $valueSet An array of float values, or a reference to, a list of numbers * @param mixed $order Order to sort the values in the value set * * @return float|string The result, or a string containing an error (0 = Descending, 1 = Ascending) */ public static function RANK($value, $valueSet, $order = self::RANK_SORT_DESCENDING) { $value = Functions::flattenSingleValue($value); $valueSet = Functions::flattenArray($valueSet); $order = ($order === null) ? self::RANK_SORT_DESCENDING : Functions::flattenSingleValue($order); try { $value = StatisticalValidations::validateFloat($value); $order = StatisticalValidations::validateInt($order); } catch (Exception $e) { return $e->getMessage(); } $valueSet = self::rankFilterValues($valueSet); if ($order === self::RANK_SORT_DESCENDING) { rsort($valueSet, SORT_NUMERIC); } else { sort($valueSet, SORT_NUMERIC); } $pos = array_search($value, $valueSet); if ($pos === false) { return ExcelError::NA(); } return ++$pos; } protected static function percentileFilterValues(array $dataSet): array { return array_filter( $dataSet, function ($value): bool { return is_numeric($value) && !is_string($value); } ); } protected static function rankFilterValues(array $dataSet): array { return array_filter( $dataSet, function ($value): bool { return is_numeric($value); } ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Trends.php 0000644 00000034246 15002227416 0021773 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Trend\Trend; class Trends { use ArrayEnabled; private static function filterTrendValues(array &$array1, array &$array2): void { foreach ($array1 as $key => $value) { if ((is_bool($value)) || (is_string($value)) || ($value === null)) { unset($array1[$key], $array2[$key]); } } } /** * @param mixed $array1 should be array, but scalar is made into one * @param mixed $array2 should be array, but scalar is made into one */ private static function checkTrendArrays(&$array1, &$array2): void { if (!is_array($array1)) { $array1 = [$array1]; } if (!is_array($array2)) { $array2 = [$array2]; } $array1 = Functions::flattenArray($array1); $array2 = Functions::flattenArray($array2); self::filterTrendValues($array1, $array2); self::filterTrendValues($array2, $array1); // Reset the array indexes $array1 = array_merge($array1); $array2 = array_merge($array2); } protected static function validateTrendArrays(array $yValues, array $xValues): void { $yValueCount = count($yValues); $xValueCount = count($xValues); if (($yValueCount === 0) || ($yValueCount !== $xValueCount)) { throw new Exception(ExcelError::NA()); } elseif ($yValueCount === 1) { throw new Exception(ExcelError::DIV0()); } } /** * CORREL. * * Returns covariance, the average of the products of deviations for each data point pair. * * @param mixed $yValues array of mixed Data Series Y * @param null|mixed $xValues array of mixed Data Series X * * @return float|string */ public static function CORREL($yValues, $xValues = null) { if (($xValues === null) || (!is_array($yValues)) || (!is_array($xValues))) { return ExcelError::VALUE(); } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getCorrelation(); } /** * COVAR. * * Returns covariance, the average of the products of deviations for each data point pair. * * @param mixed $yValues array of mixed Data Series Y * @param mixed $xValues array of mixed Data Series X * * @return float|string */ public static function COVAR($yValues, $xValues) { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getCovariance(); } /** * FORECAST. * * Calculates, or predicts, a future value by using existing values. * The predicted value is a y-value for a given x-value. * * @param mixed $xValue Float value of X for which we want to find Y * Or can be an array of values * @param mixed $yValues array of mixed Data Series Y * @param mixed $xValues of mixed Data Series X * * @return array|bool|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function FORECAST($xValue, $yValues, $xValues) { if (is_array($xValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $xValue, $yValues, $xValues); } try { $xValue = StatisticalValidations::validateFloat($xValue); self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getValueOfYForX($xValue); } /** * GROWTH. * * Returns values along a predicted exponential Trend * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * * @return float[] */ public static function GROWTH($yValues, $xValues = [], $newValues = [], $const = true) { $yValues = Functions::flattenArray($yValues); $xValues = Functions::flattenArray($xValues); $newValues = Functions::flattenArray($newValues); $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); if (empty($newValues)) { $newValues = $bestFitExponential->getXValues(); } $returnArray = []; foreach ($newValues as $xValue) { $returnArray[0][] = [$bestFitExponential->getValueOfYForX($xValue)]; } return $returnArray; //* @phpstan-ignore-line } /** * INTERCEPT. * * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string */ public static function INTERCEPT($yValues, $xValues) { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getIntersect(); } /** * LINEST. * * Calculates the statistics for a line by using the "least squares" method to calculate a straight line * that best fits your data, and then returns an array that describes the line. * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * @param mixed $stats A logical (boolean) value specifying whether to return additional regression statistics * * @return array|int|string The result, or a string containing an error */ public static function LINEST($yValues, $xValues = null, $const = true, $stats = false) { $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); if ($xValues === null) { $xValues = $yValues; } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); if ($stats === true) { return [ [ $bestFitLinear->getSlope(), $bestFitLinear->getIntersect(), ], [ $bestFitLinear->getSlopeSE(), ($const === false) ? ExcelError::NA() : $bestFitLinear->getIntersectSE(), ], [ $bestFitLinear->getGoodnessOfFit(), $bestFitLinear->getStdevOfResiduals(), ], [ $bestFitLinear->getF(), $bestFitLinear->getDFResiduals(), ], [ $bestFitLinear->getSSRegression(), $bestFitLinear->getSSResiduals(), ], ]; } return [ $bestFitLinear->getSlope(), $bestFitLinear->getIntersect(), ]; } /** * LOGEST. * * Calculates an exponential curve that best fits the X and Y data series, * and then returns an array that describes the line. * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * @param mixed $stats A logical (boolean) value specifying whether to return additional regression statistics * * @return array|int|string The result, or a string containing an error */ public static function LOGEST($yValues, $xValues = null, $const = true, $stats = false) { $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); if ($xValues === null) { $xValues = $yValues; } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } foreach ($yValues as $value) { if ($value < 0.0) { return ExcelError::NAN(); } } $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); if ($stats === true) { return [ [ $bestFitExponential->getSlope(), $bestFitExponential->getIntersect(), ], [ $bestFitExponential->getSlopeSE(), ($const === false) ? ExcelError::NA() : $bestFitExponential->getIntersectSE(), ], [ $bestFitExponential->getGoodnessOfFit(), $bestFitExponential->getStdevOfResiduals(), ], [ $bestFitExponential->getF(), $bestFitExponential->getDFResiduals(), ], [ $bestFitExponential->getSSRegression(), $bestFitExponential->getSSResiduals(), ], ]; } return [ $bestFitExponential->getSlope(), $bestFitExponential->getIntersect(), ]; } /** * RSQ. * * Returns the square of the Pearson product moment correlation coefficient through data points * in known_y's and known_x's. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string The result, or a string containing an error */ public static function RSQ($yValues, $xValues) { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getGoodnessOfFit(); } /** * SLOPE. * * Returns the slope of the linear regression line through data points in known_y's and known_x's. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string The result, or a string containing an error */ public static function SLOPE($yValues, $xValues) { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getSlope(); } /** * STEYX. * * Returns the standard error of the predicted y-value for each x in the regression. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string */ public static function STEYX($yValues, $xValues) { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getStdevOfResiduals(); } /** * TREND. * * Returns values along a linear Trend * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * * @return float[] */ public static function TREND($yValues, $xValues = [], $newValues = [], $const = true) { $yValues = Functions::flattenArray($yValues); $xValues = Functions::flattenArray($xValues); $newValues = Functions::flattenArray($newValues); $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); if (empty($newValues)) { $newValues = $bestFitLinear->getXValues(); } $returnArray = []; foreach ($newValues as $xValue) { $returnArray[0][] = [$bestFitLinear->getValueOfYForX($xValue)]; } return $returnArray; //* @phpstan-ignore-line } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Averages.php 0000644 00000016732 15002227416 0022271 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Averages extends AggregateBase { /** * AVEDEV. * * Returns the average of the absolute deviations of data points from their mean. * AVEDEV is a measure of the variability in a data set. * * Excel Function: * AVEDEV(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function averageDeviations(...$args) { $aArgs = Functions::flattenArrayIndexed($args); // Return value $returnValue = 0.0; $aMean = self::average(...$args); if ($aMean === ExcelError::DIV0()) { return ExcelError::NAN(); } elseif ($aMean === ExcelError::VALUE()) { return ExcelError::VALUE(); } $aCount = 0; foreach ($aArgs as $k => $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { return ExcelError::VALUE(); } if (self::isAcceptedCountable($arg, $k)) { $returnValue += abs($arg - $aMean); ++$aCount; } } // Return if ($aCount === 0) { return ExcelError::DIV0(); } return $returnValue / $aCount; } /** * AVERAGE. * * Returns the average (arithmetic mean) of the arguments * * Excel Function: * AVERAGE(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function average(...$args) { $returnValue = $aCount = 0; // Loop through arguments foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { return ExcelError::VALUE(); } if (self::isAcceptedCountable($arg, $k)) { $returnValue += $arg; ++$aCount; } } // Return if ($aCount > 0) { return $returnValue / $aCount; } return ExcelError::DIV0(); } /** * AVERAGEA. * * Returns the average of its arguments, including numbers, text, and logical values * * Excel Function: * AVERAGEA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function averageA(...$args) { $returnValue = null; $aCount = 0; // Loop through arguments foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { if (is_numeric($arg)) { // do nothing } elseif (is_bool($arg)) { $arg = (int) $arg; } elseif (!Functions::isMatrixValue($k)) { $arg = 0; } else { return ExcelError::VALUE(); } $returnValue += $arg; ++$aCount; } if ($aCount > 0) { return $returnValue / $aCount; } return ExcelError::DIV0(); } /** * MEDIAN. * * Returns the median of the given numbers. The median is the number in the middle of a set of numbers. * * Excel Function: * MEDIAN(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function median(...$args) { $aArgs = Functions::flattenArray($args); $returnValue = ExcelError::NAN(); $aArgs = self::filterArguments($aArgs); $valueCount = count($aArgs); if ($valueCount > 0) { sort($aArgs, SORT_NUMERIC); $valueCount = $valueCount / 2; if ($valueCount == floor($valueCount)) { $returnValue = ($aArgs[$valueCount--] + $aArgs[$valueCount]) / 2; } else { $valueCount = floor($valueCount); $returnValue = $aArgs[$valueCount]; } } return $returnValue; } /** * MODE. * * Returns the most frequently occurring, or repetitive, value in an array or range of data * * Excel Function: * MODE(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function mode(...$args) { $returnValue = ExcelError::NA(); // Loop through arguments $aArgs = Functions::flattenArray($args); $aArgs = self::filterArguments($aArgs); if (!empty($aArgs)) { return self::modeCalc($aArgs); } return $returnValue; } protected static function filterArguments(array $args): array { return array_filter( $args, function ($value) { // Is it a numeric value? return is_numeric($value) && (!is_string($value)); } ); } /** * Special variant of array_count_values that isn't limited to strings and integers, * but can work with floating point numbers as values. * * @return float|string */ private static function modeCalc(array $data) { $frequencyArray = []; $index = 0; $maxfreq = 0; $maxfreqkey = ''; $maxfreqdatum = ''; foreach ($data as $datum) { $found = false; ++$index; foreach ($frequencyArray as $key => $value) { if ((string) $value['value'] == (string) $datum) { ++$frequencyArray[$key]['frequency']; $freq = $frequencyArray[$key]['frequency']; if ($freq > $maxfreq) { $maxfreq = $freq; $maxfreqkey = $key; $maxfreqdatum = $datum; } elseif ($freq == $maxfreq) { if ($frequencyArray[$key]['index'] < $frequencyArray[$maxfreqkey]['index']) { $maxfreqkey = $key; $maxfreqdatum = $datum; } } $found = true; break; } } if ($found === false) { $frequencyArray[] = [ 'value' => $datum, 'frequency' => 1, 'index' => $index, ]; } } if ($maxfreq <= 1) { return ExcelError::NA(); } return $maxfreqdatum; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Size.php 0000644 00000004704 15002227416 0021442 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Size { /** * LARGE. * * Returns the nth largest value in a data set. You can use this function to * select a value based on its relative standing. * * Excel Function: * LARGE(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function large(...$args) { $aArgs = Functions::flattenArray($args); $entry = array_pop($aArgs); if ((is_numeric($entry)) && (!is_string($entry))) { $entry = (int) floor($entry); $mArgs = self::filter($aArgs); $count = Counts::COUNT($mArgs); --$entry; if ($count === 0 || $entry < 0 || $entry >= $count) { return ExcelError::NAN(); } rsort($mArgs); return $mArgs[$entry]; } return ExcelError::VALUE(); } /** * SMALL. * * Returns the nth smallest value in a data set. You can use this function to * select a value based on its relative standing. * * Excel Function: * SMALL(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function small(...$args) { $aArgs = Functions::flattenArray($args); $entry = array_pop($aArgs); if ((is_numeric($entry)) && (!is_string($entry))) { $entry = (int) floor($entry); $mArgs = self::filter($aArgs); $count = Counts::COUNT($mArgs); --$entry; if ($count === 0 || $entry < 0 || $entry >= $count) { return ExcelError::NAN(); } sort($mArgs); return $mArgs[$entry]; } return ExcelError::VALUE(); } /** * @param mixed[] $args Data values */ protected static function filter(array $args): array { $mArgs = []; foreach ($args as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $mArgs[] = $arg; } } return $mArgs; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Standardize.php 0000644 00000003160 15002227416 0022773 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Standardize extends StatisticalValidations { use ArrayEnabled; /** * STANDARDIZE. * * Returns a normalized value from a distribution characterized by mean and standard_dev. * * @param array|float $value Value to normalize * Or can be an array of values * @param array|float $mean Mean Value * Or can be an array of values * @param array|float $stdDev Standard Deviation * Or can be an array of values * * @return array|float|string Standardized value, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function execute($value, $mean, $stdDev) { if (is_array($value) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev); } try { $value = self::validateFloat($value); $mean = self::validateFloat($mean); $stdDev = self::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev <= 0) { return ExcelError::NAN(); } return ($value - $mean) / $stdDev; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php 0000644 00000023652 15002227416 0022776 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Database\DAverage; use PhpOffice\PhpSpreadsheet\Calculation\Database\DCount; use PhpOffice\PhpSpreadsheet\Calculation\Database\DMax; use PhpOffice\PhpSpreadsheet\Calculation\Database\DMin; use PhpOffice\PhpSpreadsheet\Calculation\Database\DSum; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcException; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class Conditional { private const CONDITION_COLUMN_NAME = 'CONDITION'; private const VALUE_COLUMN_NAME = 'VALUE'; private const CONDITIONAL_COLUMN_NAME = 'CONDITIONAL %d'; /** * AVERAGEIF. * * Returns the average value from a range of cells that contain numbers within the list of arguments * * Excel Function: * AVERAGEIF(range,condition[, average_range]) * * @param mixed $range Data values * @param string $condition the criteria that defines which cells will be checked * @param mixed $averageRange Data values * * @return null|float|string */ public static function AVERAGEIF($range, $condition, $averageRange = []) { if (!is_array($range) || !is_array($averageRange) || array_key_exists(0, $range) || array_key_exists(0, $averageRange)) { throw new CalcException('Must specify range of cells, not any kind of literal'); } $database = self::databaseFromRangeAndValue($range, $averageRange); $condition = [[self::CONDITION_COLUMN_NAME, self::VALUE_COLUMN_NAME], [$condition, null]]; return DAverage::evaluate($database, self::VALUE_COLUMN_NAME, $condition); } /** * AVERAGEIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * AVERAGEIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria * * @return null|float|string */ public static function AVERAGEIFS(...$args) { if (empty($args)) { return 0.0; } elseif (count($args) === 3) { return self::AVERAGEIF($args[1], $args[2], $args[0]); } foreach ($args as $arg) { if (is_array($arg) && array_key_exists(0, $arg)) { throw new CalcException('Must specify range of cells, not any kind of literal'); } } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DAverage::evaluate($database, self::VALUE_COLUMN_NAME, $conditions); } /** * COUNTIF. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNTIF(range,condition) * * @param mixed[] $range Data values * @param string $condition the criteria that defines which cells will be counted * * @return int|string */ public static function COUNTIF($range, $condition) { // Filter out any empty values that shouldn't be included in a COUNT $range = array_filter( Functions::flattenArray($range), function ($value) { return $value !== null && $value !== ''; } ); $range = array_merge([[self::CONDITION_COLUMN_NAME]], array_chunk($range, 1)); $condition = array_merge([[self::CONDITION_COLUMN_NAME]], [[$condition]]); return DCount::evaluate($range, null, $condition, false); } /** * COUNTIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria * * @return int|string */ public static function COUNTIFS(...$args) { if (empty($args)) { return 0; } elseif (count($args) === 2) { return self::COUNTIF(...$args); } $database = self::buildDatabase(...$args); $conditions = self::buildConditionSet(...$args); return DCount::evaluate($database, null, $conditions, false); } /** * MAXIFS. * * Returns the maximum value within a range of cells that contain numbers within the list of arguments * * Excel Function: * MAXIFS(max_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria * * @return null|float|string */ public static function MAXIFS(...$args) { if (empty($args)) { return 0.0; } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DMax::evaluate($database, self::VALUE_COLUMN_NAME, $conditions, false); } /** * MINIFS. * * Returns the minimum value within a range of cells that contain numbers within the list of arguments * * Excel Function: * MINIFS(min_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria * * @return null|float|string */ public static function MINIFS(...$args) { if (empty($args)) { return 0.0; } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DMin::evaluate($database, self::VALUE_COLUMN_NAME, $conditions, false); } /** * SUMIF. * * Totals the values of cells that contain numbers within the list of arguments * * Excel Function: * SUMIF(range, criteria, [sum_range]) * * @param mixed $range Data values * @param mixed $sumRange * @param mixed $condition * * @return null|float|string */ public static function SUMIF($range, $condition, $sumRange = []) { $database = self::databaseFromRangeAndValue($range, $sumRange); $condition = [[self::CONDITION_COLUMN_NAME, self::VALUE_COLUMN_NAME], [$condition, null]]; return DSum::evaluate($database, self::VALUE_COLUMN_NAME, $condition); } /** * SUMIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * SUMIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria * * @return null|float|string */ public static function SUMIFS(...$args) { if (empty($args)) { return 0.0; } elseif (count($args) === 3) { return self::SUMIF($args[1], $args[2], $args[0]); } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DSum::evaluate($database, self::VALUE_COLUMN_NAME, $conditions); } /** @param array $args */ private static function buildConditionSet(...$args): array { $conditions = self::buildConditions(1, ...$args); // Scrutinizer thinks first parameter of array_map can't be null. It is wrong. return array_map(/** @scrutinizer ignore-type */ null, ...$conditions); } /** @param array $args */ private static function buildConditionSetForValueRange(...$args): array { $conditions = self::buildConditions(2, ...$args); if (count($conditions) === 1) { return array_map( function ($value) { return [$value]; }, $conditions[0] ); } return array_map(/** @scrutinizer ignore-type */ null, ...$conditions); } /** @param array $args */ private static function buildConditions(int $startOffset, ...$args): array { $conditions = []; $pairCount = 1; $argumentCount = count($args); for ($argument = $startOffset; $argument < $argumentCount; $argument += 2) { $conditions[] = array_merge([sprintf(self::CONDITIONAL_COLUMN_NAME, $pairCount)], [$args[$argument]]); ++$pairCount; } return $conditions; } /** @param array $args */ private static function buildDatabase(...$args): array { $database = []; return self::buildDataSet(0, $database, ...$args); } /** @param array $args */ private static function buildDatabaseWithValueRange(...$args): array { $database = []; $database[] = array_merge( [self::VALUE_COLUMN_NAME], Functions::flattenArray($args[0]) ); return self::buildDataSet(1, $database, ...$args); } /** @param array $args */ private static function buildDataSet(int $startOffset, array $database, ...$args): array { $pairCount = 1; $argumentCount = count($args); for ($argument = $startOffset; $argument < $argumentCount; $argument += 2) { $database[] = array_merge( [sprintf(self::CONDITIONAL_COLUMN_NAME, $pairCount)], Functions::flattenArray($args[$argument]) ); ++$pairCount; } return array_map(/** @scrutinizer ignore-type */ null, ...$database); } private static function databaseFromRangeAndValue(array $range, array $valueRange = []): array { $range = Functions::flattenArray($range); $valueRange = Functions::flattenArray($valueRange); if (empty($valueRange)) { $valueRange = $range; } $database = array_map(/** @scrutinizer ignore-type */ null, array_merge([self::CONDITION_COLUMN_NAME], $range), array_merge([self::VALUE_COLUMN_NAME], $valueRange)); return $database; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php 0000644 00000010563 15002227416 0022635 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Deviations { /** * DEVSQ. * * Returns the sum of squares of deviations of data points from their sample mean. * * Excel Function: * DEVSQ(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function sumSquares(...$args) { $aArgs = Functions::flattenArrayIndexed($args); $aMean = Averages::average($aArgs); if (!is_numeric($aMean)) { return ExcelError::NAN(); } // Return value $returnValue = 0.0; $aCount = -1; foreach ($aArgs as $k => $arg) { // Is it a numeric value? if ( (is_bool($arg)) && ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) ) { $arg = (int) $arg; } if ((is_numeric($arg)) && (!is_string($arg))) { $returnValue += ($arg - $aMean) ** 2; ++$aCount; } } return $aCount === 0 ? ExcelError::VALUE() : $returnValue; } /** * KURT. * * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness * or flatness of a distribution compared with the normal distribution. Positive * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a * relatively flat distribution. * * @param array ...$args Data Series * * @return float|string */ public static function kurtosis(...$args) { $aArgs = Functions::flattenArrayIndexed($args); $mean = Averages::average($aArgs); if (!is_numeric($mean)) { return ExcelError::DIV0(); } $stdDev = StandardDeviations::STDEV($aArgs); if ($stdDev > 0) { $count = $summer = 0; foreach ($aArgs as $k => $arg) { if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summer += (($arg - $mean) / $stdDev) ** 4; ++$count; } } } if ($count > 3) { return $summer * ($count * ($count + 1) / (($count - 1) * ($count - 2) * ($count - 3))) - (3 * ($count - 1) ** 2 / (($count - 2) * ($count - 3))); } } return ExcelError::DIV0(); } /** * SKEW. * * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry * of a distribution around its mean. Positive skewness indicates a distribution with an * asymmetric tail extending toward more positive values. Negative skewness indicates a * distribution with an asymmetric tail extending toward more negative values. * * @param array ...$args Data Series * * @return float|int|string The result, or a string containing an error */ public static function skew(...$args) { $aArgs = Functions::flattenArrayIndexed($args); $mean = Averages::average($aArgs); if (!is_numeric($mean)) { return ExcelError::DIV0(); } $stdDev = StandardDeviations::STDEV($aArgs); if ($stdDev === 0.0 || is_string($stdDev)) { return ExcelError::DIV0(); } $count = $summer = 0; // Loop through arguments foreach ($aArgs as $k => $arg) { if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { } elseif (!is_numeric($arg)) { return ExcelError::VALUE(); } else { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summer += (($arg - $mean) / $stdDev) ** 3; ++$count; } } } if ($count > 2) { return $summer * ($count / (($count - 1) * ($count - 2))); } return ExcelError::DIV0(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php 0000644 00000004636 15002227416 0024616 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Fisher { use ArrayEnabled; /** * FISHER. * * Returns the Fisher transformation at x. This transformation produces a function that * is normally distributed rather than skewed. Use this function to perform hypothesis * testing on the correlation coefficient. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if (($value <= -1) || ($value >= 1)) { return ExcelError::NAN(); } return 0.5 * log((1 + $value) / (1 - $value)); } /** * FISHERINV. * * Returns the inverse of the Fisher transformation. Use this transformation when * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then * FISHERINV(y) = x. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse($probability) { if (is_array($probability)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $probability); } try { DistributionValidations::validateFloat($probability); } catch (Exception $e) { return $e->getMessage(); } return (exp(2 * $probability) - 1) / (exp(2 * $probability) + 1); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php 0000644 00000012265 15002227416 0024415 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Gamma extends GammaBase { use ArrayEnabled; /** * GAMMA. * * Return the gamma function value. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function gamma($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if ((((int) $value) == ((float) $value)) && $value <= 0.0) { return ExcelError::NAN(); } return self::gammaValue($value); } /** * GAMMADIST. * * Returns the gamma distribution. * * @param mixed $value Float Value at which you want to evaluate the distribution * Or can be an array of values * @param mixed $a Parameter to the distribution as a float * Or can be an array of values * @param mixed $b Parameter to the distribution as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value, $a, $b, $cumulative) { if (is_array($value) || is_array($a) || is_array($b) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $a, $b, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $a = DistributionValidations::validateFloat($a); $b = DistributionValidations::validateFloat($b); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($a <= 0) || ($b <= 0)) { return ExcelError::NAN(); } return self::calculateDistribution($value, $a, $b, $cumulative); } /** * GAMMAINV. * * Returns the inverse of the Gamma distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $alpha Parameter to the distribution as a float * Or can be an array of values * @param mixed $beta Parameter to the distribution as a float * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse($probability, $alpha, $beta) { if (is_array($probability) || is_array($alpha) || is_array($beta)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $alpha, $beta); } try { $probability = DistributionValidations::validateProbability($probability); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); } catch (Exception $e) { return $e->getMessage(); } if (($alpha <= 0.0) || ($beta <= 0.0)) { return ExcelError::NAN(); } return self::calculateInverse($probability, $alpha, $beta); } /** * GAMMALN. * * Returns the natural logarithm of the gamma function. * * @param mixed $value Float Value at which you want to evaluate the distribution * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ln($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if ($value <= 0) { return ExcelError::NAN(); } return log(self::gammaValue($value)); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php 0000644 00000003262 15002227416 0026175 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class NewtonRaphson { private const MAX_ITERATIONS = 256; /** @var callable */ protected $callback; public function __construct(callable $callback) { $this->callback = $callback; } /** @return float|string */ public function execute(float $probability) { $xLo = 100; $xHi = 0; $dx = 1; $x = $xNew = 1; $i = 0; while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { // Apply Newton-Raphson step $result = call_user_func($this->callback, $x); $error = $result - $probability; if ($error == 0.0) { $dx = 0; } elseif ($error < 0.0) { $xLo = $x; } else { $xHi = $x; } // Avoid division by zero if ($result != 0.0) { $dx = $error / $result; $xNew = $x - $dx; } // If the NR fails to converge (which for example may be the // case if the initial guess is too rough) we apply a bisection // step to determine a more narrow interval around the root. if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { $xNew = ($xLo + $xHi) / 2; $dx = $xNew - $x; } $x = $xNew; } if ($i == self::MAX_ITERATIONS) { return ExcelError::NA(); } return $x; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php 0000644 00000001246 15002227416 0030245 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StatisticalValidations; class DistributionValidations extends StatisticalValidations { /** * @param mixed $probability */ public static function validateProbability($probability): float { $probability = self::validateFloat($probability); if ($probability < 0.0 || $probability > 1.0) { throw new Exception(ExcelError::NAN()); } return $probability; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php 0000644 00000005056 15002227416 0023560 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class F { use ArrayEnabled; /** * F.DIST. * * Returns the F probability distribution. * You can use this function to determine whether two data sets have different degrees of diversity. * For example, you can examine the test scores of men and women entering high school, and determine * if the variability in the females is different from that found in the males. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $u The numerator degrees of freedom as an integer * Or can be an array of values * @param mixed $v The denominator degrees of freedom as an integer * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value, $u, $v, $cumulative) { if (is_array($value) || is_array($u) || is_array($v) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $u, $v, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $u = DistributionValidations::validateInt($u); $v = DistributionValidations::validateInt($v); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if ($value < 0 || $u < 1 || $v < 1) { return ExcelError::NAN(); } if ($cumulative) { $adjustedValue = ($u * $value) / ($u * $value + $v); return Beta::incompleteBeta($adjustedValue, $u / 2, $v / 2); } return (Gamma::gammaValue(($v + $u) / 2) / (Gamma::gammaValue($u / 2) * Gamma::gammaValue($v / 2))) * (($u / $v) ** ($u / 2)) * (($value ** (($u - 2) / 2)) / ((1 + ($u / $v) * $value) ** (($u + $v) / 2))); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php 0000644 00000025363 15002227416 0025426 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ChiSquared { use ArrayEnabled; private const EPS = 2.22e-16; /** * CHIDIST. * * Returns the one-tailed probability of the chi-squared distribution. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distributionRightTail($value, $degrees) { if (is_array($value) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $degrees); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } if ($value < 0) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return 1; } return ExcelError::NAN(); } return 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) / Gamma::gammaValue($degrees / 2)); } /** * CHIDIST. * * Returns the one-tailed probability of the chi-squared distribution. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distributionLeftTail($value, $degrees, $cumulative) { if (is_array($value) || is_array($degrees) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $degrees, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } if ($value < 0) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return 1; } return ExcelError::NAN(); } if ($cumulative === true) { return 1 - self::distributionRightTail($value, $degrees); } return ($value ** (($degrees / 2) - 1) * exp(-$value / 2)) / ((2 ** ($degrees / 2)) * Gamma::gammaValue($degrees / 2)); } /** * CHIINV. * * Returns the inverse of the right-tailed probability of the chi-squared distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverseRightTail($probability, $degrees) { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } $callback = function ($value) use ($degrees) { return 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) / Gamma::gammaValue($degrees / 2)); }; $newtonRaphson = new NewtonRaphson($callback); return $newtonRaphson->execute($probability); } /** * CHIINV. * * Returns the inverse of the left-tailed probability of the chi-squared distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverseLeftTail($probability, $degrees) { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } return self::inverseLeftTailCalculation($probability, $degrees); } /** * CHITEST. * * Uses the chi-square test to calculate the probability that the differences between two supplied data sets * (of observed and expected frequencies), are likely to be simply due to sampling error, * or if they are likely to be real. * * @param mixed $actual an array of observed frequencies * @param mixed $expected an array of expected frequencies * * @return float|string */ public static function test($actual, $expected) { $rows = count($actual); $actual = Functions::flattenArray($actual); $expected = Functions::flattenArray($expected); $columns = intdiv(count($actual), $rows); $countActuals = count($actual); $countExpected = count($expected); if ($countActuals !== $countExpected || $countActuals === 1) { return ExcelError::NAN(); } $result = 0.0; for ($i = 0; $i < $countActuals; ++$i) { if ($expected[$i] == 0.0) { return ExcelError::DIV0(); } elseif ($expected[$i] < 0.0) { return ExcelError::NAN(); } $result += (($actual[$i] - $expected[$i]) ** 2) / $expected[$i]; } $degrees = self::degrees($rows, $columns); $result = Functions::scalar(self::distributionRightTail($result, $degrees)); return $result; } protected static function degrees(int $rows, int $columns): int { if ($rows === 1) { return $columns - 1; } elseif ($columns === 1) { return $rows - 1; } return ($columns - 1) * ($rows - 1); } private static function inverseLeftTailCalculation(float $probability, int $degrees): float { // bracket the root $min = 0; $sd = sqrt(2.0 * $degrees); $max = 2 * $sd; $s = -1; while ($s * self::pchisq($max, $degrees) > $probability * $s) { $min = $max; $max += 2 * $sd; } // Find root using bisection $chi2 = 0.5 * ($min + $max); while (($max - $min) > self::EPS * $chi2) { if ($s * self::pchisq($chi2, $degrees) > $probability * $s) { $min = $chi2; } else { $max = $chi2; } $chi2 = 0.5 * ($min + $max); } return $chi2; } private static function pchisq(float $chi2, int $degrees): float { return self::gammp($degrees, 0.5 * $chi2); } private static function gammp(int $n, float $x): float { if ($x < 0.5 * $n + 1) { return self::gser($n, $x); } return 1 - self::gcf($n, $x); } // Return the incomplete gamma function P(n/2,x) evaluated by // series representation. Algorithm from numerical recipe. // Assume that n is a positive integer and x>0, won't check arguments. // Relative error controlled by the eps parameter private static function gser(int $n, float $x): float { /** @var float */ $gln = Gamma::ln($n / 2); $a = 0.5 * $n; $ap = $a; $sum = 1.0 / $a; $del = $sum; for ($i = 1; $i < 101; ++$i) { ++$ap; $del = $del * $x / $ap; $sum += $del; if ($del < $sum * self::EPS) { break; } } return $sum * exp(-$x + $a * log($x) - $gln); } // Return the incomplete gamma function Q(n/2,x) evaluated by // its continued fraction representation. Algorithm from numerical recipe. // Assume that n is a postive integer and x>0, won't check arguments. // Relative error controlled by the eps parameter private static function gcf(int $n, float $x): float { /** @var float */ $gln = Gamma::ln($n / 2); $a = 0.5 * $n; $b = $x + 1 - $a; $fpmin = 1.e-300; $c = 1 / $fpmin; $d = 1 / $b; $h = $d; for ($i = 1; $i < 101; ++$i) { $an = -$i * ($i - $a); $b += 2; $d = $an * $d + $b; if (abs($d) < $fpmin) { $d = $fpmin; } $c = $b + $an / $c; if (abs($c) < $fpmin) { $c = $fpmin; } $d = 1 / $d; $del = $d * $c; $h = $h * $del; if (abs($del - 1) < self::EPS) { break; } } return $h * exp(-$x + $a * log($x) - $gln); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StudentT.php 0000644 00000011321 15002227416 0025135 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class StudentT { use ArrayEnabled; /** * TDIST. * * Returns the probability of Student's T distribution. * * @param mixed $value Float value for the distribution * Or can be an array of values * @param mixed $degrees Integer value for degrees of freedom * Or can be an array of values * @param mixed $tails Integer value for the number of tails (1 or 2) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value, $degrees, $tails) { if (is_array($value) || is_array($degrees) || is_array($tails)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $degrees, $tails); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); $tails = DistributionValidations::validateInt($tails); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) { return ExcelError::NAN(); } return self::calculateDistribution($value, $degrees, $tails); } /** * TINV. * * Returns the one-tailed probability of the chi-squared distribution. * * @param mixed $probability Float probability for the function * Or can be an array of values * @param mixed $degrees Integer value for degrees of freedom * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse($probability, $degrees) { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees <= 0) { return ExcelError::NAN(); } $callback = function ($value) use ($degrees) { return self::distribution($value, $degrees, 2); }; $newtonRaphson = new NewtonRaphson($callback); return $newtonRaphson->execute($probability); } /** * @return float */ private static function calculateDistribution(float $value, int $degrees, int $tails) { // tdist, which finds the probability that corresponds to a given value // of t with k degrees of freedom. This algorithm is translated from a // pascal function on p81 of "Statistical Computing in Pascal" by D // Cooke, A H Craven & G M Clark (1985: Edward Arnold (Pubs.) Ltd: // London). The above Pascal algorithm is itself a translation of the // fortran algoritm "AS 3" by B E Cooper of the Atlas Computer // Laboratory as reported in (among other places) "Applied Statistics // Algorithms", editied by P Griffiths and I D Hill (1985; Ellis // Horwood Ltd.; W. Sussex, England). $tterm = $degrees; $ttheta = atan2($value, sqrt($tterm)); $tc = cos($ttheta); $ts = sin($ttheta); if (($degrees % 2) === 1) { $ti = 3; $tterm = $tc; } else { $ti = 2; $tterm = 1; } $tsum = $tterm; while ($ti < $degrees) { $tterm *= $tc * $tc * ($ti - 1) / $ti; $tsum += $tterm; $ti += 2; } $tsum *= $ts; if (($degrees % 2) == 1) { $tsum = Functions::M_2DIVPI * ($tsum + $ttheta); } $tValue = 0.5 * (1 + $tsum); if ($tails == 1) { return 1 - abs($tValue); } return 1 - abs((1 - $tValue) - $tValue); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php 0000644 00000004543 15002227416 0025025 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; class Poisson { use ArrayEnabled; /** * POISSON. * * Returns the Poisson distribution. A common application of the Poisson distribution * is predicting the number of events over a specific time, such as the number of * cars arriving at a toll plaza in 1 minute. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $mean Mean value as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value, $mean, $cumulative) { if (is_array($value) || is_array($mean) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($mean < 0)) { return ExcelError::NAN(); } if ($cumulative) { $summer = 0; $floor = floor($value); for ($i = 0; $i <= $floor; ++$i) { /** @var float */ $fact = MathTrig\Factorial::fact($i); $summer += $mean ** $i / $fact; } return exp(0 - $mean) * $summer; } /** @var float */ $fact = MathTrig\Factorial::fact($value); return (exp(0 - $mean) * $mean ** $value) / $fact; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php 0000644 00000012662 15002227416 0025266 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class LogNormal { use ArrayEnabled; /** * LOGNORMDIST. * * Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed * with parameters mean and standard_dev. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $mean Mean value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function cumulative($value, $mean, $stdDev) { if (is_array($value) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if (($value <= 0) || ($stdDev <= 0)) { return ExcelError::NAN(); } return StandardNormal::cumulative((log($value) - $mean) / $stdDev); } /** * LOGNORM.DIST. * * Returns the lognormal distribution of x, where ln(x) is normally distributed * with parameters mean and standard_dev. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $mean Mean value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value, $mean, $stdDev, $cumulative = false) { if (is_array($value) || is_array($mean) || is_array($stdDev) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value <= 0) || ($stdDev <= 0)) { return ExcelError::NAN(); } if ($cumulative === true) { return StandardNormal::distribution((log($value) - $mean) / $stdDev, true); } return (1 / (sqrt(2 * M_PI) * $stdDev * $value)) * exp(0 - ((log($value) - $mean) ** 2 / (2 * $stdDev ** 2))); } /** * LOGINV. * * Returns the inverse of the lognormal cumulative distribution * * @param mixed $probability Float probability for which we want the value * Or can be an array of values * @param mixed $mean Mean Value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions * * @TODO Try implementing P J Acklam's refinement algorithm for greater * accuracy if I can get my head round the mathematics * (as described at) http://home.online.no/~pjacklam/notes/invnorm/ */ public static function inverse($probability, $mean, $stdDev) { if (is_array($probability) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $mean, $stdDev); } try { $probability = DistributionValidations::validateProbability($probability); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev <= 0) { return ExcelError::NAN(); } /** @var float */ $inverse = StandardNormal::inverse($probability); return exp($mean + $stdDev * $inverse); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php 0000644 00000022717 15002227416 0024251 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Beta { use ArrayEnabled; private const MAX_ITERATIONS = 256; private const LOG_GAMMA_X_MAX_VALUE = 2.55e305; private const XMININ = 2.23e-308; /** * BETADIST. * * Returns the beta distribution. * * @param mixed $value Float value at which you want to evaluate the distribution * Or can be an array of values * @param mixed $alpha Parameter to the distribution as a float * Or can be an array of values * @param mixed $beta Parameter to the distribution as a float * Or can be an array of values * @param mixed $rMin as an float * Or can be an array of values * @param mixed $rMax as an float * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value, $alpha, $beta, $rMin = 0.0, $rMax = 1.0) { if (is_array($value) || is_array($alpha) || is_array($beta) || is_array($rMin) || is_array($rMax)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $alpha, $beta, $rMin, $rMax); } $rMin = $rMin ?? 0.0; $rMax = $rMax ?? 1.0; try { $value = DistributionValidations::validateFloat($value); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); $rMax = DistributionValidations::validateFloat($rMax); $rMin = DistributionValidations::validateFloat($rMin); } catch (Exception $e) { return $e->getMessage(); } if ($rMin > $rMax) { $tmp = $rMin; $rMin = $rMax; $rMax = $tmp; } if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) { return ExcelError::NAN(); } $value -= $rMin; $value /= ($rMax - $rMin); return self::incompleteBeta($value, $alpha, $beta); } /** * BETAINV. * * Returns the inverse of the Beta distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $alpha Parameter to the distribution as a float * Or can be an array of values * @param mixed $beta Parameter to the distribution as a float * Or can be an array of values * @param mixed $rMin Minimum value as a float * Or can be an array of values * @param mixed $rMax Maximum value as a float * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse($probability, $alpha, $beta, $rMin = 0.0, $rMax = 1.0) { if (is_array($probability) || is_array($alpha) || is_array($beta) || is_array($rMin) || is_array($rMax)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $alpha, $beta, $rMin, $rMax); } $rMin = $rMin ?? 0.0; $rMax = $rMax ?? 1.0; try { $probability = DistributionValidations::validateProbability($probability); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); $rMax = DistributionValidations::validateFloat($rMax); $rMin = DistributionValidations::validateFloat($rMin); } catch (Exception $e) { return $e->getMessage(); } if ($rMin > $rMax) { $tmp = $rMin; $rMin = $rMax; $rMax = $tmp; } if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0.0)) { return ExcelError::NAN(); } return self::calculateInverse($probability, $alpha, $beta, $rMin, $rMax); } /** * @return float|string */ private static function calculateInverse(float $probability, float $alpha, float $beta, float $rMin, float $rMax) { $a = 0; $b = 2; $guess = ($a + $b) / 2; $i = 0; while ((($b - $a) > Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) { $guess = ($a + $b) / 2; $result = self::distribution($guess, $alpha, $beta); if (($result === $probability) || ($result === 0.0)) { $b = $a; } elseif ($result > $probability) { $b = $guess; } else { $a = $guess; } } if ($i === self::MAX_ITERATIONS) { return ExcelError::NA(); } return round($rMin + $guess * ($rMax - $rMin), 12); } /** * Incomplete beta function. * * @author Jaco van Kooten * @author Paul Meagher * * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992). * * @param float $x require 0<=x<=1 * @param float $p require p>0 * @param float $q require q>0 * * @return float 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow */ public static function incompleteBeta(float $x, float $p, float $q): float { if ($x <= 0.0) { return 0.0; } elseif ($x >= 1.0) { return 1.0; } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { return 0.0; } $beta_gam = exp((0 - self::logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x)); if ($x < ($p + 1.0) / ($p + $q + 2.0)) { return $beta_gam * self::betaFraction($x, $p, $q) / $p; } return 1.0 - ($beta_gam * self::betaFraction(1 - $x, $q, $p) / $q); } // Function cache for logBeta function /** @var float */ private static $logBetaCacheP = 0.0; /** @var float */ private static $logBetaCacheQ = 0.0; /** @var float */ private static $logBetaCacheResult = 0.0; /** * The natural logarithm of the beta function. * * @param float $p require p>0 * @param float $q require q>0 * * @return float 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow * * @author Jaco van Kooten */ private static function logBeta(float $p, float $q): float { if ($p != self::$logBetaCacheP || $q != self::$logBetaCacheQ) { self::$logBetaCacheP = $p; self::$logBetaCacheQ = $q; if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { self::$logBetaCacheResult = 0.0; } else { self::$logBetaCacheResult = Gamma::logGamma($p) + Gamma::logGamma($q) - Gamma::logGamma($p + $q); } } return self::$logBetaCacheResult; } /** * Evaluates of continued fraction part of incomplete beta function. * Based on an idea from Numerical Recipes (W.H. Press et al, 1992). * * @author Jaco van Kooten */ private static function betaFraction(float $x, float $p, float $q): float { $c = 1.0; $sum_pq = $p + $q; $p_plus = $p + 1.0; $p_minus = $p - 1.0; $h = 1.0 - $sum_pq * $x / $p_plus; if (abs($h) < self::XMININ) { $h = self::XMININ; } $h = 1.0 / $h; $frac = $h; $m = 1; $delta = 0.0; while ($m <= self::MAX_ITERATIONS && abs($delta - 1.0) > Functions::PRECISION) { $m2 = 2 * $m; // even index for d $d = $m * ($q - $m) * $x / (($p_minus + $m2) * ($p + $m2)); $h = 1.0 + $d * $h; if (abs($h) < self::XMININ) { $h = self::XMININ; } $h = 1.0 / $h; $c = 1.0 + $d / $c; if (abs($c) < self::XMININ) { $c = self::XMININ; } $frac *= $h * $c; // odd index for d $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2)); $h = 1.0 + $d * $h; if (abs($h) < self::XMININ) { $h = self::XMININ; } $h = 1.0 / $h; $c = 1.0 + $d / $c; if (abs($c) < self::XMININ) { $c = self::XMININ; } $delta = $h * $c; $frac *= $delta; ++$m; } return $frac; } /* private static function betaValue(float $a, float $b): float { return (Gamma::gammaValue($a) * Gamma::gammaValue($b)) / Gamma::gammaValue($a + $b); } private static function regularizedIncompleteBeta(float $value, float $a, float $b): float { return self::incompleteBeta($value, $a, $b) / self::betaValue($a, $b); } */ } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php 0000644 00000013754 15002227416 0026310 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations; class StandardNormal { use ArrayEnabled; /** * NORMSDIST. * * Returns the standard normal cumulative distribution function. The distribution has * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * * NOTE: We don't need to check for arrays to array-enable this function, because that is already * handled by the logic in Normal::distribution() * All we need to do is pass the value through as scalar or as array. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function cumulative($value) { return Normal::distribution($value, 0, 1, true); } /** * NORM.S.DIST. * * Returns the standard normal cumulative distribution function. The distribution has * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * * NOTE: We don't need to check for arrays to array-enable this function, because that is already * handled by the logic in Normal::distribution() * All we need to do is pass the value and cumulative through as scalar or as array. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value, $cumulative) { return Normal::distribution($value, 0, 1, $cumulative); } /** * NORMSINV. * * Returns the inverse of the standard normal cumulative distribution * * @param mixed $value float probability for which we want the value * Or can be an array of values * * NOTE: We don't need to check for arrays to array-enable this function, because that is already * handled by the logic in Normal::inverse() * All we need to do is pass the value through as scalar or as array * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse($value) { return Normal::inverse($value, 0, 1); } /** * GAUSS. * * Calculates the probability that a member of a standard normal population will fall between * the mean and z standard deviations from the mean. * * @param mixed $value * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function gauss($value) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (!is_numeric($value)) { return ExcelError::VALUE(); } /** @var float */ $dist = self::distribution($value, true); return $dist - 0.5; } /** * ZTEST. * * Returns the one-tailed P-value of a z-test. * * For a given hypothesized population mean, x, Z.TEST returns the probability that the sample mean would be * greater than the average of observations in the data set (array) — that is, the observed sample mean. * * @param mixed $dataSet The dataset should be an array of float values for the observations * @param mixed $m0 Alpha Parameter * Or can be an array of values * @param mixed $sigma A null or float value for the Beta (Standard Deviation) Parameter; * if null, we use the standard deviation of the dataset * Or can be an array of values * * @return array|float|string (string if result is an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function zTest($dataSet, $m0, $sigma = null) { if (is_array($m0) || is_array($sigma)) { return self::evaluateArrayArgumentsSubsetFrom([self::class, __FUNCTION__], 1, $dataSet, $m0, $sigma); } $dataSet = Functions::flattenArrayIndexed($dataSet); if (!is_numeric($m0) || ($sigma !== null && !is_numeric($sigma))) { return ExcelError::VALUE(); } if ($sigma === null) { /** @var float */ $sigma = StandardDeviations::STDEV($dataSet); } $n = count($dataSet); $sub1 = Averages::average($dataSet); return is_numeric($sub1) ? (1 - self::cumulative(($sub1 - $m0) / ($sigma / sqrt($n)))) : $sub1; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php 0000644 00000004233 15002227416 0024772 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Weibull { use ArrayEnabled; /** * WEIBULL. * * Returns the Weibull distribution. Use this distribution in reliability * analysis, such as calculating a device's mean time to failure. * * @param mixed $value Float value for the distribution * Or can be an array of values * @param mixed $alpha Float alpha Parameter * Or can be an array of values * @param mixed $beta Float beta Parameter * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string (string if result is an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value, $alpha, $beta, $cumulative) { if (is_array($value) || is_array($alpha) || is_array($beta) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $alpha, $beta, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) { return ExcelError::NAN(); } if ($cumulative) { return 1 - exp(0 - ($value / $beta) ** $alpha); } return ($alpha / $beta ** $alpha) * $value ** ($alpha - 1) * exp(0 - ($value / $beta) ** $alpha); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php 0000644 00000015774 15002227416 0024633 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Engineering; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Normal { use ArrayEnabled; public const SQRT2PI = 2.5066282746310005024157652848110452530069867406099; /** * NORMDIST. * * Returns the normal distribution for the specified mean and standard deviation. This * function has a very wide range of applications in statistics, including hypothesis * testing. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $mean Mean value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value, $mean, $stdDev, $cumulative) { if (is_array($value) || is_array($mean) || is_array($stdDev) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev < 0) { return ExcelError::NAN(); } if ($cumulative) { return 0.5 * (1 + Engineering\Erf::erfValue(($value - $mean) / ($stdDev * sqrt(2)))); } return (1 / (self::SQRT2PI * $stdDev)) * exp(0 - (($value - $mean) ** 2 / (2 * ($stdDev * $stdDev)))); } /** * NORMINV. * * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation. * * @param mixed $probability Float probability for which we want the value * Or can be an array of values * @param mixed $mean Mean Value as a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse($probability, $mean, $stdDev) { if (is_array($probability) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $mean, $stdDev); } try { $probability = DistributionValidations::validateProbability($probability); $mean = DistributionValidations::validateFloat($mean); $stdDev = DistributionValidations::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev < 0) { return ExcelError::NAN(); } return (self::inverseNcdf($probability) * $stdDev) + $mean; } /* * inverse_ncdf.php * ------------------- * begin : Friday, January 16, 2004 * copyright : (C) 2004 Michael Nickerson * email : nickersonm@yahoo.com * */ private static function inverseNcdf(float $p): float { // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html // I have not checked the accuracy of this implementation. Be aware that PHP // will truncate the coeficcients to 14 digits. // You have permission to use and distribute this function freely for // whatever purpose you want, but please show common courtesy and give credit // where credit is due. // Input paramater is $p - probability - where 0 < p < 1. // Coefficients in rational approximations static $a = [ 1 => -3.969683028665376e+01, 2 => 2.209460984245205e+02, 3 => -2.759285104469687e+02, 4 => 1.383577518672690e+02, 5 => -3.066479806614716e+01, 6 => 2.506628277459239e+00, ]; static $b = [ 1 => -5.447609879822406e+01, 2 => 1.615858368580409e+02, 3 => -1.556989798598866e+02, 4 => 6.680131188771972e+01, 5 => -1.328068155288572e+01, ]; static $c = [ 1 => -7.784894002430293e-03, 2 => -3.223964580411365e-01, 3 => -2.400758277161838e+00, 4 => -2.549732539343734e+00, 5 => 4.374664141464968e+00, 6 => 2.938163982698783e+00, ]; static $d = [ 1 => 7.784695709041462e-03, 2 => 3.224671290700398e-01, 3 => 2.445134137142996e+00, 4 => 3.754408661907416e+00, ]; // Define lower and upper region break-points. $p_low = 0.02425; //Use lower region approx. below this $p_high = 1 - $p_low; //Use upper region approx. above this if (0 < $p && $p < $p_low) { // Rational approximation for lower region. $q = sqrt(-2 * log($p)); return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); } elseif ($p_high < $p && $p < 1) { // Rational approximation for upper region. $q = sqrt(-2 * log(1 - $p)); return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); } // Rational approximation for central region. $q = $p - 0.5; $r = $q * $q; return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q / ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php 0000644 00000023273 15002227416 0025126 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations; class Binomial { use ArrayEnabled; /** * BINOMDIST. * * Returns the individual term binomial distribution probability. Use BINOMDIST in problems with * a fixed number of tests or trials, when the outcomes of any trial are only success or failure, * when trials are independent, and when the probability of success is constant throughout the * experiment. For example, BINOMDIST can calculate the probability that two of the next three * babies born are male. * * @param mixed $value Integer number of successes in trials * Or can be an array of values * @param mixed $trials Integer umber of trials * Or can be an array of values * @param mixed $probability Probability of success on each trial as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value, $trials, $probability, $cumulative) { if (is_array($value) || is_array($trials) || is_array($probability) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $trials, $probability, $cumulative); } try { $value = DistributionValidations::validateInt($value); $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($value > $trials)) { return ExcelError::NAN(); } if ($cumulative) { return self::calculateCumulativeBinomial($value, $trials, $probability); } /** @var float */ $comb = Combinations::withoutRepetition($trials, $value); return $comb * $probability ** $value * (1 - $probability) ** ($trials - $value); } /** * BINOM.DIST.RANGE. * * Returns returns the Binomial Distribution probability for the number of successes from a specified number * of trials falling into a specified range. * * @param mixed $trials Integer number of trials * Or can be an array of values * @param mixed $probability Probability of success on each trial as a float * Or can be an array of values * @param mixed $successes The integer number of successes in trials * Or can be an array of values * @param mixed $limit Upper limit for successes in trials as null, or an integer * If null, then this will indicate the same as the number of Successes * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function range($trials, $probability, $successes, $limit = null) { if (is_array($trials) || is_array($probability) || is_array($successes) || is_array($limit)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $trials, $probability, $successes, $limit); } $limit = $limit ?? $successes; try { $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $successes = DistributionValidations::validateInt($successes); $limit = DistributionValidations::validateInt($limit); } catch (Exception $e) { return $e->getMessage(); } if (($successes < 0) || ($successes > $trials)) { return ExcelError::NAN(); } if (($limit < 0) || ($limit > $trials) || $limit < $successes) { return ExcelError::NAN(); } $summer = 0; for ($i = $successes; $i <= $limit; ++$i) { /** @var float */ $comb = Combinations::withoutRepetition($trials, $i); $summer += $comb * $probability ** $i * (1 - $probability) ** ($trials - $i); } return $summer; } /** * NEGBINOMDIST. * * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that * there will be number_f failures before the number_s-th success, when the constant * probability of a success is probability_s. This function is similar to the binomial * distribution, except that the number of successes is fixed, and the number of trials is * variable. Like the binomial, trials are assumed to be independent. * * @param mixed $failures Number of Failures as an integer * Or can be an array of values * @param mixed $successes Threshold number of Successes as an integer * Or can be an array of values * @param mixed $probability Probability of success on each trial as a float * Or can be an array of values * * @return array|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions * * TODO Add support for the cumulative flag not present for NEGBINOMDIST, but introduced for NEGBINOM.DIST * The cumulative default should be false to reflect the behaviour of NEGBINOMDIST */ public static function negative($failures, $successes, $probability) { if (is_array($failures) || is_array($successes) || is_array($probability)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $failures, $successes, $probability); } try { $failures = DistributionValidations::validateInt($failures); $successes = DistributionValidations::validateInt($successes); $probability = DistributionValidations::validateProbability($probability); } catch (Exception $e) { return $e->getMessage(); } if (($failures < 0) || ($successes < 1)) { return ExcelError::NAN(); } if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { if (($failures + $successes - 1) <= 0) { return ExcelError::NAN(); } } /** @var float */ $comb = Combinations::withoutRepetition($failures + $successes - 1, $successes - 1); return $comb * ($probability ** $successes) * ((1 - $probability) ** $failures); } /** * BINOM.INV. * * Returns the smallest value for which the cumulative binomial distribution is greater * than or equal to a criterion value * * @param mixed $trials number of Bernoulli trials as an integer * Or can be an array of values * @param mixed $probability probability of a success on each trial as a float * Or can be an array of values * @param mixed $alpha criterion value as a float * Or can be an array of values * * @return array|int|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse($trials, $probability, $alpha) { if (is_array($trials) || is_array($probability) || is_array($alpha)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $trials, $probability, $alpha); } try { $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $alpha = DistributionValidations::validateFloat($alpha); } catch (Exception $e) { return $e->getMessage(); } if ($trials < 0) { return ExcelError::NAN(); } elseif (($alpha < 0.0) || ($alpha > 1.0)) { return ExcelError::NAN(); } $successes = 0; while ($successes <= $trials) { $result = self::calculateCumulativeBinomial($successes, $trials, $probability); if ($result >= $alpha) { break; } ++$successes; } return $successes; } /** * @return float|int */ private static function calculateCumulativeBinomial(int $value, int $trials, float $probability) { $summer = 0; for ($i = 0; $i <= $value; ++$i) { /** @var float */ $comb = Combinations::withoutRepetition($trials, $i); $summer += $comb * $probability ** $i * (1 - $probability) ** ($trials - $i); } return $summer; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php 0000644 00000004035 15002227416 0025655 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Exponential { use ArrayEnabled; /** * EXPONDIST. * * Returns the exponential distribution. Use EXPONDIST to model the time between events, * such as how long an automated bank teller takes to deliver cash. For example, you can * use EXPONDIST to determine the probability that the process takes at most 1 minute. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $lambda The parameter value as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($value, $lambda, $cumulative) { if (is_array($value) || is_array($lambda) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $lambda, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $lambda = DistributionValidations::validateFloat($lambda); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($lambda < 0)) { return ExcelError::NAN(); } if ($cumulative === true) { return 1 - exp(0 - $value * $lambda); } return $lambda * exp(0 - $value * $lambda); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php 0000644 00000026750 15002227416 0025214 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; abstract class GammaBase { private const LOG_GAMMA_X_MAX_VALUE = 2.55e305; private const EPS = 2.22e-16; private const MAX_VALUE = 1.2e308; private const SQRT2PI = 2.5066282746310005024157652848110452530069867406099; private const MAX_ITERATIONS = 256; /** @return float|string */ protected static function calculateDistribution(float $value, float $a, float $b, bool $cumulative) { if ($cumulative) { return self::incompleteGamma($a, $value / $b) / self::gammaValue($a); } return (1 / ($b ** $a * self::gammaValue($a))) * $value ** ($a - 1) * exp(0 - ($value / $b)); } /** @return float|string */ protected static function calculateInverse(float $probability, float $alpha, float $beta) { $xLo = 0; $xHi = $alpha * $beta * 5; $dx = 1024; $x = $xNew = 1; $i = 0; while ((abs($dx) > Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) { // Apply Newton-Raphson step $result = self::calculateDistribution($x, $alpha, $beta, true); if (!is_float($result)) { return ExcelError::NA(); } $error = $result - $probability; if ($error == 0.0) { $dx = 0; } elseif ($error < 0.0) { $xLo = $x; } else { $xHi = $x; } $pdf = self::calculateDistribution($x, $alpha, $beta, false); // Avoid division by zero if (!is_float($pdf)) { return ExcelError::NA(); } if ($pdf !== 0.0) { $dx = $error / $pdf; $xNew = $x - $dx; } // If the NR fails to converge (which for example may be the // case if the initial guess is too rough) we apply a bisection // step to determine a more narrow interval around the root. if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) { $xNew = ($xLo + $xHi) / 2; $dx = $xNew - $x; } $x = $xNew; } if ($i === self::MAX_ITERATIONS) { return ExcelError::NA(); } return $x; } // // Implementation of the incomplete Gamma function // public static function incompleteGamma(float $a, float $x): float { static $max = 32; $summer = 0; for ($n = 0; $n <= $max; ++$n) { $divisor = $a; for ($i = 1; $i <= $n; ++$i) { $divisor *= ($a + $i); } $summer += ($x ** $n / $divisor); } return $x ** $a * exp(0 - $x) * $summer; } // // Implementation of the Gamma function // public static function gammaValue(float $value): float { if ($value == 0.0) { return 0; } static $p0 = 1.000000000190015; static $p = [ 1 => 76.18009172947146, 2 => -86.50532032941677, 3 => 24.01409824083091, 4 => -1.231739572450155, 5 => 1.208650973866179e-3, 6 => -5.395239384953e-6, ]; $y = $x = $value; $tmp = $x + 5.5; $tmp -= ($x + 0.5) * log($tmp); $summer = $p0; for ($j = 1; $j <= 6; ++$j) { $summer += ($p[$j] / ++$y); } return exp(0 - $tmp + log(self::SQRT2PI * $summer / $x)); } private const LG_D1 = -0.5772156649015328605195174; private const LG_D2 = 0.4227843350984671393993777; private const LG_D4 = 1.791759469228055000094023; private const LG_P1 = [ 4.945235359296727046734888, 201.8112620856775083915565, 2290.838373831346393026739, 11319.67205903380828685045, 28557.24635671635335736389, 38484.96228443793359990269, 26377.48787624195437963534, 7225.813979700288197698961, ]; private const LG_P2 = [ 4.974607845568932035012064, 542.4138599891070494101986, 15506.93864978364947665077, 184793.2904445632425417223, 1088204.76946882876749847, 3338152.967987029735917223, 5106661.678927352456275255, 3074109.054850539556250927, ]; private const LG_P4 = [ 14745.02166059939948905062, 2426813.369486704502836312, 121475557.4045093227939592, 2663432449.630976949898078, 29403789566.34553899906876, 170266573776.5398868392998, 492612579337.743088758812, 560625185622.3951465078242, ]; private const LG_Q1 = [ 67.48212550303777196073036, 1113.332393857199323513008, 7738.757056935398733233834, 27639.87074403340708898585, 54993.10206226157329794414, 61611.22180066002127833352, 36351.27591501940507276287, 8785.536302431013170870835, ]; private const LG_Q2 = [ 183.0328399370592604055942, 7765.049321445005871323047, 133190.3827966074194402448, 1136705.821321969608938755, 5267964.117437946917577538, 13467014.54311101692290052, 17827365.30353274213975932, 9533095.591844353613395747, ]; private const LG_Q4 = [ 2690.530175870899333379843, 639388.5654300092398984238, 41355999.30241388052042842, 1120872109.61614794137657, 14886137286.78813811542398, 101680358627.2438228077304, 341747634550.7377132798597, 446315818741.9713286462081, ]; private const LG_C = [ -0.001910444077728, 8.4171387781295e-4, -5.952379913043012e-4, 7.93650793500350248e-4, -0.002777777777777681622553, 0.08333333333333333331554247, 0.0057083835261, ]; // Rough estimate of the fourth root of logGamma_xBig private const LG_FRTBIG = 2.25e76; private const PNT68 = 0.6796875; // Function cache for logGamma /** @var float */ private static $logGammaCacheResult = 0.0; /** @var float */ private static $logGammaCacheX = 0.0; /** * logGamma function. * * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. * * The natural logarithm of the gamma function. <br /> * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz <br /> * Applied Mathematics Division <br /> * Argonne National Laboratory <br /> * Argonne, IL 60439 <br /> * <p> * References: * <ol> * <li>W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.</li> * <li>K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.</li> * <li>Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.</li> * </ol> * </p> * <p> * From the original documentation: * </p> * <p> * This routine calculates the LOG(GAMMA) function for a positive real argument X. * Computation is based on an algorithm outlined in references 1 and 2. * The program uses rational functions that theoretically approximate LOG(GAMMA) * to at least 18 significant decimal digits. The approximation for X > 12 is from * reference 3, while approximations for X < 12.0 are similar to those in reference * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, * the compiler, the intrinsic functions, and proper selection of the * machine-dependent constants. * </p> * <p> * Error returns: <br /> * The program returns the value XINF for X .LE. 0.0 or when overflow would occur. * The computation is believed to be free of underflow and overflow. * </p> * * @version 1.1 * * @author Jaco van Kooten * * @return float MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 */ public static function logGamma(float $x): float { if ($x == self::$logGammaCacheX) { return self::$logGammaCacheResult; } $y = $x; if ($y > 0.0 && $y <= self::LOG_GAMMA_X_MAX_VALUE) { if ($y <= self::EPS) { $res = -log($y); } elseif ($y <= 1.5) { $res = self::logGamma1($y); } elseif ($y <= 4.0) { $res = self::logGamma2($y); } elseif ($y <= 12.0) { $res = self::logGamma3($y); } else { $res = self::logGamma4($y); } } else { // -------------------------- // Return for bad arguments // -------------------------- $res = self::MAX_VALUE; } // ------------------------------ // Final adjustments and return // ------------------------------ self::$logGammaCacheX = $x; self::$logGammaCacheResult = $res; return $res; } private static function logGamma1(float $y): float { // --------------------- // EPS .LT. X .LE. 1.5 // --------------------- if ($y < self::PNT68) { $corr = -log($y); $xm1 = $y; } else { $corr = 0.0; $xm1 = $y - 1.0; } $xden = 1.0; $xnum = 0.0; if ($y <= 0.5 || $y >= self::PNT68) { for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm1 + self::LG_P1[$i]; $xden = $xden * $xm1 + self::LG_Q1[$i]; } return $corr + $xm1 * (self::LG_D1 + $xm1 * ($xnum / $xden)); } $xm2 = $y - 1.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm2 + self::LG_P2[$i]; $xden = $xden * $xm2 + self::LG_Q2[$i]; } return $corr + $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); } private static function logGamma2(float $y): float { // --------------------- // 1.5 .LT. X .LE. 4.0 // --------------------- $xm2 = $y - 2.0; $xden = 1.0; $xnum = 0.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm2 + self::LG_P2[$i]; $xden = $xden * $xm2 + self::LG_Q2[$i]; } return $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); } protected static function logGamma3(float $y): float { // ---------------------- // 4.0 .LT. X .LE. 12.0 // ---------------------- $xm4 = $y - 4.0; $xden = -1.0; $xnum = 0.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm4 + self::LG_P4[$i]; $xden = $xden * $xm4 + self::LG_Q4[$i]; } return self::LG_D4 + $xm4 * ($xnum / $xden); } protected static function logGamma4(float $y): float { // --------------------------------- // Evaluate for argument .GE. 12.0 // --------------------------------- $res = 0.0; if ($y <= self::LG_FRTBIG) { $res = self::LG_C[6]; $ysq = $y * $y; for ($i = 0; $i < 6; ++$i) { $res = $res / $ysq + self::LG_C[$i]; } $res /= $y; $corr = log($y); $res = $res + log(self::SQRT2PI) - 0.5 * $corr; $res += $y * ($corr - 1.0); } return $res; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php 0000644 00000006325 15002227416 0026321 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations; class HyperGeometric { use ArrayEnabled; /** * HYPGEOMDIST. * * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of * sample successes, given the sample size, population successes, and population size. * * @param mixed $sampleSuccesses Integer number of successes in the sample * Or can be an array of values * @param mixed $sampleNumber Integer size of the sample * Or can be an array of values * @param mixed $populationSuccesses Integer number of successes in the population * Or can be an array of values * @param mixed $populationNumber Integer population size * Or can be an array of values * * @return array|float|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber) { if ( is_array($sampleSuccesses) || is_array($sampleNumber) || is_array($populationSuccesses) || is_array($populationNumber) ) { return self::evaluateArrayArguments( [self::class, __FUNCTION__], $sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber ); } try { $sampleSuccesses = DistributionValidations::validateInt($sampleSuccesses); $sampleNumber = DistributionValidations::validateInt($sampleNumber); $populationSuccesses = DistributionValidations::validateInt($populationSuccesses); $populationNumber = DistributionValidations::validateInt($populationNumber); } catch (Exception $e) { return $e->getMessage(); } if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) { return ExcelError::NAN(); } if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) { return ExcelError::NAN(); } if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) { return ExcelError::NAN(); } $successesPopulationAndSample = (float) Combinations::withoutRepetition($populationSuccesses, $sampleSuccesses); $numbersPopulationAndSample = (float) Combinations::withoutRepetition($populationNumber, $sampleNumber); $adjustedPopulationAndSample = (float) Combinations::withoutRepetition( $populationNumber - $populationSuccesses, $sampleNumber - $sampleSuccesses ); return $successesPopulationAndSample * $adjustedPopulationAndSample / $numbersPopulationAndSample; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php 0000644 00000007240 15002227416 0023220 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Shared\IntOrFloat; class Permutations { use ArrayEnabled; /** * PERMUT. * * Returns the number of permutations for a given number of objects that can be * selected from number objects. A permutation is any set or subset of objects or * events where internal order is significant. Permutations are different from * combinations, for which the internal order is not significant. Use this function * for lottery-style probability calculations. * * @param mixed $numObjs Integer number of different objects * Or can be an array of values * @param mixed $numInSet Integer number of objects in each permutation * Or can be an array of values * * @return array|float|int|string Number of permutations, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function PERMUT($numObjs, $numInSet) { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = StatisticalValidations::validateInt($numObjs); $numInSet = StatisticalValidations::validateInt($numInSet); } catch (Exception $e) { return $e->getMessage(); } if ($numObjs < $numInSet) { return ExcelError::NAN(); } $result1 = MathTrig\Factorial::fact($numObjs); if (is_string($result1)) { return $result1; } $result2 = MathTrig\Factorial::fact($numObjs - $numInSet); if (is_string($result2)) { return $result2; } // phpstan thinks result1 and result2 can be arrays; they can't. $result = round($result1 / $result2); // @phpstan-ignore-line return IntOrFloat::evaluate($result); } /** * PERMUTATIONA. * * Returns the number of permutations for a given number of objects (with repetitions) * that can be selected from the total objects. * * @param mixed $numObjs Integer number of different objects * Or can be an array of values * @param mixed $numInSet Integer number of objects in each permutation * Or can be an array of values * * @return array|float|int|string Number of permutations, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function PERMUTATIONA($numObjs, $numInSet) { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = StatisticalValidations::validateInt($numObjs); $numInSet = StatisticalValidations::validateInt($numInSet); } catch (Exception $e) { return $e->getMessage(); } if ($numObjs < 0 || $numInSet < 0) { return ExcelError::NAN(); } $result = $numObjs ** $numInSet; return IntOrFloat::evaluate($result); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php 0000644 00000000631 15002227416 0022507 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; abstract class MaxMinBase { /** * @param mixed $value * * @return mixed */ protected static function datatypeAdjustmentAllowStrings($value) { if (is_bool($value)) { return (int) $value; } elseif (is_string($value)) { return 0; } return $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Variances.php 0000644 00000011755 15002227416 0022447 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Variances extends VarianceBase { /** * VAR. * * Estimates variance based on a sample. * * Excel Function: * VAR(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VAR(...$args) { $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArray($args); $aCount = 0; foreach ($aArgs as $arg) { $arg = self::datatypeAdjustmentBooleans($arg); // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } if ($aCount > 1) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * ($aCount - 1)); } return $returnValue; } /** * VARA. * * Estimates variance based on a sample, including numbers, text, and logical values * * Excel Function: * VARA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARA(...$args) { $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); $aCount = 0; foreach ($aArgs as $k => $arg) { if ((is_string($arg)) && (Functions::isValue($k))) { return ExcelError::VALUE(); } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } } if ($aCount > 1) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * ($aCount - 1)); } return $returnValue; } /** * VARP. * * Calculates variance based on the entire population * * Excel Function: * VARP(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARP(...$args) { // Return value $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArray($args); $aCount = 0; foreach ($aArgs as $arg) { $arg = self::datatypeAdjustmentBooleans($arg); // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } if ($aCount > 0) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * $aCount); } return $returnValue; } /** * VARPA. * * Calculates variance based on the entire population, including numbers, text, and logical values * * Excel Function: * VARPA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARPA(...$args) { $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); $aCount = 0; foreach ($aArgs as $k => $arg) { if ((is_string($arg)) && (Functions::isValue($k))) { return ExcelError::VALUE(); } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } } if ($aCount > 0) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * $aCount); } return $returnValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php 0000644 00000004416 15002227416 0022143 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; class Minimum extends MaxMinBase { /** * MIN. * * MIN returns the value of the element of the values passed that has the smallest value, * with negative numbers considered smaller than positive numbers. * * Excel Function: * MIN(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float */ public static function min(...$args) { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { if (($returnValue === null) || ($arg < $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } return $returnValue; } /** * MINA. * * Returns the smallest value in a list of arguments, including numbers, text, and logical values * * Excel Function: * MINA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float */ public static function minA(...$args) { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); if (($returnValue === null) || ($arg < $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } return $returnValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php 0000644 00000001715 15002227416 0025211 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class StatisticalValidations { /** * @param mixed $value */ public static function validateFloat($value): float { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (float) $value; } /** * @param mixed $value */ public static function validateInt($value): int { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (int) floor((float) $value); } /** * @param mixed $value */ public static function validateBool($value): bool { if (!is_bool($value) && !is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (bool) $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Averages/Mean.php 0000644 00000007107 15002227416 0023145 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum; class Mean { /** * GEOMEAN. * * Returns the geometric mean of an array or range of positive data. For example, you * can use GEOMEAN to calculate average growth rate given compound interest with * variable rates. * * Excel Function: * GEOMEAN(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function geometric(...$args) { $aArgs = Functions::flattenArray($args); $aMean = MathTrig\Operations::product($aArgs); if (is_numeric($aMean) && ($aMean > 0)) { $aCount = Counts::COUNT($aArgs); if (Minimum::min($aArgs) > 0) { return $aMean ** (1 / $aCount); } } return ExcelError::NAN(); } /** * HARMEAN. * * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the * arithmetic mean of reciprocals. * * Excel Function: * HARMEAN(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function harmonic(...$args) { // Loop through arguments $aArgs = Functions::flattenArray($args); if (Minimum::min($aArgs) < 0) { return ExcelError::NAN(); } $returnValue = 0; $aCount = 0; foreach ($aArgs as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { if ($arg <= 0) { return ExcelError::NAN(); } $returnValue += (1 / $arg); ++$aCount; } } // Return if ($aCount > 0) { return 1 / ($returnValue / $aCount); } return ExcelError::NA(); } /** * TRIMMEAN. * * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean * taken by excluding a percentage of data points from the top and bottom tails * of a data set. * * Excel Function: * TRIMEAN(value1[,value2[, ...]], $discard) * * @param mixed $args Data values * * @return float|string */ public static function trim(...$args) { $aArgs = Functions::flattenArray($args); // Calculate $percent = array_pop($aArgs); if ((is_numeric($percent)) && (!is_string($percent))) { if (($percent < 0) || ($percent > 1)) { return ExcelError::NAN(); } $mArgs = []; foreach ($aArgs as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $mArgs[] = $arg; } } $discard = floor(Counts::COUNT($mArgs) * $percent / 2); sort($mArgs); for ($i = 0; $i < $discard; ++$i) { array_pop($mArgs); array_shift($mArgs); } return Averages::average($mArgs); } return ExcelError::VALUE(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php 0000644 00000004277 15002227416 0024323 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; class StandardDeviations { /** * STDEV. * * Estimates standard deviation based on a sample. The standard deviation is a measure of how * widely values are dispersed from the average value (the mean). * * Excel Function: * STDEV(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function STDEV(...$args) { $result = Variances::VAR(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } /** * STDEVA. * * Estimates standard deviation based on a sample, including numbers, text, and logical values * * Excel Function: * STDEVA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function STDEVA(...$args) { $result = Variances::VARA(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } /** * STDEVP. * * Calculates standard deviation based on the entire population * * Excel Function: * STDEVP(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function STDEVP(...$args) { $result = Variances::VARP(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } /** * STDEVPA. * * Calculates standard deviation based on the entire population, including numbers, text, and logical values * * Excel Function: * STDEVPA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function STDEVPA(...$args) { $result = Variances::VARPA(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php 0000644 00000045401 15002227416 0020213 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Shared\Date; class Functions { const PRECISION = 8.88E-016; /** * 2 / PI. */ const M_2DIVPI = 0.63661977236758134307553505349006; const COMPATIBILITY_EXCEL = 'Excel'; const COMPATIBILITY_GNUMERIC = 'Gnumeric'; const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc'; /** Use of RETURNDATE_PHP_NUMERIC is discouraged - not 32-bit Y2038-safe, no timezone. */ const RETURNDATE_PHP_NUMERIC = 'P'; /** Use of RETURNDATE_UNIX_TIMESTAMP is discouraged - not 32-bit Y2038-safe, no timezone. */ const RETURNDATE_UNIX_TIMESTAMP = 'P'; const RETURNDATE_PHP_OBJECT = 'O'; const RETURNDATE_PHP_DATETIME_OBJECT = 'O'; const RETURNDATE_EXCEL = 'E'; /** * Compatibility mode to use for error checking and responses. * * @var string */ protected static $compatibilityMode = self::COMPATIBILITY_EXCEL; /** * Data Type to use when returning date values. * * @var string */ protected static $returnDateType = self::RETURNDATE_EXCEL; /** * Set the Compatibility Mode. * * @param string $compatibilityMode Compatibility Mode * Permitted values are: * Functions::COMPATIBILITY_EXCEL 'Excel' * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' * * @return bool (Success or Failure) */ public static function setCompatibilityMode($compatibilityMode) { if ( ($compatibilityMode == self::COMPATIBILITY_EXCEL) || ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) || ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE) ) { self::$compatibilityMode = $compatibilityMode; return true; } return false; } /** * Return the current Compatibility Mode. * * @return string Compatibility Mode * Possible Return values are: * Functions::COMPATIBILITY_EXCEL 'Excel' * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' */ public static function getCompatibilityMode() { return self::$compatibilityMode; } /** * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP DateTime Object). * * @param string $returnDateType Return Date Format * Permitted values are: * Functions::RETURNDATE_UNIX_TIMESTAMP 'P' * Functions::RETURNDATE_PHP_DATETIME_OBJECT 'O' * Functions::RETURNDATE_EXCEL 'E' * * @return bool Success or failure */ public static function setReturnDateType($returnDateType) { if ( ($returnDateType == self::RETURNDATE_UNIX_TIMESTAMP) || ($returnDateType == self::RETURNDATE_PHP_DATETIME_OBJECT) || ($returnDateType == self::RETURNDATE_EXCEL) ) { self::$returnDateType = $returnDateType; return true; } return false; } /** * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object). * * @return string Return Date Format * Possible Return values are: * Functions::RETURNDATE_UNIX_TIMESTAMP 'P' * Functions::RETURNDATE_PHP_DATETIME_OBJECT 'O' * Functions::RETURNDATE_EXCEL ' 'E' */ public static function getReturnDateType() { return self::$returnDateType; } /** * DUMMY. * * @return string #Not Yet Implemented */ public static function DUMMY() { return '#Not Yet Implemented'; } /** @param mixed $idx */ public static function isMatrixValue($idx): bool { return (substr_count($idx, '.') <= 1) || (preg_match('/\.[A-Z]/', $idx) > 0); } /** @param mixed $idx */ public static function isValue($idx): bool { return substr_count($idx, '.') === 0; } /** @param mixed $idx */ public static function isCellValue($idx): bool { return substr_count($idx, '.') > 1; } /** @param mixed $condition */ public static function ifCondition($condition): string { $condition = self::flattenSingleValue($condition); if ($condition === '') { return '=""'; } if (!is_string($condition) || !in_array($condition[0], ['>', '<', '='], true)) { $condition = self::operandSpecialHandling($condition); if (is_bool($condition)) { return '=' . ($condition ? 'TRUE' : 'FALSE'); } elseif (!is_numeric($condition)) { if ($condition !== '""') { // Not an empty string // Escape any quotes in the string value $condition = (string) preg_replace('/"/ui', '""', $condition); } $condition = Calculation::wrapResult(strtoupper($condition)); } return str_replace('""""', '""', '=' . $condition); } preg_match('/(=|<[>=]?|>=?)(.*)/', $condition, $matches); [, $operator, $operand] = $matches; $operand = self::operandSpecialHandling($operand); if (is_numeric(trim($operand, '"'))) { $operand = trim($operand, '"'); } elseif (!is_numeric($operand) && $operand !== 'FALSE' && $operand !== 'TRUE') { $operand = str_replace('"', '""', $operand); $operand = Calculation::wrapResult(strtoupper($operand)); } return str_replace('""""', '""', $operator . $operand); } /** * @param mixed $operand * * @return mixed */ private static function operandSpecialHandling($operand) { if (is_numeric($operand) || is_bool($operand)) { return $operand; } elseif (strtoupper($operand) === Calculation::getTRUE() || strtoupper($operand) === Calculation::getFALSE()) { return strtoupper($operand); } // Check for percentage if (preg_match('/^\-?\d*\.?\d*\s?\%$/', $operand)) { return ((float) rtrim($operand, '%')) / 100; } // Check for dates if (($dateValueOperand = Date::stringToExcel($operand)) !== false) { return $dateValueOperand; } return $operand; } /** * NULL. * * Returns the error value #NULL! * * @deprecated 1.23.0 Use the null() method in the Information\ExcelError class instead * @see Information\ExcelError::null() * * @return string #NULL! */ public static function null() { return Information\ExcelError::null(); } /** * NaN. * * Returns the error value #NUM! * * @deprecated 1.23.0 Use the NAN() method in the Information\Error class instead * @see Information\ExcelError::NAN() * * @return string #NUM! */ public static function NAN() { return Information\ExcelError::NAN(); } /** * REF. * * Returns the error value #REF! * * @deprecated 1.23.0 Use the REF() method in the Information\ExcelError class instead * @see Information\ExcelError::REF() * * @return string #REF! */ public static function REF() { return Information\ExcelError::REF(); } /** * NA. * * Excel Function: * =NA() * * Returns the error value #N/A * #N/A is the error value that means "no value is available." * * @deprecated 1.23.0 Use the NA() method in the Information\ExcelError class instead * @see Information\ExcelError::NA() * * @return string #N/A! */ public static function NA() { return Information\ExcelError::NA(); } /** * VALUE. * * Returns the error value #VALUE! * * @deprecated 1.23.0 Use the VALUE() method in the Information\ExcelError class instead * @see Information\ExcelError::VALUE() * * @return string #VALUE! */ public static function VALUE() { return Information\ExcelError::VALUE(); } /** * NAME. * * Returns the error value #NAME? * * @deprecated 1.23.0 Use the NAME() method in the Information\ExcelError class instead * @see Information\ExcelError::NAME() * * @return string #NAME? */ public static function NAME() { return Information\ExcelError::NAME(); } /** * DIV0. * * @deprecated 1.23.0 Use the DIV0() method in the Information\ExcelError class instead * @see Information\ExcelError::DIV0() * * @return string #Not Yet Implemented */ public static function DIV0() { return Information\ExcelError::DIV0(); } /** * ERROR_TYPE. * * @param mixed $value Value to check * * @deprecated 1.23.0 Use the type() method in the Information\ExcelError class instead * @see Information\ExcelError::type() * * @return array|int|string */ public static function errorType($value = '') { return Information\ExcelError::type($value); } /** * IS_BLANK. * * @param mixed $value Value to check * * @deprecated 1.23.0 Use the isBlank() method in the Information\Value class instead * @see Information\Value::isBlank() * * @return array|bool */ public static function isBlank($value = null) { return Information\Value::isBlank($value); } /** * IS_ERR. * * @param mixed $value Value to check * * @deprecated 1.23.0 Use the isErr() method in the Information\ErrorValue class instead * @see Information\ErrorValue::isErr() * * @return array|bool */ public static function isErr($value = '') { return Information\ErrorValue::isErr($value); } /** * IS_ERROR. * * @param mixed $value Value to check * * @deprecated 1.23.0 Use the isError() method in the Information\ErrorValue class instead * @see Information\ErrorValue::isError() * * @return array|bool */ public static function isError($value = '') { return Information\ErrorValue::isError($value); } /** * IS_NA. * * @param mixed $value Value to check * * @deprecated 1.23.0 Use the isNa() method in the Information\ErrorValue class instead * @see Information\ErrorValue::isNa() * * @return array|bool */ public static function isNa($value = '') { return Information\ErrorValue::isNa($value); } /** * IS_EVEN. * * @param mixed $value Value to check * * @deprecated 1.23.0 Use the isEven() method in the Information\Value class instead * @see Information\Value::isEven() * * @return array|bool|string */ public static function isEven($value = null) { return Information\Value::isEven($value); } /** * IS_ODD. * * @param mixed $value Value to check * * @deprecated 1.23.0 Use the isOdd() method in the Information\Value class instead * @see Information\Value::isOdd() * * @return array|bool|string */ public static function isOdd($value = null) { return Information\Value::isOdd($value); } /** * IS_NUMBER. * * @param mixed $value Value to check * * @deprecated 1.23.0 Use the isNumber() method in the Information\Value class instead * @see Information\Value::isNumber() * * @return array|bool */ public static function isNumber($value = null) { return Information\Value::isNumber($value); } /** * IS_LOGICAL. * * @param mixed $value Value to check * * @deprecated 1.23.0 Use the isLogical() method in the Information\Value class instead * @see Information\Value::isLogical() * * @return array|bool */ public static function isLogical($value = null) { return Information\Value::isLogical($value); } /** * IS_TEXT. * * @param mixed $value Value to check * * @deprecated 1.23.0 Use the isText() method in the Information\Value class instead * @see Information\Value::isText() * * @return array|bool */ public static function isText($value = null) { return Information\Value::isText($value); } /** * IS_NONTEXT. * * @param mixed $value Value to check * * @deprecated 1.23.0 Use the isNonText() method in the Information\Value class instead * @see Information\Value::isNonText() * * @return array|bool */ public static function isNonText($value = null) { return Information\Value::isNonText($value); } /** * N. * * Returns a value converted to a number * * @deprecated 1.23.0 Use the asNumber() method in the Information\Value class instead * @see Information\Value::asNumber() * * @param null|mixed $value The value you want converted * * @return number|string N converts values listed in the following table * If value is or refers to N returns * A number That number * A date The serial number of that date * TRUE 1 * FALSE 0 * An error value The error value * Anything else 0 */ public static function n($value = null) { return Information\Value::asNumber($value); } /** * TYPE. * * Returns a number that identifies the type of a value * * @deprecated 1.23.0 Use the type() method in the Information\Value class instead * @see Information\Value::type() * * @param null|mixed $value The value you want tested * * @return number N converts values listed in the following table * If value is or refers to N returns * A number 1 * Text 2 * Logical Value 4 * An error value 16 * Array or Matrix 64 */ public static function TYPE($value = null) { return Information\Value::type($value); } /** * Convert a multi-dimensional array to a simple 1-dimensional array. * * @param array|mixed $array Array to be flattened * * @return array Flattened array */ public static function flattenArray($array) { if (!is_array($array)) { return (array) $array; } $flattened = []; $stack = array_values($array); while (!empty($stack)) { $value = array_shift($stack); if (is_array($value)) { array_unshift($stack, ...array_values($value)); } else { $flattened[] = $value; } } return $flattened; } /** * @param mixed $value * * @return null|mixed */ public static function scalar($value) { if (!is_array($value)) { return $value; } do { $value = array_pop($value); } while (is_array($value)); return $value; } /** * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing. * * @param array|mixed $array Array to be flattened * * @return array Flattened array */ public static function flattenArrayIndexed($array) { if (!is_array($array)) { return (array) $array; } $arrayValues = []; foreach ($array as $k1 => $value) { if (is_array($value)) { foreach ($value as $k2 => $val) { if (is_array($val)) { foreach ($val as $k3 => $v) { $arrayValues[$k1 . '.' . $k2 . '.' . $k3] = $v; } } else { $arrayValues[$k1 . '.' . $k2] = $val; } } } else { $arrayValues[$k1] = $value; } } return $arrayValues; } /** * Convert an array to a single scalar value by extracting the first element. * * @param mixed $value Array or scalar value * * @return mixed */ public static function flattenSingleValue($value = '') { while (is_array($value)) { $value = array_shift($value); } return $value; } /** * ISFORMULA. * * @deprecated 1.23.0 Use the isFormula() method in the Information\Value class instead * @see Information\Value::isFormula() * * @param mixed $cellReference The cell to check * @param ?Cell $cell The current cell (containing this formula) * * @return array|bool|string */ public static function isFormula($cellReference = '', ?Cell $cell = null) { return Information\Value::isFormula($cellReference, $cell); } public static function expandDefinedName(string $coordinate, Cell $cell): string { $worksheet = $cell->getWorksheet(); $spreadsheet = $worksheet->getParentOrThrow(); // Uppercase coordinate $pCoordinatex = strtoupper($coordinate); // Eliminate leading equal sign $pCoordinatex = (string) preg_replace('/^=/', '', $pCoordinatex); $defined = $spreadsheet->getDefinedName($pCoordinatex, $worksheet); if ($defined !== null) { $worksheet2 = $defined->getWorkSheet(); if (!$defined->isFormula() && $worksheet2 !== null) { $coordinate = "'" . $worksheet2->getTitle() . "'!" . (string) preg_replace('/^=/', '', str_replace('$', '', $defined->getValue())); } } return $coordinate; } public static function trimTrailingRange(string $coordinate): string { return (string) preg_replace('/:[\\w\$]+$/', '', $coordinate); } public static function trimSheetFromCellReference(string $coordinate): string { if (strpos($coordinate, '!') !== false) { $coordinate = substr($coordinate, strrpos($coordinate, '!') + 1); } return $coordinate; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Operations.php 0000644 00000015047 15002227416 0021743 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Logical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Operations { use ArrayEnabled; /** * LOGICAL_AND. * * Returns boolean TRUE if all its arguments are TRUE; returns FALSE if one or more argument is FALSE. * * Excel Function: * =AND(logical1[,logical2[, ...]]) * * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays * or references that contain logical values. * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @param mixed ...$args Data values * * @return bool|string the logical AND of the arguments */ public static function logicalAnd(...$args) { return self::countTrueValues($args, function (int $trueValueCount, int $count): bool { return $trueValueCount === $count; }); } /** * LOGICAL_OR. * * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE. * * Excel Function: * =OR(logical1[,logical2[, ...]]) * * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays * or references that contain logical values. * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @param mixed $args Data values * * @return bool|string the logical OR of the arguments */ public static function logicalOr(...$args) { return self::countTrueValues($args, function (int $trueValueCount): bool { return $trueValueCount > 0; }); } /** * LOGICAL_XOR. * * Returns the Exclusive Or logical operation for one or more supplied conditions. * i.e. the Xor function returns TRUE if an odd number of the supplied conditions evaluate to TRUE, * and FALSE otherwise. * * Excel Function: * =XOR(logical1[,logical2[, ...]]) * * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays * or references that contain logical values. * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @param mixed $args Data values * * @return bool|string the logical XOR of the arguments */ public static function logicalXor(...$args) { return self::countTrueValues($args, function (int $trueValueCount): bool { return $trueValueCount % 2 === 1; }); } /** * NOT. * * Returns the boolean inverse of the argument. * * Excel Function: * =NOT(logical) * * The argument must evaluate to a logical value such as TRUE or FALSE * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE * Or can be an array of values * * @return array|bool|string the boolean inverse of the argument * If an array of values is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function NOT($logical = false) { if (is_array($logical)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $logical); } if (is_string($logical)) { $logical = mb_strtoupper($logical, 'UTF-8'); if (($logical == 'TRUE') || ($logical == Calculation::getTRUE())) { return false; } elseif (($logical == 'FALSE') || ($logical == Calculation::getFALSE())) { return true; } return ExcelError::VALUE(); } return !$logical; } /** * @return bool|string */ private static function countTrueValues(array $args, callable $func) { $trueValueCount = 0; $count = 0; $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { ++$count; // Is it a boolean value? if (is_bool($arg)) { $trueValueCount += $arg; } elseif (is_string($arg)) { $isLiteral = !Functions::isCellValue($k); $arg = mb_strtoupper($arg, 'UTF-8'); if ($isLiteral && ($arg == 'TRUE' || $arg == Calculation::getTRUE())) { ++$trueValueCount; } elseif ($isLiteral && ($arg == 'FALSE' || $arg == Calculation::getFALSE())) { //$trueValueCount += 0; } else { --$count; } } elseif (is_int($arg) || is_float($arg)) { $trueValueCount += (int) ($arg != 0); } else { --$count; } } return ($count === 0) ? ExcelError::VALUE() : $func($trueValueCount, $count); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Conditional.php 0000644 00000021471 15002227416 0022061 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Logical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Information\Value; class Conditional { use ArrayEnabled; /** * STATEMENT_IF. * * Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE. * * Excel Function: * =IF(condition[,returnIfTrue[,returnIfFalse]]) * * Condition is any value or expression that can be evaluated to TRUE or FALSE. * For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100, * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE. * This argument can use any comparison calculation operator. * ReturnIfTrue is the value that is returned if condition evaluates to TRUE. * For example, if this argument is the text string "Within budget" and * the condition argument evaluates to TRUE, then the IF function returns the text "Within budget" * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). * To display the word TRUE, use the logical value TRUE for this argument. * ReturnIfTrue can be another formula. * ReturnIfFalse is the value that is returned if condition evaluates to FALSE. * For example, if this argument is the text string "Over budget" and the condition argument evaluates * to FALSE, then the IF function returns the text "Over budget". * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned. * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned. * ReturnIfFalse can be another formula. * * @param mixed $condition Condition to evaluate * @param mixed $returnIfTrue Value to return when condition is true * Note that this can be an array value * @param mixed $returnIfFalse Optional value to return when condition is false * Note that this can be an array value * * @return mixed The value of returnIfTrue or returnIfFalse determined by condition */ public static function statementIf($condition = true, $returnIfTrue = 0, $returnIfFalse = false) { $condition = ($condition === null) ? true : Functions::flattenSingleValue($condition); if (ErrorValue::isError($condition)) { return $condition; } $returnIfTrue = $returnIfTrue ?? 0; $returnIfFalse = $returnIfFalse ?? false; return ((bool) $condition) ? $returnIfTrue : $returnIfFalse; } /** * STATEMENT_SWITCH. * * Returns corresponding with first match (any data type such as a string, numeric, date, etc). * * Excel Function: * =SWITCH (expression, value1, result1, value2, result2, ... value_n, result_n [, default]) * * Expression * The expression to compare to a list of values. * value1, value2, ... value_n * A list of values that are compared to expression. * The SWITCH function is looking for the first value that matches the expression. * result1, result2, ... result_n * A list of results. The SWITCH function returns the corresponding result when a value * matches expression. * Note that these can be array values to be returned * default * Optional. It is the default to return if expression does not match any of the values * (value1, value2, ... value_n). * Note that this can be an array value to be returned * * @param mixed $arguments Statement arguments * * @return mixed The value of matched expression */ public static function statementSwitch(...$arguments) { $result = ExcelError::VALUE(); if (count($arguments) > 0) { $targetValue = Functions::flattenSingleValue($arguments[0]); $argc = count($arguments) - 1; $switchCount = floor($argc / 2); $hasDefaultClause = $argc % 2 !== 0; $defaultClause = $argc % 2 === 0 ? null : $arguments[$argc]; $switchSatisfied = false; if ($switchCount > 0) { for ($index = 0; $index < $switchCount; ++$index) { if ($targetValue == Functions::flattenSingleValue($arguments[$index * 2 + 1])) { $result = $arguments[$index * 2 + 2]; $switchSatisfied = true; break; } } } if ($switchSatisfied !== true) { $result = $hasDefaultClause ? $defaultClause : ExcelError::NA(); } } return $result; } /** * IFERROR. * * Excel Function: * =IFERROR(testValue,errorpart) * * @param mixed $testValue Value to check, is also the value returned when no error * Or can be an array of values * @param mixed $errorpart Value to return when testValue is an error condition * Note that this can be an array value to be returned * * @return mixed The value of errorpart or testValue determined by error condition * If an array of values is passed as the $testValue argument, then the returned result will also be * an array with the same dimensions */ public static function IFERROR($testValue = '', $errorpart = '') { if (is_array($testValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $testValue, $errorpart); } $errorpart = $errorpart ?? ''; $testValue = $testValue ?? 0; // this is how Excel handles empty cell return self::statementIf(ErrorValue::isError($testValue), $errorpart, $testValue); } /** * IFNA. * * Excel Function: * =IFNA(testValue,napart) * * @param mixed $testValue Value to check, is also the value returned when not an NA * Or can be an array of values * @param mixed $napart Value to return when testValue is an NA condition * Note that this can be an array value to be returned * * @return mixed The value of errorpart or testValue determined by error condition * If an array of values is passed as the $testValue argument, then the returned result will also be * an array with the same dimensions */ public static function IFNA($testValue = '', $napart = '') { if (is_array($testValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $testValue, $napart); } $napart = $napart ?? ''; $testValue = $testValue ?? 0; // this is how Excel handles empty cell return self::statementIf(ErrorValue::isNa($testValue), $napart, $testValue); } /** * IFS. * * Excel Function: * =IFS(testValue1;returnIfTrue1;testValue2;returnIfTrue2;...;testValue_n;returnIfTrue_n) * * testValue1 ... testValue_n * Conditions to Evaluate * returnIfTrue1 ... returnIfTrue_n * Value returned if corresponding testValue (nth) was true * * @param mixed ...$arguments Statement arguments * Note that this can be an array value to be returned * * @return mixed|string The value of returnIfTrue_n, if testValue_n was true. #N/A if none of testValues was true */ public static function IFS(...$arguments) { $argumentCount = count($arguments); if ($argumentCount % 2 != 0) { return ExcelError::NA(); } // We use instance of Exception as a falseValue in order to prevent string collision with value in cell $falseValueException = new Exception(); for ($i = 0; $i < $argumentCount; $i += 2) { $testValue = ($arguments[$i] === null) ? '' : Functions::flattenSingleValue($arguments[$i]); $returnIfTrue = ($arguments[$i + 1] === null) ? '' : $arguments[$i + 1]; $result = self::statementIf($testValue, $returnIfTrue, $falseValueException); if ($result !== $falseValueException) { return $result; } } return ExcelError::NA(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Boolean.php 0000644 00000001035 15002227416 0021167 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Logical; class Boolean { /** * TRUE. * * Returns the boolean TRUE. * * Excel Function: * =TRUE() * * @return bool True */ public static function true(): bool { return true; } /** * FALSE. * * Returns the boolean FALSE. * * Excel Function: * =FALSE() * * @return bool False */ public static function false(): bool { return false; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/ExcelError.php 0000644 00000006756 15002227416 0022614 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Information; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; class ExcelError { use ArrayEnabled; /** * List of error codes. * * @var array<string, string> */ public const ERROR_CODES = [ 'null' => '#NULL!', // 1 'divisionbyzero' => '#DIV/0!', // 2 'value' => '#VALUE!', // 3 'reference' => '#REF!', // 4 'name' => '#NAME?', // 5 'num' => '#NUM!', // 6 'na' => '#N/A', // 7 'gettingdata' => '#GETTING_DATA', // 8 'spill' => '#SPILL!', // 9 'connect' => '#CONNECT!', //10 'blocked' => '#BLOCKED!', //11 'unknown' => '#UNKNOWN!', //12 'field' => '#FIELD!', //13 'calculation' => '#CALC!', //14 ]; /** * List of error codes. Replaced by constant; * previously it was public and updateable, allowing * user to make inappropriate alterations. * * @deprecated 1.25.0 Use ERROR_CODES constant instead. * * @var array<string, string> */ public static $errorCodes = self::ERROR_CODES; /** * @param mixed $value */ public static function throwError($value): string { return in_array($value, self::ERROR_CODES, true) ? $value : self::ERROR_CODES['value']; } /** * ERROR_TYPE. * * @param mixed $value Value to check * * @return array|int|string */ public static function type($value = '') { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } $i = 1; foreach (self::ERROR_CODES as $errorCode) { if ($value === $errorCode) { return $i; } ++$i; } return self::NA(); } /** * NULL. * * Returns the error value #NULL! * * @return string #NULL! */ public static function null(): string { return self::ERROR_CODES['null']; } /** * NaN. * * Returns the error value #NUM! * * @return string #NUM! */ public static function NAN(): string { return self::ERROR_CODES['num']; } /** * REF. * * Returns the error value #REF! * * @return string #REF! */ public static function REF(): string { return self::ERROR_CODES['reference']; } /** * NA. * * Excel Function: * =NA() * * Returns the error value #N/A * #N/A is the error value that means "no value is available." * * @return string #N/A! */ public static function NA(): string { return self::ERROR_CODES['na']; } /** * VALUE. * * Returns the error value #VALUE! * * @return string #VALUE! */ public static function VALUE(): string { return self::ERROR_CODES['value']; } /** * NAME. * * Returns the error value #NAME? * * @return string #NAME? */ public static function NAME(): string { return self::ERROR_CODES['name']; } /** * DIV0. * * @return string #DIV/0! */ public static function DIV0(): string { return self::ERROR_CODES['divisionbyzero']; } /** * CALC. * * @return string #CALC! */ public static function CALC(): string { return self::ERROR_CODES['calculation']; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/Value.php 0000644 00000023606 15002227416 0021607 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Information; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\NamedRange; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Value { use ArrayEnabled; /** * IS_BLANK. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isBlank($value = null) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return $value === null; } /** * IS_REF. * * @param mixed $value Value to check * * @return bool */ public static function isRef($value, ?Cell $cell = null) { if ($cell === null || $value === $cell->getCoordinate()) { return false; } $cellValue = Functions::trimTrailingRange($value); if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/ui', $cellValue) === 1) { [$worksheet, $cellValue] = Worksheet::extractSheetTitle($cellValue, true); if (!empty($worksheet) && $cell->getWorksheet()->getParentOrThrow()->getSheetByName($worksheet) === null) { return false; } [$column, $row] = Coordinate::indexesFromString($cellValue); if ($column > 16384 || $row > 1048576) { return false; } return true; } $namedRange = $cell->getWorksheet()->getParentOrThrow()->getNamedRange($value); return $namedRange instanceof NamedRange; } /** * IS_EVEN. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isEven($value = null) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if ($value === null) { return ExcelError::NAME(); } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) { return ExcelError::VALUE(); } return ((int) fmod($value, 2)) === 0; } /** * IS_ODD. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool|string * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isOdd($value = null) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if ($value === null) { return ExcelError::NAME(); } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) { return ExcelError::VALUE(); } return ((int) fmod($value, 2)) !== 0; } /** * IS_NUMBER. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isNumber($value = null) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (is_string($value)) { return false; } return is_numeric($value); } /** * IS_LOGICAL. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isLogical($value = null) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return is_bool($value); } /** * IS_TEXT. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isText($value = null) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return is_string($value) && !ErrorValue::isError($value); } /** * IS_NONTEXT. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isNonText($value = null) { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return !self::isText($value); } /** * ISFORMULA. * * @param mixed $cellReference The cell to check * @param ?Cell $cell The current cell (containing this formula) * * @return array|bool|string */ public static function isFormula($cellReference = '', ?Cell $cell = null) { if ($cell === null) { return ExcelError::REF(); } $fullCellReference = Functions::expandDefinedName((string) $cellReference, $cell); if (strpos($cellReference, '!') !== false) { $cellReference = Functions::trimSheetFromCellReference($cellReference); $cellReferences = Coordinate::extractAllCellReferencesInRange($cellReference); if (count($cellReferences) > 1) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $cellReferences, $cell); } } $fullCellReference = Functions::trimTrailingRange($fullCellReference); preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $fullCellReference, $matches); $fullCellReference = $matches[6] . $matches[7]; $worksheetName = str_replace("''", "'", trim($matches[2], "'")); $worksheet = (!empty($worksheetName)) ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($worksheetName) : $cell->getWorksheet(); return ($worksheet !== null) ? $worksheet->getCell($fullCellReference)->isFormula() : ExcelError::REF(); } /** * N. * * Returns a value converted to a number * * @param null|mixed $value The value you want converted * * @return number|string N converts values listed in the following table * If value is or refers to N returns * A number That number value * A date The Excel serialized number of that date * TRUE 1 * FALSE 0 * An error value The error value * Anything else 0 */ public static function asNumber($value = null) { while (is_array($value)) { $value = array_shift($value); } switch (gettype($value)) { case 'double': case 'float': case 'integer': return $value; case 'boolean': return (int) $value; case 'string': // Errors if ((strlen($value) > 0) && ($value[0] == '#')) { return $value; } break; } return 0; } /** * TYPE. * * Returns a number that identifies the type of a value * * @param null|mixed $value The value you want tested * * @return number N converts values listed in the following table * If value is or refers to N returns * A number 1 * Text 2 * Logical Value 4 * An error value 16 * Array or Matrix 64 */ public static function type($value = null) { $value = Functions::flattenArrayIndexed($value); if (is_array($value) && (count($value) > 1)) { end($value); $a = key($value); // Range of cells is an error if (Functions::isCellValue($a)) { return 16; // Test for Matrix } elseif (Functions::isMatrixValue($a)) { return 64; } } elseif (empty($value)) { // Empty Cell return 1; } $value = Functions::flattenSingleValue($value); if (($value === null) || (is_float($value)) || (is_int($value))) { return 1; } elseif (is_bool($value)) { return 4; } elseif (is_array($value)) { return 64; } elseif (is_string($value)) { // Errors if ((strlen($value) > 0) && ($value[0] == '#')) { return 16; } return 2; } return 0; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/ErrorValue.php 0000644 00000003654 15002227416 0022622 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Information; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; class ErrorValue { use ArrayEnabled; /** * IS_ERR. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isErr($value = '') { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return self::isError($value) && (!self::isNa(($value))); } /** * IS_ERROR. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isError($value = '') { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (!is_string($value)) { return false; } return in_array($value, ExcelError::ERROR_CODES, true); } /** * IS_NA. * * @param mixed $value Value to check * Or can be an array of values * * @return array|bool * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function isNa($value = '') { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } return $value === ExcelError::NA(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering.php 0000644 00000147460 15002227416 0020505 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; use Complex\Complex; use PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions; use PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations; /** * @deprecated 1.18.0 */ class Engineering { /** * EULER. * * @deprecated 1.18.0 * Use Engineering\Constants::EULER instead * @see Engineering\Constants::EULER */ public const EULER = 2.71828182845904523536; /** * BESSELI. * * Returns the modified Bessel function In(x), which is equivalent to the Bessel function evaluated * for purely imaginary arguments * * Excel Function: * BESSELI(x,ord) * * @deprecated 1.17.0 * Use the BESSELI() method in the Engineering\BesselI class instead * @see Engineering\BesselI::BESSELI() * * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELI returns the #VALUE! error value. * @param int $ord The order of the Bessel function. * If ord is not an integer, it is truncated. * If $ord is nonnumeric, BESSELI returns the #VALUE! error value. * If $ord < 0, BESSELI returns the #NUM! error value. * * @return array|float|string Result, or a string containing an error */ public static function BESSELI($x, $ord) { return Engineering\BesselI::BESSELI($x, $ord); } /** * BESSELJ. * * Returns the Bessel function * * Excel Function: * BESSELJ(x,ord) * * @deprecated 1.17.0 * Use the BESSELJ() method in the Engineering\BesselJ class instead * @see Engineering\BesselJ::BESSELJ() * * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELJ returns the #VALUE! error value. * @param int $ord The order of the Bessel function. If n is not an integer, it is truncated. * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value. * If $ord < 0, BESSELJ returns the #NUM! error value. * * @return array|float|string Result, or a string containing an error */ public static function BESSELJ($x, $ord) { return Engineering\BesselJ::BESSELJ($x, $ord); } /** * BESSELK. * * Returns the modified Bessel function Kn(x), which is equivalent to the Bessel functions evaluated * for purely imaginary arguments. * * Excel Function: * BESSELK(x,ord) * * @deprecated 1.17.0 * Use the BESSELK() method in the Engineering\BesselK class instead * @see Engineering\BesselK::BESSELK() * * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELK returns the #VALUE! error value. * @param int $ord The order of the Bessel function. If n is not an integer, it is truncated. * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. * If $ord < 0, BESSELK returns the #NUM! error value. * * @return array|float|string Result, or a string containing an error */ public static function BESSELK($x, $ord) { return Engineering\BesselK::BESSELK($x, $ord); } /** * BESSELY. * * Returns the Bessel function, which is also called the Weber function or the Neumann function. * * Excel Function: * BESSELY(x,ord) * * @deprecated 1.17.0 * Use the BESSELY() method in the Engineering\BesselY class instead * @see Engineering\BesselY::BESSELY() * * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELY returns the #VALUE! error value. * @param int $ord The order of the Bessel function. If n is not an integer, it is truncated. * If $ord is nonnumeric, BESSELY returns the #VALUE! error value. * If $ord < 0, BESSELY returns the #NUM! error value. * * @return array|float|string Result, or a string containing an error */ public static function BESSELY($x, $ord) { return Engineering\BesselY::BESSELY($x, $ord); } /** * BINTODEC. * * Return a binary value as decimal. * * Excel Function: * BIN2DEC(x) * * @deprecated 1.17.0 * Use the toDecimal() method in the Engineering\ConvertBinary class instead * @see Engineering\ConvertBinary::toDecimal() * * @param mixed $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2DEC returns the #NUM! error value. * * @return array|string */ public static function BINTODEC($x) { return Engineering\ConvertBinary::toDecimal($x); } /** * BINTOHEX. * * Return a binary value as hex. * * Excel Function: * BIN2HEX(x[,places]) * * @deprecated 1.17.0 * Use the toHex() method in the Engineering\ConvertBinary class instead * @see Engineering\ConvertBinary::toHex() * * @param mixed $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2HEX returns the #NUM! error value. * @param mixed $places The number of characters to use. If places is omitted, BIN2HEX uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, BIN2HEX returns the #VALUE! error value. * If places is negative, BIN2HEX returns the #NUM! error value. * * @return array|string */ public static function BINTOHEX($x, $places = null) { return Engineering\ConvertBinary::toHex($x, $places); } /** * BINTOOCT. * * Return a binary value as octal. * * Excel Function: * BIN2OCT(x[,places]) * * @deprecated 1.17.0 * Use the toOctal() method in the Engineering\ConvertBinary class instead * @see Engineering\ConvertBinary::toOctal() * * @param mixed $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2OCT returns the #NUM! error value. * @param mixed $places The number of characters to use. If places is omitted, BIN2OCT uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, BIN2OCT returns the #VALUE! error value. * If places is negative, BIN2OCT returns the #NUM! error value. * * @return array|string */ public static function BINTOOCT($x, $places = null) { return Engineering\ConvertBinary::toOctal($x, $places); } /** * DECTOBIN. * * Return a decimal value as binary. * * Excel Function: * DEC2BIN(x[,places]) * * @deprecated 1.17.0 * Use the toBinary() method in the Engineering\ConvertDecimal class instead * @see Engineering\ConvertDecimal::toBinary() * * @param mixed $x The decimal integer you want to convert. If number is negative, * valid place values are ignored and DEC2BIN returns a 10-character * (10-bit) binary number in which the most significant bit is the sign * bit. The remaining 9 bits are magnitude bits. Negative numbers are * represented using two's-complement notation. * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error * value. * If number is nonnumeric, DEC2BIN returns the #VALUE! error value. * If DEC2BIN requires more than places characters, it returns the #NUM! * error value. * @param mixed $places The number of characters to use. If places is omitted, DEC2BIN uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2BIN returns the #VALUE! error value. * If places is zero or negative, DEC2BIN returns the #NUM! error value. * * @return array|string */ public static function DECTOBIN($x, $places = null) { return Engineering\ConvertDecimal::toBinary($x, $places); } /** * DECTOHEX. * * Return a decimal value as hex. * * Excel Function: * DEC2HEX(x[,places]) * * @deprecated 1.17.0 * Use the toHex() method in the Engineering\ConvertDecimal class instead * @see Engineering\ConvertDecimal::toHex() * * @param mixed $x The decimal integer you want to convert. If number is negative, * places is ignored and DEC2HEX returns a 10-character (40-bit) * hexadecimal number in which the most significant bit is the sign * bit. The remaining 39 bits are magnitude bits. Negative numbers * are represented using two's-complement notation. * If number < -549,755,813,888 or if number > 549,755,813,887, * DEC2HEX returns the #NUM! error value. * If number is nonnumeric, DEC2HEX returns the #VALUE! error value. * If DEC2HEX requires more than places characters, it returns the * #NUM! error value. * @param mixed $places The number of characters to use. If places is omitted, DEC2HEX uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2HEX returns the #VALUE! error value. * If places is zero or negative, DEC2HEX returns the #NUM! error value. * * @return array|string */ public static function DECTOHEX($x, $places = null) { return Engineering\ConvertDecimal::toHex($x, $places); } /** * DECTOOCT. * * Return an decimal value as octal. * * Excel Function: * DEC2OCT(x[,places]) * * @deprecated 1.17.0 * Use the toOctal() method in the Engineering\ConvertDecimal class instead * @see Engineering\ConvertDecimal::toOctal() * * @param mixed $x The decimal integer you want to convert. If number is negative, * places is ignored and DEC2OCT returns a 10-character (30-bit) * octal number in which the most significant bit is the sign bit. * The remaining 29 bits are magnitude bits. Negative numbers are * represented using two's-complement notation. * If number < -536,870,912 or if number > 536,870,911, DEC2OCT * returns the #NUM! error value. * If number is nonnumeric, DEC2OCT returns the #VALUE! error value. * If DEC2OCT requires more than places characters, it returns the * #NUM! error value. * @param mixed $places The number of characters to use. If places is omitted, DEC2OCT uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2OCT returns the #VALUE! error value. * If places is zero or negative, DEC2OCT returns the #NUM! error value. * * @return array|string */ public static function DECTOOCT($x, $places = null) { return Engineering\ConvertDecimal::toOctal($x, $places); } /** * HEXTOBIN. * * Return a hex value as binary. * * Excel Function: * HEX2BIN(x[,places]) * * @deprecated 1.17.0 * Use the toBinary() method in the Engineering\ConvertHex class instead * @see Engineering\ConvertHex::toBinary() * * @param mixed $x the hexadecimal number (as a string) that you want to convert. * Number cannot contain more than 10 characters. * The most significant bit of number is the sign bit (40th bit from the right). * The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is negative, HEX2BIN ignores places and returns a 10-character binary number. * If number is negative, it cannot be less than FFFFFFFE00, * and if number is positive, it cannot be greater than 1FF. * If number is not a valid hexadecimal number, HEX2BIN returns the #NUM! error value. * If HEX2BIN requires more than places characters, it returns the #NUM! error value. * @param mixed $places The number of characters to use. If places is omitted, * HEX2BIN uses the minimum number of characters necessary. Places * is useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, HEX2BIN returns the #VALUE! error value. * If places is negative, HEX2BIN returns the #NUM! error value. * * @return array|string */ public static function HEXTOBIN($x, $places = null) { return Engineering\ConvertHex::toBinary($x, $places); } /** * HEXTODEC. * * Return a hex value as decimal. * * Excel Function: * HEX2DEC(x) * * @deprecated 1.17.0 * Use the toDecimal() method in the Engineering\ConvertHex class instead * @see Engineering\ConvertHex::toDecimal() * * @param mixed $x The hexadecimal number (as a string) that you want to convert. This number cannot * contain more than 10 characters (40 bits). The most significant * bit of number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement * notation. * If number is not a valid hexadecimal number, HEX2DEC returns the * #NUM! error value. * * @return array|string */ public static function HEXTODEC($x) { return Engineering\ConvertHex::toDecimal($x); } /** * HEXTOOCT. * * Return a hex value as octal. * * Excel Function: * HEX2OCT(x[,places]) * * @deprecated 1.17.0 * Use the toOctal() method in the Engineering\ConvertHex class instead * @see Engineering\ConvertHex::toOctal() * * @param mixed $x The hexadecimal number (as a string) that you want to convert. Number cannot * contain more than 10 characters. The most significant bit of * number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement * notation. * If number is negative, HEX2OCT ignores places and returns a * 10-character octal number. * If number is negative, it cannot be less than FFE0000000, and * if number is positive, it cannot be greater than 1FFFFFFF. * If number is not a valid hexadecimal number, HEX2OCT returns * the #NUM! error value. * If HEX2OCT requires more than places characters, it returns * the #NUM! error value. * @param mixed $places The number of characters to use. If places is omitted, HEX2OCT * uses the minimum number of characters necessary. Places is * useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, HEX2OCT returns the #VALUE! error * value. * If places is negative, HEX2OCT returns the #NUM! error value. * * @return array|string */ public static function HEXTOOCT($x, $places = null) { return Engineering\ConvertHex::toOctal($x, $places); } /** * OCTTOBIN. * * Return an octal value as binary. * * Excel Function: * OCT2BIN(x[,places]) * * @deprecated 1.17.0 * Use the toBinary() method in the Engineering\ConvertOctal class instead * @see Engineering\ConvertOctal::toBinary() * * @param mixed $x The octal number you want to convert. Number may not * contain more than 10 characters. The most significant * bit of number is the sign bit. The remaining 29 bits * are magnitude bits. Negative numbers are represented * using two's-complement notation. * If number is negative, OCT2BIN ignores places and returns * a 10-character binary number. * If number is negative, it cannot be less than 7777777000, * and if number is positive, it cannot be greater than 777. * If number is not a valid octal number, OCT2BIN returns * the #NUM! error value. * If OCT2BIN requires more than places characters, it * returns the #NUM! error value. * @param mixed $places The number of characters to use. If places is omitted, * OCT2BIN uses the minimum number of characters necessary. * Places is useful for padding the return value with * leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, OCT2BIN returns the #VALUE! * error value. * If places is negative, OCT2BIN returns the #NUM! error * value. * * @return array|string */ public static function OCTTOBIN($x, $places = null) { return Engineering\ConvertOctal::toBinary($x, $places); } /** * OCTTODEC. * * Return an octal value as decimal. * * Excel Function: * OCT2DEC(x) * * @deprecated 1.17.0 * Use the toDecimal() method in the Engineering\ConvertOctal class instead * @see Engineering\ConvertOctal::toDecimal() * * @param mixed $x The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using * two's-complement notation. * If number is not a valid octal number, OCT2DEC returns the * #NUM! error value. * * @return array|string */ public static function OCTTODEC($x) { return Engineering\ConvertOctal::toDecimal($x); } /** * OCTTOHEX. * * Return an octal value as hex. * * Excel Function: * OCT2HEX(x[,places]) * * @deprecated 1.17.0 * Use the toHex() method in the Engineering\ConvertOctal class instead * @see Engineering\ConvertOctal::toHex() * * @param mixed $x The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using * two's-complement notation. * If number is negative, OCT2HEX ignores places and returns a * 10-character hexadecimal number. * If number is not a valid octal number, OCT2HEX returns the * #NUM! error value. * If OCT2HEX requires more than places characters, it returns * the #NUM! error value. * @param mixed $places The number of characters to use. If places is omitted, OCT2HEX * uses the minimum number of characters necessary. Places is useful * for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, OCT2HEX returns the #VALUE! error value. * If places is negative, OCT2HEX returns the #NUM! error value. * * @return array|string */ public static function OCTTOHEX($x, $places = null) { return Engineering\ConvertOctal::toHex($x, $places); } /** * COMPLEX. * * Converts real and imaginary coefficients into a complex number of the form x +/- yi or x +/- yj. * * Excel Function: * COMPLEX(realNumber,imaginary[,suffix]) * * @deprecated 1.18.0 * Use the COMPLEX() method in the Engineering\Complex class instead * @see Engineering\Complex::COMPLEX() * * @param array|float $realNumber the real coefficient of the complex number * @param array|float $imaginary the imaginary coefficient of the complex number * @param array|string $suffix The suffix for the imaginary component of the complex number. * If omitted, the suffix is assumed to be "i". * * @return array|string */ public static function COMPLEX($realNumber = 0.0, $imaginary = 0.0, $suffix = 'i') { return Engineering\Complex::COMPLEX($realNumber, $imaginary, $suffix); } /** * IMAGINARY. * * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format. * * Excel Function: * IMAGINARY(complexNumber) * * @deprecated 1.18.0 * Use the IMAGINARY() method in the Engineering\Complex class instead * @see Engineering\Complex::IMAGINARY() * * @param string $complexNumber the complex number for which you want the imaginary * coefficient * * @return array|float|string */ public static function IMAGINARY($complexNumber) { return Engineering\Complex::IMAGINARY($complexNumber); } /** * IMREAL. * * Returns the real coefficient of a complex number in x + yi or x + yj text format. * * Excel Function: * IMREAL(complexNumber) * * @deprecated 1.18.0 * Use the IMREAL() method in the Engineering\Complex class instead * @see Engineering\Complex::IMREAL() * * @param string $complexNumber the complex number for which you want the real coefficient * * @return array|float|string */ public static function IMREAL($complexNumber) { return Engineering\Complex::IMREAL($complexNumber); } /** * IMABS. * * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format. * * Excel Function: * IMABS(complexNumber) * * @deprecated 1.18.0 * Use the IMABS() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMABS() * * @param string $complexNumber the complex number for which you want the absolute value * * @return array|float|string */ public static function IMABS($complexNumber) { return ComplexFunctions::IMABS($complexNumber); } /** * IMARGUMENT. * * Returns the argument theta of a complex number, i.e. the angle in radians from the real * axis to the representation of the number in polar coordinates. * * Excel Function: * IMARGUMENT(complexNumber) * * @deprecated 1.18.0 * Use the IMARGUMENT() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMARGUMENT() * * @param array|string $complexNumber the complex number for which you want the argument theta * * @return array|float|string */ public static function IMARGUMENT($complexNumber) { return ComplexFunctions::IMARGUMENT($complexNumber); } /** * IMCONJUGATE. * * Returns the complex conjugate of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCONJUGATE(complexNumber) * * @deprecated 1.18.0 * Use the IMCONJUGATE() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMCONJUGATE() * * @param array|string $complexNumber the complex number for which you want the conjugate * * @return array|string */ public static function IMCONJUGATE($complexNumber) { return ComplexFunctions::IMCONJUGATE($complexNumber); } /** * IMCOS. * * Returns the cosine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOS(complexNumber) * * @deprecated 1.18.0 * Use the IMCOS() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMCOS() * * @param array|string $complexNumber the complex number for which you want the cosine * * @return array|float|string */ public static function IMCOS($complexNumber) { return ComplexFunctions::IMCOS($complexNumber); } /** * IMCOSH. * * Returns the hyperbolic cosine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOSH(complexNumber) * * @deprecated 1.18.0 * Use the IMCOSH() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMCOSH() * * @param array|string $complexNumber the complex number for which you want the hyperbolic cosine * * @return array|float|string */ public static function IMCOSH($complexNumber) { return ComplexFunctions::IMCOSH($complexNumber); } /** * IMCOT. * * Returns the cotangent of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCOT(complexNumber) * * @deprecated 1.18.0 * Use the IMCOT() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMCOT() * * @param array|string $complexNumber the complex number for which you want the cotangent * * @return array|float|string */ public static function IMCOT($complexNumber) { return ComplexFunctions::IMCOT($complexNumber); } /** * IMCSC. * * Returns the cosecant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCSC(complexNumber) * * @deprecated 1.18.0 * Use the IMCSC() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMCSC() * * @param array|string $complexNumber the complex number for which you want the cosecant * * @return array|float|string */ public static function IMCSC($complexNumber) { return ComplexFunctions::IMCSC($complexNumber); } /** * IMCSCH. * * Returns the hyperbolic cosecant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMCSCH(complexNumber) * * @deprecated 1.18.0 * Use the IMCSCH() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMCSCH() * * @param array|string $complexNumber the complex number for which you want the hyperbolic cosecant * * @return array|float|string */ public static function IMCSCH($complexNumber) { return ComplexFunctions::IMCSCH($complexNumber); } /** * IMSIN. * * Returns the sine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSIN(complexNumber) * * @deprecated 1.18.0 * Use the IMSIN() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMSIN() * * @param string $complexNumber the complex number for which you want the sine * * @return array|float|string */ public static function IMSIN($complexNumber) { return ComplexFunctions::IMSIN($complexNumber); } /** * IMSINH. * * Returns the hyperbolic sine of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSINH(complexNumber) * * @deprecated 1.18.0 * Use the IMSINH() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMSINH() * * @param string $complexNumber the complex number for which you want the hyperbolic sine * * @return array|float|string */ public static function IMSINH($complexNumber) { return ComplexFunctions::IMSINH($complexNumber); } /** * IMSEC. * * Returns the secant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSEC(complexNumber) * * @deprecated 1.18.0 * Use the IMSEC() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMSEC() * * @param string $complexNumber the complex number for which you want the secant * * @return array|float|string */ public static function IMSEC($complexNumber) { return ComplexFunctions::IMSEC($complexNumber); } /** * IMSECH. * * Returns the hyperbolic secant of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSECH(complexNumber) * * @deprecated 1.18.0 * Use the IMSECH() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMSECH() * * @param string $complexNumber the complex number for which you want the hyperbolic secant * * @return array|float|string */ public static function IMSECH($complexNumber) { return ComplexFunctions::IMSECH($complexNumber); } /** * IMTAN. * * Returns the tangent of a complex number in x + yi or x + yj text format. * * Excel Function: * IMTAN(complexNumber) * * @deprecated 1.18.0 * Use the IMTAN() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMTAN() * * @param string $complexNumber the complex number for which you want the tangent * * @return array|float|string */ public static function IMTAN($complexNumber) { return ComplexFunctions::IMTAN($complexNumber); } /** * IMSQRT. * * Returns the square root of a complex number in x + yi or x + yj text format. * * Excel Function: * IMSQRT(complexNumber) * * @deprecated 1.18.0 * Use the IMSQRT() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMSQRT() * * @param string $complexNumber the complex number for which you want the square root * * @return array|string */ public static function IMSQRT($complexNumber) { return ComplexFunctions::IMSQRT($complexNumber); } /** * IMLN. * * Returns the natural logarithm of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLN(complexNumber) * * @deprecated 1.18.0 * Use the IMLN() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMLN() * * @param string $complexNumber the complex number for which you want the natural logarithm * * @return array|string */ public static function IMLN($complexNumber) { return ComplexFunctions::IMLN($complexNumber); } /** * IMLOG10. * * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLOG10(complexNumber) * * @deprecated 1.18.0 * Use the IMLOG10() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMLOG10() * * @param string $complexNumber the complex number for which you want the common logarithm * * @return array|string */ public static function IMLOG10($complexNumber) { return ComplexFunctions::IMLOG10($complexNumber); } /** * IMLOG2. * * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format. * * Excel Function: * IMLOG2(complexNumber) * * @deprecated 1.18.0 * Use the IMLOG2() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMLOG2() * * @param string $complexNumber the complex number for which you want the base-2 logarithm * * @return array|string */ public static function IMLOG2($complexNumber) { return ComplexFunctions::IMLOG2($complexNumber); } /** * IMEXP. * * Returns the exponential of a complex number in x + yi or x + yj text format. * * Excel Function: * IMEXP(complexNumber) * * @deprecated 1.18.0 * Use the IMEXP() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMEXP() * * @param string $complexNumber the complex number for which you want the exponential * * @return array|string */ public static function IMEXP($complexNumber) { return ComplexFunctions::IMEXP($complexNumber); } /** * IMPOWER. * * Returns a complex number in x + yi or x + yj text format raised to a power. * * Excel Function: * IMPOWER(complexNumber,realNumber) * * @deprecated 1.18.0 * Use the IMPOWER() method in the Engineering\ComplexFunctions class instead * @see ComplexFunctions::IMPOWER() * * @param string $complexNumber the complex number you want to raise to a power * @param float $realNumber the power to which you want to raise the complex number * * @return array|string */ public static function IMPOWER($complexNumber, $realNumber) { return ComplexFunctions::IMPOWER($complexNumber, $realNumber); } /** * IMDIV. * * Returns the quotient of two complex numbers in x + yi or x + yj text format. * * Excel Function: * IMDIV(complexDividend,complexDivisor) * * @deprecated 1.18.0 * Use the IMDIV() method in the Engineering\ComplexOperations class instead * @see ComplexOperations::IMDIV() * * @param string $complexDividend the complex numerator or dividend * @param string $complexDivisor the complex denominator or divisor * * @return array|string */ public static function IMDIV($complexDividend, $complexDivisor) { return ComplexOperations::IMDIV($complexDividend, $complexDivisor); } /** * IMSUB. * * Returns the difference of two complex numbers in x + yi or x + yj text format. * * Excel Function: * IMSUB(complexNumber1,complexNumber2) * * @deprecated 1.18.0 * Use the IMSUB() method in the Engineering\ComplexOperations class instead * @see ComplexOperations::IMSUB() * * @param string $complexNumber1 the complex number from which to subtract complexNumber2 * @param string $complexNumber2 the complex number to subtract from complexNumber1 * * @return array|string */ public static function IMSUB($complexNumber1, $complexNumber2) { return ComplexOperations::IMSUB($complexNumber1, $complexNumber2); } /** * IMSUM. * * Returns the sum of two or more complex numbers in x + yi or x + yj text format. * * Excel Function: * IMSUM(complexNumber[,complexNumber[,...]]) * * @deprecated 1.18.0 * Use the IMSUM() method in the Engineering\ComplexOperations class instead * @see ComplexOperations::IMSUM() * * @param string ...$complexNumbers Series of complex numbers to add * * @return string */ public static function IMSUM(...$complexNumbers) { return ComplexOperations::IMSUM(...$complexNumbers); } /** * IMPRODUCT. * * Returns the product of two or more complex numbers in x + yi or x + yj text format. * * Excel Function: * IMPRODUCT(complexNumber[,complexNumber[,...]]) * * @deprecated 1.18.0 * Use the IMPRODUCT() method in the Engineering\ComplexOperations class instead * @see ComplexOperations::IMPRODUCT() * * @param string ...$complexNumbers Series of complex numbers to multiply * * @return string */ public static function IMPRODUCT(...$complexNumbers) { return ComplexOperations::IMPRODUCT(...$complexNumbers); } /** * DELTA. * * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise. * Use this function to filter a set of values. For example, by summing several DELTA * functions you calculate the count of equal pairs. This function is also known as the * Kronecker Delta function. * * Excel Function: * DELTA(a[,b]) * * @deprecated 1.17.0 * Use the DELTA() method in the Engineering\Compare class instead * @see Engineering\Compare::DELTA() * * @param float $a the first number * @param float $b The second number. If omitted, b is assumed to be zero. * * @return array|int|string (string in the event of an error) */ public static function DELTA($a, $b = 0) { return Engineering\Compare::DELTA($a, $b); } /** * GESTEP. * * Excel Function: * GESTEP(number[,step]) * * Returns 1 if number >= step; returns 0 (zero) otherwise * Use this function to filter a set of values. For example, by summing several GESTEP * functions you calculate the count of values that exceed a threshold. * * @deprecated 1.17.0 * Use the GESTEP() method in the Engineering\Compare class instead * @see Engineering\Compare::GESTEP() * * @param float $number the value to test against step * @param float $step The threshold value. If you omit a value for step, GESTEP uses zero. * * @return array|int|string (string in the event of an error) */ public static function GESTEP($number, $step = 0) { return Engineering\Compare::GESTEP($number, $step); } /** * BITAND. * * Returns the bitwise AND of two integer values. * * Excel Function: * BITAND(number1, number2) * * @deprecated 1.17.0 * Use the BITAND() method in the Engineering\BitWise class instead * @see Engineering\BitWise::BITAND() * * @param int $number1 * @param int $number2 * * @return array|int|string */ public static function BITAND($number1, $number2) { return Engineering\BitWise::BITAND($number1, $number2); } /** * BITOR. * * Returns the bitwise OR of two integer values. * * Excel Function: * BITOR(number1, number2) * * @deprecated 1.17.0 * Use the BITOR() method in the Engineering\BitWise class instead * @see Engineering\BitWise::BITOR() * * @param int $number1 * @param int $number2 * * @return array|int|string */ public static function BITOR($number1, $number2) { return Engineering\BitWise::BITOR($number1, $number2); } /** * BITXOR. * * Returns the bitwise XOR of two integer values. * * Excel Function: * BITXOR(number1, number2) * * @deprecated 1.17.0 * Use the BITXOR() method in the Engineering\BitWise class instead * @see Engineering\BitWise::BITXOR() * * @param int $number1 * @param int $number2 * * @return array|int|string */ public static function BITXOR($number1, $number2) { return Engineering\BitWise::BITXOR($number1, $number2); } /** * BITLSHIFT. * * Returns the number value shifted left by shift_amount bits. * * Excel Function: * BITLSHIFT(number, shift_amount) * * @deprecated 1.17.0 * Use the BITLSHIFT() method in the Engineering\BitWise class instead * @see Engineering\BitWise::BITLSHIFT() * * @param int $number * @param int $shiftAmount * * @return array|float|int|string */ public static function BITLSHIFT($number, $shiftAmount) { return Engineering\BitWise::BITLSHIFT($number, $shiftAmount); } /** * BITRSHIFT. * * Returns the number value shifted right by shift_amount bits. * * Excel Function: * BITRSHIFT(number, shift_amount) * * @deprecated 1.17.0 * Use the BITRSHIFT() method in the Engineering\BitWise class instead * @see Engineering\BitWise::BITRSHIFT() * * @param int $number * @param int $shiftAmount * * @return array|float|int|string */ public static function BITRSHIFT($number, $shiftAmount) { return Engineering\BitWise::BITRSHIFT($number, $shiftAmount); } /** * ERF. * * Returns the error function integrated between the lower and upper bound arguments. * * Note: In Excel 2007 or earlier, if you input a negative value for the upper or lower bound arguments, * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was * improved, so that it can now calculate the function for both positive and negative ranges. * PhpSpreadsheet follows Excel 2010 behaviour, and accepts negative arguments. * * Excel Function: * ERF(lower[,upper]) * * @deprecated 1.17.0 * Use the ERF() method in the Engineering\Erf class instead * @see Engineering\Erf::ERF() * * @param float $lower lower bound for integrating ERF * @param float $upper upper bound for integrating ERF. * If omitted, ERF integrates between zero and lower_limit * * @return array|float|string */ public static function ERF($lower, $upper = null) { return Engineering\Erf::ERF($lower, $upper); } /** * ERFPRECISE. * * Returns the error function integrated between the lower and upper bound arguments. * * Excel Function: * ERF.PRECISE(limit) * * @deprecated 1.17.0 * Use the ERFPRECISE() method in the Engineering\Erf class instead * @see Engineering\Erf::ERFPRECISE() * * @param float $limit bound for integrating ERF * * @return array|float|string */ public static function ERFPRECISE($limit) { return Engineering\Erf::ERFPRECISE($limit); } /** * ERFC. * * Returns the complementary ERF function integrated between x and infinity * * Note: In Excel 2007 or earlier, if you input a negative value for the lower bound argument, * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was * improved, so that it can now calculate the function for both positive and negative x values. * PhpSpreadsheet follows Excel 2010 behaviour, and accepts nagative arguments. * * Excel Function: * ERFC(x) * * @deprecated 1.17.0 * Use the ERFC() method in the Engineering\ErfC class instead * @see Engineering\ErfC::ERFC() * * @param float $x The lower bound for integrating ERFC * * @return array|float|string */ public static function ERFC($x) { return Engineering\ErfC::ERFC($x); } /** * getConversionGroups * Returns a list of the different conversion groups for UOM conversions. * * @deprecated 1.16.0 * Use the getConversionCategories() method in the Engineering\ConvertUOM class instead * @see Engineering\ConvertUOM::getConversionCategories() * * @return array */ public static function getConversionGroups() { return Engineering\ConvertUOM::getConversionCategories(); } /** * getConversionGroupUnits * Returns an array of units of measure, for a specified conversion group, or for all groups. * * @deprecated 1.16.0 * Use the getConversionCategoryUnits() method in the ConvertUOM class instead * @see Engineering\ConvertUOM::getConversionCategoryUnits() * * @param null|mixed $category * * @return array */ public static function getConversionGroupUnits($category = null) { return Engineering\ConvertUOM::getConversionCategoryUnits($category); } /** * getConversionGroupUnitDetails. * * @deprecated 1.16.0 * Use the getConversionCategoryUnitDetails() method in the ConvertUOM class instead * @see Engineering\ConvertUOM::getConversionCategoryUnitDetails() * * @param null|mixed $category * * @return array */ public static function getConversionGroupUnitDetails($category = null) { return Engineering\ConvertUOM::getConversionCategoryUnitDetails($category); } /** * getConversionMultipliers * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * * @deprecated 1.16.0 * Use the getConversionMultipliers() method in the ConvertUOM class instead * @see Engineering\ConvertUOM::getConversionMultipliers() * * @return mixed[] */ public static function getConversionMultipliers() { return Engineering\ConvertUOM::getConversionMultipliers(); } /** * getBinaryConversionMultipliers. * * Returns an array of the additional Multiplier prefixes that can be used with Information Units of Measure * in CONVERTUOM(). * * @deprecated 1.16.0 * Use the getBinaryConversionMultipliers() method in the ConvertUOM class instead * @see Engineering\ConvertUOM::getBinaryConversionMultipliers() * * @return mixed[] */ public static function getBinaryConversionMultipliers() { return Engineering\ConvertUOM::getBinaryConversionMultipliers(); } /** * CONVERTUOM. * * Converts a number from one measurement system to another. * For example, CONVERT can translate a table of distances in miles to a table of distances * in kilometers. * * Excel Function: * CONVERT(value,fromUOM,toUOM) * * @deprecated 1.16.0 * Use the CONVERT() method in the ConvertUOM class instead * @see Engineering\ConvertUOM::CONVERT() * * @param float|int $value the value in fromUOM to convert * @param string $fromUOM the units for value * @param string $toUOM the units for the result * * @return array|float|string */ public static function CONVERTUOM($value, $fromUOM, $toUOM) { return Engineering\ConvertUOM::CONVERT($value, $fromUOM, $toUOM); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical.php 0000644 00000156157 15002227416 0020542 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Confidence; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Permutations; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances; /** * @deprecated 1.18.0 */ class Statistical { const LOG_GAMMA_X_MAX_VALUE = 2.55e305; const EPS = 2.22e-16; const MAX_VALUE = 1.2e308; const SQRT2PI = 2.5066282746310005024157652848110452530069867406099; /** * AVEDEV. * * Returns the average of the absolute deviations of data points from their mean. * AVEDEV is a measure of the variability in a data set. * * Excel Function: * AVEDEV(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the averageDeviations() method in the Statistical\Averages class instead * @see Statistical\Averages::averageDeviations() * * @param mixed ...$args Data values * * @return float|string */ public static function AVEDEV(...$args) { return Averages::averageDeviations(...$args); } /** * AVERAGE. * * Returns the average (arithmetic mean) of the arguments * * Excel Function: * AVERAGE(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the average() method in the Statistical\Averages class instead * @see Statistical\Averages::average() * * @param mixed ...$args Data values * * @return float|string */ public static function AVERAGE(...$args) { return Averages::average(...$args); } /** * AVERAGEA. * * Returns the average of its arguments, including numbers, text, and logical values * * Excel Function: * AVERAGEA(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the averageA() method in the Statistical\Averages class instead * @see Statistical\Averages::averageA() * * @param mixed ...$args Data values * * @return float|string */ public static function AVERAGEA(...$args) { return Averages::averageA(...$args); } /** * AVERAGEIF. * * Returns the average value from a range of cells that contain numbers within the list of arguments * * Excel Function: * AVERAGEIF(value1[,value2[, ...]],condition) * * @deprecated 1.17.0 * Use the AVERAGEIF() method in the Statistical\Conditional class instead * @see Statistical\Conditional::AVERAGEIF() * * @param mixed $range Data values * @param string $condition the criteria that defines which cells will be checked * @param mixed[] $averageRange Data values * * @return null|float|string */ public static function AVERAGEIF($range, $condition, $averageRange = []) { return Conditional::AVERAGEIF($range, $condition, $averageRange); } /** * BETADIST. * * Returns the beta distribution. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\Beta class instead * @see Statistical\Distributions\Beta::distribution() * * @param float $value Value at which you want to evaluate the distribution * @param float $alpha Parameter to the distribution * @param float $beta Parameter to the distribution * @param mixed $rMin * @param mixed $rMax * * @return array|float|string */ public static function BETADIST($value, $alpha, $beta, $rMin = 0, $rMax = 1) { return Statistical\Distributions\Beta::distribution($value, $alpha, $beta, $rMin, $rMax); } /** * BETAINV. * * Returns the inverse of the Beta distribution. * * @deprecated 1.18.0 * Use the inverse() method in the Statistical\Distributions\Beta class instead * @see Statistical\Distributions\Beta::inverse() * * @param float $probability Probability at which you want to evaluate the distribution * @param float $alpha Parameter to the distribution * @param float $beta Parameter to the distribution * @param float $rMin Minimum value * @param float $rMax Maximum value * * @return array|float|string */ public static function BETAINV($probability, $alpha, $beta, $rMin = 0, $rMax = 1) { return Statistical\Distributions\Beta::inverse($probability, $alpha, $beta, $rMin, $rMax); } /** * BINOMDIST. * * Returns the individual term binomial distribution probability. Use BINOMDIST in problems with * a fixed number of tests or trials, when the outcomes of any trial are only success or failure, * when trials are independent, and when the probability of success is constant throughout the * experiment. For example, BINOMDIST can calculate the probability that two of the next three * babies born are male. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\Binomial class instead * @see Statistical\Distributions\Binomial::distribution() * * @param mixed $value Number of successes in trials * @param mixed $trials Number of trials * @param mixed $probability Probability of success on each trial * @param mixed $cumulative * * @return array|float|string */ public static function BINOMDIST($value, $trials, $probability, $cumulative) { return Statistical\Distributions\Binomial::distribution($value, $trials, $probability, $cumulative); } /** * CHIDIST. * * Returns the one-tailed probability of the chi-squared distribution. * * @deprecated 1.18.0 * Use the distributionRightTail() method in the Statistical\Distributions\ChiSquared class instead * @see Statistical\Distributions\ChiSquared::distributionRightTail() * * @param float $value Value for the function * @param float $degrees degrees of freedom * * @return array|float|string */ public static function CHIDIST($value, $degrees) { return Statistical\Distributions\ChiSquared::distributionRightTail($value, $degrees); } /** * CHIINV. * * Returns the one-tailed probability of the chi-squared distribution. * * @deprecated 1.18.0 * Use the inverseRightTail() method in the Statistical\Distributions\ChiSquared class instead * @see Statistical\Distributions\ChiSquared::inverseRightTail() * * @param float $probability Probability for the function * @param float $degrees degrees of freedom * * @return array|float|string */ public static function CHIINV($probability, $degrees) { return Statistical\Distributions\ChiSquared::inverseRightTail($probability, $degrees); } /** * CONFIDENCE. * * Returns the confidence interval for a population mean * * @deprecated 1.18.0 * Use the CONFIDENCE() method in the Statistical\Confidence class instead * @see Statistical\Confidence::CONFIDENCE() * * @param float $alpha * @param float $stdDev Standard Deviation * @param float $size * * @return array|float|string */ public static function CONFIDENCE($alpha, $stdDev, $size) { return Confidence::CONFIDENCE($alpha, $stdDev, $size); } /** * CORREL. * * Returns covariance, the average of the products of deviations for each data point pair. * * @deprecated 1.18.0 * Use the CORREL() method in the Statistical\Trends class instead * @see Statistical\Trends::CORREL() * * @param mixed $yValues array of mixed Data Series Y * @param null|mixed $xValues array of mixed Data Series X * * @return float|string */ public static function CORREL($yValues, $xValues = null) { return Trends::CORREL($xValues, $yValues); } /** * COUNT. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNT(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the COUNT() method in the Statistical\Counts class instead * @see Statistical\Counts::COUNT() * * @param mixed ...$args Data values * * @return int */ public static function COUNT(...$args) { return Counts::COUNT(...$args); } /** * COUNTA. * * Counts the number of cells that are not empty within the list of arguments * * Excel Function: * COUNTA(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the COUNTA() method in the Statistical\Counts class instead * @see Statistical\Counts::COUNTA() * * @param mixed ...$args Data values * * @return int */ public static function COUNTA(...$args) { return Counts::COUNTA(...$args); } /** * COUNTBLANK. * * Counts the number of empty cells within the list of arguments * * Excel Function: * COUNTBLANK(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the COUNTBLANK() method in the Statistical\Counts class instead * @see Statistical\Counts::COUNTBLANK() * * @param mixed $range Data values * * @return int */ public static function COUNTBLANK($range) { return Counts::COUNTBLANK($range); } /** * COUNTIF. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNTIF(range,condition) * * @deprecated 1.17.0 * Use the COUNTIF() method in the Statistical\Conditional class instead * @see Statistical\Conditional::COUNTIF() * * @param mixed $range Data values * @param string $condition the criteria that defines which cells will be counted * * @return int|string */ public static function COUNTIF($range, $condition) { return Conditional::COUNTIF($range, $condition); } /** * COUNTIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @deprecated 1.17.0 * Use the COUNTIFS() method in the Statistical\Conditional class instead * @see Statistical\Conditional::COUNTIFS() * * @param mixed $args Pairs of Ranges and Criteria * * @return int|string */ public static function COUNTIFS(...$args) { return Conditional::COUNTIFS(...$args); } /** * COVAR. * * Returns covariance, the average of the products of deviations for each data point pair. * * @deprecated 1.18.0 * Use the COVAR() method in the Statistical\Trends class instead * @see Statistical\Trends::COVAR() * * @param mixed $yValues array of mixed Data Series Y * @param mixed $xValues array of mixed Data Series X * * @return float|string */ public static function COVAR($yValues, $xValues) { return Trends::COVAR($yValues, $xValues); } /** * CRITBINOM. * * Returns the smallest value for which the cumulative binomial distribution is greater * than or equal to a criterion value * * See https://support.microsoft.com/en-us/help/828117/ for details of the algorithm used * * @deprecated 1.18.0 * Use the inverse() method in the Statistical\Distributions\Binomial class instead * @see Statistical\Distributions\Binomial::inverse() * * @param float $trials number of Bernoulli trials * @param float $probability probability of a success on each trial * @param float $alpha criterion value * * @return array|int|string */ public static function CRITBINOM($trials, $probability, $alpha) { return Statistical\Distributions\Binomial::inverse($trials, $probability, $alpha); } /** * DEVSQ. * * Returns the sum of squares of deviations of data points from their sample mean. * * Excel Function: * DEVSQ(value1[,value2[, ...]]) * * @deprecated 1.18.0 * Use the sumSquares() method in the Statistical\Deviations class instead * @see Statistical\Deviations::sumSquares() * * @param mixed ...$args Data values * * @return float|string */ public static function DEVSQ(...$args) { return Statistical\Deviations::sumSquares(...$args); } /** * EXPONDIST. * * Returns the exponential distribution. Use EXPONDIST to model the time between events, * such as how long an automated bank teller takes to deliver cash. For example, you can * use EXPONDIST to determine the probability that the process takes at most 1 minute. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\Exponential class instead * @see Statistical\Distributions\Exponential::distribution() * * @param float $value Value of the function * @param float $lambda The parameter value * @param bool $cumulative * * @return array|float|string */ public static function EXPONDIST($value, $lambda, $cumulative) { return Statistical\Distributions\Exponential::distribution($value, $lambda, $cumulative); } /** * F.DIST. * * Returns the F probability distribution. * You can use this function to determine whether two data sets have different degrees of diversity. * For example, you can examine the test scores of men and women entering high school, and determine * if the variability in the females is different from that found in the males. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\F class instead * @see Statistical\Distributions\F::distribution() * * @param float $value Value of the function * @param int $u The numerator degrees of freedom * @param int $v The denominator degrees of freedom * @param bool $cumulative If cumulative is TRUE, F.DIST returns the cumulative distribution function; * if FALSE, it returns the probability density function. * * @return array|float|string */ public static function FDIST2($value, $u, $v, $cumulative) { return Statistical\Distributions\F::distribution($value, $u, $v, $cumulative); } /** * FISHER. * * Returns the Fisher transformation at x. This transformation produces a function that * is normally distributed rather than skewed. Use this function to perform hypothesis * testing on the correlation coefficient. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\Fisher class instead * @see Statistical\Distributions\Fisher::distribution() * * @param float $value * * @return array|float|string */ public static function FISHER($value) { return Statistical\Distributions\Fisher::distribution($value); } /** * FISHERINV. * * Returns the inverse of the Fisher transformation. Use this transformation when * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then * FISHERINV(y) = x. * * @deprecated 1.18.0 * Use the inverse() method in the Statistical\Distributions\Fisher class instead * @see Statistical\Distributions\Fisher::inverse() * * @param float $value * * @return array|float|string */ public static function FISHERINV($value) { return Statistical\Distributions\Fisher::inverse($value); } /** * FORECAST. * * Calculates, or predicts, a future value by using existing values. The predicted value is a y-value for a given x-value. * * @deprecated 1.18.0 * Use the FORECAST() method in the Statistical\Trends class instead * @see Statistical\Trends::FORECAST() * * @param float $xValue Value of X for which we want to find Y * @param mixed $yValues array of mixed Data Series Y * @param mixed $xValues of mixed Data Series X * * @return array|bool|float|string */ public static function FORECAST($xValue, $yValues, $xValues) { return Trends::FORECAST($xValue, $yValues, $xValues); } /** * GAMMA. * * Returns the gamma function value. * * @deprecated 1.18.0 * Use the gamma() method in the Statistical\Distributions\Gamma class instead * @see Statistical\Distributions\Gamma::gamma() * * @param float $value * * @return array|float|string The result, or a string containing an error */ public static function GAMMAFunction($value) { return Statistical\Distributions\Gamma::gamma($value); } /** * GAMMADIST. * * Returns the gamma distribution. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\Gamma class instead * @see Statistical\Distributions\Gamma::distribution() * * @param float $value Value at which you want to evaluate the distribution * @param float $a Parameter to the distribution * @param float $b Parameter to the distribution * @param bool $cumulative * * @return array|float|string */ public static function GAMMADIST($value, $a, $b, $cumulative) { return Statistical\Distributions\Gamma::distribution($value, $a, $b, $cumulative); } /** * GAMMAINV. * * Returns the inverse of the Gamma distribution. * * @deprecated 1.18.0 * Use the inverse() method in the Statistical\Distributions\Gamma class instead * @see Statistical\Distributions\Gamma::inverse() * * @param float $probability Probability at which you want to evaluate the distribution * @param float $alpha Parameter to the distribution * @param float $beta Parameter to the distribution * * @return array|float|string */ public static function GAMMAINV($probability, $alpha, $beta) { return Statistical\Distributions\Gamma::inverse($probability, $alpha, $beta); } /** * GAMMALN. * * Returns the natural logarithm of the gamma function. * * @deprecated 1.18.0 * Use the ln() method in the Statistical\Distributions\Gamma class instead * @see Statistical\Distributions\Gamma::ln() * * @param float $value * * @return array|float|string */ public static function GAMMALN($value) { return Statistical\Distributions\Gamma::ln($value); } /** * GAUSS. * * Calculates the probability that a member of a standard normal population will fall between * the mean and z standard deviations from the mean. * * @deprecated 1.18.0 * Use the gauss() method in the Statistical\Distributions\StandardNormal class instead * @see Statistical\Distributions\StandardNormal::gauss() * * @param float $value * * @return array|float|string The result, or a string containing an error */ public static function GAUSS($value) { return Statistical\Distributions\StandardNormal::gauss($value); } /** * GEOMEAN. * * Returns the geometric mean of an array or range of positive data. For example, you * can use GEOMEAN to calculate average growth rate given compound interest with * variable rates. * * Excel Function: * GEOMEAN(value1[,value2[, ...]]) * * @deprecated 1.18.0 * Use the geometric() method in the Statistical\Averages\Mean class instead * @see Statistical\Averages\Mean::geometric() * * @param mixed ...$args Data values * * @return float|string */ public static function GEOMEAN(...$args) { return Statistical\Averages\Mean::geometric(...$args); } /** * GROWTH. * * Returns values along a predicted exponential Trend * * @deprecated 1.18.0 * Use the GROWTH() method in the Statistical\Trends class instead * @see Statistical\Trends::GROWTH() * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param bool $const a logical value specifying whether to force the intersect to equal 0 * * @return float[] */ public static function GROWTH($yValues, $xValues = [], $newValues = [], $const = true) { return Trends::GROWTH($yValues, $xValues, $newValues, $const); } /** * HARMEAN. * * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the * arithmetic mean of reciprocals. * * Excel Function: * HARMEAN(value1[,value2[, ...]]) * * @deprecated 1.18.0 * Use the harmonic() method in the Statistical\Averages\Mean class instead * @see Statistical\Averages\Mean::harmonic() * * @param mixed ...$args Data values * * @return float|string */ public static function HARMEAN(...$args) { return Statistical\Averages\Mean::harmonic(...$args); } /** * HYPGEOMDIST. * * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of * sample successes, given the sample size, population successes, and population size. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\HyperGeometric class instead * @see Statistical\Distributions\HyperGeometric::distribution() * * @param mixed $sampleSuccesses Number of successes in the sample * @param mixed $sampleNumber Size of the sample * @param mixed $populationSuccesses Number of successes in the population * @param mixed $populationNumber Population size * * @return array|float|string */ public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber) { return Statistical\Distributions\HyperGeometric::distribution( $sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber ); } /** * INTERCEPT. * * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values. * * @deprecated 1.18.0 * Use the INTERCEPT() method in the Statistical\Trends class instead * @see Statistical\Trends::INTERCEPT() * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string */ public static function INTERCEPT($yValues, $xValues) { return Trends::INTERCEPT($yValues, $xValues); } /** * KURT. * * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness * or flatness of a distribution compared with the normal distribution. Positive * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a * relatively flat distribution. * * @deprecated 1.18.0 * Use the kurtosis() method in the Statistical\Deviations class instead * @see Statistical\Deviations::kurtosis() * * @param array ...$args Data Series * * @return float|string */ public static function KURT(...$args) { return Statistical\Deviations::kurtosis(...$args); } /** * LARGE. * * Returns the nth largest value in a data set. You can use this function to * select a value based on its relative standing. * * Excel Function: * LARGE(value1[,value2[, ...]],entry) * * @deprecated 1.18.0 * Use the large() method in the Statistical\Size class instead * @see Statistical\Size::large() * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function LARGE(...$args) { return Statistical\Size::large(...$args); } /** * LINEST. * * Calculates the statistics for a line by using the "least squares" method to calculate a straight line that best fits your data, * and then returns an array that describes the line. * * @deprecated 1.18.0 * Use the LINEST() method in the Statistical\Trends class instead * @see Statistical\Trends::LINEST() * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param bool $const a logical value specifying whether to force the intersect to equal 0 * @param bool $stats a logical value specifying whether to return additional regression statistics * * @return array|int|string The result, or a string containing an error */ public static function LINEST($yValues, $xValues = null, $const = true, $stats = false) { return Trends::LINEST($yValues, $xValues, $const, $stats); } /** * LOGEST. * * Calculates an exponential curve that best fits the X and Y data series, * and then returns an array that describes the line. * * @deprecated 1.18.0 * Use the LOGEST() method in the Statistical\Trends class instead * @see Statistical\Trends::LOGEST() * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param bool $const a logical value specifying whether to force the intersect to equal 0 * @param bool $stats a logical value specifying whether to return additional regression statistics * * @return array|int|string The result, or a string containing an error */ public static function LOGEST($yValues, $xValues = null, $const = true, $stats = false) { return Trends::LOGEST($yValues, $xValues, $const, $stats); } /** * LOGINV. * * Returns the inverse of the normal cumulative distribution * * @deprecated 1.18.0 * Use the inverse() method in the Statistical\Distributions\LogNormal class instead * @see Statistical\Distributions\LogNormal::inverse() * * @param float $probability * @param float $mean * @param float $stdDev * * @return array|float|string The result, or a string containing an error * * @TODO Try implementing P J Acklam's refinement algorithm for greater * accuracy if I can get my head round the mathematics * (as described at) http://home.online.no/~pjacklam/notes/invnorm/ */ public static function LOGINV($probability, $mean, $stdDev) { return Statistical\Distributions\LogNormal::inverse($probability, $mean, $stdDev); } /** * LOGNORMDIST. * * Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed * with parameters mean and standard_dev. * * @deprecated 1.18.0 * Use the cumulative() method in the Statistical\Distributions\LogNormal class instead * @see Statistical\Distributions\LogNormal::cumulative() * * @param float $value * @param float $mean * @param float $stdDev * * @return array|float|string The result, or a string containing an error */ public static function LOGNORMDIST($value, $mean, $stdDev) { return Statistical\Distributions\LogNormal::cumulative($value, $mean, $stdDev); } /** * LOGNORM.DIST. * * Returns the lognormal distribution of x, where ln(x) is normally distributed * with parameters mean and standard_dev. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\LogNormal class instead * @see Statistical\Distributions\LogNormal::distribution() * * @param float $value * @param float $mean * @param float $stdDev * @param bool $cumulative * * @return array|float|string The result, or a string containing an error */ public static function LOGNORMDIST2($value, $mean, $stdDev, $cumulative = false) { return Statistical\Distributions\LogNormal::distribution($value, $mean, $stdDev, $cumulative); } /** * MAX. * * MAX returns the value of the element of the values passed that has the highest value, * with negative numbers considered smaller than positive numbers. * * Excel Function: * max(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the MAX() method in the Statistical\Maximum class instead * @see Statistical\Maximum::max() * * @param mixed ...$args Data values * * @return float */ public static function MAX(...$args) { return Maximum::max(...$args); } /** * MAXA. * * Returns the greatest value in a list of arguments, including numbers, text, and logical values * * Excel Function: * maxA(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the MAXA() method in the Statistical\Maximum class instead * @see Statistical\Maximum::maxA() * * @param mixed ...$args Data values * * @return float */ public static function MAXA(...$args) { return Maximum::maxA(...$args); } /** * MAXIFS. * * Counts the maximum value within a range of cells that contain numbers within the list of arguments * * Excel Function: * MAXIFS(max_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...) * * @deprecated 1.17.0 * Use the MAXIFS() method in the Statistical\Conditional class instead * @see Statistical\Conditional::MAXIFS() * * @param mixed $args Data range and criterias * * @return null|float|string */ public static function MAXIFS(...$args) { return Conditional::MAXIFS(...$args); } /** * MEDIAN. * * Returns the median of the given numbers. The median is the number in the middle of a set of numbers. * * Excel Function: * MEDIAN(value1[,value2[, ...]]) * * @deprecated 1.18.0 * Use the median() method in the Statistical\Averages class instead * @see Statistical\Averages::median() * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function MEDIAN(...$args) { return Statistical\Averages::median(...$args); } /** * MIN. * * MIN returns the value of the element of the values passed that has the smallest value, * with negative numbers considered smaller than positive numbers. * * Excel Function: * MIN(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the min() method in the Statistical\Minimum class instead * @see Statistical\Minimum::min() * * @param mixed ...$args Data values * * @return float */ public static function MIN(...$args) { return Minimum::min(...$args); } /** * MINA. * * Returns the smallest value in a list of arguments, including numbers, text, and logical values * * Excel Function: * MINA(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the minA() method in the Statistical\Minimum class instead * @see Statistical\Minimum::minA() * * @param mixed ...$args Data values * * @return float */ public static function MINA(...$args) { return Minimum::minA(...$args); } /** * MINIFS. * * Returns the minimum value within a range of cells that contain numbers within the list of arguments * * Excel Function: * MINIFS(min_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...) * * @deprecated 1.17.0 * Use the MINIFS() method in the Statistical\Conditional class instead * @see Statistical\Conditional::MINIFS() * * @param mixed $args Data range and criterias * * @return null|float|string */ public static function MINIFS(...$args) { return Conditional::MINIFS(...$args); } /** * MODE. * * Returns the most frequently occurring, or repetitive, value in an array or range of data * * Excel Function: * MODE(value1[,value2[, ...]]) * * @deprecated 1.18.0 * Use the mode() method in the Statistical\Averages class instead * @see Statistical\Averages::mode() * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function MODE(...$args) { return Statistical\Averages::mode(...$args); } /** * NEGBINOMDIST. * * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that * there will be number_f failures before the number_s-th success, when the constant * probability of a success is probability_s. This function is similar to the binomial * distribution, except that the number of successes is fixed, and the number of trials is * variable. Like the binomial, trials are assumed to be independent. * * @deprecated 1.18.0 * Use the negative() method in the Statistical\Distributions\Binomial class instead * @see Statistical\Distributions\Binomial::negative() * * @param mixed $failures Number of Failures * @param mixed $successes Threshold number of Successes * @param mixed $probability Probability of success on each trial * * @return array|float|string The result, or a string containing an error */ public static function NEGBINOMDIST($failures, $successes, $probability) { return Statistical\Distributions\Binomial::negative($failures, $successes, $probability); } /** * NORMDIST. * * Returns the normal distribution for the specified mean and standard deviation. This * function has a very wide range of applications in statistics, including hypothesis * testing. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\Normal class instead * @see Statistical\Distributions\Normal::distribution() * * @param mixed $value * @param mixed $mean Mean Value * @param mixed $stdDev Standard Deviation * @param mixed $cumulative * * @return array|float|string The result, or a string containing an error */ public static function NORMDIST($value, $mean, $stdDev, $cumulative) { return Statistical\Distributions\Normal::distribution($value, $mean, $stdDev, $cumulative); } /** * NORMINV. * * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation. * * @deprecated 1.18.0 * Use the inverse() method in the Statistical\Distributions\Normal class instead * @see Statistical\Distributions\Normal::inverse() * * @param mixed $probability * @param mixed $mean Mean Value * @param mixed $stdDev Standard Deviation * * @return array|float|string The result, or a string containing an error */ public static function NORMINV($probability, $mean, $stdDev) { return Statistical\Distributions\Normal::inverse($probability, $mean, $stdDev); } /** * NORMSDIST. * * Returns the standard normal cumulative distribution function. The distribution has * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * * @deprecated 1.18.0 * Use the cumulative() method in the Statistical\Distributions\StandardNormal class instead * @see Statistical\Distributions\StandardNormal::cumulative() * * @param mixed $value * * @return array|float|string The result, or a string containing an error */ public static function NORMSDIST($value) { return Statistical\Distributions\StandardNormal::cumulative($value); } /** * NORM.S.DIST. * * Returns the standard normal cumulative distribution function. The distribution has * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\StandardNormal class instead * @see Statistical\Distributions\StandardNormal::distribution() * * @param mixed $value * @param mixed $cumulative * * @return array|float|string The result, or a string containing an error */ public static function NORMSDIST2($value, $cumulative) { return Statistical\Distributions\StandardNormal::distribution($value, $cumulative); } /** * NORMSINV. * * Returns the inverse of the standard normal cumulative distribution * * @deprecated 1.18.0 * Use the inverse() method in the Statistical\Distributions\StandardNormal class instead * @see Statistical\Distributions\StandardNormal::inverse() * * @param mixed $value * * @return array|float|string The result, or a string containing an error */ public static function NORMSINV($value) { return Statistical\Distributions\StandardNormal::inverse($value); } /** * PERCENTILE. * * Returns the nth percentile of values in a range.. * * Excel Function: * PERCENTILE(value1[,value2[, ...]],entry) * * @deprecated 1.18.0 * Use the PERCENTILE() method in the Statistical\Percentiles class instead * @see Statistical\Percentiles::PERCENTILE() * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function PERCENTILE(...$args) { return Statistical\Percentiles::PERCENTILE(...$args); } /** * PERCENTRANK. * * Returns the rank of a value in a data set as a percentage of the data set. * Note that the returned rank is simply rounded to the appropriate significant digits, * rather than floored (as MS Excel), so value 3 for a value set of 1, 2, 3, 4 will return * 0.667 rather than 0.666 * * @deprecated 1.18.0 * Use the PERCENTRANK() method in the Statistical\Percentiles class instead * @see Statistical\Percentiles::PERCENTRANK() * * @param mixed $valueSet An array of, or a reference to, a list of numbers * @param mixed $value the number whose rank you want to find * @param mixed $significance the number of significant digits for the returned percentage value * * @return float|string (string if result is an error) */ public static function PERCENTRANK($valueSet, $value, $significance = 3) { return Statistical\Percentiles::PERCENTRANK($valueSet, $value, $significance); } /** * PERMUT. * * Returns the number of permutations for a given number of objects that can be * selected from number objects. A permutation is any set or subset of objects or * events where internal order is significant. Permutations are different from * combinations, for which the internal order is not significant. Use this function * for lottery-style probability calculations. * * @deprecated 1.17.0 * Use the PERMUT() method in the Statistical\Permutations class instead * @see Statistical\Permutations::PERMUT() * * @param int $numObjs Number of different objects * @param int $numInSet Number of objects in each permutation * * @return array|float|int|string Number of permutations, or a string containing an error */ public static function PERMUT($numObjs, $numInSet) { return Permutations::PERMUT($numObjs, $numInSet); } /** * POISSON. * * Returns the Poisson distribution. A common application of the Poisson distribution * is predicting the number of events over a specific time, such as the number of * cars arriving at a toll plaza in 1 minute. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\Poisson class instead * @see Statistical\Distributions\Poisson::distribution() * * @param mixed $value * @param mixed $mean Mean Value * @param mixed $cumulative * * @return array|float|string The result, or a string containing an error */ public static function POISSON($value, $mean, $cumulative) { return Statistical\Distributions\Poisson::distribution($value, $mean, $cumulative); } /** * QUARTILE. * * Returns the quartile of a data set. * * Excel Function: * QUARTILE(value1[,value2[, ...]],entry) * * @deprecated 1.18.0 * Use the QUARTILE() method in the Statistical\Percentiles class instead * @see Statistical\Percentiles::QUARTILE() * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function QUARTILE(...$args) { return Statistical\Percentiles::QUARTILE(...$args); } /** * RANK. * * Returns the rank of a number in a list of numbers. * * @deprecated 1.18.0 * Use the RANK() method in the Statistical\Percentiles class instead * @see Statistical\Percentiles::RANK() * * @param mixed $value the number whose rank you want to find * @param mixed $valueSet An array of, or a reference to, a list of numbers * @param mixed $order Order to sort the values in the value set * * @return float|string The result, or a string containing an error */ public static function RANK($value, $valueSet, $order = 0) { return Statistical\Percentiles::RANK($value, $valueSet, $order); } /** * RSQ. * * Returns the square of the Pearson product moment correlation coefficient through data points in known_y's and known_x's. * * @deprecated 1.18.0 * Use the RSQ() method in the Statistical\Trends class instead * @see Statistical\Trends::RSQ() * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string The result, or a string containing an error */ public static function RSQ($yValues, $xValues) { return Trends::RSQ($yValues, $xValues); } /** * SKEW. * * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry * of a distribution around its mean. Positive skewness indicates a distribution with an * asymmetric tail extending toward more positive values. Negative skewness indicates a * distribution with an asymmetric tail extending toward more negative values. * * @deprecated 1.18.0 * Use the skew() method in the Statistical\Deviations class instead * @see Statistical\Deviations::skew() * * @param array ...$args Data Series * * @return float|string The result, or a string containing an error */ public static function SKEW(...$args) { return Statistical\Deviations::skew(...$args); } /** * SLOPE. * * Returns the slope of the linear regression line through data points in known_y's and known_x's. * * @deprecated 1.18.0 * Use the SLOPE() method in the Statistical\Trends class instead * @see Statistical\Trends::SLOPE() * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string The result, or a string containing an error */ public static function SLOPE($yValues, $xValues) { return Trends::SLOPE($yValues, $xValues); } /** * SMALL. * * Returns the nth smallest value in a data set. You can use this function to * select a value based on its relative standing. * * Excel Function: * SMALL(value1[,value2[, ...]],entry) * * @deprecated 1.18.0 * Use the small() method in the Statistical\Size class instead * @see Statistical\Size::small() * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function SMALL(...$args) { return Statistical\Size::small(...$args); } /** * STANDARDIZE. * * Returns a normalized value from a distribution characterized by mean and standard_dev. * * @deprecated 1.18.0 * Use the execute() method in the Statistical\Standardize class instead * @see Statistical\Standardize::execute() * * @param float $value Value to normalize * @param float $mean Mean Value * @param float $stdDev Standard Deviation * * @return array|float|string Standardized value, or a string containing an error */ public static function STANDARDIZE($value, $mean, $stdDev) { return Statistical\Standardize::execute($value, $mean, $stdDev); } /** * STDEV. * * Estimates standard deviation based on a sample. The standard deviation is a measure of how * widely values are dispersed from the average value (the mean). * * Excel Function: * STDEV(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the STDEV() method in the Statistical\StandardDeviations class instead * @see Statistical\StandardDeviations::STDEV() * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function STDEV(...$args) { return StandardDeviations::STDEV(...$args); } /** * STDEVA. * * Estimates standard deviation based on a sample, including numbers, text, and logical values * * Excel Function: * STDEVA(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the STDEVA() method in the Statistical\StandardDeviations class instead * @see Statistical\StandardDeviations::STDEVA() * * @param mixed ...$args Data values * * @return float|string */ public static function STDEVA(...$args) { return StandardDeviations::STDEVA(...$args); } /** * STDEVP. * * Calculates standard deviation based on the entire population * * Excel Function: * STDEVP(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the STDEVP() method in the Statistical\StandardDeviations class instead * @see Statistical\StandardDeviations::STDEVP() * * @param mixed ...$args Data values * * @return float|string */ public static function STDEVP(...$args) { return StandardDeviations::STDEVP(...$args); } /** * STDEVPA. * * Calculates standard deviation based on the entire population, including numbers, text, and logical values * * Excel Function: * STDEVPA(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the STDEVPA() method in the Statistical\StandardDeviations class instead * @see Statistical\StandardDeviations::STDEVPA() * * @param mixed ...$args Data values * * @return float|string */ public static function STDEVPA(...$args) { return StandardDeviations::STDEVPA(...$args); } /** * STEYX. * * @deprecated 1.18.0 * Use the STEYX() method in the Statistical\Trends class instead * @see Statistical\Trends::STEYX() * * Returns the standard error of the predicted y-value for each x in the regression. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string */ public static function STEYX($yValues, $xValues) { return Trends::STEYX($yValues, $xValues); } /** * TDIST. * * Returns the probability of Student's T distribution. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\StudentT class instead * @see Statistical\Distributions\StudentT::distribution() * * @param float $value Value for the function * @param float $degrees degrees of freedom * @param float $tails number of tails (1 or 2) * * @return array|float|string The result, or a string containing an error */ public static function TDIST($value, $degrees, $tails) { return Statistical\Distributions\StudentT::distribution($value, $degrees, $tails); } /** * TINV. * * Returns the one-tailed probability of the Student-T distribution. * * @deprecated 1.18.0 * Use the inverse() method in the Statistical\Distributions\StudentT class instead * @see Statistical\Distributions\StudentT::inverse() * * @param float $probability Probability for the function * @param float $degrees degrees of freedom * * @return array|float|string The result, or a string containing an error */ public static function TINV($probability, $degrees) { return Statistical\Distributions\StudentT::inverse($probability, $degrees); } /** * TREND. * * Returns values along a linear Trend * * @deprecated 1.18.0 * Use the TREND() method in the Statistical\Trends class instead * @see Statistical\Trends::TREND() * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param bool $const a logical value specifying whether to force the intersect to equal 0 * * @return float[] */ public static function TREND($yValues, $xValues = [], $newValues = [], $const = true) { return Trends::TREND($yValues, $xValues, $newValues, $const); } /** * TRIMMEAN. * * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean * taken by excluding a percentage of data points from the top and bottom tails * of a data set. * * Excel Function: * TRIMEAN(value1[,value2[, ...]], $discard) * * @deprecated 1.18.0 * Use the trim() method in the Statistical\Averages\Mean class instead * @see Statistical\Averages\Mean::trim() * * @param mixed $args Data values * * @return float|string */ public static function TRIMMEAN(...$args) { return Statistical\Averages\Mean::trim(...$args); } /** * VARFunc. * * Estimates variance based on a sample. * * Excel Function: * VAR(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the VAR() method in the Statistical\Variances class instead * @see Statistical\Variances::VAR() * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARFunc(...$args) { return Variances::VAR(...$args); } /** * VARA. * * Estimates variance based on a sample, including numbers, text, and logical values * * Excel Function: * VARA(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the VARA() method in the Statistical\Variances class instead * @see Statistical\Variances::VARA() * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARA(...$args) { return Variances::VARA(...$args); } /** * VARP. * * Calculates variance based on the entire population * * Excel Function: * VARP(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the VARP() method in the Statistical\Variances class instead * @see Statistical\Variances::VARP() * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARP(...$args) { return Variances::VARP(...$args); } /** * VARPA. * * Calculates variance based on the entire population, including numbers, text, and logical values * * Excel Function: * VARPA(value1[,value2[, ...]]) * * @deprecated 1.17.0 * Use the VARPA() method in the Statistical\Variances class instead * @see Statistical\Variances::VARPA() * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARPA(...$args) { return Variances::VARPA(...$args); } /** * WEIBULL. * * Returns the Weibull distribution. Use this distribution in reliability * analysis, such as calculating a device's mean time to failure. * * @deprecated 1.18.0 * Use the distribution() method in the Statistical\Distributions\Weibull class instead * @see Statistical\Distributions\Weibull::distribution() * * @param float $value * @param float $alpha Alpha Parameter * @param float $beta Beta Parameter * @param bool $cumulative * * @return array|float|string (string if result is an error) */ public static function WEIBULL($value, $alpha, $beta, $cumulative) { return Statistical\Distributions\Weibull::distribution($value, $alpha, $beta, $cumulative); } /** * ZTEST. * * Returns the one-tailed P-value of a z-test. * * For a given hypothesized population mean, x, Z.TEST returns the probability that the sample mean would be * greater than the average of observations in the data set (array) — that is, the observed sample mean. * * @deprecated 1.18.0 * Use the zTest() method in the Statistical\Distributions\StandardNormal class instead * @see Statistical\Distributions\StandardNormal::zTest() * * @param mixed $dataSet * @param float $m0 Alpha Parameter * @param float $sigma Beta Parameter * * @return array|float|string (string if result is an error) */ public static function ZTEST($dataSet, $m0, $sigma = null) { return Statistical\Distributions\StandardNormal::zTest($dataSet, $m0, $sigma); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/ArrayEnabled.php 0000644 00000011700 15002227416 0020567 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Engine\ArrayArgumentHelper; use PhpOffice\PhpSpreadsheet\Calculation\Engine\ArrayArgumentProcessor; trait ArrayEnabled { /** * @var ArrayArgumentHelper */ private static $arrayArgumentHelper; /** * @param array|false $arguments Can be changed to array for Php8.1+ */ private static function initialiseHelper($arguments): void { if (self::$arrayArgumentHelper === null) { self::$arrayArgumentHelper = new ArrayArgumentHelper(); } self::$arrayArgumentHelper->initialise(($arguments === false) ? [] : $arguments); } /** * Handles array argument processing when the function accepts a single argument that can be an array argument. * Example use for: * DAYOFMONTH() or FACT(). */ protected static function evaluateSingleArgumentArray(callable $method, array $values): array { $result = []; foreach ($values as $value) { $result[] = $method($value); } return $result; } /** * Handles array argument processing when the function accepts multiple arguments, * and any of them can be an array argument. * Example use for: * ROUND() or DATE(). * * @param mixed ...$arguments */ protected static function evaluateArrayArguments(callable $method, ...$arguments): array { self::initialiseHelper($arguments); $arguments = self::$arrayArgumentHelper->arguments(); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } /** * Handles array argument processing when the function accepts multiple arguments, * but only the first few (up to limit) can be an array arguments. * Example use for: * NETWORKDAYS() or CONCATENATE(), where the last argument is a matrix (or a series of values) that need * to be treated as a such rather than as an array arguments. * * @param mixed ...$arguments */ protected static function evaluateArrayArgumentsSubset(callable $method, int $limit, ...$arguments): array { self::initialiseHelper(array_slice($arguments, 0, $limit)); $trailingArguments = array_slice($arguments, $limit); $arguments = self::$arrayArgumentHelper->arguments(); $arguments = array_merge($arguments, $trailingArguments); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } /** * @param mixed $value */ private static function testFalse($value): bool { return $value === false; } /** * Handles array argument processing when the function accepts multiple arguments, * but only the last few (from start) can be an array arguments. * Example use for: * Z.TEST() or INDEX(), where the first argument 1 is a matrix that needs to be treated as a dataset * rather than as an array argument. * * @param mixed ...$arguments */ protected static function evaluateArrayArgumentsSubsetFrom(callable $method, int $start, ...$arguments): array { $arrayArgumentsSubset = array_combine( range($start, count($arguments) - $start), array_slice($arguments, $start) ); if (self::testFalse($arrayArgumentsSubset)) { return ['#VALUE!']; } self::initialiseHelper($arrayArgumentsSubset); $leadingArguments = array_slice($arguments, 0, $start); $arguments = self::$arrayArgumentHelper->arguments(); $arguments = array_merge($leadingArguments, $arguments); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } /** * Handles array argument processing when the function accepts multiple arguments, * and any of them can be an array argument except for the one specified by ignore. * Example use for: * HLOOKUP() and VLOOKUP(), where argument 1 is a matrix that needs to be treated as a database * rather than as an array argument. * * @param mixed ...$arguments */ protected static function evaluateArrayArgumentsIgnore(callable $method, int $ignore, ...$arguments): array { $leadingArguments = array_slice($arguments, 0, $ignore); $ignoreArgument = array_slice($arguments, $ignore, 1); $trailingArguments = array_slice($arguments, $ignore + 1); self::initialiseHelper(array_merge($leadingArguments, [[null]], $trailingArguments)); $arguments = self::$arrayArgumentHelper->arguments(); array_splice($arguments, $ignore, 1, $ignoreArgument); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial.php 0000644 00000170415 15002227416 0020133 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Amortization; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar; use PhpOffice\PhpSpreadsheet\Calculation\Financial\InterestRate; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; use PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill; /** * @deprecated 1.18.0 */ class Financial { const FINANCIAL_MAX_ITERATIONS = 128; const FINANCIAL_PRECISION = 1.0e-08; /** * ACCRINT. * * Returns the accrued interest for a security that pays periodic interest. * * Excel Function: * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis][,calc_method]) * * @deprecated 1.18.0 * Use the periodic() method in the Financial\Securities\AccruedInterest class instead * @see Securities\AccruedInterest::periodic() * * @param mixed $issue the security's issue date * @param mixed $firstInterest the security's first interest date * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date * when the security is traded to the buyer. * @param mixed $rate the security's annual coupon rate * @param mixed $parValue The security's par value. * If you omit par, ACCRINT uses $1,000. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * @param mixed $calcMethod * If true, use Issue to Settlement * If false, use FirstInterest to Settlement * * @return float|string Result, or a string containing an error */ public static function ACCRINT( $issue, $firstInterest, $settlement, $rate, $parValue = 1000, $frequency = 1, $basis = 0, $calcMethod = true ) { return Securities\AccruedInterest::periodic( $issue, $firstInterest, $settlement, $rate, $parValue, $frequency, $basis, $calcMethod ); } /** * ACCRINTM. * * Returns the accrued interest for a security that pays interest at maturity. * * Excel Function: * ACCRINTM(issue,settlement,rate[,par[,basis]]) * * @deprecated 1.18.0 * Use the atMaturity() method in the Financial\Securities\AccruedInterest class instead * @see Financial\Securities\AccruedInterest::atMaturity() * * @param mixed $issue The security's issue date * @param mixed $settlement The security's settlement (or maturity) date * @param mixed $rate The security's annual coupon rate * @param mixed $parValue The security's par value. * If you omit par, ACCRINT uses $1,000. * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function ACCRINTM($issue, $settlement, $rate, $parValue = 1000, $basis = 0) { return Securities\AccruedInterest::atMaturity($issue, $settlement, $rate, $parValue, $basis); } /** * AMORDEGRC. * * Returns the depreciation for each accounting period. * This function is provided for the French accounting system. If an asset is purchased in * the middle of the accounting period, the prorated depreciation is taken into account. * The function is similar to AMORLINC, except that a depreciation coefficient is applied in * the calculation depending on the life of the assets. * This function will return the depreciation until the last period of the life of the assets * or until the cumulated value of depreciation is greater than the cost of the assets minus * the salvage value. * * Excel Function: * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * * @deprecated 1.18.0 * Use the AMORDEGRC() method in the Financial\Amortization class instead * @see Financial\Amortization::AMORDEGRC() * * @param float $cost The cost of the asset * @param mixed $purchased Date of the purchase of the asset * @param mixed $firstPeriod Date of the end of the first period * @param mixed $salvage The salvage value at the end of the life of the asset * @param float $period The period * @param float $rate Rate of depreciation * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string (string containing the error type if there is an error) */ public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0) { return Amortization::AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis); } /** * AMORLINC. * * Returns the depreciation for each accounting period. * This function is provided for the French accounting system. If an asset is purchased in * the middle of the accounting period, the prorated depreciation is taken into account. * * Excel Function: * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * * @deprecated 1.18.0 * Use the AMORLINC() method in the Financial\Amortization class instead * @see Financial\Amortization::AMORLINC() * * @param float $cost The cost of the asset * @param mixed $purchased Date of the purchase of the asset * @param mixed $firstPeriod Date of the end of the first period * @param mixed $salvage The salvage value at the end of the life of the asset * @param float $period The period * @param float $rate Rate of depreciation * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string (string containing the error type if there is an error) */ public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0) { return Amortization::AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis); } /** * COUPDAYBS. * * Returns the number of days from the beginning of the coupon period to the settlement date. * * Excel Function: * COUPDAYBS(settlement,maturity,frequency[,basis]) * * @deprecated 1.18.0 * Use the COUPDAYBS() method in the Financial\Coupons class instead * @see Financial\Coupons::COUPDAYBS() * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param int $frequency the number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string */ public static function COUPDAYBS($settlement, $maturity, $frequency, $basis = 0) { return Coupons::COUPDAYBS($settlement, $maturity, $frequency, $basis); } /** * COUPDAYS. * * Returns the number of days in the coupon period that contains the settlement date. * * Excel Function: * COUPDAYS(settlement,maturity,frequency[,basis]) * * @deprecated 1.18.0 * Use the COUPDAYS() method in the Financial\Coupons class instead * @see Financial\Coupons::COUPDAYS() * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency the number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string */ public static function COUPDAYS($settlement, $maturity, $frequency, $basis = 0) { return Coupons::COUPDAYS($settlement, $maturity, $frequency, $basis); } /** * COUPDAYSNC. * * Returns the number of days from the settlement date to the next coupon date. * * Excel Function: * COUPDAYSNC(settlement,maturity,frequency[,basis]) * * @deprecated 1.18.0 * Use the COUPDAYSNC() method in the Financial\Coupons class instead * @see Financial\Coupons::COUPDAYSNC() * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency the number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string */ public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis = 0) { return Coupons::COUPDAYSNC($settlement, $maturity, $frequency, $basis); } /** * COUPNCD. * * Returns the next coupon date after the settlement date. * * Excel Function: * COUPNCD(settlement,maturity,frequency[,basis]) * * @deprecated 1.18.0 * Use the COUPNCD() method in the Financial\Coupons class instead * @see Financial\Coupons::COUPNCD() * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency the number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function COUPNCD($settlement, $maturity, $frequency, $basis = 0) { return Coupons::COUPNCD($settlement, $maturity, $frequency, $basis); } /** * COUPNUM. * * Returns the number of coupons payable between the settlement date and maturity date, * rounded up to the nearest whole coupon. * * Excel Function: * COUPNUM(settlement,maturity,frequency[,basis]) * * @deprecated 1.18.0 * Use the COUPNUM() method in the Financial\Coupons class instead * @see Financial\Coupons::COUPNUM() * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency the number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return int|string */ public static function COUPNUM($settlement, $maturity, $frequency, $basis = 0) { return Coupons::COUPNUM($settlement, $maturity, $frequency, $basis); } /** * COUPPCD. * * Returns the previous coupon date before the settlement date. * * Excel Function: * COUPPCD(settlement,maturity,frequency[,basis]) * * @deprecated 1.18.0 * Use the COUPPCD() method in the Financial\Coupons class instead * @see Financial\Coupons::COUPPCD() * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency the number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function COUPPCD($settlement, $maturity, $frequency, $basis = 0) { return Coupons::COUPPCD($settlement, $maturity, $frequency, $basis); } /** * CUMIPMT. * * Returns the cumulative interest paid on a loan between the start and end periods. * * Excel Function: * CUMIPMT(rate,nper,pv,start,end[,type]) * * @deprecated 1.18.0 * Use the interest() method in the Financial\CashFlow\Constant\Periodic\Cumulative class instead * @see Financial\CashFlow\Constant\Periodic\Cumulative::interest() * * @param float $rate The Interest rate * @param int $nper The total number of payment periods * @param float $pv Present Value * @param int $start The first period in the calculation. * Payment periods are numbered beginning with 1. * @param int $end the last period in the calculation * @param int $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * * @return float|string */ public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) { return Financial\CashFlow\Constant\Periodic\Cumulative::interest($rate, $nper, $pv, $start, $end, $type); } /** * CUMPRINC. * * Returns the cumulative principal paid on a loan between the start and end periods. * * Excel Function: * CUMPRINC(rate,nper,pv,start,end[,type]) * * @deprecated 1.18.0 * Use the principal() method in the Financial\CashFlow\Constant\Periodic\Cumulative class instead * @see Financial\CashFlow\Constant\Periodic\Cumulative::principal() * * @param float $rate The Interest rate * @param int $nper The total number of payment periods * @param float $pv Present Value * @param int $start The first period in the calculation. * Payment periods are numbered beginning with 1. * @param int $end the last period in the calculation * @param int $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * * @return float|string */ public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) { return Financial\CashFlow\Constant\Periodic\Cumulative::principal($rate, $nper, $pv, $start, $end, $type); } /** * DB. * * Returns the depreciation of an asset for a specified period using the * fixed-declining balance method. * This form of depreciation is used if you want to get a higher depreciation value * at the beginning of the depreciation (as opposed to linear depreciation). The * depreciation value is reduced with every depreciation period by the depreciation * already deducted from the initial cost. * * Excel Function: * DB(cost,salvage,life,period[,month]) * * @deprecated 1.18.0 * Use the DB() method in the Financial\Depreciation class instead * @see Financial\Depreciation::DB() * * @param float $cost Initial cost of the asset * @param float $salvage Value at the end of the depreciation. * (Sometimes called the salvage value of the asset) * @param int $life Number of periods over which the asset is depreciated. * (Sometimes called the useful life of the asset) * @param int $period The period for which you want to calculate the * depreciation. Period must use the same units as life. * @param int $month Number of months in the first year. If month is omitted, * it defaults to 12. * * @return float|string */ public static function DB($cost, $salvage, $life, $period, $month = 12) { return Depreciation::DB($cost, $salvage, $life, $period, $month); } /** * DDB. * * Returns the depreciation of an asset for a specified period using the * double-declining balance method or some other method you specify. * * Excel Function: * DDB(cost,salvage,life,period[,factor]) * * @deprecated 1.18.0 * Use the DDB() method in the Financial\Depreciation class instead * @see Financial\Depreciation::DDB() * * @param float $cost Initial cost of the asset * @param float $salvage Value at the end of the depreciation. * (Sometimes called the salvage value of the asset) * @param int $life Number of periods over which the asset is depreciated. * (Sometimes called the useful life of the asset) * @param int $period The period for which you want to calculate the * depreciation. Period must use the same units as life. * @param float $factor The rate at which the balance declines. * If factor is omitted, it is assumed to be 2 (the * double-declining balance method). * * @return float|string */ public static function DDB($cost, $salvage, $life, $period, $factor = 2.0) { return Depreciation::DDB($cost, $salvage, $life, $period, $factor); } /** * DISC. * * Returns the discount rate for a security. * * Excel Function: * DISC(settlement,maturity,price,redemption[,basis]) * * @deprecated 1.18.0 * Use the discount() method in the Financial\Securities\Rates class instead * @see Financial\Securities\Rates::discount() * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $price The security's price per $100 face value * @param int $redemption The security's redemption value per $100 face value * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string */ public static function DISC($settlement, $maturity, $price, $redemption, $basis = 0) { return Financial\Securities\Rates::discount($settlement, $maturity, $price, $redemption, $basis); } /** * DOLLARDE. * * Converts a dollar price expressed as an integer part and a fraction * part into a dollar price expressed as a decimal number. * Fractional dollar numbers are sometimes used for security prices. * * Excel Function: * DOLLARDE(fractional_dollar,fraction) * * @deprecated 1.18.0 * Use the decimal() method in the Financial\Dollar class instead * @see Financial\Dollar::decimal() * * @param array|float $fractional_dollar Fractional Dollar * @param array|int $fraction Fraction * * @return array|float|string */ public static function DOLLARDE($fractional_dollar = null, $fraction = 0) { return Dollar::decimal($fractional_dollar, $fraction); } /** * DOLLARFR. * * Converts a dollar price expressed as a decimal number into a dollar price * expressed as a fraction. * Fractional dollar numbers are sometimes used for security prices. * * Excel Function: * DOLLARFR(decimal_dollar,fraction) * * @deprecated 1.18.0 * Use the fractional() method in the Financial\Dollar class instead * @see Financial\Dollar::fractional() * * @param array|float $decimal_dollar Decimal Dollar * @param array|int $fraction Fraction * * @return array|float|string */ public static function DOLLARFR($decimal_dollar = null, $fraction = 0) { return Dollar::fractional($decimal_dollar, $fraction); } /** * EFFECT. * * Returns the effective interest rate given the nominal rate and the number of * compounding payments per year. * * Excel Function: * EFFECT(nominal_rate,npery) * * @deprecated 1.18.0 * Use the effective() method in the Financial\InterestRate class instead * @see Financial\InterestRate::effective() * * @param float $nominalRate Nominal interest rate * @param int $periodsPerYear Number of compounding payments per year * * @return float|string */ public static function EFFECT($nominalRate = 0, $periodsPerYear = 0) { return Financial\InterestRate::effective($nominalRate, $periodsPerYear); } /** * FV. * * Returns the Future Value of a cash flow with constant payments and interest rate (annuities). * * Excel Function: * FV(rate,nper,pmt[,pv[,type]]) * * @deprecated 1.18.0 * Use the futureValue() method in the Financial\CashFlow\Constant\Periodic class instead * @see Financial\CashFlow\Constant\Periodic::futureValue() * * @param float $rate The interest rate per period * @param int $nper Total number of payment periods in an annuity * @param float $pmt The payment made each period: it cannot change over the * life of the annuity. Typically, pmt contains principal * and interest but no other fees or taxes. * @param float $pv present Value, or the lump-sum amount that a series of * future payments is worth right now * @param int $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * * @return float|string */ public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) { return Financial\CashFlow\Constant\Periodic::futureValue($rate, $nper, $pmt, $pv, $type); } /** * FVSCHEDULE. * * Returns the future value of an initial principal after applying a series of compound interest rates. * Use FVSCHEDULE to calculate the future value of an investment with a variable or adjustable rate. * * Excel Function: * FVSCHEDULE(principal,schedule) * * @deprecated 1.18.0 * Use the futureValue() method in the Financial\CashFlow\Single class instead * @see Financial\CashFlow\Single::futureValue() * * @param float $principal the present value * @param float[] $schedule an array of interest rates to apply * * @return float|string */ public static function FVSCHEDULE($principal, $schedule) { return Financial\CashFlow\Single::futureValue($principal, $schedule); } /** * INTRATE. * * Returns the interest rate for a fully invested security. * * Excel Function: * INTRATE(settlement,maturity,investment,redemption[,basis]) * * @deprecated 1.18.0 * Use the interest() method in the Financial\Securities\Rates class instead * @see Financial\Securities\Rates::interest() * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param int $investment the amount invested in the security * @param int $redemption the amount to be received at maturity * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string */ public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis = 0) { return Financial\Securities\Rates::interest($settlement, $maturity, $investment, $redemption, $basis); } /** * IPMT. * * Returns the interest payment for a given period for an investment based on periodic, constant payments * and a constant interest rate. * * Excel Function: * IPMT(rate,per,nper,pv[,fv][,type]) * * @deprecated 1.18.0 * Use the payment() method in the Financial\CashFlow\Constant\Periodic\Interest class instead * @see Financial\CashFlow\Constant\Periodic\Interest::payment() * * @param float $rate Interest rate per period * @param int $per Period for which we want to find the interest * @param int $nper Number of periods * @param float $pv Present Value * @param float $fv Future Value * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string */ public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) { return Financial\CashFlow\Constant\Periodic\Interest::payment($rate, $per, $nper, $pv, $fv, $type); } /** * IRR. * * Returns the internal rate of return for a series of cash flows represented by the numbers in values. * These cash flows do not have to be even, as they would be for an annuity. However, the cash flows must occur * at regular intervals, such as monthly or annually. The internal rate of return is the interest rate received * for an investment consisting of payments (negative values) and income (positive values) that occur at regular * periods. * * Excel Function: * IRR(values[,guess]) * * @deprecated 1.18.0 * Use the rate() method in the Financial\CashFlow\Variable\Periodic class instead * @see Financial\CashFlow\Variable\Periodic::rate() * * @param mixed $values An array or a reference to cells that contain numbers for which you want * to calculate the internal rate of return. * Values must contain at least one positive value and one negative value to * calculate the internal rate of return. * @param mixed $guess A number that you guess is close to the result of IRR * * @return float|string */ public static function IRR($values, $guess = 0.1) { return Financial\CashFlow\Variable\Periodic::rate($values, $guess); } /** * ISPMT. * * Returns the interest payment for an investment based on an interest rate and a constant payment schedule. * * Excel Function: * =ISPMT(interest_rate, period, number_payments, pv) * * @deprecated 1.18.0 * Use the schedulePayment() method in the Financial\CashFlow\Constant\Periodic\Interest class instead * @see Financial\CashFlow\Constant\Periodic\Interest::schedulePayment() * * interest_rate is the interest rate for the investment * * period is the period to calculate the interest rate. It must be betweeen 1 and number_payments. * * number_payments is the number of payments for the annuity * * pv is the loan amount or present value of the payments * * @param array $args * * @return float|string */ public static function ISPMT(...$args) { return Financial\CashFlow\Constant\Periodic\Interest::schedulePayment(...$args); } /** * MIRR. * * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both * the cost of the investment and the interest received on reinvestment of cash. * * Excel Function: * MIRR(values,finance_rate, reinvestment_rate) * * @deprecated 1.18.0 * Use the modifiedRate() method in the Financial\CashFlow\Variable\Periodic class instead * @see Financial\CashFlow\Variable\Periodic::modifiedRate() * * @param mixed $values An array or a reference to cells that contain a series of payments and * income occurring at regular intervals. * Payments are negative value, income is positive values. * @param mixed $finance_rate The interest rate you pay on the money used in the cash flows * @param mixed $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them * * @return float|string Result, or a string containing an error */ public static function MIRR($values, $finance_rate, $reinvestment_rate) { return Financial\CashFlow\Variable\Periodic::modifiedRate($values, $finance_rate, $reinvestment_rate); } /** * NOMINAL. * * Returns the nominal interest rate given the effective rate and the number of compounding payments per year. * * Excel Function: * NOMINAL(effect_rate, npery) * * @deprecated 1.18.0 * Use the nominal() method in the Financial\InterestRate class instead * @see Financial\InterestRate::nominal() * * @param float $effectiveRate Effective interest rate * @param int $periodsPerYear Number of compounding payments per year * * @return float|string Result, or a string containing an error */ public static function NOMINAL($effectiveRate = 0, $periodsPerYear = 0) { return InterestRate::nominal($effectiveRate, $periodsPerYear); } /** * NPER. * * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate. * * @deprecated 1.18.0 * Use the periods() method in the Financial\CashFlow\Constant\Periodic class instead * @see Financial\CashFlow\Constant\Periodic::periods() * * @param float $rate Interest rate per period * @param int $pmt Periodic payment (annuity) * @param float $pv Present Value * @param float $fv Future Value * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) { return Financial\CashFlow\Constant\Periodic::periods($rate, $pmt, $pv, $fv, $type); } /** * NPV. * * Returns the Net Present Value of a cash flow series given a discount rate. * * @deprecated 1.18.0 * Use the presentValue() method in the Financial\CashFlow\Variable\Periodic class instead * @see Financial\CashFlow\Variable\Periodic::presentValue() * * @param array $args * * @return float */ public static function NPV(...$args) { return Financial\CashFlow\Variable\Periodic::presentValue(...$args); } /** * PDURATION. * * Calculates the number of periods required for an investment to reach a specified value. * * @deprecated 1.18.0 * Use the periods() method in the Financial\CashFlow\Single class instead * @see Financial\CashFlow\Single::periods() * * @param float $rate Interest rate per period * @param float $pv Present Value * @param float $fv Future Value * * @return float|string Result, or a string containing an error */ public static function PDURATION($rate = 0, $pv = 0, $fv = 0) { return Financial\CashFlow\Single::periods($rate, $pv, $fv); } /** * PMT. * * Returns the constant payment (annuity) for a cash flow with a constant interest rate. * * @deprecated 1.18.0 * Use the annuity() method in the Financial\CashFlow\Constant\Periodic\Payments class instead * @see Financial\CashFlow\Constant\Periodic\Payments::annuity() * * @param float $rate Interest rate per period * @param int $nper Number of periods * @param float $pv Present Value * @param float $fv Future Value * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) { return Financial\CashFlow\Constant\Periodic\Payments::annuity($rate, $nper, $pv, $fv, $type); } /** * PPMT. * * Returns the interest payment for a given period for an investment based on periodic, constant payments * and a constant interest rate. * * @deprecated 1.18.0 * Use the interestPayment() method in the Financial\CashFlow\Constant\Periodic\Payments class instead * @see Financial\CashFlow\Constant\Periodic\Payments::interestPayment() * * @param float $rate Interest rate per period * @param int $per Period for which we want to find the interest * @param int $nper Number of periods * @param float $pv Present Value * @param float $fv Future Value * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) { return Financial\CashFlow\Constant\Periodic\Payments::interestPayment($rate, $per, $nper, $pv, $fv, $type); } /** * PRICE. * * Returns the price per $100 face value of a security that pays periodic interest. * * @deprecated 1.18.0 * Use the price() method in the Financial\Securities\Price class instead * @see Financial\Securities\Price::price() * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param float $rate the security's annual coupon rate * @param float $yield the security's annual yield * @param float $redemption The number of coupon payments per year. * For annual payments, frequency = 1; * for semiannual, frequency = 2; * for quarterly, frequency = 4. * @param int $frequency * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis = 0) { return Securities\Price::price($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis); } /** * PRICEDISC. * * Returns the price per $100 face value of a discounted security. * * @deprecated 1.18.0 * Use the priceDiscounted() method in the Financial\Securities\Price class instead * @see Financial\Securities\Price::priceDiscounted() * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $discount The security's discount rate * @param int $redemption The security's redemption value per $100 face value * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis = 0) { return Securities\Price::priceDiscounted($settlement, $maturity, $discount, $redemption, $basis); } /** * PRICEMAT. * * Returns the price per $100 face value of a security that pays interest at maturity. * * @deprecated 1.18.0 * Use the priceAtMaturity() method in the Financial\Securities\Price class instead * @see Financial\Securities\Price::priceAtMaturity() * * @param mixed $settlement The security's settlement date. * The security's settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param mixed $rate The security's interest rate at date of issue * @param mixed $yield The security's annual yield * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis = 0) { return Securities\Price::priceAtMaturity($settlement, $maturity, $issue, $rate, $yield, $basis); } /** * PV. * * Returns the Present Value of a cash flow with constant payments and interest rate (annuities). * * @deprecated 1.18.0 * Use the presentValue() method in the Financial\CashFlow\Constant\Periodic class instead * @see Financial\CashFlow\Constant\Periodic::presentValue() * * @param float $rate Interest rate per period * @param int $nper Number of periods * @param float $pmt Periodic payment (annuity) * @param float $fv Future Value * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) { return Financial\CashFlow\Constant\Periodic::presentValue($rate, $nper, $pmt, $fv, $type); } /** * RATE. * * Returns the interest rate per period of an annuity. * RATE is calculated by iteration and can have zero or more solutions. * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations, * RATE returns the #NUM! error value. * * Excel Function: * RATE(nper,pmt,pv[,fv[,type[,guess]]]) * * @deprecated 1.18.0 * Use the rate() method in the Financial\CashFlow\Constant\Periodic\Interest class instead * @see Financial\CashFlow\Constant\Periodic\Interest::rate() * * @param mixed $nper The total number of payment periods in an annuity * @param mixed $pmt The payment made each period and cannot change over the life * of the annuity. * Typically, pmt includes principal and interest but no other * fees or taxes. * @param mixed $pv The present value - the total amount that a series of future * payments is worth now * @param mixed $fv The future value, or a cash balance you want to attain after * the last payment is made. If fv is omitted, it is assumed * to be 0 (the future value of a loan, for example, is 0). * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * @param mixed $guess Your guess for what the rate will be. * If you omit guess, it is assumed to be 10 percent. * * @return float|string */ public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) { return Financial\CashFlow\Constant\Periodic\Interest::rate($nper, $pmt, $pv, $fv, $type, $guess); } /** * RECEIVED. * * Returns the amount received at maturity for a fully invested Security. * * @deprecated 1.18.0 * Use the received() method in the Financial\Securities\Price class instead * @see Financial\Securities\Price::received() * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $investment The amount invested in the security * @param mixed $discount The security's discount rate * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis = 0) { return Financial\Securities\Price::received($settlement, $maturity, $investment, $discount, $basis); } /** * RRI. * * Calculates the interest rate required for an investment to grow to a specified future value . * * @deprecated 1.18.0 * Use the interestRate() method in the Financial\CashFlow\Single class instead * @see Financial\CashFlow\Single::interestRate() * * @param float $nper The number of periods over which the investment is made * @param float $pv Present Value * @param float $fv Future Value * * @return float|string Result, or a string containing an error */ public static function RRI($nper = 0, $pv = 0, $fv = 0) { return Financial\CashFlow\Single::interestRate($nper, $pv, $fv); } /** * SLN. * * Returns the straight-line depreciation of an asset for one period * * @deprecated 1.18.0 * Use the SLN() method in the Financial\Depreciation class instead * @see Financial\Depreciation::SLN() * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated * * @return float|string Result, or a string containing an error */ public static function SLN($cost, $salvage, $life) { return Depreciation::SLN($cost, $salvage, $life); } /** * SYD. * * Returns the sum-of-years' digits depreciation of an asset for a specified period. * * @deprecated 1.18.0 * Use the SYD() method in the Financial\Depreciation class instead * @see Financial\Depreciation::SYD() * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated * @param mixed $period Period * * @return float|string Result, or a string containing an error */ public static function SYD($cost, $salvage, $life, $period) { return Depreciation::SYD($cost, $salvage, $life, $period); } /** * TBILLEQ. * * Returns the bond-equivalent yield for a Treasury bill. * * @deprecated 1.18.0 * Use the bondEquivalentYield() method in the Financial\TreasuryBill class instead * @see Financial\TreasuryBill::bondEquivalentYield() * * @param mixed $settlement The Treasury bill's settlement date. * The Treasury bill's settlement date is the date after the issue date when the * Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param mixed $discount The Treasury bill's discount rate * * @return float|string Result, or a string containing an error */ public static function TBILLEQ($settlement, $maturity, $discount) { return TreasuryBill::bondEquivalentYield($settlement, $maturity, $discount); } /** * TBILLPRICE. * * Returns the price per $100 face value for a Treasury bill. * * @deprecated 1.18.0 * Use the price() method in the Financial\TreasuryBill class instead * @see Financial\TreasuryBill::price() * * @param mixed $settlement The Treasury bill's settlement date. * The Treasury bill's settlement date is the date after the issue date * when the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param mixed $discount The Treasury bill's discount rate * * @return float|string Result, or a string containing an error */ public static function TBILLPRICE($settlement, $maturity, $discount) { return TreasuryBill::price($settlement, $maturity, $discount); } /** * TBILLYIELD. * * Returns the yield for a Treasury bill. * * @deprecated 1.18.0 * Use the yield() method in the Financial\TreasuryBill class instead * @see Financial\TreasuryBill::yield() * * @param mixed $settlement The Treasury bill's settlement date. * The Treasury bill's settlement date is the date after the issue date * when the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param mixed $price The Treasury bill's price per $100 face value * * @return float|mixed|string */ public static function TBILLYIELD($settlement, $maturity, $price) { return TreasuryBill::yield($settlement, $maturity, $price); } /** * XIRR. * * Returns the internal rate of return for a schedule of cash flows that is not necessarily periodic. * * Excel Function: * =XIRR(values,dates,guess) * * @deprecated 1.18.0 * Use the rate() method in the Financial\CashFlow\Variable\NonPeriodic class instead * @see Financial\CashFlow\Variable\NonPeriodic::rate() * * @param float[] $values A series of cash flow payments * The series of values must contain at least one positive value & one negative value * @param mixed[] $dates A series of payment dates * The first payment date indicates the beginning of the schedule of payments * All other dates must be later than this date, but they may occur in any order * @param float $guess An optional guess at the expected answer * * @return float|mixed|string */ public static function XIRR($values, $dates, $guess = 0.1) { return Financial\CashFlow\Variable\NonPeriodic::rate($values, $dates, $guess); } /** * XNPV. * * Returns the net present value for a schedule of cash flows that is not necessarily periodic. * To calculate the net present value for a series of cash flows that is periodic, use the NPV function. * * Excel Function: * =XNPV(rate,values,dates) * * @deprecated 1.18.0 * Use the presentValue() method in the Financial\CashFlow\Variable\NonPeriodic class instead * @see Financial\CashFlow\Variable\NonPeriodic::presentValue() * * @param float $rate the discount rate to apply to the cash flows * @param float[] $values A series of cash flows that corresponds to a schedule of payments in dates. * The first payment is optional and corresponds to a cost or payment that occurs * at the beginning of the investment. * If the first value is a cost or payment, it must be a negative value. * All succeeding payments are discounted based on a 365-day year. * The series of values must contain at least one positive value and one negative value. * @param mixed[] $dates A schedule of payment dates that corresponds to the cash flow payments. * The first payment date indicates the beginning of the schedule of payments. * All other dates must be later than this date, but they may occur in any order. * * @return float|mixed|string */ public static function XNPV($rate, $values, $dates) { return Financial\CashFlow\Variable\NonPeriodic::presentValue($rate, $values, $dates); } /** * YIELDDISC. * * Returns the annual yield of a security that pays interest at maturity. * * @deprecated 1.18.0 * Use the yieldDiscounted() method in the Financial\Securities\Yields class instead * @see Financial\Securities\Yields::yieldDiscounted() * * @param mixed $settlement The security's settlement date. * The security's settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $price The security's price per $100 face value * @param int $redemption The security's redemption value per $100 face value * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis = 0) { return Securities\Yields::yieldDiscounted($settlement, $maturity, $price, $redemption, $basis); } /** * YIELDMAT. * * Returns the annual yield of a security that pays interest at maturity. * * @deprecated 1.18.0 * Use the yieldAtMaturity() method in the Financial\Securities\Yields class instead * @see Financial\Securities\Yields::yieldAtMaturity() * * @param mixed $settlement The security's settlement date. * The security's settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param mixed $rate The security's interest rate at date of issue * @param mixed $price The security's price per $100 face value * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis = 0) { return Securities\Yields::yieldAtMaturity($settlement, $maturity, $issue, $rate, $price, $basis); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php 0000644 00000746166 15002227416 0020521 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Engine\BranchPruner; use PhpOffice\PhpSpreadsheet\Calculation\Engine\CyclicReferenceStack; use PhpOffice\PhpSpreadsheet\Calculation\Engine\Logger; use PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands; use PhpOffice\PhpSpreadsheet\Calculation\Token\Stack; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use ReflectionClassConstant; use ReflectionMethod; use ReflectionParameter; use Throwable; class Calculation { /** Constants */ /** Regular Expressions */ // Numeric operand const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?'; // String operand const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"'; // Opening bracket const CALCULATION_REGEXP_OPENBRACE = '\('; // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it) const CALCULATION_REGEXP_FUNCTION = '@?(?:_xlfn\.)?(?:_xlws\.)?([\p{L}][\p{L}\p{N}\.]*)[\s]*\('; // Cell reference (cell or range of cells, with or without a sheet reference) const CALCULATION_REGEXP_CELLREF = '((([^\s,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?\$?\b([a-z]{1,3})\$?(\d{1,7})(?![\w.])'; // Cell reference (with or without a sheet reference) ensuring absolute/relative const CALCULATION_REGEXP_CELLREF_RELATIVE = '((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?\b[a-z]{1,3})(\$?\d{1,7})(?![\w.])'; const CALCULATION_REGEXP_COLUMN_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\".(?:[^\"]|\"[^!])?\"))!)?(\$?[a-z]{1,3})):(?![.*])'; const CALCULATION_REGEXP_ROW_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?[1-9][0-9]{0,6})):(?![.*])'; // Cell reference (with or without a sheet reference) ensuring absolute/relative // Cell ranges ensuring absolute/relative const CALCULATION_REGEXP_COLUMNRANGE_RELATIVE = '(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; const CALCULATION_REGEXP_ROWRANGE_RELATIVE = '(\$?\d{1,7}):(\$?\d{1,7})'; // Defined Names: Named Range of cells, or Named Formulae const CALCULATION_REGEXP_DEFINEDNAME = '((([^\s,!&%^\/\*\+<>=-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?([_\p{L}][_\p{L}\p{N}\.]*)'; // Structured Reference (Fully Qualified and Unqualified) const CALCULATION_REGEXP_STRUCTURED_REFERENCE = '([\p{L}_\\\\][\p{L}\p{N}\._]+)?(\[(?:[^\d\]+-])?)'; // Error const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?'; /** constants */ const RETURN_ARRAY_AS_ERROR = 'error'; const RETURN_ARRAY_AS_VALUE = 'value'; const RETURN_ARRAY_AS_ARRAY = 'array'; const FORMULA_OPEN_FUNCTION_BRACE = '('; const FORMULA_CLOSE_FUNCTION_BRACE = ')'; const FORMULA_OPEN_MATRIX_BRACE = '{'; const FORMULA_CLOSE_MATRIX_BRACE = '}'; const FORMULA_STRING_QUOTE = '"'; /** @var string */ private static $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE; /** * Instance of this class. * * @var ?Calculation */ private static $instance; /** * Instance of the spreadsheet this Calculation Engine is using. * * @var ?Spreadsheet */ private $spreadsheet; /** * Calculation cache. * * @var array */ private $calculationCache = []; /** * Calculation cache enabled. * * @var bool */ private $calculationCacheEnabled = true; /** * @var BranchPruner */ private $branchPruner; /** * @var bool */ private $branchPruningEnabled = true; /** * List of operators that can be used within formulae * The true/false value indicates whether it is a binary operator or a unary operator. */ private const CALCULATION_OPERATORS = [ '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '%' => false, '~' => false, '>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true, '∩' => true, '∪' => true, ':' => true, ]; /** * List of binary operators (those that expect two operands). */ private const BINARY_OPERATORS = [ '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true, '∩' => true, '∪' => true, ':' => true, ]; /** * The debug log generated by the calculation engine. * * @var Logger */ private $debugLog; /** * Flag to determine how formula errors should be handled * If true, then a user error will be triggered * If false, then an exception will be thrown. * * @var ?bool * * @deprecated 1.25.2 use setSuppressFormulaErrors() instead */ public $suppressFormulaErrors; /** @var bool */ private $suppressFormulaErrorsNew = false; /** * Error message for any error that was raised/thrown by the calculation engine. * * @var null|string */ public $formulaError; /** * Reference Helper. * * @var ReferenceHelper */ private static $referenceHelper; /** * An array of the nested cell references accessed by the calculation engine, used for the debug log. * * @var CyclicReferenceStack */ private $cyclicReferenceStack; /** @var array */ private $cellStack = []; /** * Current iteration counter for cyclic formulae * If the value is 0 (or less) then cyclic formulae will throw an exception, * otherwise they will iterate to the limit defined here before returning a result. * * @var int */ private $cyclicFormulaCounter = 1; /** @var string */ private $cyclicFormulaCell = ''; /** * Number of iterations for cyclic formulae. * * @var int */ public $cyclicFormulaCount = 1; /** * The current locale setting. * * @var string */ private static $localeLanguage = 'en_us'; // US English (default locale) /** * List of available locale settings * Note that this is read for the locale subdirectory only when requested. * * @var string[] */ private static $validLocaleLanguages = [ 'en', // English (default language) ]; /** * Locale-specific argument separator for function arguments. * * @var string */ private static $localeArgumentSeparator = ','; /** @var array */ private static $localeFunctions = []; /** * Locale-specific translations for Excel constants (True, False and Null). * * @var array<string, string> */ private static $localeBoolean = [ 'TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL', ]; public static function getLocaleBoolean(string $index): string { return self::$localeBoolean[$index]; } /** * Excel constant string translations to their PHP equivalents * Constant conversion from text name/value to actual (datatyped) value. * * @var array<string, mixed> */ private static $excelConstants = [ 'TRUE' => true, 'FALSE' => false, 'NULL' => null, ]; public static function keyInExcelConstants(string $key): bool { return array_key_exists($key, self::$excelConstants); } /** @return mixed */ public static function getExcelConstants(string $key) { return self::$excelConstants[$key]; } /** * Array of functions usable on Spreadsheet. * In theory, this could be const rather than static; * however, Phpstan breaks trying to analyze it when attempted. * *@var array */ private static $phpSpreadsheetFunctions = [ 'ABS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Absolute::class, 'evaluate'], 'argumentCount' => '1', ], 'ACCRINT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\AccruedInterest::class, 'periodic'], 'argumentCount' => '4-8', ], 'ACCRINTM' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\AccruedInterest::class, 'atMaturity'], 'argumentCount' => '3-5', ], 'ACOS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'acos'], 'argumentCount' => '1', ], 'ACOSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'acosh'], 'argumentCount' => '1', ], 'ACOT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acot'], 'argumentCount' => '1', ], 'ACOTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acoth'], 'argumentCount' => '1', ], 'ADDRESS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Address::class, 'cell'], 'argumentCount' => '2-5', ], 'AGGREGATE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3+', ], 'AMORDEGRC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Amortization::class, 'AMORDEGRC'], 'argumentCount' => '6,7', ], 'AMORLINC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Amortization::class, 'AMORLINC'], 'argumentCount' => '6,7', ], 'ANCHORARRAY' => [ 'category' => Category::CATEGORY_UNCATEGORISED, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'AND' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'logicalAnd'], 'argumentCount' => '1+', ], 'ARABIC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Arabic::class, 'evaluate'], 'argumentCount' => '1', ], 'AREAS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'ARRAYTOTEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'fromArray'], 'argumentCount' => '1,2', ], 'ASC' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'ASIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'asin'], 'argumentCount' => '1', ], 'ASINH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'asinh'], 'argumentCount' => '1', ], 'ATAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan'], 'argumentCount' => '1', ], 'ATAN2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan2'], 'argumentCount' => '2', ], 'ATANH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atanh'], 'argumentCount' => '1', ], 'AVEDEV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'averageDeviations'], 'argumentCount' => '1+', ], 'AVERAGE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'average'], 'argumentCount' => '1+', ], 'AVERAGEA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'averageA'], 'argumentCount' => '1+', ], 'AVERAGEIF' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIF'], 'argumentCount' => '2,3', ], 'AVERAGEIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIFS'], 'argumentCount' => '3+', ], 'BAHTTEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'BASE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Base::class, 'evaluate'], 'argumentCount' => '2,3', ], 'BESSELI' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselI::class, 'BESSELI'], 'argumentCount' => '2', ], 'BESSELJ' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselJ::class, 'BESSELJ'], 'argumentCount' => '2', ], 'BESSELK' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselK::class, 'BESSELK'], 'argumentCount' => '2', ], 'BESSELY' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselY::class, 'BESSELY'], 'argumentCount' => '2', ], 'BETADIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'distribution'], 'argumentCount' => '3-5', ], 'BETA.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4-6', ], 'BETAINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], 'argumentCount' => '3-5', ], 'BETA.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], 'argumentCount' => '3-5', ], 'BIN2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toDecimal'], 'argumentCount' => '1', ], 'BIN2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toHex'], 'argumentCount' => '1,2', ], 'BIN2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toOctal'], 'argumentCount' => '1,2', ], 'BINOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], 'argumentCount' => '4', ], 'BINOM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], 'argumentCount' => '4', ], 'BINOM.DIST.RANGE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'range'], 'argumentCount' => '3,4', ], 'BINOM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], 'argumentCount' => '3', ], 'BITAND' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITAND'], 'argumentCount' => '2', ], 'BITOR' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITOR'], 'argumentCount' => '2', ], 'BITXOR' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITXOR'], 'argumentCount' => '2', ], 'BITLSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITLSHIFT'], 'argumentCount' => '2', ], 'BITRSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITRSHIFT'], 'argumentCount' => '2', ], 'BYCOL' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'BYROW' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'ceiling'], 'argumentCount' => '1-2', // 2 for Excel, 1-2 for Ods/Gnumeric ], 'CEILING.MATH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'math'], 'argumentCount' => '1-3', ], 'CEILING.PRECISE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'precise'], 'argumentCount' => '1,2', ], 'CELL' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1,2', ], 'CHAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'character'], 'argumentCount' => '1', ], 'CHIDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], 'argumentCount' => '2', ], 'CHISQ.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionLeftTail'], 'argumentCount' => '3', ], 'CHISQ.DIST.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], 'argumentCount' => '2', ], 'CHIINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], 'argumentCount' => '2', ], 'CHISQ.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseLeftTail'], 'argumentCount' => '2', ], 'CHISQ.INV.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], 'argumentCount' => '2', ], 'CHITEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], 'argumentCount' => '2', ], 'CHISQ.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], 'argumentCount' => '2', ], 'CHOOSE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Selection::class, 'CHOOSE'], 'argumentCount' => '2+', ], 'CHOOSECOLS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2+', ], 'CHOOSEROWS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2+', ], 'CLEAN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Trim::class, 'nonPrintable'], 'argumentCount' => '1', ], 'CODE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'code'], 'argumentCount' => '1', ], 'COLUMN' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMN'], 'argumentCount' => '-1', 'passCellReference' => true, 'passByReference' => [true], ], 'COLUMNS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMNS'], 'argumentCount' => '1', ], 'COMBIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Combinations::class, 'withoutRepetition'], 'argumentCount' => '2', ], 'COMBINA' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Combinations::class, 'withRepetition'], 'argumentCount' => '2', ], 'COMPLEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Complex::class, 'COMPLEX'], 'argumentCount' => '2,3', ], 'CONCAT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'], 'argumentCount' => '1+', ], 'CONCATENATE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'], 'argumentCount' => '1+', ], 'CONFIDENCE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], 'argumentCount' => '3', ], 'CONFIDENCE.NORM' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], 'argumentCount' => '3', ], 'CONFIDENCE.T' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'CONVERT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertUOM::class, 'CONVERT'], 'argumentCount' => '3', ], 'CORREL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'CORREL'], 'argumentCount' => '2', ], 'COS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'cos'], 'argumentCount' => '1', ], 'COSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'cosh'], 'argumentCount' => '1', ], 'COT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'cot'], 'argumentCount' => '1', ], 'COTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'coth'], 'argumentCount' => '1', ], 'COUNT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNT'], 'argumentCount' => '1+', ], 'COUNTA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNTA'], 'argumentCount' => '1+', ], 'COUNTBLANK' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNTBLANK'], 'argumentCount' => '1', ], 'COUNTIF' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'COUNTIF'], 'argumentCount' => '2', ], 'COUNTIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'COUNTIFS'], 'argumentCount' => '2+', ], 'COUPDAYBS' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYBS'], 'argumentCount' => '3,4', ], 'COUPDAYS' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYS'], 'argumentCount' => '3,4', ], 'COUPDAYSNC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYSNC'], 'argumentCount' => '3,4', ], 'COUPNCD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPNCD'], 'argumentCount' => '3,4', ], 'COUPNUM' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPNUM'], 'argumentCount' => '3,4', ], 'COUPPCD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPPCD'], 'argumentCount' => '3,4', ], 'COVAR' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'COVAR'], 'argumentCount' => '2', ], 'COVARIANCE.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'COVAR'], 'argumentCount' => '2', ], 'COVARIANCE.S' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'CRITBINOM' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], 'argumentCount' => '3', ], 'CSC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csc'], 'argumentCount' => '1', ], 'CSCH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csch'], 'argumentCount' => '1', ], 'CUBEKPIMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEMEMBERPROPERTY' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBERANKEDMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBESET' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBESETCOUNT' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEVALUE' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUMIPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'interest'], 'argumentCount' => '6', ], 'CUMPRINC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'principal'], 'argumentCount' => '6', ], 'DATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Date::class, 'fromYMD'], 'argumentCount' => '3', ], 'DATEDIF' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Difference::class, 'interval'], 'argumentCount' => '2,3', ], 'DATESTRING' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'DATEVALUE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateValue::class, 'fromString'], 'argumentCount' => '1', ], 'DAVERAGE' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DAverage::class, 'evaluate'], 'argumentCount' => '3', ], 'DAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateParts::class, 'day'], 'argumentCount' => '1', ], 'DAYS' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Days::class, 'between'], 'argumentCount' => '2', ], 'DAYS360' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Days360::class, 'between'], 'argumentCount' => '2,3', ], 'DB' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'DB'], 'argumentCount' => '4,5', ], 'DBCS' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'DCOUNT' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DCount::class, 'evaluate'], 'argumentCount' => '3', ], 'DCOUNTA' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DCountA::class, 'evaluate'], 'argumentCount' => '3', ], 'DDB' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'DDB'], 'argumentCount' => '4,5', ], 'DEC2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toBinary'], 'argumentCount' => '1,2', ], 'DEC2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toHex'], 'argumentCount' => '1,2', ], 'DEC2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toOctal'], 'argumentCount' => '1,2', ], 'DECIMAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'DEGREES' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Angle::class, 'toDegrees'], 'argumentCount' => '1', ], 'DELTA' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Compare::class, 'DELTA'], 'argumentCount' => '1,2', ], 'DEVSQ' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Deviations::class, 'sumSquares'], 'argumentCount' => '1+', ], 'DGET' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DGet::class, 'evaluate'], 'argumentCount' => '3', ], 'DISC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Rates::class, 'discount'], 'argumentCount' => '4,5', ], 'DMAX' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DMax::class, 'evaluate'], 'argumentCount' => '3', ], 'DMIN' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DMin::class, 'evaluate'], 'argumentCount' => '3', ], 'DOLLAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'DOLLAR'], 'argumentCount' => '1,2', ], 'DOLLARDE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Dollar::class, 'decimal'], 'argumentCount' => '2', ], 'DOLLARFR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Dollar::class, 'fractional'], 'argumentCount' => '2', ], 'DPRODUCT' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DProduct::class, 'evaluate'], 'argumentCount' => '3', ], 'DROP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-3', ], 'DSTDEV' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DStDev::class, 'evaluate'], 'argumentCount' => '3', ], 'DSTDEVP' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DStDevP::class, 'evaluate'], 'argumentCount' => '3', ], 'DSUM' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DSum::class, 'evaluate'], 'argumentCount' => '3', ], 'DURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5,6', ], 'DVAR' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DVar::class, 'evaluate'], 'argumentCount' => '3', ], 'DVARP' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DVarP::class, 'evaluate'], 'argumentCount' => '3', ], 'ECMA.CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1,2', ], 'EDATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Month::class, 'adjust'], 'argumentCount' => '2', ], 'EFFECT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\InterestRate::class, 'effective'], 'argumentCount' => '2', ], 'ENCODEURL' => [ 'category' => Category::CATEGORY_WEB, 'functionCall' => [Web\Service::class, 'urlEncode'], 'argumentCount' => '1', ], 'EOMONTH' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Month::class, 'lastDay'], 'argumentCount' => '2', ], 'ERF' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Erf::class, 'ERF'], 'argumentCount' => '1,2', ], 'ERF.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Erf::class, 'ERFPRECISE'], 'argumentCount' => '1', ], 'ERFC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERFC.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERROR.TYPE' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ExcelError::class, 'type'], 'argumentCount' => '1', ], 'EVEN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'even'], 'argumentCount' => '1', ], 'EXACT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'exact'], 'argumentCount' => '2', ], 'EXP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Exp::class, 'evaluate'], 'argumentCount' => '1', ], 'EXPAND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-4', ], 'EXPONDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'], 'argumentCount' => '3', ], 'EXPON.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'], 'argumentCount' => '3', ], 'FACT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Factorial::class, 'fact'], 'argumentCount' => '1', ], 'FACTDOUBLE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Factorial::class, 'factDouble'], 'argumentCount' => '1', ], 'FALSE' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Boolean::class, 'FALSE'], 'argumentCount' => '0', ], 'FDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'F.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\F::class, 'distribution'], 'argumentCount' => '4', ], 'F.DIST.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'FILTER' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Filter::class, 'filter'], 'argumentCount' => '2-3', ], 'FILTERXML' => [ 'category' => Category::CATEGORY_WEB, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'FIND' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'sensitive'], 'argumentCount' => '2,3', ], 'FINDB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'sensitive'], 'argumentCount' => '2,3', ], 'FINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'F.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'F.INV.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'FISHER' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Fisher::class, 'distribution'], 'argumentCount' => '1', ], 'FISHERINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Fisher::class, 'inverse'], 'argumentCount' => '1', ], 'FIXED' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'FIXEDFORMAT'], 'argumentCount' => '1-3', ], 'FLOOR' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Floor::class, 'floor'], 'argumentCount' => '1-2', // Excel requries 2, Ods/Gnumeric 1-2 ], 'FLOOR.MATH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Floor::class, 'math'], 'argumentCount' => '1-3', ], 'FLOOR.PRECISE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Floor::class, 'precise'], 'argumentCount' => '1-2', ], 'FORECAST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'FORECAST'], 'argumentCount' => '3', ], 'FORECAST.ETS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'FORECAST.ETS.CONFINT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'FORECAST.ETS.SEASONALITY' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-4', ], 'FORECAST.ETS.STAT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'FORECAST.LINEAR' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'FORECAST'], 'argumentCount' => '3', ], 'FORMULATEXT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Formula::class, 'text'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'FREQUENCY' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'FTEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'F.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'FV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'futureValue'], 'argumentCount' => '3-5', ], 'FVSCHEDULE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Single::class, 'futureValue'], 'argumentCount' => '2', ], 'GAMMA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'gamma'], 'argumentCount' => '1', ], 'GAMMADIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'], 'argumentCount' => '4', ], 'GAMMA.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'], 'argumentCount' => '4', ], 'GAMMAINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'], 'argumentCount' => '3', ], 'GAMMA.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'], 'argumentCount' => '3', ], 'GAMMALN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'], 'argumentCount' => '1', ], 'GAMMALN.PRECISE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'], 'argumentCount' => '1', ], 'GAUSS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'gauss'], 'argumentCount' => '1', ], 'GCD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Gcd::class, 'evaluate'], 'argumentCount' => '1+', ], 'GEOMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages\Mean::class, 'geometric'], 'argumentCount' => '1+', ], 'GESTEP' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Compare::class, 'GESTEP'], 'argumentCount' => '1,2', ], 'GETPIVOTDATA' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2+', ], 'GROWTH' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'GROWTH'], 'argumentCount' => '1-4', ], 'HARMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages\Mean::class, 'harmonic'], 'argumentCount' => '1+', ], 'HEX2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertHex::class, 'toBinary'], 'argumentCount' => '1,2', ], 'HEX2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertHex::class, 'toDecimal'], 'argumentCount' => '1', ], 'HEX2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertHex::class, 'toOctal'], 'argumentCount' => '1,2', ], 'HLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\HLookup::class, 'lookup'], 'argumentCount' => '3,4', ], 'HOUR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeParts::class, 'hour'], 'argumentCount' => '1', ], 'HSTACK' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'HYPERLINK' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Hyperlink::class, 'set'], 'argumentCount' => '1,2', 'passCellReference' => true, ], 'HYPGEOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\HyperGeometric::class, 'distribution'], 'argumentCount' => '4', ], 'HYPGEOM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5', ], 'IF' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'statementIf'], 'argumentCount' => '1-3', ], 'IFERROR' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'IFERROR'], 'argumentCount' => '2', ], 'IFNA' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'IFNA'], 'argumentCount' => '2', ], 'IFS' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'IFS'], 'argumentCount' => '2+', ], 'IMABS' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMABS'], 'argumentCount' => '1', ], 'IMAGINARY' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Complex::class, 'IMAGINARY'], 'argumentCount' => '1', ], 'IMARGUMENT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMARGUMENT'], 'argumentCount' => '1', ], 'IMCONJUGATE' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCONJUGATE'], 'argumentCount' => '1', ], 'IMCOS' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOS'], 'argumentCount' => '1', ], 'IMCOSH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOSH'], 'argumentCount' => '1', ], 'IMCOT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOT'], 'argumentCount' => '1', ], 'IMCSC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSC'], 'argumentCount' => '1', ], 'IMCSCH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSCH'], 'argumentCount' => '1', ], 'IMDIV' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMDIV'], 'argumentCount' => '2', ], 'IMEXP' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMEXP'], 'argumentCount' => '1', ], 'IMLN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLN'], 'argumentCount' => '1', ], 'IMLOG10' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG10'], 'argumentCount' => '1', ], 'IMLOG2' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG2'], 'argumentCount' => '1', ], 'IMPOWER' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMPOWER'], 'argumentCount' => '2', ], 'IMPRODUCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMPRODUCT'], 'argumentCount' => '1+', ], 'IMREAL' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Complex::class, 'IMREAL'], 'argumentCount' => '1', ], 'IMSEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSEC'], 'argumentCount' => '1', ], 'IMSECH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSECH'], 'argumentCount' => '1', ], 'IMSIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSIN'], 'argumentCount' => '1', ], 'IMSINH' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSINH'], 'argumentCount' => '1', ], 'IMSQRT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSQRT'], 'argumentCount' => '1', ], 'IMSUB' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUB'], 'argumentCount' => '2', ], 'IMSUM' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUM'], 'argumentCount' => '1+', ], 'IMTAN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ComplexFunctions::class, 'IMTAN'], 'argumentCount' => '1', ], 'INDEX' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Matrix::class, 'index'], 'argumentCount' => '2-4', ], 'INDIRECT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Indirect::class, 'INDIRECT'], 'argumentCount' => '1,2', 'passCellReference' => true, ], 'INFO' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'INT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\IntClass::class, 'evaluate'], 'argumentCount' => '1', ], 'INTERCEPT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'INTERCEPT'], 'argumentCount' => '2', ], 'INTRATE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Rates::class, 'interest'], 'argumentCount' => '4,5', ], 'IPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'payment'], 'argumentCount' => '4-6', ], 'IRR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'rate'], 'argumentCount' => '1,2', ], 'ISBLANK' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isBlank'], 'argumentCount' => '1', ], 'ISERR' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ErrorValue::class, 'isErr'], 'argumentCount' => '1', ], 'ISERROR' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ErrorValue::class, 'isError'], 'argumentCount' => '1', ], 'ISEVEN' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isEven'], 'argumentCount' => '1', ], 'ISFORMULA' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isFormula'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'ISLOGICAL' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isLogical'], 'argumentCount' => '1', ], 'ISNA' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ErrorValue::class, 'isNa'], 'argumentCount' => '1', ], 'ISNONTEXT' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isNonText'], 'argumentCount' => '1', ], 'ISNUMBER' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isNumber'], 'argumentCount' => '1', ], 'ISO.CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1,2', ], 'ISODD' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isOdd'], 'argumentCount' => '1', ], 'ISOMITTED' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'ISOWEEKNUM' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Week::class, 'isoWeekNumber'], 'argumentCount' => '1', ], 'ISPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'schedulePayment'], 'argumentCount' => '4', ], 'ISREF' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isRef'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'ISTEXT' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'isText'], 'argumentCount' => '1', ], 'ISTHAIDIGIT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'JIS' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'KURT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Deviations::class, 'kurtosis'], 'argumentCount' => '1+', ], 'LAMBDA' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'LARGE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Size::class, 'large'], 'argumentCount' => '2', ], 'LCM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Lcm::class, 'evaluate'], 'argumentCount' => '1+', ], 'LEFT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'left'], 'argumentCount' => '1,2', ], 'LEFTB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'left'], 'argumentCount' => '1,2', ], 'LEN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'length'], 'argumentCount' => '1', ], 'LENB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'length'], 'argumentCount' => '1', ], 'LET' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'LINEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'LINEST'], 'argumentCount' => '1-4', ], 'LN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Logarithms::class, 'natural'], 'argumentCount' => '1', ], 'LOG' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Logarithms::class, 'withBase'], 'argumentCount' => '1,2', ], 'LOG10' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Logarithms::class, 'base10'], 'argumentCount' => '1', ], 'LOGEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'LOGEST'], 'argumentCount' => '1-4', ], 'LOGINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'], 'argumentCount' => '3', ], 'LOGNORMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'cumulative'], 'argumentCount' => '3', ], 'LOGNORM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'distribution'], 'argumentCount' => '4', ], 'LOGNORM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'], 'argumentCount' => '3', ], 'LOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Lookup::class, 'lookup'], 'argumentCount' => '2,3', ], 'LOWER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CaseConvert::class, 'lower'], 'argumentCount' => '1', ], 'MAKEARRAY' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'MAP' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'MATCH' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\ExcelMatch::class, 'MATCH'], 'argumentCount' => '2,3', ], 'MAX' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Maximum::class, 'max'], 'argumentCount' => '1+', ], 'MAXA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Maximum::class, 'maxA'], 'argumentCount' => '1+', ], 'MAXIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'MAXIFS'], 'argumentCount' => '3+', ], 'MDETERM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'determinant'], 'argumentCount' => '1', ], 'MDURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5,6', ], 'MEDIAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'median'], 'argumentCount' => '1+', ], 'MEDIANIF' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2+', ], 'MID' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'mid'], 'argumentCount' => '3', ], 'MIDB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'mid'], 'argumentCount' => '3', ], 'MIN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Minimum::class, 'min'], 'argumentCount' => '1+', ], 'MINA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Minimum::class, 'minA'], 'argumentCount' => '1+', ], 'MINIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'MINIFS'], 'argumentCount' => '3+', ], 'MINUTE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeParts::class, 'minute'], 'argumentCount' => '1', ], 'MINVERSE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'inverse'], 'argumentCount' => '1', ], 'MIRR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'modifiedRate'], 'argumentCount' => '3', ], 'MMULT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'multiply'], 'argumentCount' => '2', ], 'MOD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'mod'], 'argumentCount' => '2', ], 'MODE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'mode'], 'argumentCount' => '1+', ], 'MODE.MULT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'MODE.SNGL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'mode'], 'argumentCount' => '1+', ], 'MONTH' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateParts::class, 'month'], 'argumentCount' => '1', ], 'MROUND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'multiple'], 'argumentCount' => '2', ], 'MULTINOMIAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Factorial::class, 'multinomial'], 'argumentCount' => '1+', ], 'MUNIT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'identity'], 'argumentCount' => '1', ], 'N' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'asNumber'], 'argumentCount' => '1', ], 'NA' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ExcelError::class, 'NA'], 'argumentCount' => '0', ], 'NEGBINOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'negative'], 'argumentCount' => '3', ], 'NEGBINOM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4', ], 'NETWORKDAYS' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\NetworkDays::class, 'count'], 'argumentCount' => '2-3', ], 'NETWORKDAYS.INTL' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-4', ], 'NOMINAL' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\InterestRate::class, 'nominal'], 'argumentCount' => '2', ], 'NORMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'], 'argumentCount' => '4', ], 'NORM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'], 'argumentCount' => '4', ], 'NORMINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'], 'argumentCount' => '3', ], 'NORM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'], 'argumentCount' => '3', ], 'NORMSDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'cumulative'], 'argumentCount' => '1', ], 'NORM.S.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'distribution'], 'argumentCount' => '1,2', ], 'NORMSINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'], 'argumentCount' => '1', ], 'NORM.S.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'], 'argumentCount' => '1', ], 'NOT' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'NOT'], 'argumentCount' => '1', ], 'NOW' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Current::class, 'now'], 'argumentCount' => '0', ], 'NPER' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'periods'], 'argumentCount' => '3-5', ], 'NPV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'presentValue'], 'argumentCount' => '2+', ], 'NUMBERSTRING' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'NUMBERVALUE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'NUMBERVALUE'], 'argumentCount' => '1+', ], 'OCT2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertOctal::class, 'toBinary'], 'argumentCount' => '1,2', ], 'OCT2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertOctal::class, 'toDecimal'], 'argumentCount' => '1', ], 'OCT2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertOctal::class, 'toHex'], 'argumentCount' => '1,2', ], 'ODD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'odd'], 'argumentCount' => '1', ], 'ODDFPRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '8,9', ], 'ODDFYIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '8,9', ], 'ODDLPRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '7,8', ], 'ODDLYIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '7,8', ], 'OFFSET' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Offset::class, 'OFFSET'], 'argumentCount' => '3-5', 'passCellReference' => true, 'passByReference' => [true], ], 'OR' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'logicalOr'], 'argumentCount' => '1+', ], 'PDURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Single::class, 'periods'], 'argumentCount' => '3', ], 'PEARSON' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'CORREL'], 'argumentCount' => '2', ], 'PERCENTILE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'], 'argumentCount' => '2', ], 'PERCENTILE.EXC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'PERCENTILE.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'], 'argumentCount' => '2', ], 'PERCENTRANK' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'], 'argumentCount' => '2,3', ], 'PERCENTRANK.EXC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2,3', ], 'PERCENTRANK.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'], 'argumentCount' => '2,3', ], 'PERMUT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Permutations::class, 'PERMUT'], 'argumentCount' => '2', ], 'PERMUTATIONA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Permutations::class, 'PERMUTATIONA'], 'argumentCount' => '2', ], 'PHONETIC' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'PHI' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'PI' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'pi', 'argumentCount' => '0', ], 'PMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'annuity'], 'argumentCount' => '3-5', ], 'POISSON' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'], 'argumentCount' => '3', ], 'POISSON.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'], 'argumentCount' => '3', ], 'POWER' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'power'], 'argumentCount' => '2', ], 'PPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'interestPayment'], 'argumentCount' => '4-6', ], 'PRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'price'], 'argumentCount' => '6,7', ], 'PRICEDISC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'priceDiscounted'], 'argumentCount' => '4,5', ], 'PRICEMAT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'priceAtMaturity'], 'argumentCount' => '5,6', ], 'PROB' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3,4', ], 'PRODUCT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'product'], 'argumentCount' => '1+', ], 'PROPER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CaseConvert::class, 'proper'], 'argumentCount' => '1', ], 'PV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'presentValue'], 'argumentCount' => '3-5', ], 'QUARTILE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'], 'argumentCount' => '2', ], 'QUARTILE.EXC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'QUARTILE.INC' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'], 'argumentCount' => '2', ], 'QUOTIENT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Operations::class, 'quotient'], 'argumentCount' => '2', ], 'RADIANS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Angle::class, 'toRadians'], 'argumentCount' => '1', ], 'RAND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Random::class, 'rand'], 'argumentCount' => '0', ], 'RANDARRAY' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Random::class, 'randArray'], 'argumentCount' => '0-5', ], 'RANDBETWEEN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Random::class, 'randBetween'], 'argumentCount' => '2', ], 'RANK' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'RANK'], 'argumentCount' => '2,3', ], 'RANK.AVG' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2,3', ], 'RANK.EQ' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Percentiles::class, 'RANK'], 'argumentCount' => '2,3', ], 'RATE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'rate'], 'argumentCount' => '3-6', ], 'RECEIVED' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Price::class, 'received'], 'argumentCount' => '4-5', ], 'REDUCE' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'REPLACE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Replace::class, 'replace'], 'argumentCount' => '4', ], 'REPLACEB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Replace::class, 'replace'], 'argumentCount' => '4', ], 'REPT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'builtinREPT'], 'argumentCount' => '2', ], 'RIGHT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'right'], 'argumentCount' => '1,2', ], 'RIGHTB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'right'], 'argumentCount' => '1,2', ], 'ROMAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Roman::class, 'evaluate'], 'argumentCount' => '1,2', ], 'ROUND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'round'], 'argumentCount' => '2', ], 'ROUNDBAHTDOWN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'ROUNDBAHTUP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'ROUNDDOWN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'down'], 'argumentCount' => '2', ], 'ROUNDUP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'up'], 'argumentCount' => '2', ], 'ROW' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROW'], 'argumentCount' => '-1', 'passCellReference' => true, 'passByReference' => [true], ], 'ROWS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROWS'], 'argumentCount' => '1', ], 'RRI' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Single::class, 'interestRate'], 'argumentCount' => '3', ], 'RSQ' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'RSQ'], 'argumentCount' => '2', ], 'RTD' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'SEARCH' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'insensitive'], 'argumentCount' => '2,3', ], 'SCAN' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'SEARCHB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Search::class, 'insensitive'], 'argumentCount' => '2,3', ], 'SEC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Secant::class, 'sec'], 'argumentCount' => '1', ], 'SECH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Secant::class, 'sech'], 'argumentCount' => '1', ], 'SECOND' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeParts::class, 'second'], 'argumentCount' => '1', ], 'SEQUENCE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\MatrixFunctions::class, 'sequence'], 'argumentCount' => '1-4', ], 'SERIESSUM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SeriesSum::class, 'evaluate'], 'argumentCount' => '4', ], 'SHEET' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '0,1', ], 'SHEETS' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '0,1', ], 'SIGN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sign::class, 'evaluate'], 'argumentCount' => '1', ], 'SIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'sin'], 'argumentCount' => '1', ], 'SINGLE' => [ 'category' => Category::CATEGORY_UNCATEGORISED, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'SINH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'sinh'], 'argumentCount' => '1', ], 'SKEW' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Deviations::class, 'skew'], 'argumentCount' => '1+', ], 'SKEW.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'SLN' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'SLN'], 'argumentCount' => '3', ], 'SLOPE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'SLOPE'], 'argumentCount' => '2', ], 'SMALL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Size::class, 'small'], 'argumentCount' => '2', ], 'SORT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Sort::class, 'sort'], 'argumentCount' => '1-4', ], 'SORTBY' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Sort::class, 'sortBy'], 'argumentCount' => '2+', ], 'SQRT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sqrt::class, 'sqrt'], 'argumentCount' => '1', ], 'SQRTPI' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sqrt::class, 'pi'], 'argumentCount' => '1', ], 'STANDARDIZE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Standardize::class, 'execute'], 'argumentCount' => '3', ], 'STDEV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'], 'argumentCount' => '1+', ], 'STDEV.S' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'], 'argumentCount' => '1+', ], 'STDEV.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'], 'argumentCount' => '1+', ], 'STDEVA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVA'], 'argumentCount' => '1+', ], 'STDEVP' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'], 'argumentCount' => '1+', ], 'STDEVPA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVPA'], 'argumentCount' => '1+', ], 'STEYX' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'STEYX'], 'argumentCount' => '2', ], 'SUBSTITUTE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Replace::class, 'substitute'], 'argumentCount' => '3,4', ], 'SUBTOTAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Subtotal::class, 'evaluate'], 'argumentCount' => '2+', 'passCellReference' => true, ], 'SUM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sum::class, 'sumErroringStrings'], 'argumentCount' => '1+', ], 'SUMIF' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Statistical\Conditional::class, 'SUMIF'], 'argumentCount' => '2,3', ], 'SUMIFS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Statistical\Conditional::class, 'SUMIFS'], 'argumentCount' => '3+', ], 'SUMPRODUCT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Sum::class, 'product'], 'argumentCount' => '1+', ], 'SUMSQ' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumSquare'], 'argumentCount' => '1+', ], 'SUMX2MY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredMinusYSquared'], 'argumentCount' => '2', ], 'SUMX2PY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredPlusYSquared'], 'argumentCount' => '2', ], 'SUMXMY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\SumSquares::class, 'sumXMinusYSquared'], 'argumentCount' => '2', ], 'SWITCH' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Conditional::class, 'statementSwitch'], 'argumentCount' => '3+', ], 'SYD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'SYD'], 'argumentCount' => '4', ], 'T' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'test'], 'argumentCount' => '1', ], 'TAKE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-3', ], 'TAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'tan'], 'argumentCount' => '1', ], 'TANH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'tanh'], 'argumentCount' => '1', ], 'TBILLEQ' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\TreasuryBill::class, 'bondEquivalentYield'], 'argumentCount' => '3', ], 'TBILLPRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\TreasuryBill::class, 'price'], 'argumentCount' => '3', ], 'TBILLYIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\TreasuryBill::class, 'yield'], 'argumentCount' => '3', ], 'TDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'distribution'], 'argumentCount' => '3', ], 'T.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'T.DIST.2T' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'T.DIST.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'TEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'TEXTFORMAT'], 'argumentCount' => '2', ], 'TEXTAFTER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'after'], 'argumentCount' => '2-6', ], 'TEXTBEFORE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Extract::class, 'before'], 'argumentCount' => '2-6', ], 'TEXTJOIN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'TEXTJOIN'], 'argumentCount' => '3+', ], 'TEXTSPLIT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'split'], 'argumentCount' => '2-6', ], 'THAIDAYOFWEEK' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAIDIGIT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAIMONTHOFYEAR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAINUMSOUND' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAINUMSTRING' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAISTRINGLENGTH' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'THAIYEAR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'TIME' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Time::class, 'fromHMS'], 'argumentCount' => '3', ], 'TIMEVALUE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\TimeValue::class, 'fromString'], 'argumentCount' => '1', ], 'TINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'], 'argumentCount' => '2', ], 'T.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'], 'argumentCount' => '2', ], 'T.INV.2T' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'TODAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Current::class, 'today'], 'argumentCount' => '0', ], 'TOCOL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1-3', ], 'TOROW' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1-3', ], 'TRANSPOSE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Matrix::class, 'transpose'], 'argumentCount' => '1', ], 'TREND' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'TREND'], 'argumentCount' => '1-4', ], 'TRIM' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Trim::class, 'spaces'], 'argumentCount' => '1', ], 'TRIMMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages\Mean::class, 'trim'], 'argumentCount' => '2', ], 'TRUE' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Boolean::class, 'TRUE'], 'argumentCount' => '0', ], 'TRUNC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trunc::class, 'evaluate'], 'argumentCount' => '1,2', ], 'TTEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4', ], 'T.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4', ], 'TYPE' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\Value::class, 'type'], 'argumentCount' => '1', ], 'UNICHAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'character'], 'argumentCount' => '1', ], 'UNICODE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'code'], 'argumentCount' => '1', ], 'UNIQUE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Unique::class, 'unique'], 'argumentCount' => '1+', ], 'UPPER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CaseConvert::class, 'upper'], 'argumentCount' => '1', ], 'USDOLLAR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Dollar::class, 'format'], 'argumentCount' => '2', ], 'VALUE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'VALUE'], 'argumentCount' => '1', ], 'VALUETOTEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'valueToText'], 'argumentCount' => '1,2', ], 'VAR' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VAR'], 'argumentCount' => '1+', ], 'VAR.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARP'], 'argumentCount' => '1+', ], 'VAR.S' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VAR'], 'argumentCount' => '1+', ], 'VARA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARA'], 'argumentCount' => '1+', ], 'VARP' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARP'], 'argumentCount' => '1+', ], 'VARPA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Variances::class, 'VARPA'], 'argumentCount' => '1+', ], 'VDB' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5-7', ], 'VLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\VLookup::class, 'lookup'], 'argumentCount' => '3,4', ], 'VSTACK' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'WEBSERVICE' => [ 'category' => Category::CATEGORY_WEB, 'functionCall' => [Web\Service::class, 'webService'], 'argumentCount' => '1', ], 'WEEKDAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Week::class, 'day'], 'argumentCount' => '1,2', ], 'WEEKNUM' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Week::class, 'number'], 'argumentCount' => '1,2', ], 'WEIBULL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'], 'argumentCount' => '4', ], 'WEIBULL.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'], 'argumentCount' => '4', ], 'WORKDAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\WorkDay::class, 'date'], 'argumentCount' => '2-3', ], 'WORKDAY.INTL' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-4', ], 'WRAPCOLS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-3', ], 'WRAPROWS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2-3', ], 'XIRR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'rate'], 'argumentCount' => '2,3', ], 'XLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3-6', ], 'XNPV' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'presentValue'], 'argumentCount' => '3', ], 'XMATCH' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2,3', ], 'XOR' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'logicalXor'], 'argumentCount' => '1+', ], 'YEAR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateParts::class, 'year'], 'argumentCount' => '1', ], 'YEARFRAC' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\YearFrac::class, 'fraction'], 'argumentCount' => '2,3', ], 'YIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '6,7', ], 'YIELDDISC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Yields::class, 'yieldDiscounted'], 'argumentCount' => '4,5', ], 'YIELDMAT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Yields::class, 'yieldAtMaturity'], 'argumentCount' => '5,6', ], 'ZTEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'], 'argumentCount' => '2-3', ], 'Z.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'], 'argumentCount' => '2-3', ], ]; /** * Internal functions used for special control purposes. * * @var array */ private static $controlFunctions = [ 'MKMATRIX' => [ 'argumentCount' => '*', 'functionCall' => [Internal\MakeMatrix::class, 'make'], ], 'NAME.ERROR' => [ 'argumentCount' => '*', 'functionCall' => [Functions::class, 'NAME'], ], 'WILDCARDMATCH' => [ 'argumentCount' => '2', 'functionCall' => [Internal\WildcardMatch::class, 'compare'], ], ]; public function __construct(?Spreadsheet $spreadsheet = null) { $this->spreadsheet = $spreadsheet; $this->cyclicReferenceStack = new CyclicReferenceStack(); $this->debugLog = new Logger($this->cyclicReferenceStack); $this->branchPruner = new BranchPruner($this->branchPruningEnabled); self::$referenceHelper = ReferenceHelper::getInstance(); } private static function loadLocales(): void { $localeFileDirectory = __DIR__ . '/locale/'; $localeFileNames = glob($localeFileDirectory . '*', GLOB_ONLYDIR) ?: []; foreach ($localeFileNames as $filename) { $filename = substr($filename, strlen($localeFileDirectory)); if ($filename != 'en') { self::$validLocaleLanguages[] = $filename; } } } /** * Get an instance of this class. * * @param ?Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object, * or NULL to create a standalone calculation engine */ public static function getInstance(?Spreadsheet $spreadsheet = null): self { if ($spreadsheet !== null) { $instance = $spreadsheet->getCalculationEngine(); if (isset($instance)) { return $instance; } } if (!isset(self::$instance) || (self::$instance === null)) { self::$instance = new self(); } return self::$instance; } /** * Flush the calculation cache for any existing instance of this class * but only if a Calculation instance exists. */ public function flushInstance(): void { $this->clearCalculationCache(); $this->branchPruner->clearBranchStore(); } /** * Get the Logger for this calculation engine instance. * * @return Logger */ public function getDebugLog() { return $this->debugLog; } /** * __clone implementation. Cloning should not be allowed in a Singleton! */ final public function __clone() { throw new Exception('Cloning the calculation engine is not allowed!'); } /** * Return the locale-specific translation of TRUE. * * @return string locale-specific translation of TRUE */ public static function getTRUE(): string { return self::$localeBoolean['TRUE']; } /** * Return the locale-specific translation of FALSE. * * @return string locale-specific translation of FALSE */ public static function getFALSE(): string { return self::$localeBoolean['FALSE']; } /** * Set the Array Return Type (Array or Value of first element in the array). * * @param string $returnType Array return type * * @return bool Success or failure */ public static function setArrayReturnType($returnType) { if ( ($returnType == self::RETURN_ARRAY_AS_VALUE) || ($returnType == self::RETURN_ARRAY_AS_ERROR) || ($returnType == self::RETURN_ARRAY_AS_ARRAY) ) { self::$returnArrayAsType = $returnType; return true; } return false; } /** * Return the Array Return Type (Array or Value of first element in the array). * * @return string $returnType Array return type */ public static function getArrayReturnType() { return self::$returnArrayAsType; } /** * Is calculation caching enabled? * * @return bool */ public function getCalculationCacheEnabled() { return $this->calculationCacheEnabled; } /** * Enable/disable calculation cache. * * @param bool $calculationCacheEnabled */ public function setCalculationCacheEnabled($calculationCacheEnabled): void { $this->calculationCacheEnabled = $calculationCacheEnabled; $this->clearCalculationCache(); } /** * Enable calculation cache. */ public function enableCalculationCache(): void { $this->setCalculationCacheEnabled(true); } /** * Disable calculation cache. */ public function disableCalculationCache(): void { $this->setCalculationCacheEnabled(false); } /** * Clear calculation cache. */ public function clearCalculationCache(): void { $this->calculationCache = []; } /** * Clear calculation cache for a specified worksheet. * * @param string $worksheetName */ public function clearCalculationCacheForWorksheet($worksheetName): void { if (isset($this->calculationCache[$worksheetName])) { unset($this->calculationCache[$worksheetName]); } } /** * Rename calculation cache for a specified worksheet. * * @param string $fromWorksheetName * @param string $toWorksheetName */ public function renameCalculationCacheForWorksheet($fromWorksheetName, $toWorksheetName): void { if (isset($this->calculationCache[$fromWorksheetName])) { $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName]; unset($this->calculationCache[$fromWorksheetName]); } } /** * Enable/disable calculation cache. * * @param mixed $enabled */ public function setBranchPruningEnabled($enabled): void { $this->branchPruningEnabled = $enabled; $this->branchPruner = new BranchPruner($this->branchPruningEnabled); } public function enableBranchPruning(): void { $this->setBranchPruningEnabled(true); } public function disableBranchPruning(): void { $this->setBranchPruningEnabled(false); } /** * Get the currently defined locale code. * * @return string */ public function getLocale() { return self::$localeLanguage; } private function getLocaleFile(string $localeDir, string $locale, string $language, string $file): string { $localeFileName = $localeDir . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . $file; if (!file_exists($localeFileName)) { // If there isn't a locale specific file, look for a language specific file $localeFileName = $localeDir . $language . DIRECTORY_SEPARATOR . $file; if (!file_exists($localeFileName)) { throw new Exception('Locale file not found'); } } return $localeFileName; } /** * Set the locale code. * * @param string $locale The locale to use for formula translation, eg: 'en_us' * * @return bool */ public function setLocale(string $locale) { // Identify our locale and language $language = $locale = strtolower($locale); if (strpos($locale, '_') !== false) { [$language] = explode('_', $locale); } if (count(self::$validLocaleLanguages) == 1) { self::loadLocales(); } // Test whether we have any language data for this language (any locale) if (in_array($language, self::$validLocaleLanguages, true)) { // initialise language/locale settings self::$localeFunctions = []; self::$localeArgumentSeparator = ','; self::$localeBoolean = ['TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL']; // Default is US English, if user isn't requesting US english, then read the necessary data from the locale files if ($locale !== 'en_us') { $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]); // Search for a file with a list of function names for locale try { $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions'); } catch (Exception $e) { return false; } // Retrieve the list of locale or language specific function names $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; foreach ($localeFunctions as $localeFunction) { [$localeFunction] = explode('##', $localeFunction); // Strip out comments if (strpos($localeFunction, '=') !== false) { [$fName, $lfName] = array_map('trim', explode('=', $localeFunction)); if ((substr($fName, 0, 1) === '*' || isset(self::$phpSpreadsheetFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) { self::$localeFunctions[$fName] = $lfName; } } } // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions if (isset(self::$localeFunctions['TRUE'])) { self::$localeBoolean['TRUE'] = self::$localeFunctions['TRUE']; } if (isset(self::$localeFunctions['FALSE'])) { self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE']; } try { $configFile = $this->getLocaleFile($localeDir, $locale, $language, 'config'); } catch (Exception $e) { return false; } $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; foreach ($localeSettings as $localeSetting) { [$localeSetting] = explode('##', $localeSetting); // Strip out comments if (strpos($localeSetting, '=') !== false) { [$settingName, $settingValue] = array_map('trim', explode('=', $localeSetting)); $settingName = strtoupper($settingName); if ($settingValue !== '') { switch ($settingName) { case 'ARGUMENTSEPARATOR': self::$localeArgumentSeparator = $settingValue; break; } } } } } self::$functionReplaceFromExcel = self::$functionReplaceToExcel = self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null; self::$localeLanguage = $locale; return true; } return false; } public static function translateSeparator( string $fromSeparator, string $toSeparator, string $formula, int &$inBracesLevel, string $openBrace = self::FORMULA_OPEN_FUNCTION_BRACE, string $closeBrace = self::FORMULA_CLOSE_FUNCTION_BRACE ): string { $strlen = mb_strlen($formula); for ($i = 0; $i < $strlen; ++$i) { $chr = mb_substr($formula, $i, 1); switch ($chr) { case $openBrace: ++$inBracesLevel; break; case $closeBrace: --$inBracesLevel; break; case $fromSeparator: if ($inBracesLevel > 0) { $formula = mb_substr($formula, 0, $i) . $toSeparator . mb_substr($formula, $i + 1); } } } return $formula; } private static function translateFormulaBlock( array $from, array $to, string $formula, int &$inFunctionBracesLevel, int &$inMatrixBracesLevel, string $fromSeparator, string $toSeparator ): string { // Function Names $formula = (string) preg_replace($from, $to, $formula); // Temporarily adjust matrix separators so that they won't be confused with function arguments $formula = self::translateSeparator(';', '|', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = self::translateSeparator(',', '!', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); // Function Argument Separators $formula = self::translateSeparator($fromSeparator, $toSeparator, $formula, $inFunctionBracesLevel); // Restore matrix separators $formula = self::translateSeparator('|', ';', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = self::translateSeparator('!', ',', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); return $formula; } private static function translateFormula(array $from, array $to, string $formula, string $fromSeparator, string $toSeparator): string { // Convert any Excel function names and constant names to the required language; // and adjust function argument separators if (self::$localeLanguage !== 'en_us') { $inFunctionBracesLevel = 0; $inMatrixBracesLevel = 0; // If there is the possibility of separators within a quoted string, then we treat them as literals if (strpos($formula, self::FORMULA_STRING_QUOTE) !== false) { // So instead we skip replacing in any quoted strings by only replacing in every other array element // after we've exploded the formula $temp = explode(self::FORMULA_STRING_QUOTE, $formula); $notWithinQuotes = false; foreach ($temp as &$value) { // Only adjust in alternating array entries $notWithinQuotes = $notWithinQuotes === false; if ($notWithinQuotes === true) { $value = self::translateFormulaBlock($from, $to, $value, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator); } } unset($value); // Then rebuild the formula string $formula = implode(self::FORMULA_STRING_QUOTE, $temp); } else { // If there's no quoted strings, then we do a simple count/replace $formula = self::translateFormulaBlock($from, $to, $formula, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator); } } return $formula; } /** @var ?array */ private static $functionReplaceFromExcel; /** @var ?array */ private static $functionReplaceToLocale; /** * @param string $formula * * @return string */ public function _translateFormulaToLocale($formula) { // Build list of function names and constants for translation if (self::$functionReplaceFromExcel === null) { self::$functionReplaceFromExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelFunctionName, '/') . '([\s]*\()/ui'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui'; } } if (self::$functionReplaceToLocale === null) { self::$functionReplaceToLocale = []; foreach (self::$localeFunctions as $localeFunctionName) { self::$functionReplaceToLocale[] = '$1' . trim($localeFunctionName) . '$2'; } foreach (self::$localeBoolean as $localeBoolean) { self::$functionReplaceToLocale[] = '$1' . trim($localeBoolean) . '$2'; } } return self::translateFormula( self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$localeArgumentSeparator ); } /** @var ?array */ private static $functionReplaceFromLocale; /** @var ?array */ private static $functionReplaceToExcel; /** * @param string $formula * * @return string */ public function _translateFormulaToEnglish($formula) { if (self::$functionReplaceFromLocale === null) { self::$functionReplaceFromLocale = []; foreach (self::$localeFunctions as $localeFunctionName) { self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($localeFunctionName, '/') . '([\s]*\()/ui'; } foreach (self::$localeBoolean as $excelBoolean) { self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui'; } } if (self::$functionReplaceToExcel === null) { self::$functionReplaceToExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { self::$functionReplaceToExcel[] = '$1' . trim($excelFunctionName) . '$2'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { self::$functionReplaceToExcel[] = '$1' . trim($excelBoolean) . '$2'; } } return self::translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$localeArgumentSeparator, ','); } /** * @param string $function * * @return string */ public static function localeFunc($function) { if (self::$localeLanguage !== 'en_us') { $functionName = trim($function, '('); if (isset(self::$localeFunctions[$functionName])) { $brace = ($functionName != $function); $function = self::$localeFunctions[$functionName]; if ($brace) { $function .= '('; } } } return $function; } /** * Wrap string values in quotes. * * @param mixed $value * * @return mixed */ public static function wrapResult($value) { if (is_string($value)) { // Error values cannot be "wrapped" if (preg_match('/^' . self::CALCULATION_REGEXP_ERROR . '$/i', $value, $match)) { // Return Excel errors "as is" return $value; } // Return strings wrapped in quotes return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE; } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { // Convert numeric errors to NaN error return Information\ExcelError::NAN(); } return $value; } /** * Remove quotes used as a wrapper to identify string values. * * @param mixed $value * * @return mixed */ public static function unwrapResult($value) { if (is_string($value)) { if ((isset($value[0])) && ($value[0] == self::FORMULA_STRING_QUOTE) && (substr($value, -1) == self::FORMULA_STRING_QUOTE)) { return substr($value, 1, -1); } // Convert numeric errors to NAN error } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { return Information\ExcelError::NAN(); } return $value; } /** * Calculate cell value (using formula from a cell ID) * Retained for backward compatibility. * * @param Cell $cell Cell to calculate * * @return mixed */ public function calculate(?Cell $cell = null) { try { return $this->calculateCellValue($cell); } catch (\Exception $e) { throw new Exception($e->getMessage()); } } /** * Calculate the value of a cell formula. * * @param Cell $cell Cell to calculate * @param bool $resetLog Flag indicating whether the debug log should be reset or not * * @return mixed */ public function calculateCellValue(?Cell $cell = null, $resetLog = true) { if ($cell === null) { return null; } $returnArrayAsType = self::$returnArrayAsType; if ($resetLog) { // Initialise the logging settings if requested $this->formulaError = null; $this->debugLog->clearLog(); $this->cyclicReferenceStack->clear(); $this->cyclicFormulaCounter = 1; self::$returnArrayAsType = self::RETURN_ARRAY_AS_ARRAY; } // Execute the calculation for the cell formula $this->cellStack[] = [ 'sheet' => $cell->getWorksheet()->getTitle(), 'cell' => $cell->getCoordinate(), ]; $cellAddressAttempted = false; $cellAddress = null; try { $result = self::unwrapResult($this->_calculateFormulaValue($cell->getValue(), $cell->getCoordinate(), $cell)); if ($this->spreadsheet === null) { throw new Exception('null spreadsheet in calculateCellValue'); } $cellAddressAttempted = true; $cellAddress = array_pop($this->cellStack); if ($cellAddress === null) { throw new Exception('null cellAddress in calculateCellValue'); } $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']); if ($testSheet === null) { throw new Exception('worksheet not found in calculateCellValue'); } $testSheet->getCell($cellAddress['cell']); } catch (\Exception $e) { if (!$cellAddressAttempted) { $cellAddress = array_pop($this->cellStack); } if ($this->spreadsheet !== null && is_array($cellAddress) && array_key_exists('sheet', $cellAddress)) { $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']); if ($testSheet !== null && array_key_exists('cell', $cellAddress)) { $testSheet->getCell($cellAddress['cell']); } } throw new Exception($e->getMessage(), $e->getCode(), $e); } if ((is_array($result)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) { self::$returnArrayAsType = $returnArrayAsType; $testResult = Functions::flattenArray($result); if (self::$returnArrayAsType == self::RETURN_ARRAY_AS_ERROR) { return Information\ExcelError::VALUE(); } // If there's only a single cell in the array, then we allow it if (count($testResult) != 1) { // If keys are numeric, then it's a matrix result rather than a cell range result, so we permit it $r = array_keys($result); $r = array_shift($r); if (!is_numeric($r)) { return Information\ExcelError::VALUE(); } if (is_array($result[$r])) { $c = array_keys($result[$r]); $c = array_shift($c); if (!is_numeric($c)) { return Information\ExcelError::VALUE(); } } } $result = array_shift($testResult); } self::$returnArrayAsType = $returnArrayAsType; if ($result === null && $cell->getWorksheet()->getSheetView()->getShowZeros()) { return 0; } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) { return Information\ExcelError::NAN(); } return $result; } /** * Validate and parse a formula string. * * @param string $formula Formula to parse * * @return array|bool */ public function parseFormula($formula) { // Basic validation that this is indeed a formula // We return an empty array if not $formula = trim($formula); if ((!isset($formula[0])) || ($formula[0] != '=')) { return []; } $formula = ltrim(substr($formula, 1)); if (!isset($formula[0])) { return []; } // Parse the formula and return the token stack return $this->internalParseFormula($formula); } /** * Calculate the value of a formula. * * @param string $formula Formula to parse * @param string $cellID Address of the cell to calculate * @param Cell $cell Cell to calculate * * @return mixed */ public function calculateFormula($formula, $cellID = null, ?Cell $cell = null) { // Initialise the logging settings $this->formulaError = null; $this->debugLog->clearLog(); $this->cyclicReferenceStack->clear(); $resetCache = $this->getCalculationCacheEnabled(); if ($this->spreadsheet !== null && $cellID === null && $cell === null) { $cellID = 'A1'; $cell = $this->spreadsheet->getActiveSheet()->getCell($cellID); } else { // Disable calculation cacheing because it only applies to cell calculations, not straight formulae // But don't actually flush any cache $this->calculationCacheEnabled = false; } // Execute the calculation try { $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell)); } catch (\Exception $e) { throw new Exception($e->getMessage()); } if ($this->spreadsheet === null) { // Reset calculation cacheing to its previous state $this->calculationCacheEnabled = $resetCache; } return $result; } /** * @param mixed $cellValue */ public function getValueFromCache(string $cellReference, &$cellValue): bool { $this->debugLog->writeDebugLog('Testing cache value for cell %s', $cellReference); // Is calculation cacheing enabled? // If so, is the required value present in calculation cache? if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) { $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference); // Return the cached result $cellValue = $this->calculationCache[$cellReference]; return true; } return false; } /** * @param string $cellReference * @param mixed $cellValue */ public function saveValueToCache($cellReference, $cellValue): void { if ($this->calculationCacheEnabled) { $this->calculationCache[$cellReference] = $cellValue; } } /** * Parse a cell formula and calculate its value. * * @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 * * @return mixed */ public function _calculateFormulaValue($formula, $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false) { $cellValue = null; // Quote-Prefixed cell values cannot be formulae, but are treated as strings if ($cell !== null && $ignoreQuotePrefix === false && $cell->getStyle()->getQuotePrefix() === true) { return self::wrapResult((string) $formula); } if (preg_match('/^=\s*cmd\s*\|/miu', $formula) !== 0) { return self::wrapResult($formula); } // Basic validation that this is indeed a formula // We simply return the cell value if not $formula = trim($formula); if ($formula[0] != '=') { return self::wrapResult($formula); } $formula = ltrim(substr($formula, 1)); if (!isset($formula[0])) { return self::wrapResult($formula); } $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null; $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk"; $wsCellReference = $wsTitle . '!' . $cellID; if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) { return $cellValue; } $this->debugLog->writeDebugLog('Evaluating formula for cell %s', $wsCellReference); if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) { if ($this->cyclicFormulaCount <= 0) { $this->cyclicFormulaCell = ''; return $this->raiseFormulaError('Cyclic Reference in Formula'); } elseif ($this->cyclicFormulaCell === $wsCellReference) { ++$this->cyclicFormulaCounter; if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { $this->cyclicFormulaCell = ''; return $cellValue; } } elseif ($this->cyclicFormulaCell == '') { if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { return $cellValue; } $this->cyclicFormulaCell = $wsCellReference; } } $this->debugLog->writeDebugLog('Formula for cell %s is %s', $wsCellReference, $formula); // Parse the formula onto the token stack and calculate the value $this->cyclicReferenceStack->push($wsCellReference); $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $cell), $cellID, $cell); $this->cyclicReferenceStack->pop(); // Save to calculation cache if ($cellID !== null) { $this->saveValueToCache($wsCellReference, $cellValue); } // Return the calculated value return $cellValue; } /** * Ensure that paired matrix operands are both matrices and of the same size. * * @param mixed $operand1 First matrix operand * @param mixed $operand2 Second matrix operand * @param int $resize Flag indicating whether the matrices should be resized to match * and (if so), whether the smaller dimension should grow or the * larger should shrink. * 0 = no resize * 1 = shrink to fit * 2 = extend to fit * * @return array */ private static function checkMatrixOperands(&$operand1, &$operand2, $resize = 1) { // Examine each of the two operands, and turn them into an array if they aren't one already // Note that this function should only be called if one or both of the operand is already an array if (!is_array($operand1)) { [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand2); $operand1 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand1)); $resize = 0; } elseif (!is_array($operand2)) { [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand1); $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2)); $resize = 0; } [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1); [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2); if (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) { $resize = 1; } if ($resize == 2) { // Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger self::resizeMatricesExtend($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); } elseif ($resize == 1) { // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); } return [$matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns]; } /** * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0. * * @param array $matrix matrix operand * * @return int[] An array comprising the number of rows, and number of columns */ public static function getMatrixDimensions(array &$matrix) { $matrixRows = count($matrix); $matrixColumns = 0; foreach ($matrix as $rowKey => $rowValue) { if (!is_array($rowValue)) { $matrix[$rowKey] = [$rowValue]; $matrixColumns = max(1, $matrixColumns); } else { $matrix[$rowKey] = array_values($rowValue); $matrixColumns = max(count($rowValue), $matrixColumns); } } $matrix = array_values($matrix); return [$matrixRows, $matrixColumns]; } /** * Ensure that paired matrix operands are both matrices of the same size. * * @param mixed $matrix1 First matrix operand * @param mixed $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand * @param int $matrix2Columns Column size of second matrix operand */ private static function resizeMatricesShrink(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns): void { if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { if ($matrix2Rows < $matrix1Rows) { for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) { unset($matrix1[$i]); } } if ($matrix2Columns < $matrix1Columns) { for ($i = 0; $i < $matrix1Rows; ++$i) { for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { unset($matrix1[$i][$j]); } } } } if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { if ($matrix1Rows < $matrix2Rows) { for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) { unset($matrix2[$i]); } } if ($matrix1Columns < $matrix2Columns) { for ($i = 0; $i < $matrix2Rows; ++$i) { for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { unset($matrix2[$i][$j]); } } } } } /** * Ensure that paired matrix operands are both matrices of the same size. * * @param mixed $matrix1 First matrix operand * @param mixed $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand * @param int $matrix2Columns Column size of second matrix operand */ private static function resizeMatricesExtend(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns): void { if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { if ($matrix2Columns < $matrix1Columns) { for ($i = 0; $i < $matrix2Rows; ++$i) { $x = $matrix2[$i][$matrix2Columns - 1]; for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { $matrix2[$i][$j] = $x; } } } if ($matrix2Rows < $matrix1Rows) { $x = $matrix2[$matrix2Rows - 1]; for ($i = 0; $i < $matrix1Rows; ++$i) { $matrix2[$i] = $x; } } } if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { if ($matrix1Columns < $matrix2Columns) { for ($i = 0; $i < $matrix1Rows; ++$i) { $x = $matrix1[$i][$matrix1Columns - 1]; for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { $matrix1[$i][$j] = $x; } } } if ($matrix1Rows < $matrix2Rows) { $x = $matrix1[$matrix1Rows - 1]; for ($i = 0; $i < $matrix2Rows; ++$i) { $matrix1[$i] = $x; } } } } /** * Format details of an operand for display in the log (based on operand type). * * @param mixed $value First matrix operand * * @return mixed */ private function showValue($value) { if ($this->debugLog->getWriteDebugLog()) { $testArray = Functions::flattenArray($value); if (count($testArray) == 1) { $value = array_pop($testArray); } if (is_array($value)) { $returnMatrix = []; $pad = $rpad = ', '; foreach ($value as $row) { if (is_array($row)) { $returnMatrix[] = implode($pad, array_map([$this, 'showValue'], $row)); $rpad = '; '; } else { $returnMatrix[] = $this->showValue($row); } } return '{ ' . implode($rpad, $returnMatrix) . ' }'; } elseif (is_string($value) && (trim($value, self::FORMULA_STRING_QUOTE) == $value)) { return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE; } elseif (is_bool($value)) { return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; } elseif ($value === null) { return self::$localeBoolean['NULL']; } } return Functions::flattenSingleValue($value); } /** * Format type and details of an operand for display in the log (based on operand type). * * @param mixed $value First matrix operand * * @return null|string */ private function showTypeDetails($value) { if ($this->debugLog->getWriteDebugLog()) { $testArray = Functions::flattenArray($value); if (count($testArray) == 1) { $value = array_pop($testArray); } if ($value === null) { return 'a NULL value'; } elseif (is_float($value)) { $typeString = 'a floating point number'; } elseif (is_int($value)) { $typeString = 'an integer number'; } elseif (is_bool($value)) { $typeString = 'a boolean'; } elseif (is_array($value)) { $typeString = 'a matrix'; } else { if ($value == '') { return 'an empty string'; } elseif ($value[0] == '#') { return 'a ' . $value . ' error'; } $typeString = 'a string'; } return $typeString . ' with a value of ' . $this->showValue($value); } return null; } /** * @param string $formula * * @return false|string False indicates an error */ private function convertMatrixReferences($formula) { static $matrixReplaceFrom = [self::FORMULA_OPEN_MATRIX_BRACE, ';', self::FORMULA_CLOSE_MATRIX_BRACE]; static $matrixReplaceTo = ['MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))']; // Convert any Excel matrix references to the MKMATRIX() function if (strpos($formula, self::FORMULA_OPEN_MATRIX_BRACE) !== false) { // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators if (strpos($formula, self::FORMULA_STRING_QUOTE) !== false) { // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded // the formula $temp = explode(self::FORMULA_STRING_QUOTE, $formula); // Open and Closed counts used for trapping mismatched braces in the formula $openCount = $closeCount = 0; $notWithinQuotes = false; foreach ($temp as &$value) { // Only count/replace in alternating array entries $notWithinQuotes = $notWithinQuotes === false; if ($notWithinQuotes === true) { $openCount += substr_count($value, self::FORMULA_OPEN_MATRIX_BRACE); $closeCount += substr_count($value, self::FORMULA_CLOSE_MATRIX_BRACE); $value = str_replace($matrixReplaceFrom, $matrixReplaceTo, $value); } } unset($value); // Then rebuild the formula string $formula = implode(self::FORMULA_STRING_QUOTE, $temp); } else { // If there's no quoted strings, then we do a simple count/replace $openCount = substr_count($formula, self::FORMULA_OPEN_MATRIX_BRACE); $closeCount = substr_count($formula, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = str_replace($matrixReplaceFrom, $matrixReplaceTo, $formula); } // Trap for mismatched braces and trigger an appropriate error if ($openCount < $closeCount) { if ($openCount > 0) { return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '}'"); } return $this->raiseFormulaError("Formula Error: Unexpected '}' encountered"); } elseif ($openCount > $closeCount) { if ($closeCount > 0) { return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '{'"); } return $this->raiseFormulaError("Formula Error: Unexpected '{' encountered"); } } return $formula; } /** * Binary Operators. * These operators always work on two values. * Array key is the operator, the value indicates whether this is a left or right associative operator. * * @var array */ private static $operatorAssociativity = [ '^' => 0, // Exponentiation '*' => 0, '/' => 0, // Multiplication and Division '+' => 0, '-' => 0, // Addition and Subtraction '&' => 0, // Concatenation '∪' => 0, '∩' => 0, ':' => 0, // Union, Intersect and Range '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, // Comparison ]; /** * Comparison (Boolean) Operators. * These operators work on two values, but always return a boolean result. * * @var array */ private static $comparisonOperators = ['>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true]; /** * Operator Precedence. * This list includes all valid operators, whether binary (including boolean) or unary (such as %). * Array key is the operator, the value is its precedence. * * @var array */ private static $operatorPrecedence = [ ':' => 9, // Range '∩' => 8, // Intersect '∪' => 7, // Union '~' => 6, // Negation '%' => 5, // Percentage '^' => 4, // Exponentiation '*' => 3, '/' => 3, // Multiplication and Division '+' => 2, '-' => 2, // Addition and Subtraction '&' => 1, // Concatenation '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, // Comparison ]; // Convert infix to postfix notation /** * @param string $formula * * @return array<int, mixed>|false */ private function internalParseFormula($formula, ?Cell $cell = null) { if (($formula = $this->convertMatrixReferences(trim($formula))) === false) { return false; } // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet), // so we store the parent worksheet so that we can re-attach it when necessary $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null; $regexpMatchString = '/^((?<string>' . self::CALCULATION_REGEXP_STRING . ')|(?<function>' . self::CALCULATION_REGEXP_FUNCTION . ')|(?<cellRef>' . self::CALCULATION_REGEXP_CELLREF . ')|(?<colRange>' . self::CALCULATION_REGEXP_COLUMN_RANGE . ')|(?<rowRange>' . self::CALCULATION_REGEXP_ROW_RANGE . ')|(?<number>' . self::CALCULATION_REGEXP_NUMBER . ')|(?<openBrace>' . self::CALCULATION_REGEXP_OPENBRACE . ')|(?<structuredReference>' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . ')|(?<definedName>' . self::CALCULATION_REGEXP_DEFINEDNAME . ')|(?<error>' . self::CALCULATION_REGEXP_ERROR . '))/sui'; // Start with initialisation $index = 0; $stack = new Stack($this->branchPruner); $output = []; $expectingOperator = false; // We use this test in syntax-checking the expression to determine when a // - is a negation or + is a positive operator rather than an operation $expectingOperand = false; // We use this test in syntax-checking the expression to determine whether an operand // should be null in a function call // The guts of the lexical parser // Loop through the formula extracting each operator and operand in turn while (true) { // Branch pruning: we adapt the output item to the context (it will // be used to limit its computation) $this->branchPruner->initialiseForLoop(); $opCharacter = $formula[$index]; // Get the first character of the value at the current index position // Check for two-character operators (e.g. >=, <=, <>) if ((isset(self::$comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset(self::$comparisonOperators[$formula[$index + 1]]))) { $opCharacter .= $formula[++$index]; } // Find out if we're currently at the beginning of a number, variable, cell/row/column reference, // function, defined name, structured reference, parenthesis, error or operand $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match); $expectingOperatorCopy = $expectingOperator; if ($opCharacter === '-' && !$expectingOperator) { // Is it a negation instead of a minus? // Put a negation on the stack $stack->push('Unary Operator', '~'); ++$index; // and drop the negation symbol } elseif ($opCharacter === '%' && $expectingOperator) { // Put a percentage on the stack $stack->push('Unary Operator', '%'); ++$index; } elseif ($opCharacter === '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded? ++$index; // Drop the redundant plus symbol } elseif ((($opCharacter === '~') || ($opCharacter === '∩') || ($opCharacter === '∪')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde, union or intersect because they are legal return $this->raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression } elseif ((isset(self::CALCULATION_OPERATORS[$opCharacter]) || $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack? while ( $stack->count() > 0 && ($o2 = $stack->last()) && isset(self::CALCULATION_OPERATORS[$o2['value']]) && @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']]) ) { $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output } // Finally put our current operator onto the stack $stack->push('Binary Operator', $opCharacter); ++$index; $expectingOperator = false; } elseif ($opCharacter === ')' && $expectingOperator) { // Are we expecting to close a parenthesis? $expectingOperand = false; while (($o2 = $stack->pop()) && $o2['value'] !== '(') { // Pop off the stack back to the last ( $output[] = $o2; } $d = $stack->last(2); // Branch pruning we decrease the depth whether is it a function // call or a parenthesis $this->branchPruner->decrementDepth(); if (is_array($d) && preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'], $matches)) { // Did this parenthesis just close a function? try { $this->branchPruner->closingBrace($d['value']); } catch (Exception $e) { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } $functionName = $matches[1]; // Get the function name $d = $stack->pop(); $argumentCount = $d['value'] ?? 0; // See how many arguments there were (argument count is the next value stored on the stack) $output[] = $d; // Dump the argument count on the output $output[] = $stack->pop(); // Pop the function and push onto the output if (isset(self::$controlFunctions[$functionName])) { $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount']; // Scrutinizer says functionCall is unused after this assignment. // It might be right, but I'm too lazy to confirm. $functionCall = self::$controlFunctions[$functionName]['functionCall']; self::doNothing($functionCall); } elseif (isset(self::$phpSpreadsheetFunctions[$functionName])) { $expectedArgumentCount = self::$phpSpreadsheetFunctions[$functionName]['argumentCount']; $functionCall = self::$phpSpreadsheetFunctions[$functionName]['functionCall']; self::doNothing($functionCall); } else { // did we somehow push a non-function on the stack? this should never happen return $this->raiseFormulaError('Formula Error: Internal error, non-function on stack'); } // Check the argument count $argumentCountError = false; $expectedArgumentCountString = null; if (is_numeric($expectedArgumentCount)) { if ($expectedArgumentCount < 0) { if ($argumentCount > abs($expectedArgumentCount)) { $argumentCountError = true; $expectedArgumentCountString = 'no more than ' . abs($expectedArgumentCount); } } else { if ($argumentCount != $expectedArgumentCount) { $argumentCountError = true; $expectedArgumentCountString = $expectedArgumentCount; } } } elseif ($expectedArgumentCount != '*') { $isOperandOrFunction = preg_match('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch); self::doNothing($isOperandOrFunction); switch ($argMatch[2] ?? '') { case '+': if ($argumentCount < $argMatch[1]) { $argumentCountError = true; $expectedArgumentCountString = $argMatch[1] . ' or more '; } break; case '-': if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) { $argumentCountError = true; $expectedArgumentCountString = 'between ' . $argMatch[1] . ' and ' . $argMatch[3]; } break; case ',': if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) { $argumentCountError = true; $expectedArgumentCountString = 'either ' . $argMatch[1] . ' or ' . $argMatch[3]; } break; } } if ($argumentCountError) { return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, " . $expectedArgumentCountString . ' expected'); } } ++$index; } elseif ($opCharacter === ',') { // Is this the separator for function arguments? try { $this->branchPruner->argumentSeparator(); } catch (Exception $e) { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } while (($o2 = $stack->pop()) && $o2['value'] !== '(') { // Pop off the stack back to the last ( $output[] = $o2; // pop the argument expression stuff and push onto the output } // If we've a comma when we're expecting an operand, then what we actually have is a null operand; // so push a null onto the stack if (($expectingOperand) || (!$expectingOperator)) { $output[] = ['type' => 'Empty Argument', 'value' => self::$excelConstants['NULL'], 'reference' => 'NULL']; } // make sure there was a function $d = $stack->last(2); if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'] ?? '', $matches)) { // Can we inject a dummy function at this point so that the braces at least have some context // because at least the braces are paired up (at this stage in the formula) // MS Excel allows this if the content is cell references; but doesn't allow actual values, // but at this point, we can't differentiate (so allow both) return $this->raiseFormulaError('Formula Error: Unexpected ,'); } /** @var array $d */ $d = $stack->pop(); ++$d['value']; // increment the argument count $stack->pushStackItem($d); $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again $expectingOperator = false; $expectingOperand = true; ++$index; } elseif ($opCharacter === '(' && !$expectingOperator) { // Branch pruning: we go deeper $this->branchPruner->incrementDepth(); $stack->push('Brace', '(', null); ++$index; } elseif ($isOperandOrFunction && !$expectingOperatorCopy) { // do we now have a function/variable/number? $expectingOperator = true; $expectingOperand = false; $val = $match[1]; $length = strlen($val); if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) { $val = (string) preg_replace('/\s/u', '', $val); if (isset(self::$phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) { // it's a function $valToUpper = strtoupper($val); } else { $valToUpper = 'NAME.ERROR('; } // here $matches[1] will contain values like "IF" // and $val "IF(" $this->branchPruner->functionCall($valToUpper); $stack->push('Function', $valToUpper); // tests if the function is closed right after opening $ax = preg_match('/^\s*\)/u', substr($formula, $index + $length)); if ($ax) { $stack->push('Operand Count for Function ' . $valToUpper . ')', 0); $expectingOperator = true; } else { $stack->push('Operand Count for Function ' . $valToUpper . ')', 1); $expectingOperator = false; } $stack->push('Brace', '('); } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $val, $matches)) { // Watch for this case-change when modifying to allow cell references in different worksheets... // Should only be applied to the actual cell column, not the worksheet name // If the last entry on the stack was a : operator, then we have a cell range reference $testPrevOp = $stack->last(1); if ($testPrevOp !== null && $testPrevOp['value'] === ':') { // If we have a worksheet reference, then we're playing with a 3D reference if ($matches[2] === '') { // Otherwise, we 'inherit' the worksheet reference from the start cell reference // The start of the cell range reference should be the last entry in $output $rangeStartCellRef = $output[count($output) - 1]['value'] ?? ''; if ($rangeStartCellRef === ':') { // Do we have chained range operators? $rangeStartCellRef = $output[count($output) - 2]['value'] ?? ''; } preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches); if (array_key_exists(2, $rangeStartMatches)) { if ($rangeStartMatches[2] > '') { $val = $rangeStartMatches[2] . '!' . $val; } } else { $val = Information\ExcelError::REF(); } } else { $rangeStartCellRef = $output[count($output) - 1]['value'] ?? ''; if ($rangeStartCellRef === ':') { // Do we have chained range operators? $rangeStartCellRef = $output[count($output) - 2]['value'] ?? ''; } preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches); if ($rangeStartMatches[2] !== $matches[2]) { return $this->raiseFormulaError('3D Range references are not yet supported'); } } } elseif (strpos($val, '!') === false && $pCellParent !== null) { $worksheet = $pCellParent->getTitle(); $val = "'{$worksheet}'!{$val}"; } // unescape any apostrophes or double quotes in worksheet name $val = str_replace(["''", '""'], ["'", '"'], $val); $outputItem = $stack->getStackItem('Cell Reference', $val, $val); $output[] = $outputItem; } elseif (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '$/miu', $val, $matches)) { try { $structuredReference = Operands\StructuredReference::fromParser($formula, $index, $matches); } catch (Exception $e) { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } $val = $structuredReference->value(); $length = strlen($val); $outputItem = $stack->getStackItem(Operands\StructuredReference::NAME, $structuredReference, null); $output[] = $outputItem; $expectingOperator = true; } else { // it's a variable, constant, string, number or boolean $localeConstant = false; $stackItemType = 'Value'; $stackItemReference = null; // If the last entry on the stack was a : operator, then we may have a row or column range reference $testPrevOp = $stack->last(1); if ($testPrevOp !== null && $testPrevOp['value'] === ':') { $stackItemType = 'Cell Reference'; if ( !is_numeric($val) && ((ctype_alpha($val) === false || strlen($val) > 3)) && (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $val) !== false) && ($this->spreadsheet === null || $this->spreadsheet->getNamedRange($val) !== null) ) { $namedRange = ($this->spreadsheet === null) ? null : $this->spreadsheet->getNamedRange($val); if ($namedRange !== null) { $stackItemType = 'Defined Name'; $address = str_replace('$', '', $namedRange->getValue()); $stackItemReference = $val; if (strpos($address, ':') !== false) { // We'll need to manipulate the stack for an actual named range rather than a named cell $fromTo = explode(':', $address); $to = array_pop($fromTo); foreach ($fromTo as $from) { $output[] = $stack->getStackItem($stackItemType, $from, $stackItemReference); $output[] = $stack->getStackItem('Binary Operator', ':'); } $address = $to; } $val = $address; } } elseif ($val === Information\ExcelError::REF()) { $stackItemReference = $val; } else { $startRowColRef = $output[count($output) - 1]['value'] ?? ''; [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true); $rangeSheetRef = $rangeWS1; if ($rangeWS1 !== '') { $rangeWS1 .= '!'; } $rangeSheetRef = trim($rangeSheetRef, "'"); [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true); if ($rangeWS2 !== '') { $rangeWS2 .= '!'; } else { $rangeWS2 = $rangeWS1; } $refSheet = $pCellParent; if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) { $refSheet = $pCellParent->getParentOrThrow()->getSheetByName($rangeSheetRef); } if (ctype_digit($val) && $val <= 1048576) { // Row range $stackItemType = 'Row Reference'; /** @var int $valx */ $valx = $val; $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($valx) : AddressRange::MAX_COLUMN; // Max 16,384 columns for Excel2007 $val = "{$rangeWS2}{$endRowColRef}{$val}"; } elseif (ctype_alpha($val) && strlen($val) <= 3) { // Column range $stackItemType = 'Column Reference'; $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow($val) : AddressRange::MAX_ROW; // Max 1,048,576 rows for Excel2007 $val = "{$rangeWS2}{$val}{$endRowColRef}"; } $stackItemReference = $val; } } elseif ($opCharacter === self::FORMULA_STRING_QUOTE) { // UnEscape any quotes within the string $val = self::wrapResult(str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($val))); } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) { $stackItemType = 'Constant'; $excelConstant = trim(strtoupper($val)); $val = self::$excelConstants[$excelConstant]; $stackItemReference = $excelConstant; } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) { $stackItemType = 'Constant'; $val = self::$excelConstants[$localeConstant]; $stackItemReference = $localeConstant; } elseif ( preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference) ) { $val = $rowRangeReference[1]; $length = strlen($rowRangeReference[1]); $stackItemType = 'Row Reference'; // unescape any apostrophes or double quotes in worksheet name $val = str_replace(["''", '""'], ["'", '"'], $val); $column = 'A'; if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) { $column = $pCellParent->getHighestDataColumn($val); } $val = "{$rowRangeReference[2]}{$column}{$rowRangeReference[7]}"; $stackItemReference = $val; } elseif ( preg_match('/^' . self::CALCULATION_REGEXP_COLUMN_RANGE . '/miu', substr($formula, $index), $columnRangeReference) ) { $val = $columnRangeReference[1]; $length = strlen($val); $stackItemType = 'Column Reference'; // unescape any apostrophes or double quotes in worksheet name $val = str_replace(["''", '""'], ["'", '"'], $val); $row = '1'; if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) { $row = $pCellParent->getHighestDataRow($val); } $val = "{$val}{$row}"; $stackItemReference = $val; } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', $val, $match)) { $stackItemType = 'Defined Name'; $stackItemReference = $val; } elseif (is_numeric($val)) { if ((strpos((string) $val, '.') !== false) || (stripos((string) $val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) { $val = (float) $val; } else { $val = (int) $val; } } $details = $stack->getStackItem($stackItemType, $val, $stackItemReference); if ($localeConstant) { $details['localeValue'] = $localeConstant; } $output[] = $details; } $index += $length; } elseif ($opCharacter === '$') { // absolute row or column range ++$index; } elseif ($opCharacter === ')') { // miscellaneous error checking if ($expectingOperand) { $output[] = ['type' => 'Empty Argument', 'value' => self::$excelConstants['NULL'], 'reference' => 'NULL']; $expectingOperand = false; $expectingOperator = true; } else { return $this->raiseFormulaError("Formula Error: Unexpected ')'"); } } elseif (isset(self::CALCULATION_OPERATORS[$opCharacter]) && !$expectingOperator) { return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'"); } else { // I don't even want to know what you did to get here return $this->raiseFormulaError('Formula Error: An unexpected error occurred'); } // Test for end of formula string if ($index == strlen($formula)) { // Did we end with an operator?. // Only valid for the % unary operator if ((isset(self::CALCULATION_OPERATORS[$opCharacter])) && ($opCharacter != '%')) { return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands"); } break; } // Ignore white space while (($formula[$index] === "\n") || ($formula[$index] === "\r")) { ++$index; } if ($formula[$index] === ' ') { while ($formula[$index] === ' ') { ++$index; } // If we're expecting an operator, but only have a space between the previous and next operands (and both are // Cell References, Defined Names or Structured References) then we have an INTERSECTION operator $countOutputMinus1 = count($output) - 1; if ( ($expectingOperator) && array_key_exists($countOutputMinus1, $output) && is_array($output[$countOutputMinus1]) && array_key_exists('type', $output[$countOutputMinus1]) && ( (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/miu', substr($formula, $index), $match)) && ($output[$countOutputMinus1]['type'] === 'Cell Reference') || (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match)) && ($output[$countOutputMinus1]['type'] === 'Defined Name' || $output[$countOutputMinus1]['type'] === 'Value') || (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '.*/miu', substr($formula, $index), $match)) && ($output[$countOutputMinus1]['type'] === Operands\StructuredReference::NAME || $output[$countOutputMinus1]['type'] === 'Value') ) ) { while ( $stack->count() > 0 && ($o2 = $stack->last()) && isset(self::CALCULATION_OPERATORS[$o2['value']]) && @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']]) ) { $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output } $stack->push('Binary Operator', '∩'); // Put an Intersect Operator on the stack $expectingOperator = false; } } } while (($op = $stack->pop()) !== null) { // pop everything off the stack and push onto output if ((is_array($op) && $op['value'] == '(')) { return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced } $output[] = $op; } return $output; } /** * @param array $operandData * * @return mixed */ private static function dataTestReference(&$operandData) { $operand = $operandData['value']; if (($operandData['reference'] === null) && (is_array($operand))) { $rKeys = array_keys($operand); $rowKey = array_shift($rKeys); if (is_array($operand[$rowKey]) === false) { $operandData['value'] = $operand[$rowKey]; return $operand[$rowKey]; } $cKeys = array_keys(array_keys($operand[$rowKey])); $colKey = array_shift($cKeys); if (ctype_upper("$colKey")) { $operandData['reference'] = $colKey . $rowKey; } } return $operand; } /** * @param mixed $tokens * @param null|string $cellID * * @return array<int, mixed>|false */ private function processTokenStack($tokens, $cellID = null, ?Cell $cell = null) { if ($tokens === false) { return false; } // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection), // so we store the parent cell collection so that we can re-attach it when necessary $pCellWorksheet = ($cell !== null) ? $cell->getWorksheet() : null; $pCellParent = ($cell !== null) ? $cell->getParent() : null; $stack = new Stack($this->branchPruner); // Stores branches that have been pruned $fakedForBranchPruning = []; // help us to know when pruning ['branchTestId' => true/false] $branchStore = []; // Loop through each token in turn foreach ($tokens as $tokenData) { $token = $tokenData['value']; // Branch pruning: skip useless resolutions $storeKey = $tokenData['storeKey'] ?? null; if ($this->branchPruningEnabled && isset($tokenData['onlyIf'])) { $onlyIfStoreKey = $tokenData['onlyIf']; $storeValue = $branchStore[$onlyIfStoreKey] ?? null; $storeValueAsBool = ($storeValue === null) ? true : (bool) Functions::flattenSingleValue($storeValue); if (is_array($storeValue)) { $wrappedItem = end($storeValue); $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem; } if ( (isset($storeValue) || $tokenData['reference'] === 'NULL') && (!$storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch')) ) { // If branching value is not true, we don't need to compute if (!isset($fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey])) { $stack->push('Value', 'Pruned branch (only if ' . $onlyIfStoreKey . ') ' . $token); $fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey] = true; } if (isset($storeKey)) { // We are processing an if condition // We cascade the pruning to the depending branches $branchStore[$storeKey] = 'Pruned branch'; $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true; $fakedForBranchPruning['onlyIf-' . $storeKey] = true; } continue; } } if ($this->branchPruningEnabled && isset($tokenData['onlyIfNot'])) { $onlyIfNotStoreKey = $tokenData['onlyIfNot']; $storeValue = $branchStore[$onlyIfNotStoreKey] ?? null; $storeValueAsBool = ($storeValue === null) ? true : (bool) Functions::flattenSingleValue($storeValue); if (is_array($storeValue)) { $wrappedItem = end($storeValue); $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem; } if ( (isset($storeValue) || $tokenData['reference'] === 'NULL') && ($storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch')) ) { // If branching value is true, we don't need to compute if (!isset($fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey])) { $stack->push('Value', 'Pruned branch (only if not ' . $onlyIfNotStoreKey . ') ' . $token); $fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey] = true; } if (isset($storeKey)) { // We are processing an if condition // We cascade the pruning to the depending branches $branchStore[$storeKey] = 'Pruned branch'; $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true; $fakedForBranchPruning['onlyIf-' . $storeKey] = true; } continue; } } if ($token instanceof Operands\StructuredReference) { if ($cell === null) { return $this->raiseFormulaError('Structured References must exist in a Cell context'); } try { $cellRange = $token->parse($cell); if (strpos($cellRange, ':') !== false) { $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell Range %s', $token->value(), $cellRange); $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 { $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell %s', $token->value(), $cellRange); $cellValue = $cell->getWorksheet()->getCell($cellRange)->getCalculatedValue(false); $stack->push('Cell Reference', $cellValue, $cellRange); $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($cellValue)); } } catch (Exception $e) { if ($e->getCode() === Exception::CALCULATION_ENGINE_PUSH_TO_STACK) { $stack->push('Error', Information\ExcelError::REF(), null); $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as error value %s', $token->value(), Information\ExcelError::REF()); } else { return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e); } } } elseif (!is_numeric($token) && !is_object($token) && isset(self::BINARY_OPERATORS[$token])) { // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack // We must have two operands, error if we don't if (($operand2Data = $stack->pop()) === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); } if (($operand1Data = $stack->pop()) === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); } $operand1 = self::dataTestReference($operand1Data); $operand2 = self::dataTestReference($operand2Data); // Log what we're doing if ($token == ':') { $this->debugLog->writeDebugLog('Evaluating Range %s %s %s', $this->showValue($operand1Data['reference']), $token, $this->showValue($operand2Data['reference'])); } else { $this->debugLog->writeDebugLog('Evaluating %s %s %s', $this->showValue($operand1), $token, $this->showValue($operand2)); } // Process the operation in the appropriate manner switch ($token) { // Comparison (Boolean) Operators case '>': // Greater than case '<': // Less than case '>=': // Greater than or Equal to case '<=': // Less than or Equal to case '=': // Equality case '<>': // Inequality $result = $this->executeBinaryComparisonOperation($operand1, $operand2, (string) $token, $stack); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } break; // Binary Operators case ':': // Range if ($operand1Data['type'] === 'Defined Name') { if (preg_match('/$' . self::CALCULATION_REGEXP_DEFINEDNAME . '^/mui', $operand1Data['reference']) !== false && $this->spreadsheet !== null) { $definedName = $this->spreadsheet->getNamedRange($operand1Data['reference']); if ($definedName !== null) { $operand1Data['reference'] = $operand1Data['value'] = str_replace('$', '', $definedName->getValue()); } } } if (strpos($operand1Data['reference'] ?? '', '!') !== false) { [$sheet1, $operand1Data['reference']] = Worksheet::extractSheetTitle($operand1Data['reference'], true); } else { $sheet1 = ($pCellWorksheet !== null) ? $pCellWorksheet->getTitle() : ''; } [$sheet2, $operand2Data['reference']] = Worksheet::extractSheetTitle($operand2Data['reference'], true); if (empty($sheet2)) { $sheet2 = $sheet1; } if (trim($sheet1, "'") === trim($sheet2, "'")) { if ($operand1Data['reference'] === null && $cell !== null) { if (is_array($operand1Data['value'])) { $operand1Data['reference'] = $cell->getCoordinate(); } elseif ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) { $operand1Data['reference'] = $cell->getColumn() . $operand1Data['value']; } elseif (trim($operand1Data['value']) == '') { $operand1Data['reference'] = $cell->getCoordinate(); } else { $operand1Data['reference'] = $operand1Data['value'] . $cell->getRow(); } } if ($operand2Data['reference'] === null && $cell !== null) { if (is_array($operand2Data['value'])) { $operand2Data['reference'] = $cell->getCoordinate(); } elseif ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) { $operand2Data['reference'] = $cell->getColumn() . $operand2Data['value']; } elseif (trim($operand2Data['value']) == '') { $operand2Data['reference'] = $cell->getCoordinate(); } else { $operand2Data['reference'] = $operand2Data['value'] . $cell->getRow(); } } $oData = array_merge(explode(':', $operand1Data['reference']), explode(':', $operand2Data['reference'])); $oCol = $oRow = []; $breakNeeded = false; foreach ($oData as $oDatum) { try { $oCR = Coordinate::coordinateFromString($oDatum); $oCol[] = Coordinate::columnIndexFromString($oCR[0]) - 1; $oRow[] = $oCR[1]; } catch (\Exception $e) { $stack->push('Error', Information\ExcelError::REF(), null); $breakNeeded = true; break; } } if ($breakNeeded) { break; } $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); } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellValue)); $stack->push('Cell Reference', $cellValue, $cellRef); } else { $this->debugLog->writeDebugLog('Evaluation Result is a #REF! Error'); $stack->push('Error', Information\ExcelError::REF(), null); } break; case '+': // Addition case '-': // Subtraction case '*': // Multiplication case '/': // Division case '^': // Exponential $result = $this->executeNumericBinaryOperation($operand1, $operand2, $token, $stack); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } break; case '&': // Concatenation // If either of the operands is a matrix, we need to treat them both as matrices // (converting the other operand to a matrix if need be); then perform the required // matrix operation $operand1 = self::boolToString($operand1); $operand2 = self::boolToString($operand2); if (is_array($operand1) || is_array($operand2)) { if (is_string($operand1)) { $operand1 = self::unwrapResult($operand1); } if (is_string($operand2)) { $operand2 = self::unwrapResult($operand2); } // Ensure that both operands are arrays/matrices [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 2); for ($row = 0; $row < $rows; ++$row) { for ($column = 0; $column < $columns; ++$column) { $operand1[$row][$column] = Shared\StringHelper::substring( self::boolToString($operand1[$row][$column]) . self::boolToString($operand2[$row][$column]), 0, DataType::MAX_STRING_LENGTH ); } } $result = $operand1; } else { // In theory, we should truncate here. // But I can't figure out a formula // using the concatenation operator // with literals that fits in 32K, // so I don't think we can overflow here. $result = self::FORMULA_STRING_QUOTE . str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($operand1) . self::unwrapResult($operand2)) . self::FORMULA_STRING_QUOTE; } $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); $stack->push('Value', $result); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } break; case '∩': // Intersect $rowIntersect = array_intersect_key($operand1, $operand2); $cellIntersect = $oCol = $oRow = []; foreach (array_keys($rowIntersect) as $row) { $oRow[] = $row; foreach ($rowIntersect[$row] as $col => $data) { $oCol[] = Coordinate::columnIndexFromString($col) - 1; $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]); } } if (count(Functions::flattenArray($cellIntersect)) === 0) { $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect)); $stack->push('Error', Information\ExcelError::null(), null); } else { $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect)); $stack->push('Value', $cellIntersect, $cellRef); } break; } } 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 === '~') { $this->debugLog->writeDebugLog('Evaluating Negation of %s', $this->showValue($arg)); $multiplier = -1; } else { $this->debugLog->writeDebugLog('Evaluating Percentile of %s', $this->showValue($arg)); $multiplier = 0.01; } if (is_array($arg)) { $operand2 = $multiplier; $result = $arg; [$rows, $columns] = self::checkMatrixOperands($result, $operand2, 0); for ($row = 0; $row < $rows; ++$row) { for ($column = 0; $column < $columns; ++$column) { if (self::isNumericOrBool($result[$row][$column])) { $result[$row][$column] *= $multiplier; } else { $result[$row][$column] = self::makeError($result[$row][$column]); } } } $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); $stack->push('Value', $result); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } } else { $this->executeNumericBinaryOperation($multiplier, $arg, '*', $stack); } } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token ?? '', $matches)) { $cellRef = null; if (isset($matches[8])) { if ($cell === null) { // We can't access the range, so return a REF error $cellValue = Information\ExcelError::REF(); } else { $cellRef = $matches[6] . $matches[7] . ':' . $matches[9] . $matches[10]; if ($matches[2] > '') { $matches[2] = trim($matches[2], "\"'"); if ((strpos($matches[2], '[') !== false) || (strpos($matches[2], ']') !== false)) { // It's a Reference to an external spreadsheet (not currently supported) return $this->raiseFormulaError('Unable to access External Workbook'); } $matches[2] = trim($matches[2], "\"'"); $this->debugLog->writeDebugLog('Evaluating Cell Range %s in worksheet %s', $cellRef, $matches[2]); if ($pCellParent !== null && $this->spreadsheet !== null) { $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false); } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result for cells %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue)); } else { $this->debugLog->writeDebugLog('Evaluating Cell Range %s in current worksheet', $cellRef); if ($pCellParent !== null) { $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result for cells %s is %s', $cellRef, $this->showTypeDetails($cellValue)); } } } else { if ($cell === null) { // We can't access the cell, so return a REF error $cellValue = Information\ExcelError::REF(); } else { $cellRef = $matches[6] . $matches[7]; if ($matches[2] > '') { $matches[2] = trim($matches[2], "\"'"); if ((strpos($matches[2], '[') !== false) || (strpos($matches[2], ']') !== false)) { // It's a Reference to an external spreadsheet (not currently supported) return $this->raiseFormulaError('Unable to access External Workbook'); } $this->debugLog->writeDebugLog('Evaluating Cell %s in worksheet %s', $cellRef, $matches[2]); if ($pCellParent !== null && $this->spreadsheet !== null) { $cellSheet = $this->spreadsheet->getSheetByName($matches[2]); if ($cellSheet && $cellSheet->cellExists($cellRef)) { $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false); $cell->attach($pCellParent); } else { $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef; $cellValue = ($cellSheet !== null) ? null : Information\ExcelError::REF(); } } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } $this->debugLog->writeDebugLog('Evaluation Result for cell %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue)); } else { $this->debugLog->writeDebugLog('Evaluating Cell %s in current worksheet', $cellRef); if ($pCellParent !== null && $pCellParent->has($cellRef)) { $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); $cell->attach($pCellParent); } else { $cellValue = null; } $this->debugLog->writeDebugLog('Evaluation Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue)); } } } $stack->push('Cell Value', $cellValue, $cellRef); if (isset($storeKey)) { $branchStore[$storeKey] = $cellValue; } } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $token ?? '', $matches)) { // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on if ($cell !== null && $pCellParent !== null) { $cell->attach($pCellParent); } $functionName = $matches[1]; $argCount = $stack->pop(); $argCount = $argCount['value']; if ($functionName !== 'MKMATRIX') { $this->debugLog->writeDebugLog('Evaluating Function %s() with %s argument%s', self::localeFunc($functionName), (($argCount == 0) ? 'no' : $argCount), (($argCount == 1) ? '' : 's')); } if ((isset(self::$phpSpreadsheetFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) { // function $passByReference = false; $passCellReference = false; $functionCall = null; if (isset(self::$phpSpreadsheetFunctions[$functionName])) { $functionCall = self::$phpSpreadsheetFunctions[$functionName]['functionCall']; $passByReference = isset(self::$phpSpreadsheetFunctions[$functionName]['passByReference']); $passCellReference = isset(self::$phpSpreadsheetFunctions[$functionName]['passCellReference']); } elseif (isset(self::$controlFunctions[$functionName])) { $functionCall = self::$controlFunctions[$functionName]['functionCall']; $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']); $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']); } // get the arguments for this function $args = $argArrayVals = []; $emptyArguments = []; for ($i = 0; $i < $argCount; ++$i) { $arg = $stack->pop(); $a = $argCount - $i - 1; if ( ($passByReference) && (isset(self::$phpSpreadsheetFunctions[$functionName]['passByReference'][$a])) && (self::$phpSpreadsheetFunctions[$functionName]['passByReference'][$a]) ) { if ($arg['reference'] === null) { $args[] = $cellID; if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($cellID); } } else { $args[] = $arg['reference']; if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($arg['reference']); } } } else { $emptyArguments[] = ($arg['type'] === 'Empty Argument'); $args[] = self::unwrapResult($arg['value']); if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($arg['value']); } } } // Reverse the order of the arguments krsort($args); krsort($emptyArguments); if ($argCount > 0) { $args = $this->addDefaultArgumentValues($functionCall, $args, $emptyArguments); } if (($passByReference) && ($argCount == 0)) { $args[] = $cellID; $argArrayVals[] = $this->showValue($cellID); } if ($functionName !== 'MKMATRIX') { if ($this->debugLog->getWriteDebugLog()) { krsort($argArrayVals); $this->debugLog->writeDebugLog('Evaluating %s ( %s )', self::localeFunc($functionName), implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals))); } } // Process the argument with the appropriate function call $args = $this->addCellReference($args, $passCellReference, $functionCall, $cell); if (!is_array($functionCall)) { foreach ($args as &$arg) { $arg = Functions::flattenSingleValue($arg); } unset($arg); } $result = call_user_func_array($functionCall, $args); if ($functionName !== 'MKMATRIX') { $this->debugLog->writeDebugLog('Evaluation Result for %s() function call is %s', self::localeFunc($functionName), $this->showTypeDetails($result)); } $stack->push('Value', self::wrapResult($result)); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } } } else { // if the token is a number, boolean, string or an Excel error, push it onto the stack if (isset(self::$excelConstants[strtoupper($token ?? '')])) { $excelConstant = strtoupper($token); $stack->push('Constant Value', self::$excelConstants[$excelConstant]); if (isset($storeKey)) { $branchStore[$storeKey] = self::$excelConstants[$excelConstant]; } $this->debugLog->writeDebugLog('Evaluating Constant %s as %s', $excelConstant, $this->showTypeDetails(self::$excelConstants[$excelConstant])); } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) { $stack->push($tokenData['type'], $token, $tokenData['reference']); if (isset($storeKey)) { $branchStore[$storeKey] = $token; } } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token, $matches)) { // if the token is a named range or formula, evaluate it and push the result onto the stack $definedName = $matches[6]; if ($cell === null || $pCellWorksheet === null) { return $this->raiseFormulaError("undefined name '$token'"); } $this->debugLog->writeDebugLog('Evaluating Defined Name %s', $definedName); $namedRange = DefinedName::resolveName($definedName, $pCellWorksheet); if ($namedRange === null) { return $this->raiseFormulaError("undefined name '$definedName'"); } $result = $this->evaluateDefinedName($cell, $namedRange, $pCellWorksheet, $stack); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } } else { return $this->raiseFormulaError("undefined name '$token'"); } } } // when we're out of tokens, the stack should have a single element, the final result if ($stack->count() != 1) { return $this->raiseFormulaError('internal error'); } $output = $stack->pop(); $output = $output['value']; return $output; } /** * @param mixed $operand * @param mixed $stack * * @return bool */ private function validateBinaryOperand(&$operand, &$stack) { if (is_array($operand)) { if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) { do { $operand = array_pop($operand); } while (is_array($operand)); } } // Numbers, matrices and booleans can pass straight through, as they're already valid if (is_string($operand)) { // We only need special validations for the operand if it is a string // Start by stripping off the quotation marks we use to identify true excel string values internally if ($operand > '' && $operand[0] == self::FORMULA_STRING_QUOTE) { $operand = self::unwrapResult($operand); } // If the string is a numeric value, we treat it as a numeric, so no further testing if (!is_numeric($operand)) { // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations if ($operand > '' && $operand[0] == '#') { $stack->push('Value', $operand); $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($operand)); return false; } elseif (Engine\FormattedNumber::convertToNumberIfFormatted($operand) === false) { // If not a numeric, a fraction or a percentage, then it's a text string, and so can't be used in mathematical binary operations $stack->push('Error', '#VALUE!'); $this->debugLog->writeDebugLog('Evaluation Result is a %s', $this->showTypeDetails('#VALUE!')); return false; } } } // return a true if the value of the operand is one that we can use in normal binary mathematical operations return true; } /** * @param mixed $operand1 * @param mixed $operand2 * @param string $operation * * @return array */ private function executeArrayComparison($operand1, $operand2, $operation, Stack &$stack, bool $recursingArrays) { $result = []; if (!is_array($operand2)) { // Operand 1 is an array, Operand 2 is a scalar foreach ($operand1 as $x => $operandData) { $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2)); $this->executeBinaryComparisonOperation($operandData, $operand2, $operation, $stack); $r = $stack->pop(); $result[$x] = $r['value']; } } elseif (!is_array($operand1)) { // Operand 1 is a scalar, Operand 2 is an array foreach ($operand2 as $x => $operandData) { $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operand1), $operation, $this->showValue($operandData)); $this->executeBinaryComparisonOperation($operand1, $operandData, $operation, $stack); $r = $stack->pop(); $result[$x] = $r['value']; } } else { // Operand 1 and Operand 2 are both arrays if (!$recursingArrays) { self::checkMatrixOperands($operand1, $operand2, 2); } foreach ($operand1 as $x => $operandData) { $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2[$x])); $this->executeBinaryComparisonOperation($operandData, $operand2[$x], $operation, $stack, true); $r = $stack->pop(); $result[$x] = $r['value']; } } // Log the result details $this->debugLog->writeDebugLog('Comparison Evaluation Result is %s', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Array', $result); return $result; } /** * @param mixed $operand1 * @param mixed $operand2 * @param string $operation * @param bool $recursingArrays * * @return mixed */ private function executeBinaryComparisonOperation($operand1, $operand2, $operation, Stack &$stack, $recursingArrays = false) { // If we're dealing with matrix operations, we want a matrix result if ((is_array($operand1)) || (is_array($operand2))) { return $this->executeArrayComparison($operand1, $operand2, $operation, $stack, $recursingArrays); } $result = BinaryComparison::compare($operand1, $operand2, $operation); // Log the result details $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Value', $result); return $result; } /** * @param mixed $operand1 * @param mixed $operand2 * @param string $operation * @param Stack $stack * * @return bool|mixed */ private function executeNumericBinaryOperation($operand1, $operand2, $operation, &$stack) { // Validate the two operands if ( ($this->validateBinaryOperand($operand1, $stack) === false) || ($this->validateBinaryOperand($operand2, $stack) === false) ) { return false; } if ( (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) && ((is_string($operand1) && !is_numeric($operand1) && strlen($operand1) > 0) || (is_string($operand2) && !is_numeric($operand2) && strlen($operand2) > 0)) ) { $result = Information\ExcelError::VALUE(); } elseif (is_array($operand1) || is_array($operand2)) { // Ensure that both operands are arrays/matrices if (is_array($operand1)) { foreach ($operand1 as $key => $value) { $operand1[$key] = Functions::flattenArray($value); } } if (is_array($operand2)) { foreach ($operand2 as $key => $value) { $operand2[$key] = Functions::flattenArray($value); } } [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 2); for ($row = 0; $row < $rows; ++$row) { for ($column = 0; $column < $columns; ++$column) { if ($operand1[$row][$column] === null) { $operand1[$row][$column] = 0; } elseif (!self::isNumericOrBool($operand1[$row][$column])) { $operand1[$row][$column] = self::makeError($operand1[$row][$column]); continue; } if ($operand2[$row][$column] === null) { $operand2[$row][$column] = 0; } elseif (!self::isNumericOrBool($operand2[$row][$column])) { $operand1[$row][$column] = self::makeError($operand2[$row][$column]); continue; } switch ($operation) { case '+': $operand1[$row][$column] += $operand2[$row][$column]; break; case '-': $operand1[$row][$column] -= $operand2[$row][$column]; break; case '*': $operand1[$row][$column] *= $operand2[$row][$column]; break; case '/': if ($operand2[$row][$column] == 0) { $operand1[$row][$column] = Information\ExcelError::DIV0(); } else { $operand1[$row][$column] /= $operand2[$row][$column]; } break; case '^': $operand1[$row][$column] = $operand1[$row][$column] ** $operand2[$row][$column]; break; default: throw new Exception('Unsupported numeric binary operation'); } } } $result = $operand1; } else { // If we're dealing with non-matrix operations, execute the necessary operation switch ($operation) { // Addition case '+': $result = $operand1 + $operand2; break; // Subtraction case '-': $result = $operand1 - $operand2; break; // Multiplication case '*': $result = $operand1 * $operand2; break; // Division case '/': if ($operand2 == 0) { // Trap for Divide by Zero error $stack->push('Error', Information\ExcelError::DIV0()); $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails(Information\ExcelError::DIV0())); return false; } $result = $operand1 / $operand2; break; // Power case '^': $result = $operand1 ** $operand2; break; default: throw new Exception('Unsupported numeric binary operation'); } } // Log the result details $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Value', $result); return $result; } /** * Trigger an error, but nicely, if need be. * * @return false */ protected function raiseFormulaError(string $errorMessage, int $code = 0, ?Throwable $exception = null) { $this->formulaError = $errorMessage; $this->cyclicReferenceStack->clear(); $suppress = /** @scrutinizer ignore-deprecated */ $this->suppressFormulaErrors ?? $this->suppressFormulaErrorsNew; if (!$suppress) { throw new Exception($errorMessage, $code, $exception); } return false; } /** * Extract range values. * * @param string $range String based range representation * @param Worksheet $worksheet Worksheet * @param bool $resetLog Flag indicating whether calculation log should be reset or not * * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ public function extractCellRange(&$range = 'A1', ?Worksheet $worksheet = null, $resetLog = true) { // Return value $returnValue = []; if ($worksheet !== null) { $worksheetName = $worksheet->getTitle(); if (strpos($range, '!') !== false) { [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true); $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName); } // Extract range $aReferences = Coordinate::extractAllCellReferencesInRange($range); $range = "'" . $worksheetName . "'" . '!' . $range; $currentCol = ''; $currentRow = 0; if (!isset($aReferences[1])) { // Single cell in range sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow); if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) { $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } } else { // Extract cell data for all cells in the range foreach ($aReferences as $reference) { // Extract range sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow); if ($worksheet !== null && $worksheet->cellExists($reference)) { $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } } } } return $returnValue; } /** * Extract range values. * * @param string $range String based range representation * @param null|Worksheet $worksheet Worksheet * @param bool $resetLog Flag indicating whether calculation log should be reset or not * * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, $resetLog = true) { // Return value $returnValue = []; if ($worksheet !== null) { if (strpos($range, '!') !== false) { [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true); $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName); } // Named range? $namedRange = ($worksheet === null) ? null : DefinedName::resolveName($range, $worksheet); if ($namedRange === null) { return Information\ExcelError::REF(); } $worksheet = $namedRange->getWorksheet(); $range = $namedRange->getValue(); $splitRange = Coordinate::splitRange($range); // Convert row and column references if ($worksheet !== null && ctype_alpha($splitRange[0][0])) { $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $worksheet->getHighestRow(); } elseif ($worksheet !== null && ctype_digit($splitRange[0][0])) { $range = 'A' . $splitRange[0][0] . ':' . $worksheet->getHighestColumn() . $splitRange[0][1]; } // Extract range $aReferences = Coordinate::extractAllCellReferencesInRange($range); if (!isset($aReferences[1])) { // Single cell (or single column or row) in range [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]); if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) { $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } } else { // Extract cell data for all cells in the range foreach ($aReferences as $reference) { // Extract range [$currentCol, $currentRow] = Coordinate::coordinateFromString($reference); if ($worksheet !== null && $worksheet->cellExists($reference)) { $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } } } } return $returnValue; } /** * Is a specific function implemented? * * @param string $function Function Name * * @return bool */ public function isImplemented($function) { $function = strtoupper($function); $notImplemented = !isset(self::$phpSpreadsheetFunctions[$function]) || (is_array(self::$phpSpreadsheetFunctions[$function]['functionCall']) && self::$phpSpreadsheetFunctions[$function]['functionCall'][1] === 'DUMMY'); return !$notImplemented; } /** * Get a list of all implemented functions as an array of function objects. */ public static function getFunctions(): array { return self::$phpSpreadsheetFunctions; } /** * Get a list of implemented Excel function names. * * @return array */ public function getImplementedFunctionNames() { $returnValue = []; foreach (self::$phpSpreadsheetFunctions as $functionName => $function) { if ($this->isImplemented($functionName)) { $returnValue[] = $functionName; } } return $returnValue; } private function addDefaultArgumentValues(array $functionCall, array $args, array $emptyArguments): array { $reflector = new ReflectionMethod(implode('::', $functionCall)); $methodArguments = $reflector->getParameters(); if (count($methodArguments) > 0) { // Apply any defaults for empty argument values foreach ($emptyArguments as $argumentId => $isArgumentEmpty) { if ($isArgumentEmpty === true) { $reflectedArgumentId = count($args) - (int) $argumentId - 1; if ( !array_key_exists($reflectedArgumentId, $methodArguments) || $methodArguments[$reflectedArgumentId]->isVariadic() ) { break; } $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]); } } } return $args; } /** * @return null|mixed */ private function getArgumentDefaultValue(ReflectionParameter $methodArgument) { $defaultValue = null; if ($methodArgument->isDefaultValueAvailable()) { $defaultValue = $methodArgument->getDefaultValue(); if ($methodArgument->isDefaultValueConstant()) { $constantName = $methodArgument->getDefaultValueConstantName() ?? ''; // read constant value if (strpos($constantName, '::') !== false) { [$className, $constantName] = explode('::', $constantName); $constantReflector = new ReflectionClassConstant($className, $constantName); return $constantReflector->getValue(); } return constant($constantName); } } return $defaultValue; } /** * Add cell reference if needed while making sure that it is the last argument. * * @param bool $passCellReference * @param array|string $functionCall * * @return array */ private function addCellReference(array $args, $passCellReference, $functionCall, ?Cell $cell = null) { if ($passCellReference) { if (is_array($functionCall)) { $className = $functionCall[0]; $methodName = $functionCall[1]; $reflectionMethod = new ReflectionMethod($className, $methodName); $argumentCount = count($reflectionMethod->getParameters()); while (count($args) < $argumentCount - 1) { $args[] = null; } } $args[] = $cell; } return $args; } /** * @return mixed|string */ private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksheet $cellWorksheet, Stack $stack) { $definedNameScope = $namedRange->getScope(); if ($definedNameScope !== null && $definedNameScope !== $cellWorksheet) { // The defined name isn't in our current scope, so #REF $result = Information\ExcelError::REF(); $stack->push('Error', $result, $namedRange->getName()); return $result; } $definedNameValue = $namedRange->getValue(); $definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range'; $definedNameWorksheet = $namedRange->getWorksheet(); if ($definedNameValue[0] !== '=') { $definedNameValue = '=' . $definedNameValue; } $this->debugLog->writeDebugLog('Defined Name is a %s with a value of %s', $definedNameType, $definedNameValue); $recursiveCalculationCell = ($definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet) ? $definedNameWorksheet->getCell('A1') : $cell; $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate(); // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns $definedNameValue = self::$referenceHelper->updateFormulaReferencesAnyWorksheet( $definedNameValue, Coordinate::columnIndexFromString($cell->getColumn()) - 1, $cell->getRow() - 1 ); $this->debugLog->writeDebugLog('Value adjusted for relative references is %s', $definedNameValue); $recursiveCalculator = new self($this->spreadsheet); $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog()); $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog()); $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true); if ($this->getDebugLog()->getWriteDebugLog()) { $this->debugLog->mergeDebugLog(array_slice($recursiveCalculator->getDebugLog()->getLog(), 3)); $this->debugLog->writeDebugLog('Evaluation Result for Named %s %s is %s', $definedNameType, $namedRange->getName(), $this->showTypeDetails($result)); } $stack->push('Defined Name', $result, $namedRange->getName()); return $result; } public function setSuppressFormulaErrors(bool $suppressFormulaErrors): void { $this->suppressFormulaErrorsNew = $suppressFormulaErrors; } public function getSuppressFormulaErrors(): bool { return $this->suppressFormulaErrorsNew; } /** @param mixed $arg */ private static function doNothing($arg): bool { return (bool) $arg; } /** * @param mixed $operand1 * * @return mixed */ private static function boolToString($operand1) { if (is_bool($operand1)) { $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; } elseif ($operand1 === null) { $operand1 = ''; } return $operand1; } /** @param mixed $operand */ private static function isNumericOrBool($operand): bool { return is_numeric($operand) || is_bool($operand); } /** @param mixed $operand */ private static function makeError($operand = ''): string { return Information\ErrorValue::isError($operand) ? $operand : Information\ExcelError::VALUE(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig.php 0000644 00000121367 15002227416 0017770 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; /** * @deprecated 1.18.0 */ class MathTrig { /** * ARABIC. * * Converts a Roman numeral to an Arabic numeral. * * Excel Function: * ARABIC(text) * * @deprecated 1.18.0 * Use the evaluate method in the MathTrig\Arabic class instead * @see MathTrig\Arabic::evaluate() * * @param array|string $roman * * @return array|int|string the arabic numberal contrived from the roman numeral */ public static function ARABIC($roman) { return MathTrig\Arabic::evaluate($roman); } /** * ATAN2. * * This function calculates the arc tangent of the two variables x and y. It is similar to * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used * to determine the quadrant of the result. * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between * -pi and pi, excluding -pi. * * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function. * * Excel Function: * ATAN2(xCoordinate,yCoordinate) * * @deprecated 1.18.0 * Use the atan2 method in the MathTrig\Trig\Tangent class instead * @see MathTrig\Trig\Tangent::atan2() * * @param array|float $xCoordinate the x-coordinate of the point * @param array|float $yCoordinate the y-coordinate of the point * * @return array|float|string the inverse tangent of the specified x- and y-coordinates, or a string containing an error */ public static function ATAN2($xCoordinate = null, $yCoordinate = null) { return MathTrig\Trig\Tangent::atan2($xCoordinate, $yCoordinate); } /** * BASE. * * Converts a number into a text representation with the given radix (base). * * Excel Function: * BASE(Number, Radix [Min_length]) * * @deprecated 1.18.0 * Use the evaluate method in the MathTrig\Base class instead * @see MathTrig\Base::evaluate() * * @param float $number * @param float $radix * @param int $minLength * * @return array|string the text representation with the given radix (base) */ public static function BASE($number, $radix, $minLength = null) { return MathTrig\Base::evaluate($number, $radix, $minLength); } /** * CEILING. * * Returns number rounded up, away from zero, to the nearest multiple of significance. * For example, if you want to avoid using pennies in your prices and your product is * priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the * nearest nickel. * * Excel Function: * CEILING(number[,significance]) * * @deprecated 1.17.0 * Use the ceiling() method in the MathTrig\Ceiling class instead * @see MathTrig\Ceiling::ceiling() * * @param float $number the number you want to round * @param float $significance the multiple to which you want to round * * @return array|float|string Rounded Number, or a string containing an error */ public static function CEILING($number, $significance = null) { return MathTrig\Ceiling::ceiling($number, $significance); } /** * COMBIN. * * Returns the number of combinations for a given number of items. Use COMBIN to * determine the total possible number of groups for a given number of items. * * Excel Function: * COMBIN(numObjs,numInSet) * * @deprecated 1.18.0 * Use the withoutRepetition() method in the MathTrig\Combinations class instead * @see MathTrig\Combinations::withoutRepetition() * * @param array|int $numObjs Number of different objects * @param array|int $numInSet Number of objects in each combination * * @return array|float|int|string Number of combinations, or a string containing an error */ public static function COMBIN($numObjs, $numInSet) { return MathTrig\Combinations::withoutRepetition($numObjs, $numInSet); } /** * EVEN. * * Returns number rounded up to the nearest even integer. * You can use this function for processing items that come in twos. For example, * a packing crate accepts rows of one or two items. The crate is full when * the number of items, rounded up to the nearest two, matches the crate's * capacity. * * Excel Function: * EVEN(number) * * @deprecated 1.18.0 * Use the even() method in the MathTrig\Round class instead * @see MathTrig\Round::even() * * @param array|float $number Number to round * * @return array|float|int|string Rounded Number, or a string containing an error */ public static function EVEN($number) { return MathTrig\Round::even($number); } /** * Helper function for Even. * * @deprecated 1.18.0 * Use the evaluate() method in the MathTrig\Helpers class instead * @see MathTrig\Helpers::getEven() */ public static function getEven(float $number): int { return (int) MathTrig\Helpers::getEven($number); } /** * FACT. * * Returns the factorial of a number. * The factorial of a number is equal to 1*2*3*...* number. * * Excel Function: * FACT(factVal) * * @deprecated 1.18.0 * Use the fact() method in the MathTrig\Factorial class instead * @see MathTrig\Factorial::fact() * * @param array|float $factVal Factorial Value * * @return array|float|int|string Factorial, or a string containing an error */ public static function FACT($factVal) { return MathTrig\Factorial::fact($factVal); } /** * FACTDOUBLE. * * Returns the double factorial of a number. * * Excel Function: * FACTDOUBLE(factVal) * * @deprecated 1.18.0 * Use the factDouble() method in the MathTrig\Factorial class instead * @see MathTrig\Factorial::factDouble() * * @param array|float $factVal Factorial Value * * @return array|float|int|string Double Factorial, or a string containing an error */ public static function FACTDOUBLE($factVal) { return MathTrig\Factorial::factDouble($factVal); } /** * FLOOR. * * Rounds number down, toward zero, to the nearest multiple of significance. * * Excel Function: * FLOOR(number[,significance]) * * @deprecated 1.17.0 * Use the floor() method in the MathTrig\Floor class instead * @see MathTrig\Floor::floor() * * @param float $number Number to round * @param float $significance Significance * * @return array|float|string Rounded Number, or a string containing an error */ public static function FLOOR($number, $significance = null) { return MathTrig\Floor::floor($number, $significance); } /** * FLOOR.MATH. * * Round a number down to the nearest integer or to the nearest multiple of significance. * * Excel Function: * FLOOR.MATH(number[,significance[,mode]]) * * @deprecated 1.17.0 * Use the math() method in the MathTrig\Floor class instead * @see MathTrig\Floor::math() * * @param float $number Number to round * @param float $significance Significance * @param int $mode direction to round negative numbers * * @return array|float|string Rounded Number, or a string containing an error */ public static function FLOORMATH($number, $significance = null, $mode = 0) { return MathTrig\Floor::math($number, $significance, $mode); } /** * FLOOR.PRECISE. * * Rounds number down, toward zero, to the nearest multiple of significance. * * Excel Function: * FLOOR.PRECISE(number[,significance]) * * @deprecated 1.17.0 * Use the precise() method in the MathTrig\Floor class instead * @see MathTrig\Floor::precise() * * @param float $number Number to round * @param float $significance Significance * * @return array|float|string Rounded Number, or a string containing an error */ public static function FLOORPRECISE($number, $significance = 1) { return MathTrig\Floor::precise($number, $significance); } /** * INT. * * Casts a floating point value to an integer * * Excel Function: * INT(number) * * @deprecated 1.17.0 * Use the evaluate() method in the MathTrig\IntClass class instead * @see MathTrig\IntClass::evaluate() * * @param array|float $number Number to cast to an integer * * @return array|int|string Integer value, or a string containing an error */ public static function INT($number) { return MathTrig\IntClass::evaluate($number); } /** * GCD. * * Returns the greatest common divisor of a series of numbers. * The greatest common divisor is the largest integer that divides both * number1 and number2 without a remainder. * * Excel Function: * GCD(number1[,number2[, ...]]) * * @deprecated 1.18.0 * Use the evaluate() method in the MathTrig\Gcd class instead * @see MathTrig\Gcd::evaluate() * * @param mixed ...$args Data values * * @return int|mixed|string Greatest Common Divisor, or a string containing an error */ public static function GCD(...$args) { return MathTrig\Gcd::evaluate(...$args); } /** * LCM. * * Returns the lowest common multiplier of a series of numbers * The least common multiple is the smallest positive integer that is a multiple * of all integer arguments number1, number2, and so on. Use LCM to add fractions * with different denominators. * * Excel Function: * LCM(number1[,number2[, ...]]) * * @deprecated 1.18.0 * Use the evaluate() method in the MathTrig\Lcm class instead * @see MathTrig\Lcm::evaluate() * * @param mixed ...$args Data values * * @return int|string Lowest Common Multiplier, or a string containing an error */ public static function LCM(...$args) { return MathTrig\Lcm::evaluate(...$args); } /** * LOG_BASE. * * Returns the logarithm of a number to a specified base. The default base is 10. * * Excel Function: * LOG(number[,base]) * * @deprecated 1.18.0 * Use the withBase() method in the MathTrig\Logarithms class instead * @see MathTrig\Logarithms::withBase() * * @param float $number The positive real number for which you want the logarithm * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10. * * @return array|float|string The result, or a string containing an error */ public static function logBase($number, $base = 10) { return MathTrig\Logarithms::withBase($number, $base); } /** * MDETERM. * * Returns the matrix determinant of an array. * * Excel Function: * MDETERM(array) * * @deprecated 1.18.0 * Use the determinant() method in the MathTrig\MatrixFunctions class instead * @see MathTrig\MatrixFunctions::determinant() * * @param array $matrixValues A matrix of values * * @return float|string The result, or a string containing an error */ public static function MDETERM($matrixValues) { return MathTrig\MatrixFunctions::determinant($matrixValues); } /** * MINVERSE. * * Returns the inverse matrix for the matrix stored in an array. * * Excel Function: * MINVERSE(array) * * @deprecated 1.18.0 * Use the inverse() method in the MathTrig\MatrixFunctions class instead * @see MathTrig\MatrixFunctions::inverse() * * @param array $matrixValues A matrix of values * * @return array|string The result, or a string containing an error */ public static function MINVERSE($matrixValues) { return MathTrig\MatrixFunctions::inverse($matrixValues); } /** * MMULT. * * @deprecated 1.18.0 * Use the multiply() method in the MathTrig\MatrixFunctions class instead * @see MathTrig\MatrixFunctions::multiply() * * @param array $matrixData1 A matrix of values * @param array $matrixData2 A matrix of values * * @return array|string The result, or a string containing an error */ public static function MMULT($matrixData1, $matrixData2) { return MathTrig\MatrixFunctions::multiply($matrixData1, $matrixData2); } /** * MOD. * * @deprecated 1.18.0 * Use the mod() method in the MathTrig\Operations class instead * @see MathTrig\Operations::mod() * * @param int $a Dividend * @param int $b Divisor * * @return array|float|int|string Remainder, or a string containing an error */ public static function MOD($a = 1, $b = 1) { return MathTrig\Operations::mod($a, $b); } /** * MROUND. * * Rounds a number to the nearest multiple of a specified value * * @deprecated 1.17.0 * Use the multiple() method in the MathTrig\Mround class instead * @see MathTrig\Round::multiple() * * @param float $number Number to round * @param array|int $multiple Multiple to which you want to round $number * * @return array|float|string Rounded Number, or a string containing an error */ public static function MROUND($number, $multiple) { return MathTrig\Round::multiple($number, $multiple); } /** * MULTINOMIAL. * * Returns the ratio of the factorial of a sum of values to the product of factorials. * * @deprecated 1.18.0 * Use the multinomial method in the MathTrig\Factorial class instead * @see MathTrig\Factorial::multinomial() * * @param mixed[] $args An array of mixed values for the Data Series * * @return float|string The result, or a string containing an error */ public static function MULTINOMIAL(...$args) { return MathTrig\Factorial::multinomial(...$args); } /** * ODD. * * Returns number rounded up to the nearest odd integer. * * @deprecated 1.18.0 * Use the odd method in the MathTrig\Round class instead * @see MathTrig\Round::odd() * * @param array|float $number Number to round * * @return array|float|int|string Rounded Number, or a string containing an error */ public static function ODD($number) { return MathTrig\Round::odd($number); } /** * POWER. * * Computes x raised to the power y. * * @deprecated 1.18.0 * Use the evaluate method in the MathTrig\Power class instead * @see MathTrig\Operations::power() * * @param float $x * @param float $y * * @return array|float|int|string The result, or a string containing an error */ public static function POWER($x = 0, $y = 2) { return MathTrig\Operations::power($x, $y); } /** * PRODUCT. * * PRODUCT returns the product of all the values and cells referenced in the argument list. * * @deprecated 1.18.0 * Use the product method in the MathTrig\Operations class instead * @see MathTrig\Operations::product() * * Excel Function: * PRODUCT(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function PRODUCT(...$args) { return MathTrig\Operations::product(...$args); } /** * QUOTIENT. * * QUOTIENT function returns the integer portion of a division. Numerator is the divided number * and denominator is the divisor. * * @deprecated 1.18.0 * Use the quotient method in the MathTrig\Operations class instead * @see MathTrig\Operations::quotient() * * Excel Function: * QUOTIENT(value1[,value2[, ...]]) * * @param mixed $numerator * @param mixed $denominator * * @return array|int|string */ public static function QUOTIENT($numerator, $denominator) { return MathTrig\Operations::quotient($numerator, $denominator); } /** * RAND/RANDBETWEEN. * * @deprecated 1.18.0 * Use the randBetween or randBetween method in the MathTrig\Random class instead * @see MathTrig\Random::randBetween() * * @param int $min Minimal value * @param int $max Maximal value * * @return array|float|int|string Random number */ public static function RAND($min = 0, $max = 0) { return MathTrig\Random::randBetween($min, $max); } /** * ROMAN. * * Converts a number to Roman numeral * * @deprecated 1.17.0 * Use the evaluate() method in the MathTrig\Roman class instead * @see MathTrig\Roman::evaluate() * * @param mixed $aValue Number to convert * @param mixed $style Number indicating one of five possible forms * * @return array|string Roman numeral, or a string containing an error */ public static function ROMAN($aValue, $style = 0) { return MathTrig\Roman::evaluate($aValue, $style); } /** * ROUNDUP. * * Rounds a number up to a specified number of decimal places * * @deprecated 1.17.0 * Use the up() method in the MathTrig\Round class instead * @see MathTrig\Round::up() * * @param array|float $number Number to round * @param array|int $digits Number of digits to which you want to round $number * * @return array|float|string Rounded Number, or a string containing an error */ public static function ROUNDUP($number, $digits) { return MathTrig\Round::up($number, $digits); } /** * ROUNDDOWN. * * Rounds a number down to a specified number of decimal places * * @deprecated 1.17.0 * Use the down() method in the MathTrig\Round class instead * @see MathTrig\Round::down() * * @param array|float $number Number to round * @param array|int $digits Number of digits to which you want to round $number * * @return array|float|string Rounded Number, or a string containing an error */ public static function ROUNDDOWN($number, $digits) { return MathTrig\Round::down($number, $digits); } /** * SERIESSUM. * * Returns the sum of a power series * * @deprecated 1.18.0 * Use the evaluate method in the MathTrig\SeriesSum class instead * @see MathTrig\SeriesSum::evaluate() * * @param mixed $x Input value * @param mixed $n Initial power * @param mixed $m Step * @param mixed[] $args An array of coefficients for the Data Series * * @return array|float|string The result, or a string containing an error */ public static function SERIESSUM($x, $n, $m, ...$args) { return MathTrig\SeriesSum::evaluate($x, $n, $m, ...$args); } /** * SIGN. * * Determines the sign of a number. Returns 1 if the number is positive, zero (0) * if the number is 0, and -1 if the number is negative. * * @deprecated 1.18.0 * Use the evaluate method in the MathTrig\Sign class instead * @see MathTrig\Sign::evaluate() * * @param array|float $number Number to round * * @return array|int|string sign value, or a string containing an error */ public static function SIGN($number) { return MathTrig\Sign::evaluate($number); } /** * returnSign = returns 0/-1/+1. * * @deprecated 1.18.0 * Use the returnSign method in the MathTrig\Helpers class instead * @see MathTrig\Helpers::returnSign() */ public static function returnSign(float $number): int { return MathTrig\Helpers::returnSign($number); } /** * SQRTPI. * * Returns the square root of (number * pi). * * @deprecated 1.18.0 * Use the pi method in the MathTrig\Sqrt class instead * @see MathTrig\Sqrt::sqrt() * * @param array|float $number Number * * @return array|float|string Square Root of Number * Pi, or a string containing an error */ public static function SQRTPI($number) { return MathTrig\Sqrt::pi($number); } /** * SUBTOTAL. * * Returns a subtotal in a list or database. * * @deprecated 1.18.0 * Use the evaluate method in the MathTrig\Subtotal class instead * @see MathTrig\Subtotal::evaluate() * * @param int $functionType * A number 1 to 11 that specifies which function to * use in calculating subtotals within a range * list * Numbers 101 to 111 shadow the functions of 1 to 11 * but ignore any values in the range that are * in hidden rows or columns * @param mixed[] $args A mixed data series of values * * @return float|string */ public static function SUBTOTAL($functionType, ...$args) { return MathTrig\Subtotal::evaluate($functionType, ...$args); } /** * SUM. * * SUM computes the sum of all the values and cells referenced in the argument list. * * @deprecated 1.18.0 * Use the sumErroringStrings method in the MathTrig\Sum class instead * @see MathTrig\Sum::sumErroringStrings() * * Excel Function: * SUM(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function SUM(...$args) { return MathTrig\Sum::sumIgnoringStrings(...$args); } /** * SUMIF. * * Totals the values of cells that contain numbers within the list of arguments * * Excel Function: * SUMIF(range, criteria, [sum_range]) * * @deprecated 1.17.0 * Use the SUMIF() method in the Statistical\Conditional class instead * @see Statistical\Conditional::SUMIF() * * @param mixed $range Data values * @param string $criteria the criteria that defines which cells will be summed * @param mixed $sumRange * * @return null|float|string */ public static function SUMIF($range, $criteria, $sumRange = []) { return Statistical\Conditional::SUMIF($range, $criteria, $sumRange); } /** * SUMIFS. * * Totals the values of cells that contain numbers within the list of arguments * * Excel Function: * SUMIFS(sum_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...) * * @deprecated 1.17.0 * Use the SUMIFS() method in the Statistical\Conditional class instead * @see Statistical\Conditional::SUMIFS() * * @param mixed $args Data values * * @return null|float|string */ public static function SUMIFS(...$args) { return Statistical\Conditional::SUMIFS(...$args); } /** * SUMPRODUCT. * * Excel Function: * SUMPRODUCT(value1[,value2[, ...]]) * * @deprecated 1.18.0 * Use the product method in the MathTrig\Sum class instead * @see MathTrig\Sum::product() * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function SUMPRODUCT(...$args) { return MathTrig\Sum::product(...$args); } /** * SUMSQ. * * SUMSQ returns the sum of the squares of the arguments * * @deprecated 1.18.0 * Use the sumSquare method in the MathTrig\SumSquares class instead * @see MathTrig\SumSquares::sumSquare() * * Excel Function: * SUMSQ(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string */ public static function SUMSQ(...$args) { return MathTrig\SumSquares::sumSquare(...$args); } /** * SUMX2MY2. * * @deprecated 1.18.0 * Use the sumXSquaredMinusYSquared method in the MathTrig\SumSquares class instead * @see MathTrig\SumSquares::sumXSquaredMinusYSquared() * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * * @return float|string */ public static function SUMX2MY2($matrixData1, $matrixData2) { return MathTrig\SumSquares::sumXSquaredMinusYSquared($matrixData1, $matrixData2); } /** * SUMX2PY2. * * @deprecated 1.18.0 * Use the sumXSquaredPlusYSquared method in the MathTrig\SumSquares class instead * @see MathTrig\SumSquares::sumXSquaredPlusYSquared() * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * * @return float|string */ public static function SUMX2PY2($matrixData1, $matrixData2) { return MathTrig\SumSquares::sumXSquaredPlusYSquared($matrixData1, $matrixData2); } /** * SUMXMY2. * * @deprecated 1.18.0 * Use the sumXMinusYSquared method in the MathTrig\SumSquares class instead * @see MathTrig\SumSquares::sumXMinusYSquared() * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * * @return float|string */ public static function SUMXMY2($matrixData1, $matrixData2) { return MathTrig\SumSquares::sumXMinusYSquared($matrixData1, $matrixData2); } /** * TRUNC. * * Truncates value to the number of fractional digits by number_digits. * * @deprecated 1.17.0 * Use the evaluate() method in the MathTrig\Trunc class instead * @see MathTrig\Trunc::evaluate() * * @param float $value * @param int $digits * * @return array|float|string Truncated value, or a string containing an error */ public static function TRUNC($value = 0, $digits = 0) { return MathTrig\Trunc::evaluate($value, $digits); } /** * SEC. * * Returns the secant of an angle. * * @deprecated 1.18.0 * Use the sec method in the MathTrig\Trig\Secant class instead * @see MathTrig\Trig\Secant::sec() * * @param array|float $angle Number * * @return array|float|string The secant of the angle */ public static function SEC($angle) { return MathTrig\Trig\Secant::sec($angle); } /** * SECH. * * Returns the hyperbolic secant of an angle. * * @deprecated 1.18.0 * Use the sech method in the MathTrig\Trig\Secant class instead * @see MathTrig\Trig\Secant::sech() * * @param array|float $angle Number * * @return array|float|string The hyperbolic secant of the angle */ public static function SECH($angle) { return MathTrig\Trig\Secant::sech($angle); } /** * CSC. * * Returns the cosecant of an angle. * * @deprecated 1.18.0 * Use the csc method in the MathTrig\Trig\Cosecant class instead * @see MathTrig\Trig\Cosecant::csc() * * @param array|float $angle Number * * @return array|float|string The cosecant of the angle */ public static function CSC($angle) { return MathTrig\Trig\Cosecant::csc($angle); } /** * CSCH. * * Returns the hyperbolic cosecant of an angle. * * @deprecated 1.18.0 * Use the csch method in the MathTrig\Trig\Cosecant class instead * @see MathTrig\Trig\Cosecant::csch() * * @param array|float $angle Number * * @return array|float|string The hyperbolic cosecant of the angle */ public static function CSCH($angle) { return MathTrig\Trig\Cosecant::csch($angle); } /** * COT. * * Returns the cotangent of an angle. * * @deprecated 1.18.0 * Use the cot method in the MathTrig\Trig\Cotangent class instead * @see MathTrig\Trig\Cotangent::cot() * * @param array|float $angle Number * * @return array|float|string The cotangent of the angle */ public static function COT($angle) { return MathTrig\Trig\Cotangent::cot($angle); } /** * COTH. * * Returns the hyperbolic cotangent of an angle. * * @deprecated 1.18.0 * Use the coth method in the MathTrig\Trig\Cotangent class instead * @see MathTrig\Trig\Cotangent::coth() * * @param array|float $angle Number * * @return array|float|string The hyperbolic cotangent of the angle */ public static function COTH($angle) { return MathTrig\Trig\Cotangent::coth($angle); } /** * ACOT. * * Returns the arccotangent of a number. * * @deprecated 1.18.0 * Use the acot method in the MathTrig\Trig\Cotangent class instead * @see MathTrig\Trig\Cotangent::acot() * * @param array|float $number Number * * @return array|float|string The arccotangent of the number */ public static function ACOT($number) { return MathTrig\Trig\Cotangent::acot($number); } /** * Return NAN or value depending on argument. * * @deprecated 1.18.0 * Use the numberOrNan method in the MathTrig\Helpers class instead * @see MathTrig\Helpers::numberOrNan() * * @param float $result Number * * @return float|string */ public static function numberOrNan($result) { return MathTrig\Helpers::numberOrNan($result); } /** * ACOTH. * * Returns the hyperbolic arccotangent of a number. * * @deprecated 1.18.0 * Use the acoth method in the MathTrig\Trig\Cotangent class instead * @see MathTrig\Trig\Cotangent::acoth() * * @param array|float $number Number * * @return array|float|string The hyperbolic arccotangent of the number */ public static function ACOTH($number) { return MathTrig\Trig\Cotangent::acoth($number); } /** * ROUND. * * Returns the result of builtin function round after validating args. * * @deprecated 1.17.0 * Use the round() method in the MathTrig\Round class instead * @see MathTrig\Round::round() * * @param array|mixed $number Should be numeric * @param array|mixed $precision Should be int * * @return array|float|string Rounded number */ public static function builtinROUND($number, $precision) { return MathTrig\Round::round($number, $precision); } /** * ABS. * * Returns the result of builtin function abs after validating args. * * @deprecated 1.18.0 * Use the evaluate method in the MathTrig\Absolute class instead * @see MathTrig\Absolute::evaluate() * * @param array|mixed $number Should be numeric * * @return array|float|int|string Rounded number */ public static function builtinABS($number) { return MathTrig\Absolute::evaluate($number); } /** * ACOS. * * @deprecated 1.18.0 * Use the acos method in the MathTrig\Trig\Cosine class instead * @see MathTrig\Trig\Cosine::acos() * * Returns the result of builtin function acos after validating args. * * @param array|float $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinACOS($number) { return MathTrig\Trig\Cosine::acos($number); } /** * ACOSH. * * Returns the result of builtin function acosh after validating args. * * @deprecated 1.18.0 * Use the acosh method in the MathTrig\Trig\Cosine class instead * @see MathTrig\Trig\Cosine::acosh() * * @param array|float $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinACOSH($number) { return MathTrig\Trig\Cosine::acosh($number); } /** * ASIN. * * Returns the result of builtin function asin after validating args. * * @deprecated 1.18.0 * Use the asin method in the MathTrig\Trig\Sine class instead * @see MathTrig\Trig\Sine::asin() * * @param array|float $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinASIN($number) { return MathTrig\Trig\Sine::asin($number); } /** * ASINH. * * Returns the result of builtin function asinh after validating args. * * @deprecated 1.18.0 * Use the asinh method in the MathTrig\Trig\Sine class instead * @see MathTrig\Trig\Sine::asinh() * * @param array|float $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinASINH($number) { return MathTrig\Trig\Sine::asinh($number); } /** * ATAN. * * Returns the result of builtin function atan after validating args. * * @deprecated 1.18.0 * Use the atan method in the MathTrig\Trig\Tangent class instead * @see MathTrig\Trig\Tangent::atan() * * @param array|float $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinATAN($number) { return MathTrig\Trig\Tangent::atan($number); } /** * ATANH. * * Returns the result of builtin function atanh after validating args. * * @deprecated 1.18.0 * Use the atanh method in the MathTrig\Trig\Tangent class instead * @see MathTrig\Trig\Tangent::atanh() * * @param array|float $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinATANH($number) { return MathTrig\Trig\Tangent::atanh($number); } /** * COS. * * Returns the result of builtin function cos after validating args. * * @deprecated 1.18.0 * Use the cos method in the MathTrig\Trig\Cosine class instead * @see MathTrig\Trig\Cosine::cos() * * @param array|mixed $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinCOS($number) { return MathTrig\Trig\Cosine::cos($number); } /** * COSH. * * Returns the result of builtin function cos after validating args. * * @deprecated 1.18.0 * Use the cosh method in the MathTrig\Trig\Cosine class instead * @see MathTrig\Trig\Cosine::cosh() * * @param array|mixed $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinCOSH($number) { return MathTrig\Trig\Cosine::cosh($number); } /** * DEGREES. * * Returns the result of builtin function rad2deg after validating args. * * @deprecated 1.18.0 * Use the toDegrees method in the MathTrig\Angle class instead * @see MathTrig\Angle::toDegrees() * * @param array|mixed $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinDEGREES($number) { return MathTrig\Angle::toDegrees($number); } /** * EXP. * * Returns the result of builtin function exp after validating args. * * @deprecated 1.18.0 * Use the evaluate method in the MathTrig\Exp class instead * @see MathTrig\Exp::evaluate() * * @param array|mixed $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinEXP($number) { return MathTrig\Exp::evaluate($number); } /** * LN. * * Returns the result of builtin function log after validating args. * * @deprecated 1.18.0 * Use the natural method in the MathTrig\Logarithms class instead * @see MathTrig\Logarithms::natural() * * @param mixed $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinLN($number) { return MathTrig\Logarithms::natural($number); } /** * LOG10. * * Returns the result of builtin function log after validating args. * * @deprecated 1.18.0 * Use the natural method in the MathTrig\Logarithms class instead * @see MathTrig\Logarithms::base10() * * @param mixed $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinLOG10($number) { return MathTrig\Logarithms::base10($number); } /** * RADIANS. * * Returns the result of builtin function deg2rad after validating args. * * @deprecated 1.18.0 * Use the toRadians method in the MathTrig\Angle class instead * @see MathTrig\Angle::toRadians() * * @param array|mixed $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinRADIANS($number) { return MathTrig\Angle::toRadians($number); } /** * SIN. * * Returns the result of builtin function sin after validating args. * * @deprecated 1.18.0 * Use the sin method in the MathTrig\Trig\Sine class instead * @see MathTrig\Trig\Sine::evaluate() * * @param array|mixed $number Should be numeric * * @return array|float|string sine */ public static function builtinSIN($number) { return MathTrig\Trig\Sine::sin($number); } /** * SINH. * * Returns the result of builtin function sinh after validating args. * * @deprecated 1.18.0 * Use the sinh method in the MathTrig\Trig\Sine class instead * @see MathTrig\Trig\Sine::sinh() * * @param array|mixed $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinSINH($number) { return MathTrig\Trig\Sine::sinh($number); } /** * SQRT. * * Returns the result of builtin function sqrt after validating args. * * @deprecated 1.18.0 * Use the sqrt method in the MathTrig\Sqrt class instead * @see MathTrig\Sqrt::sqrt() * * @param array|mixed $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinSQRT($number) { return MathTrig\Sqrt::sqrt($number); } /** * TAN. * * Returns the result of builtin function tan after validating args. * * @deprecated 1.18.0 * Use the tan method in the MathTrig\Trig\Tangent class instead * @see MathTrig\Trig\Tangent::tan() * * @param array|mixed $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinTAN($number) { return MathTrig\Trig\Tangent::tan($number); } /** * TANH. * * Returns the result of builtin function sinh after validating args. * * @deprecated 1.18.0 * Use the tanh method in the MathTrig\Trig\Tangent class instead * @see MathTrig\Trig\Tangent::tanh() * * @param array|mixed $number Should be numeric * * @return array|float|string Rounded number */ public static function builtinTANH($number) { return MathTrig\Trig\Tangent::tanh($number); } /** * Many functions accept null/false/true argument treated as 0/0/1. * * @deprecated 1.18.0 * Use the validateNumericNullBool method in the MathTrig\Helpers class instead * @see MathTrig\Helpers::validateNumericNullBool() * * @param mixed $number */ public static function nullFalseTrueToNumber(&$number): void { $number = Functions::flattenSingleValue($number); if ($number === null) { $number = 0; } elseif (is_bool($number)) { $number = (int) $number; } } } phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaToken.php 0000644 00000010317 15002227416 0020647 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; /** * PARTLY BASED ON: * Copyright (c) 2007 E. W. Bachtal, Inc. * * 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. * * https://ewbi.blogs.com/develops/2007/03/excel_formula_p.html * https://ewbi.blogs.com/develops/2004/12/excel_formula_p.html */ class FormulaToken { // Token types const TOKEN_TYPE_NOOP = 'Noop'; const TOKEN_TYPE_OPERAND = 'Operand'; const TOKEN_TYPE_FUNCTION = 'Function'; const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression'; const TOKEN_TYPE_ARGUMENT = 'Argument'; const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix'; const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix'; const TOKEN_TYPE_OPERATORPOSTFIX = 'OperatorPostfix'; const TOKEN_TYPE_WHITESPACE = 'Whitespace'; const TOKEN_TYPE_UNKNOWN = 'Unknown'; // Token subtypes const TOKEN_SUBTYPE_NOTHING = 'Nothing'; const TOKEN_SUBTYPE_START = 'Start'; const TOKEN_SUBTYPE_STOP = 'Stop'; const TOKEN_SUBTYPE_TEXT = 'Text'; const TOKEN_SUBTYPE_NUMBER = 'Number'; const TOKEN_SUBTYPE_LOGICAL = 'Logical'; const TOKEN_SUBTYPE_ERROR = 'Error'; const TOKEN_SUBTYPE_RANGE = 'Range'; const TOKEN_SUBTYPE_MATH = 'Math'; const TOKEN_SUBTYPE_CONCATENATION = 'Concatenation'; const TOKEN_SUBTYPE_INTERSECTION = 'Intersection'; const TOKEN_SUBTYPE_UNION = 'Union'; /** * Value. * * @var string */ private $value; /** * Token Type (represented by TOKEN_TYPE_*). * * @var string */ private $tokenType; /** * Token SubType (represented by TOKEN_SUBTYPE_*). * * @var string */ private $tokenSubType; /** * Create a new FormulaToken. * * @param string $value * @param string $tokenType Token type (represented by TOKEN_TYPE_*) * @param string $tokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*) */ public function __construct($value, $tokenType = self::TOKEN_TYPE_UNKNOWN, $tokenSubType = self::TOKEN_SUBTYPE_NOTHING) { // Initialise values $this->value = $value; $this->tokenType = $tokenType; $this->tokenSubType = $tokenSubType; } /** * Get Value. * * @return string */ public function getValue() { return $this->value; } /** * Set Value. * * @param string $value */ public function setValue($value): void { $this->value = $value; } /** * Get Token Type (represented by TOKEN_TYPE_*). * * @return string */ public function getTokenType() { return $this->tokenType; } /** * Set Token Type (represented by TOKEN_TYPE_*). * * @param string $value */ public function setTokenType($value): void { $this->tokenType = $value; } /** * Get Token SubType (represented by TOKEN_SUBTYPE_*). * * @return string */ public function getTokenSubType() { return $this->tokenSubType; } /** * Set Token SubType (represented by TOKEN_SUBTYPE_*). * * @param string $value */ public function setTokenSubType($value): void { $this->tokenSubType = $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef.php 0000644 00000040202 15002227416 0020143 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Address; use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\HLookup; use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Indirect; use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Lookup; use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix; use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Offset; use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation; use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\VLookup; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; /** * @deprecated 1.18.0 */ class LookupRef { /** * CELL_ADDRESS. * * Creates a cell address as text, given specified row and column numbers. * * Excel Function: * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText]) * * @deprecated 1.18.0 * Use the cell() method in the LookupRef\Address class instead * @see LookupRef\Address::cell() * * @param mixed $row Row number to use in the cell reference * @param mixed $column Column number to use in the cell reference * @param int $relativity Flag indicating the type of reference to return * 1 or omitted Absolute * 2 Absolute row; relative column * 3 Relative row; absolute column * 4 Relative * @param bool $referenceStyle A logical value that specifies the A1 or R1C1 reference style. * TRUE or omitted CELL_ADDRESS returns an A1-style reference * FALSE CELL_ADDRESS returns an R1C1-style reference * @param array|string $sheetText Optional Name of worksheet to use * * @return array|string */ public static function cellAddress($row, $column, $relativity = 1, $referenceStyle = true, $sheetText = '') { return Address::cell($row, $column, $relativity, $referenceStyle, $sheetText); } /** * COLUMN. * * Returns the column number of the given cell reference * If the cell reference is a range of cells, COLUMN returns the column numbers of each column * in the reference as a horizontal array. * If cell reference is omitted, and the function is being called through the calculation engine, * then it is assumed to be the reference of the cell in which the COLUMN function appears; * otherwise this function returns 1. * * Excel Function: * =COLUMN([cellAddress]) * * @deprecated 1.18.0 * Use the COLUMN() method in the LookupRef\RowColumnInformation class instead * @see LookupRef\RowColumnInformation::COLUMN() * * @param null|array|string $cellAddress A reference to a range of cells for which you want the column numbers * * @return int|int[]|string */ public static function COLUMN($cellAddress = null, ?Cell $cell = null) { return RowColumnInformation::COLUMN($cellAddress, $cell); } /** * COLUMNS. * * Returns the number of columns in an array or reference. * * Excel Function: * =COLUMNS(cellAddress) * * @deprecated 1.18.0 * Use the COLUMNS() method in the LookupRef\RowColumnInformation class instead * @see LookupRef\RowColumnInformation::COLUMNS() * * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells * for which you want the number of columns * * @return int|string The number of columns in cellAddress, or a string if arguments are invalid */ public static function COLUMNS($cellAddress = null) { return RowColumnInformation::COLUMNS($cellAddress); } /** * ROW. * * Returns the row number of the given cell reference * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference * as a vertical array. * If cell reference is omitted, and the function is being called through the calculation engine, * then it is assumed to be the reference of the cell in which the ROW function appears; * otherwise this function returns 1. * * Excel Function: * =ROW([cellAddress]) * * @deprecated 1.18.0 * Use the ROW() method in the LookupRef\RowColumnInformation class instead * @see LookupRef\RowColumnInformation::ROW() * * @param null|array|string $cellAddress A reference to a range of cells for which you want the row numbers * * @return int|mixed[]|string */ public static function ROW($cellAddress = null, ?Cell $cell = null) { return RowColumnInformation::ROW($cellAddress, $cell); } /** * ROWS. * * Returns the number of rows in an array or reference. * * Excel Function: * =ROWS(cellAddress) * * @deprecated 1.18.0 * Use the ROWS() method in the LookupRef\RowColumnInformation class instead * @see LookupRef\RowColumnInformation::ROWS() * * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells * for which you want the number of rows * * @return int|string The number of rows in cellAddress, or a string if arguments are invalid */ public static function ROWS($cellAddress = null) { return RowColumnInformation::ROWS($cellAddress); } /** * HYPERLINK. * * Excel Function: * =HYPERLINK(linkURL,displayName) * * @deprecated 1.18.0 * Use the set() method in the LookupRef\Hyperlink class instead * @see LookupRef\Hyperlink::set() * * @param mixed $linkURL Expect string. Value to check, is also the value returned when no error * @param mixed $displayName Expect string. Value to return when testValue is an error condition * @param Cell $cell The cell to set the hyperlink in * * @return string The value of $displayName (or $linkURL if $displayName was blank) */ public static function HYPERLINK($linkURL = '', $displayName = null, ?Cell $cell = null) { return LookupRef\Hyperlink::set($linkURL, $displayName, $cell); } /** * INDIRECT. * * Returns the reference specified by a text string. * References are immediately evaluated to display their contents. * * Excel Function: * =INDIRECT(cellAddress) * * @deprecated 1.18.0 * Use the INDIRECT() method in the LookupRef\Indirect class instead * @see LookupRef\Indirect::INDIRECT() * * @param array|string $cellAddress $cellAddress The cell address of the current cell (containing this formula) * @param Cell $cell The current cell (containing this formula) * * @return array|string An array containing a cell or range of cells, or a string on error * * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010 */ public static function INDIRECT($cellAddress, Cell $cell) { return Indirect::INDIRECT($cellAddress, true, $cell); } /** * OFFSET. * * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells. * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and * the number of columns to be returned. * * Excel Function: * =OFFSET(cellAddress, rows, cols, [height], [width]) * * @deprecated 1.18.0 * Use the OFFSET() method in the LookupRef\Offset class instead * @see LookupRef\Offset::OFFSET() * * @param null|string $cellAddress The reference from which you want to base the offset. * Reference must refer to a cell or range of adjacent cells; * otherwise, OFFSET returns the #VALUE! error value. * @param mixed $rows The number of rows, up or down, that you want the upper-left cell to refer to. * Using 5 as the rows argument specifies that the upper-left cell in the * reference is five rows below reference. Rows can be positive (which means * below the starting reference) or negative (which means above the starting * reference). * @param mixed $columns The number of columns, to the left or right, that you want the upper-left cell * of the result to refer to. Using 5 as the cols argument specifies that the * upper-left cell in the reference is five columns to the right of reference. * Cols can be positive (which means to the right of the starting reference) * or negative (which means to the left of the starting reference). * @param mixed $height The height, in number of rows, that you want the returned reference to be. * Height must be a positive number. * @param mixed $width The width, in number of columns, that you want the returned reference to be. * Width must be a positive number. * * @return array|int|string An array containing a cell or range of cells, or a string on error */ public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null, ?Cell $cell = null) { return Offset::OFFSET($cellAddress, $rows, $columns, $height, $width, $cell); } /** * CHOOSE. * * Uses lookup_value to return a value from the list of value arguments. * Use CHOOSE to select one of up to 254 values based on the lookup_value. * * Excel Function: * =CHOOSE(index_num, value1, [value2], ...) * * @deprecated 1.18.0 * Use the choose() method in the LookupRef\Selection class instead * @see LookupRef\Selection::choose() * * @param array $chooseArgs * * @return mixed The selected value */ public static function CHOOSE(...$chooseArgs) { return LookupRef\Selection::choose(...$chooseArgs); } /** * MATCH. * * The MATCH function searches for a specified item in a range of cells * * Excel Function: * =MATCH(lookup_value, lookup_array, [match_type]) * * @deprecated 1.18.0 * Use the MATCH() method in the LookupRef\ExcelMatch class instead * @see LookupRef\ExcelMatch::MATCH() * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupArray The range of cells being searched * @param mixed $matchType The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. * If match_type is 1 or -1, the list has to be ordered. * * @return array|int|string The relative position of the found item */ public static function MATCH($lookupValue, $lookupArray, $matchType = 1) { return LookupRef\ExcelMatch::MATCH($lookupValue, $lookupArray, $matchType); } /** * INDEX. * * Uses an index to choose a value from a reference or array * * Excel Function: * =INDEX(range_array, row_num, [column_num]) * * @deprecated 1.18.0 * Use the index() method in the LookupRef\Matrix class instead * @see LookupRef\Matrix::index() * * @param mixed $rowNum The row in the array or range from which to return a value. * If row_num is omitted, column_num is required. * @param mixed $columnNum The column in the array or range from which to return a value. * If column_num is omitted, row_num is required. * @param mixed $matrix * * @return mixed the value of a specified cell or array of cells */ public static function INDEX($matrix, $rowNum = 0, $columnNum = 0) { return Matrix::index($matrix, $rowNum, $columnNum); } /** * TRANSPOSE. * * @deprecated 1.18.0 * Use the transpose() method in the LookupRef\Matrix class instead * @see LookupRef\Matrix::transpose() * * @param array $matrixData A matrix of values * * @return array * * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, * this function will transpose a full matrix */ public static function TRANSPOSE($matrixData) { return Matrix::transpose($matrixData); } /** * VLOOKUP * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value * in the same row based on the index_number. * * @deprecated 1.18.0 * Use the lookup() method in the LookupRef\VLookup class instead * @see LookupRef\VLookup::lookup() * * @param mixed $lookup_value The value that you want to match in lookup_array * @param mixed $lookup_array The range of cells being searched * @param mixed $index_number The column number in table_array from which the matching value must be returned. * The first column is 1. * @param mixed $not_exact_match determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) { return VLookup::lookup($lookup_value, $lookup_array, $index_number, $not_exact_match); } /** * HLOOKUP * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value * in the same column based on the index_number. * * @deprecated 1.18.0 * Use the lookup() method in the LookupRef\HLookup class instead * @see LookupRef\HLookup::lookup() * * @param mixed $lookup_value The value that you want to match in lookup_array * @param mixed $lookup_array The range of cells being searched * @param mixed $index_number The row number in table_array from which the matching value must be returned. * The first row is 1. * @param mixed $not_exact_match determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) { return HLookup::lookup($lookup_value, $lookup_array, $index_number, $not_exact_match); } /** * LOOKUP * The LOOKUP function searches for value either from a one-row or one-column range or from an array. * * @deprecated 1.18.0 * Use the lookup() method in the LookupRef\Lookup class instead * @see LookupRef\Lookup::lookup() * * @param mixed $lookup_value The value that you want to match in lookup_array * @param mixed $lookup_vector The range of cells being searched * @param null|mixed $result_vector The column from which the matching value must be returned * * @return mixed The value of the found cell */ public static function LOOKUP($lookup_value, $lookup_vector, $result_vector = null) { return Lookup::lookup($lookup_value, $lookup_vector, $result_vector); } /** * FORMULATEXT. * * @deprecated 1.18.0 * Use the text() method in the LookupRef\Formula class instead * @see LookupRef\Formula::text() * * @param mixed $cellReference The cell to check * @param Cell $cell The current cell (containing this formula) * * @return string */ public static function FORMULATEXT($cellReference = '', ?Cell $cell = null) { return LookupRef\Formula::text($cellReference, $cell); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/BinaryComparison.php 0000644 00000014551 15002227416 0021524 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class BinaryComparison { /** * Epsilon Precision used for comparisons in calculations. */ private const DELTA = 0.1e-12; /** * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters. * * @param null|string $str1 First string value for the comparison * @param null|string $str2 Second string value for the comparison */ private static function strcmpLowercaseFirst($str1, $str2): int { $inversedStr1 = StringHelper::strCaseReverse($str1 ?? ''); $inversedStr2 = StringHelper::strCaseReverse($str2 ?? ''); return strcmp($inversedStr1, $inversedStr2); } /** * PHP8.1 deprecates passing null to strcmp. * * @param null|string $str1 First string value for the comparison * @param null|string $str2 Second string value for the comparison */ private static function strcmpAllowNull($str1, $str2): int { return strcmp($str1 ?? '', $str2 ?? ''); } /** * @param mixed $operand1 * @param mixed $operand2 */ public static function compare($operand1, $operand2, string $operator): bool { // Simple validate the two operands if they are string values if (is_string($operand1) && $operand1 > '' && $operand1[0] == Calculation::FORMULA_STRING_QUOTE) { $operand1 = Calculation::unwrapResult($operand1); } if (is_string($operand2) && $operand2 > '' && $operand2[0] == Calculation::FORMULA_STRING_QUOTE) { $operand2 = Calculation::unwrapResult($operand2); } // Use case insensitive comparaison if not OpenOffice mode if (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) { if (is_string($operand1)) { $operand1 = StringHelper::strToUpper($operand1); } if (is_string($operand2)) { $operand2 = StringHelper::strToUpper($operand2); } } $useLowercaseFirstComparison = is_string($operand1) && is_string($operand2) && Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE; return self::evaluateComparison($operand1, $operand2, $operator, $useLowercaseFirstComparison); } /** * @param mixed $operand1 * @param mixed $operand2 */ private static function evaluateComparison($operand1, $operand2, string $operator, bool $useLowercaseFirstComparison): bool { switch ($operator) { // Equality case '=': return self::equal($operand1, $operand2); // Greater than case '>': return self::greaterThan($operand1, $operand2, $useLowercaseFirstComparison); // Less than case '<': return self::lessThan($operand1, $operand2, $useLowercaseFirstComparison); // Greater than or equal case '>=': return self::greaterThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison); // Less than or equal case '<=': return self::lessThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison); // Inequality case '<>': return self::notEqual($operand1, $operand2); default: throw new Exception('Unsupported binary comparison operator'); } } /** * @param mixed $operand1 * @param mixed $operand2 */ private static function equal($operand1, $operand2): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = (abs($operand1 - $operand2) < self::DELTA); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 == $operand2; } else { $result = self::strcmpAllowNull($operand1, $operand2) == 0; } return $result; } /** * @param mixed $operand1 * @param mixed $operand2 */ private static function greaterThanOrEqual($operand1, $operand2, bool $useLowercaseFirstComparison): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = ((abs($operand1 - $operand2) < self::DELTA) || ($operand1 > $operand2)); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 >= $operand2; } elseif ($useLowercaseFirstComparison) { $result = self::strcmpLowercaseFirst($operand1, $operand2) >= 0; } else { $result = self::strcmpAllowNull($operand1, $operand2) >= 0; } return $result; } /** * @param mixed $operand1 * @param mixed $operand2 */ private static function lessThanOrEqual($operand1, $operand2, bool $useLowercaseFirstComparison): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = ((abs($operand1 - $operand2) < self::DELTA) || ($operand1 < $operand2)); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 <= $operand2; } elseif ($useLowercaseFirstComparison) { $result = self::strcmpLowercaseFirst($operand1, $operand2) <= 0; } else { $result = self::strcmpAllowNull($operand1, $operand2) <= 0; } return $result; } /** * @param mixed $operand1 * @param mixed $operand2 */ private static function greaterThan($operand1, $operand2, bool $useLowercaseFirstComparison): bool { return self::lessThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison) !== true; } /** * @param mixed $operand1 * @param mixed $operand2 */ private static function lessThan($operand1, $operand2, bool $useLowercaseFirstComparison): bool { return self::greaterThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison) !== true; } /** * @param mixed $operand1 * @param mixed $operand2 */ private static function notEqual($operand1, $operand2): bool { return self::equal($operand1, $operand2) !== true; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Web.php 0000644 00000001165 15002227416 0016757 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; /** * @deprecated 1.18.0 * * @codeCoverageIgnore */ class Web { /** * WEBSERVICE. * * Returns data from a web service on the Internet or Intranet. * * Excel Function: * Webservice(url) * * @deprecated 1.18.0 * Use the webService() method in the Web\Service class instead * @see Web\Service::webService() * * @return string the output resulting from a call to the webservice */ public static function WEBSERVICE(string $url) { return Web\Service::webService($url); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DProduct.php 0000644 00000004243 15002227416 0021472 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; class DProduct extends DatabaseAbstract { /** * DPRODUCT. * * Multiplies the values in a column of a list or database that match conditions that you specify. * * Excel Function: * DPRODUCT(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return float|string */ public static function evaluate($database, $field, $criteria) { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return MathTrig\Operations::product( self::getFilteredColumn($database, $field, $criteria) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DCountA.php 0000644 00000004240 15002227416 0021240 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts; class DCountA extends DatabaseAbstract { /** * DCOUNTA. * * Counts the nonblank cells in a column of a list or database that match conditions that you specify. * * Excel Function: * DCOUNTA(database,[field],criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return int|string */ public static function evaluate($database, $field, $criteria) { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Counts::COUNTA( self::getFilteredColumn($database, $field, $criteria) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DStDevP.php 0000644 00000004413 15002227416 0021216 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations; class DStDevP extends DatabaseAbstract { /** * DSTDEVP. * * Calculates the standard deviation of a population based on the entire population by using the * numbers in a column of a list or database that match conditions that you specify. * * Excel Function: * DSTDEVP(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return float|string */ public static function evaluate($database, $field, $criteria) { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return StandardDeviations::STDEVP( self::getFilteredColumn($database, $field, $criteria) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DMax.php 0000644 00000004325 15002227416 0020600 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum; class DMax extends DatabaseAbstract { /** * DMAX. * * Returns the largest number in a column of a list or database that matches conditions you that * specify. * * Excel Function: * DMAX(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return null|float|string */ public static function evaluate($database, $field, $criteria, bool $returnError = true) { $field = self::fieldExtract($database, $field); if ($field === null) { return $returnError ? ExcelError::VALUE() : null; } return Maximum::max( self::getFilteredColumn($database, $field, $criteria) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php 0000644 00000017074 15002227416 0023144 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch; abstract class DatabaseAbstract { /** * @param array $database * @param int|string $field * @param array $criteria * * @return null|float|int|string */ abstract public static function evaluate($database, $field, $criteria); /** * fieldExtract. * * Extracts the column ID to use for the data field. * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param mixed $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. */ protected static function fieldExtract(array $database, $field): ?int { $field = strtoupper(Functions::flattenSingleValue($field) ?? ''); if ($field === '') { return null; } $fieldNames = array_map('strtoupper', array_shift($database)); if (is_numeric($field)) { $field = (int) $field - 1; if ($field < 0 || $field >= count($fieldNames)) { return null; } return $field; } $key = array_search($field, array_values($fieldNames), true); return ($key !== false) ? (int) $key : null; } /** * filter. * * Parses the selection criteria, extracts the database rows that match those criteria, and * returns that subset of rows. * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return mixed[] */ protected static function filter(array $database, array $criteria): array { $fieldNames = array_shift($database); $criteriaNames = array_shift($criteria); // Convert the criteria into a set of AND/OR conditions with [:placeholders] $query = self::buildQuery($criteriaNames, $criteria); // Loop through each row of the database return self::executeQuery($database, $query, $criteriaNames, $fieldNames); } protected static function getFilteredColumn(array $database, ?int $field, array $criteria): array { // reduce the database to a set of rows that match all the criteria $database = self::filter($database, $criteria); $defaultReturnColumnValue = ($field === null) ? 1 : null; // extract an array of values for the requested column $columnData = []; foreach ($database as $rowKey => $row) { $keys = array_keys($row); $key = $keys[$field] ?? null; $columnKey = $key ?? 'A'; $columnData[$rowKey][$columnKey] = $row[$key] ?? $defaultReturnColumnValue; } return $columnData; } private static function buildQuery(array $criteriaNames, array $criteria): string { $baseQuery = []; foreach ($criteria as $key => $criterion) { foreach ($criterion as $field => $value) { $criterionName = $criteriaNames[$field]; if ($value !== null) { $condition = self::buildCondition($value, $criterionName); $baseQuery[$key][] = $condition; } } } $rowQuery = array_map( function ($rowValue) { return (count($rowValue) > 1) ? 'AND(' . implode(',', $rowValue) . ')' : ($rowValue[0] ?? ''); }, $baseQuery ); return (count($rowQuery) > 1) ? 'OR(' . implode(',', $rowQuery) . ')' : ($rowQuery[0] ?? ''); } /** * @param mixed $criterion */ private static function buildCondition($criterion, string $criterionName): string { $ifCondition = Functions::ifCondition($criterion); // Check for wildcard characters used in the condition $result = preg_match('/(?<operator>[^"]*)(?<operand>".*[*?].*")/ui', $ifCondition, $matches); if ($result !== 1) { return "[:{$criterionName}]{$ifCondition}"; } $trueFalse = ($matches['operator'] !== '<>'); $wildcard = WildcardMatch::wildcard($matches['operand']); $condition = "WILDCARDMATCH([:{$criterionName}],{$wildcard})"; if ($trueFalse === false) { $condition = "NOT({$condition})"; } return $condition; } private static function executeQuery(array $database, string $query, array $criteria, array $fields): array { foreach ($database as $dataRow => $dataValues) { // Substitute actual values from the database row for our [:placeholders] $conditions = $query; foreach ($criteria as $criterion) { $conditions = self::processCondition($criterion, $fields, $dataValues, $conditions); } // evaluate the criteria against the row data $result = Calculation::getInstance()->_calculateFormulaValue('=' . $conditions); // If the row failed to meet the criteria, remove it from the database if ($result !== true) { unset($database[$dataRow]); } } return $database; } /** * @return mixed */ private static function processCondition(string $criterion, array $fields, array $dataValues, string $conditions) { $key = array_search($criterion, $fields, true); $dataValue = 'NULL'; if (is_bool($dataValues[$key])) { $dataValue = ($dataValues[$key]) ? 'TRUE' : 'FALSE'; } elseif ($dataValues[$key] !== null) { $dataValue = $dataValues[$key]; // escape quotes if we have a string containing quotes if (is_string($dataValue) && strpos($dataValue, '"') !== false) { $dataValue = str_replace('"', '""', $dataValue); } $dataValue = (is_string($dataValue)) ? Calculation::wrapResult(strtoupper($dataValue)) : $dataValue; } return str_replace('[:' . $criterion . ']', $dataValue, $conditions); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DAverage.php 0000644 00000004047 15002227416 0021426 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; class DAverage extends DatabaseAbstract { /** * DAVERAGE. * * Averages the values in a column of a list or database that match conditions you specify. * * Excel Function: * DAVERAGE(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return float|string */ public static function evaluate($database, $field, $criteria) { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Averages::average( self::getFilteredColumn($database, $field, $criteria) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DGet.php 0000644 00000004334 15002227416 0020572 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class DGet extends DatabaseAbstract { /** * DGET. * * Extracts a single value from a column of a list or database that matches conditions that you * specify. * * Excel Function: * DGET(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return mixed */ public static function evaluate($database, $field, $criteria) { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } $columnData = self::getFilteredColumn($database, $field, $criteria); if (count($columnData) > 1) { return ExcelError::NAN(); } $row = array_pop($columnData); return array_pop($row); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DStDev.php 0000644 00000004371 15002227416 0021101 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations; class DStDev extends DatabaseAbstract { /** * DSTDEV. * * Estimates the standard deviation of a population based on a sample by using the numbers in a * column of a list or database that match conditions that you specify. * * Excel Function: * DSTDEV(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return float|string */ public static function evaluate($database, $field, $criteria) { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return StandardDeviations::STDEV( self::getFilteredColumn($database, $field, $criteria) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DVarP.php 0000644 00000004406 15002227416 0020723 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances; class DVarP extends DatabaseAbstract { /** * DVARP. * * Calculates the variance of a population based on the entire population by using the numbers * in a column of a list or database that match conditions that you specify. * * Excel Function: * DVARP(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return float|string (string if result is an error) */ public static function evaluate($database, $field, $criteria) { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Variances::VARP( self::getFilteredColumn($database, $field, $criteria) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DVar.php 0000644 00000004364 15002227416 0020606 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances; class DVar extends DatabaseAbstract { /** * DVAR. * * Estimates the variance of a population based on a sample by using the numbers in a column * of a list or database that match conditions that you specify. * * Excel Function: * DVAR(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return float|string (string if result is an error) */ public static function evaluate($database, $field, $criteria) { $field = self::fieldExtract($database, $field); if ($field === null) { return ExcelError::VALUE(); } return Variances::VAR( self::getFilteredColumn($database, $field, $criteria) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DCount.php 0000644 00000004336 15002227416 0021145 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts; class DCount extends DatabaseAbstract { /** * DCOUNT. * * Counts the cells that contain numbers in a column of a list or database that match conditions * that you specify. * * Excel Function: * DCOUNT(database,[field],criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param null|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return int|string */ public static function evaluate($database, $field, $criteria, bool $returnError = true) { $field = self::fieldExtract($database, $field); if ($returnError && $field === null) { return ExcelError::VALUE(); } return Counts::COUNT( self::getFilteredColumn($database, $field, $criteria) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DSum.php 0000644 00000004312 15002227416 0020613 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; class DSum extends DatabaseAbstract { /** * DSUM. * * Adds the numbers in a column of a list or database that match conditions that you specify. * * Excel Function: * DSUM(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return null|float|string */ public static function evaluate($database, $field, $criteria, bool $returnNull = false) { $field = self::fieldExtract($database, $field); if ($field === null) { return $returnNull ? null : ExcelError::VALUE(); } return MathTrig\Sum::sumIgnoringStrings( self::getFilteredColumn($database, $field, $criteria) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DMin.php 0000644 00000004326 15002227416 0020577 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Database; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum; class DMin extends DatabaseAbstract { /** * DMIN. * * Returns the smallest number in a column of a list or database that matches conditions you that * specify. * * Excel Function: * DMIN(database,field,criteria) * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. * @param int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for * the first column, 2 for the second column, and so on. * @param mixed[] $criteria The range of cells that contains the conditions you specify. * You can use any range for the criteria argument, as long as it * includes at least one column label and at least one cell below * the column label in which you specify a condition for the * column. * * @return null|float|string */ public static function evaluate($database, $field, $criteria, bool $returnError = true) { $field = self::fieldExtract($database, $field); if ($field === null) { return $returnError ? ExcelError::VALUE() : null; } return Minimum::min( self::getFilteredColumn($database, $field, $criteria) ); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php 0000644 00000002052 15002227416 0026246 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\FinancialValidations; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class SecurityValidations extends FinancialValidations { /** * @param mixed $issue */ public static function validateIssueDate($issue): float { return self::validateDate($issue); } /** * @param mixed $settlement * @param mixed $maturity */ public static function validateSecurityPeriod($settlement, $maturity): void { if ($settlement >= $maturity) { throw new Exception(ExcelError::NAN()); } } /** * @param mixed $redemption */ public static function validateRedemption($redemption): float { $redemption = self::validateFloat($redemption); if ($redemption <= 0.0) { throw new Exception(ExcelError::NAN()); } return $redemption; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php 0000644 00000016075 15002227416 0023504 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Helpers; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class Yields { /** * YIELDDISC. * * Returns the annual yield of a security that pays interest at maturity. * * @param mixed $settlement The security's settlement date. * The security's settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $price The security's price per $100 face value * @param mixed $redemption The security's redemption value per $100 face value * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function yieldDiscounted( $settlement, $maturity, $price, $redemption, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $price = Functions::flattenSingleValue($price); $redemption = Functions::flattenSingleValue($redemption); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $price = SecurityValidations::validatePrice($price); $redemption = SecurityValidations::validateRedemption($redemption); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (!is_numeric($daysPerYear)) { return $daysPerYear; } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } $daysBetweenSettlementAndMaturity *= $daysPerYear; return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity); } /** * YIELDMAT. * * Returns the annual yield of a security that pays interest at maturity. * * @param mixed $settlement The security's settlement date. * The security's settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param mixed $rate The security's interest rate at date of issue * @param mixed $price The security's price per $100 face value * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function yieldAtMaturity( $settlement, $maturity, $issue, $rate, $price, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $issue = Functions::flattenSingleValue($issue); $rate = Functions::flattenSingleValue($rate); $price = Functions::flattenSingleValue($price); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $issue = SecurityValidations::validateIssueDate($issue); $rate = SecurityValidations::validateRate($rate); $price = SecurityValidations::validatePrice($price); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (!is_numeric($daysPerYear)) { return $daysPerYear; } $daysBetweenIssueAndSettlement = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return $daysBetweenIssueAndSettlement; } $daysBetweenIssueAndSettlement *= $daysPerYear; $daysBetweenIssueAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis)); if (!is_numeric($daysBetweenIssueAndMaturity)) { // return date error return $daysBetweenIssueAndMaturity; } $daysBetweenIssueAndMaturity *= $daysPerYear; $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } $daysBetweenSettlementAndMaturity *= $daysPerYear; return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) / (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) * ($daysPerYear / $daysBetweenSettlementAndMaturity); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php 0000644 00000013373 15002227416 0023327 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Rates { /** * DISC. * * Returns the discount rate for a security. * * Excel Function: * DISC(settlement,maturity,price,redemption[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $price The security's price per $100 face value * @param mixed $redemption The security's redemption value per $100 face value * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string */ public static function discount( $settlement, $maturity, $price, $redemption, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $price = Functions::flattenSingleValue($price); $redemption = Functions::flattenSingleValue($redemption); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $price = SecurityValidations::validatePrice($price); $redemption = SecurityValidations::validateRedemption($redemption); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } if ($price <= 0.0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } return (1 - $price / $redemption) / $daysBetweenSettlementAndMaturity; } /** * INTRATE. * * Returns the interest rate for a fully invested security. * * Excel Function: * INTRATE(settlement,maturity,investment,redemption[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $investment the amount invested in the security * @param mixed $redemption the amount to be received at maturity * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string */ public static function interest( $settlement, $maturity, $investment, $redemption, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $investment = Functions::flattenSingleValue($investment); $redemption = Functions::flattenSingleValue($redemption); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $investment = SecurityValidations::validateFloat($investment); $redemption = SecurityValidations::validateRedemption($redemption); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } if ($investment <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php 0000644 00000015405 15002227416 0025333 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\YearFrac; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class AccruedInterest { public const ACCRINT_CALCMODE_ISSUE_TO_SETTLEMENT = true; public const ACCRINT_CALCMODE_FIRST_INTEREST_TO_SETTLEMENT = false; /** * ACCRINT. * * Returns the accrued interest for a security that pays periodic interest. * * Excel Function: * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis][,calc_method]) * * @param mixed $issue the security's issue date * @param mixed $firstInterest the security's first interest date * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date * when the security is traded to the buyer. * @param mixed $rate The security's annual coupon rate * @param mixed $parValue The security's par value. * If you omit par, ACCRINT uses $1,000. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * @param mixed $calcMethod * * @return float|string Result, or a string containing an error */ public static function periodic( $issue, $firstInterest, $settlement, $rate, $parValue = 1000, $frequency = FinancialConstants::FREQUENCY_ANNUAL, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD, $calcMethod = self::ACCRINT_CALCMODE_ISSUE_TO_SETTLEMENT ) { self::doNothing($calcMethod); $issue = Functions::flattenSingleValue($issue); $firstInterest = Functions::flattenSingleValue($firstInterest); $settlement = Functions::flattenSingleValue($settlement); $rate = Functions::flattenSingleValue($rate); $parValue = ($parValue === null) ? 1000 : Functions::flattenSingleValue($parValue); $frequency = ($frequency === null) ? FinancialConstants::FREQUENCY_ANNUAL : Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $issue = SecurityValidations::validateIssueDate($issue); $settlement = SecurityValidations::validateSettlementDate($settlement); SecurityValidations::validateSecurityPeriod($issue, $settlement); $rate = SecurityValidations::validateRate($rate); $parValue = SecurityValidations::validateParValue($parValue); $frequency = SecurityValidations::validateFrequency($frequency); self::doNothing($frequency); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysBetweenIssueAndSettlement = Functions::scalar(YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return $daysBetweenIssueAndSettlement; } $daysBetweenFirstInterestAndSettlement = Functions::scalar(YearFrac::fraction($firstInterest, $settlement, $basis)); if (!is_numeric($daysBetweenFirstInterestAndSettlement)) { // return date error return $daysBetweenFirstInterestAndSettlement; } return $parValue * $rate * $daysBetweenIssueAndSettlement; } /** * ACCRINTM. * * Returns the accrued interest for a security that pays interest at maturity. * * Excel Function: * ACCRINTM(issue,settlement,rate[,par[,basis]]) * * @param mixed $issue The security's issue date * @param mixed $settlement The security's settlement (or maturity) date * @param mixed $rate The security's annual coupon rate * @param mixed $parValue The security's par value. * If you omit parValue, ACCRINT uses $1,000. * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function atMaturity( $issue, $settlement, $rate, $parValue = 1000, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $issue = Functions::flattenSingleValue($issue); $settlement = Functions::flattenSingleValue($settlement); $rate = Functions::flattenSingleValue($rate); $parValue = ($parValue === null) ? 1000 : Functions::flattenSingleValue($parValue); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $issue = SecurityValidations::validateIssueDate($issue); $settlement = SecurityValidations::validateSettlementDate($settlement); SecurityValidations::validateSecurityPeriod($issue, $settlement); $rate = SecurityValidations::validateRate($rate); $parValue = SecurityValidations::validateParValue($parValue); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysBetweenIssueAndSettlement = Functions::scalar(YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return $daysBetweenIssueAndSettlement; } return $parValue * $rate * $daysBetweenIssueAndSettlement; } /** @param mixed $arg */ private static function doNothing($arg): bool { return (bool) $arg; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php 0000644 00000031603 15002227416 0023307 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Helpers; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Price { /** * PRICE. * * Returns the price per $100 face value of a security that pays periodic interest. * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $rate the security's annual coupon rate * @param mixed $yield the security's annual yield * @param mixed $redemption The number of coupon payments per year. * For annual payments, frequency = 1; * for semiannual, frequency = 2; * for quarterly, frequency = 4. * @param mixed $frequency * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function price( $settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $rate = Functions::flattenSingleValue($rate); $yield = Functions::flattenSingleValue($yield); $redemption = Functions::flattenSingleValue($redemption); $frequency = Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $rate = SecurityValidations::validateRate($rate); $yield = SecurityValidations::validateYield($yield); $redemption = SecurityValidations::validateRedemption($redemption); $frequency = SecurityValidations::validateFrequency($frequency); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $dsc = (float) Coupons::COUPDAYSNC($settlement, $maturity, $frequency, $basis); $e = (float) Coupons::COUPDAYS($settlement, $maturity, $frequency, $basis); $n = (int) Coupons::COUPNUM($settlement, $maturity, $frequency, $basis); $a = (float) Coupons::COUPDAYBS($settlement, $maturity, $frequency, $basis); $baseYF = 1.0 + ($yield / $frequency); $rfp = 100 * ($rate / $frequency); $de = $dsc / $e; $result = $redemption / $baseYF ** (--$n + $de); for ($k = 0; $k <= $n; ++$k) { $result += $rfp / ($baseYF ** ($k + $de)); } $result -= $rfp * ($a / $e); return $result; } /** * PRICEDISC. * * Returns the price per $100 face value of a discounted security. * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $discount The security's discount rate * @param mixed $redemption The security's redemption value per $100 face value * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function priceDiscounted( $settlement, $maturity, $discount, $redemption, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $discount = Functions::flattenSingleValue($discount); $redemption = Functions::flattenSingleValue($redemption); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $discount = SecurityValidations::validateDiscount($discount); $redemption = SecurityValidations::validateRedemption($redemption); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity); } /** * PRICEMAT. * * Returns the price per $100 face value of a security that pays interest at maturity. * * @param mixed $settlement The security's settlement date. * The security's settlement date is the date after the issue date when the * security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param mixed $rate The security's interest rate at date of issue * @param mixed $yield The security's annual yield * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function priceAtMaturity( $settlement, $maturity, $issue, $rate, $yield, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $issue = Functions::flattenSingleValue($issue); $rate = Functions::flattenSingleValue($rate); $yield = Functions::flattenSingleValue($yield); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $issue = SecurityValidations::validateIssueDate($issue); $rate = SecurityValidations::validateRate($rate); $yield = SecurityValidations::validateYield($yield); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (!is_numeric($daysPerYear)) { return $daysPerYear; } $daysBetweenIssueAndSettlement = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis)); if (!is_numeric($daysBetweenIssueAndSettlement)) { // return date error return $daysBetweenIssueAndSettlement; } $daysBetweenIssueAndSettlement *= $daysPerYear; $daysBetweenIssueAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis)); if (!is_numeric($daysBetweenIssueAndMaturity)) { // return date error return $daysBetweenIssueAndMaturity; } $daysBetweenIssueAndMaturity *= $daysPerYear; $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return $daysBetweenSettlementAndMaturity; } $daysBetweenSettlementAndMaturity *= $daysPerYear; return (100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) / (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) - (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100); } /** * RECEIVED. * * Returns the amount received at maturity for a fully invested Security. * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue date when the security * is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $investment The amount invested in the security * @param mixed $discount The security's discount rate * @param mixed $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function received( $settlement, $maturity, $investment, $discount, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $investment = Functions::flattenSingleValue($investment); $discount = Functions::flattenSingleValue($discount); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = SecurityValidations::validateSettlementDate($settlement); $maturity = SecurityValidations::validateMaturityDate($maturity); SecurityValidations::validateSecurityPeriod($settlement, $maturity); $investment = SecurityValidations::validateFloat($investment); $discount = SecurityValidations::validateDiscount($discount); $basis = SecurityValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } if ($investment <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis); if (!is_numeric($daysBetweenSettlementAndMaturity)) { // return date error return Functions::scalar($daysBetweenSettlementAndMaturity); } return $investment / (1 - ($discount * $daysBetweenSettlementAndMaturity)); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php 0000644 00000011323 15002227416 0026760 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\CashFlowValidations; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Payments { /** * PMT. * * Returns the constant payment (annuity) for a cash flow with a constant interest rate. * * @param mixed $interestRate Interest rate per period * @param mixed $numberOfPeriods Number of periods * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function annuity( $interestRate, $numberOfPeriods, $presentValue, $futureValue = 0, $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $interestRate = Functions::flattenSingleValue($interestRate); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $interestRate = CashFlowValidations::validateRate($interestRate); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Calculate if ($interestRate != 0.0) { return (-$futureValue - $presentValue * (1 + $interestRate) ** $numberOfPeriods) / (1 + $interestRate * $type) / (((1 + $interestRate) ** $numberOfPeriods - 1) / $interestRate); } return (-$presentValue - $futureValue) / $numberOfPeriods; } /** * PPMT. * * Returns the interest payment for a given period for an investment based on periodic, constant payments * and a constant interest rate. * * @param mixed $interestRate Interest rate per period * @param mixed $period Period for which we want to find the interest * @param mixed $numberOfPeriods Number of periods * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function interestPayment( $interestRate, $period, $numberOfPeriods, $presentValue, $futureValue = 0, $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $interestRate = Functions::flattenSingleValue($interestRate); $period = Functions::flattenSingleValue($period); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $interestRate = CashFlowValidations::validateRate($interestRate); $period = CashFlowValidations::validateInt($period); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($period <= 0 || $period > $numberOfPeriods) { return ExcelError::NAN(); } // Calculate $interestAndPrincipal = new InterestAndPrincipal( $interestRate, $period, $numberOfPeriods, $presentValue, $futureValue, $type ); return $interestAndPrincipal->principal(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php 0000644 00000022220 15002227416 0026753 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\CashFlowValidations; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Interest { private const FINANCIAL_MAX_ITERATIONS = 128; private const FINANCIAL_PRECISION = 1.0e-08; /** * IPMT. * * Returns the interest payment for a given period for an investment based on periodic, constant payments * and a constant interest rate. * * Excel Function: * IPMT(rate,per,nper,pv[,fv][,type]) * * @param mixed $interestRate Interest rate per period * @param mixed $period Period for which we want to find the interest * @param mixed $numberOfPeriods Number of periods * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string */ public static function payment( $interestRate, $period, $numberOfPeriods, $presentValue, $futureValue = 0, $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $interestRate = Functions::flattenSingleValue($interestRate); $period = Functions::flattenSingleValue($period); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $interestRate = CashFlowValidations::validateRate($interestRate); $period = CashFlowValidations::validateInt($period); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($period <= 0 || $period > $numberOfPeriods) { return ExcelError::NAN(); } // Calculate $interestAndPrincipal = new InterestAndPrincipal( $interestRate, $period, $numberOfPeriods, $presentValue, $futureValue, $type ); return $interestAndPrincipal->interest(); } /** * ISPMT. * * Returns the interest payment for an investment based on an interest rate and a constant payment schedule. * * Excel Function: * =ISPMT(interest_rate, period, number_payments, pv) * * @param mixed $interestRate is the interest rate for the investment * @param mixed $period is the period to calculate the interest rate. It must be betweeen 1 and number_payments. * @param mixed $numberOfPeriods is the number of payments for the annuity * @param mixed $principleRemaining is the loan amount or present value of the payments * * @return float|string */ public static function schedulePayment($interestRate, $period, $numberOfPeriods, $principleRemaining) { $interestRate = Functions::flattenSingleValue($interestRate); $period = Functions::flattenSingleValue($period); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $principleRemaining = Functions::flattenSingleValue($principleRemaining); try { $interestRate = CashFlowValidations::validateRate($interestRate); $period = CashFlowValidations::validateInt($period); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $principleRemaining = CashFlowValidations::validateFloat($principleRemaining); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($period <= 0 || $period > $numberOfPeriods) { return ExcelError::NAN(); } // Return value $returnValue = 0; // Calculate $principlePayment = ($principleRemaining * 1.0) / ($numberOfPeriods * 1.0); for ($i = 0; $i <= $period; ++$i) { $returnValue = $interestRate * $principleRemaining * -1; $principleRemaining -= $principlePayment; // principle needs to be 0 after the last payment, don't let floating point screw it up if ($i == $numberOfPeriods) { $returnValue = 0.0; } } return $returnValue; } /** * RATE. * * Returns the interest rate per period of an annuity. * RATE is calculated by iteration and can have zero or more solutions. * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations, * RATE returns the #NUM! error value. * * Excel Function: * RATE(nper,pmt,pv[,fv[,type[,guess]]]) * * @param mixed $numberOfPeriods The total number of payment periods in an annuity * @param mixed $payment The payment made each period and cannot change over the life of the annuity. * Typically, pmt includes principal and interest but no other fees or taxes. * @param mixed $presentValue The present value - the total amount that a series of future payments is worth now * @param mixed $futureValue The future value, or a cash balance you want to attain after the last payment is made. * If fv is omitted, it is assumed to be 0 (the future value of a loan, * for example, is 0). * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * @param mixed $guess Your guess for what the rate will be. * If you omit guess, it is assumed to be 10 percent. * * @return float|string */ public static function rate( $numberOfPeriods, $payment, $presentValue, $futureValue = 0.0, $type = FinancialConstants::PAYMENT_END_OF_PERIOD, $guess = 0.1 ) { $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $payment = Functions::flattenSingleValue($payment); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); $guess = ($guess === null) ? 0.1 : Functions::flattenSingleValue($guess); try { $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $payment = CashFlowValidations::validateFloat($payment); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); $guess = CashFlowValidations::validateFloat($guess); } catch (Exception $e) { return $e->getMessage(); } $rate = $guess; // rest of code adapted from python/numpy $close = false; $iter = 0; while (!$close && $iter < self::FINANCIAL_MAX_ITERATIONS) { $nextdiff = self::rateNextGuess($rate, $numberOfPeriods, $payment, $presentValue, $futureValue, $type); if (!is_numeric($nextdiff)) { break; } $rate1 = $rate - $nextdiff; $close = abs($rate1 - $rate) < self::FINANCIAL_PRECISION; ++$iter; $rate = $rate1; } return $close ? $rate : ExcelError::NAN(); } /** @return float|string */ private static function rateNextGuess(float $rate, int $numberOfPeriods, float $payment, float $presentValue, float $futureValue, int $type) { if ($rate == 0.0) { return ExcelError::NAN(); } $tt1 = ($rate + 1) ** $numberOfPeriods; $tt2 = ($rate + 1) ** ($numberOfPeriods - 1); $numerator = $futureValue + $tt1 * $presentValue + $payment * ($tt1 - 1) * ($rate * $type + 1) / $rate; $denominator = $numberOfPeriods * $tt2 * $presentValue - $payment * ($tt1 - 1) * ($rate * $type + 1) / ($rate * $rate) + $numberOfPeriods * $payment * $tt2 * ($rate * $type + 1) / $rate + $payment * ($tt1 - 1) * $type / $rate; if ($denominator == 0) { return ExcelError::NAN(); } return $numerator / $denominator; } } src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php 0000644 00000002354 15002227416 0031167 0 ustar 00 phpspreadsheet <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; class InterestAndPrincipal { /** @var float */ protected $interest; /** @var float */ protected $principal; public function __construct( float $rate = 0.0, int $period = 0, int $numberOfPeriods = 0, float $presentValue = 0, float $futureValue = 0, int $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $payment = Payments::annuity($rate, $numberOfPeriods, $presentValue, $futureValue, $type); $capital = $presentValue; $interest = 0.0; $principal = 0.0; for ($i = 1; $i <= $period; ++$i) { $interest = ($type === FinancialConstants::PAYMENT_BEGINNING_OF_PERIOD && $i == 1) ? 0 : -$capital * $rate; $principal = (float) $payment - $interest; $capital += $principal; } $this->interest = $interest; $this->principal = $principal; } public function interest(): float { return $this->interest; } public function principal(): float { return $this->principal; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Cumulative.php 0000644 00000012221 15002227416 0027274 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant\Periodic; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\CashFlowValidations; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Cumulative { /** * CUMIPMT. * * Returns the cumulative interest paid on a loan between the start and end periods. * * Excel Function: * CUMIPMT(rate,nper,pv,start,end[,type]) * * @param mixed $rate The Interest rate * @param mixed $periods The total number of payment periods * @param mixed $presentValue Present Value * @param mixed $start The first period in the calculation. * Payment periods are numbered beginning with 1. * @param mixed $end the last period in the calculation * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * * @return float|string */ public static function interest( $rate, $periods, $presentValue, $start, $end, $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $rate = Functions::flattenSingleValue($rate); $periods = Functions::flattenSingleValue($periods); $presentValue = Functions::flattenSingleValue($presentValue); $start = Functions::flattenSingleValue($start); $end = Functions::flattenSingleValue($end); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $rate = CashFlowValidations::validateRate($rate); $periods = CashFlowValidations::validateInt($periods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $start = CashFlowValidations::validateInt($start); $end = CashFlowValidations::validateInt($end); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($start < 1 || $start > $end) { return ExcelError::NAN(); } // Calculate $interest = 0; for ($per = $start; $per <= $end; ++$per) { $ipmt = Interest::payment($rate, $per, $periods, $presentValue, 0, $type); if (is_string($ipmt)) { return $ipmt; } $interest += $ipmt; } return $interest; } /** * CUMPRINC. * * Returns the cumulative principal paid on a loan between the start and end periods. * * Excel Function: * CUMPRINC(rate,nper,pv,start,end[,type]) * * @param mixed $rate The Interest rate * @param mixed $periods The total number of payment periods as an integer * @param mixed $presentValue Present Value * @param mixed $start The first period in the calculation. * Payment periods are numbered beginning with 1. * @param mixed $end the last period in the calculation * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * * @return float|string */ public static function principal( $rate, $periods, $presentValue, $start, $end, $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $rate = Functions::flattenSingleValue($rate); $periods = Functions::flattenSingleValue($periods); $presentValue = Functions::flattenSingleValue($presentValue); $start = Functions::flattenSingleValue($start); $end = Functions::flattenSingleValue($end); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $rate = CashFlowValidations::validateRate($rate); $periods = CashFlowValidations::validateInt($periods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $start = CashFlowValidations::validateInt($start); $end = CashFlowValidations::validateInt($end); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($start < 1 || $start > $end) { return ExcelError::VALUE(); } // Calculate $principal = 0; for ($per = $start; $per <= $end; ++$per) { $ppmt = Payments::interestPayment($rate, $per, $periods, $presentValue, 0, $type); if (is_string($ppmt)) { return $ppmt; } $principal += $ppmt; } return $principal; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic.php 0000644 00000017346 15002227416 0025173 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Constant; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\CashFlowValidations; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Periodic { /** * FV. * * Returns the Future Value of a cash flow with constant payments and interest rate (annuities). * * Excel Function: * FV(rate,nper,pmt[,pv[,type]]) * * @param mixed $rate The interest rate per period * @param mixed $numberOfPeriods Total number of payment periods in an annuity as an integer * @param mixed $payment The payment made each period: it cannot change over the * life of the annuity. Typically, pmt contains principal * and interest but no other fees or taxes. * @param mixed $presentValue present Value, or the lump-sum amount that a series of * future payments is worth right now * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. * * @return float|string */ public static function futureValue( $rate, $numberOfPeriods, $payment = 0.0, $presentValue = 0.0, $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $rate = Functions::flattenSingleValue($rate); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $payment = ($payment === null) ? 0.0 : Functions::flattenSingleValue($payment); $presentValue = ($presentValue === null) ? 0.0 : Functions::flattenSingleValue($presentValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $rate = CashFlowValidations::validateRate($rate); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $payment = CashFlowValidations::validateFloat($payment); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } return self::calculateFutureValue($rate, $numberOfPeriods, $payment, $presentValue, $type); } /** * PV. * * Returns the Present Value of a cash flow with constant payments and interest rate (annuities). * * @param mixed $rate Interest rate per period * @param mixed $numberOfPeriods Number of periods as an integer * @param mixed $payment Periodic payment (annuity) * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function presentValue( $rate, $numberOfPeriods, $payment = 0.0, $futureValue = 0.0, $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $rate = Functions::flattenSingleValue($rate); $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); $payment = ($payment === null) ? 0.0 : Functions::flattenSingleValue($payment); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $rate = CashFlowValidations::validateRate($rate); $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); $payment = CashFlowValidations::validateFloat($payment); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($numberOfPeriods < 0) { return ExcelError::NAN(); } return self::calculatePresentValue($rate, $numberOfPeriods, $payment, $futureValue, $type); } /** * NPER. * * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate. * * @param mixed $rate Interest rate per period * @param mixed $payment Periodic payment (annuity) * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error */ public static function periods( $rate, $payment, $presentValue, $futureValue = 0.0, $type = FinancialConstants::PAYMENT_END_OF_PERIOD ) { $rate = Functions::flattenSingleValue($rate); $payment = Functions::flattenSingleValue($payment); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); try { $rate = CashFlowValidations::validateRate($rate); $payment = CashFlowValidations::validateFloat($payment); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); $type = CashFlowValidations::validatePeriodType($type); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($payment == 0.0) { return ExcelError::NAN(); } return self::calculatePeriods($rate, $payment, $presentValue, $futureValue, $type); } private static function calculateFutureValue( float $rate, int $numberOfPeriods, float $payment, float $presentValue, int $type ): float { if ($rate !== null && $rate != 0) { return -$presentValue * (1 + $rate) ** $numberOfPeriods - $payment * (1 + $rate * $type) * ((1 + $rate) ** $numberOfPeriods - 1) / $rate; } return -$presentValue - $payment * $numberOfPeriods; } private static function calculatePresentValue( float $rate, int $numberOfPeriods, float $payment, float $futureValue, int $type ): float { if ($rate != 0.0) { return (-$payment * (1 + $rate * $type) * (((1 + $rate) ** $numberOfPeriods - 1) / $rate) - $futureValue) / (1 + $rate) ** $numberOfPeriods; } return -$futureValue - $payment * $numberOfPeriods; } /** * @return float|string */ private static function calculatePeriods( float $rate, float $payment, float $presentValue, float $futureValue, int $type ) { if ($rate != 0.0) { if ($presentValue == 0.0) { return ExcelError::NAN(); } return log(($payment * (1 + $rate * $type) / $rate - $futureValue) / ($presentValue + $payment * (1 + $rate * $type) / $rate)) / log(1 + $rate); } return (-$presentValue - $futureValue) / $payment; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php 0000644 00000007267 15002227416 0023066 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Single { /** * FVSCHEDULE. * * Returns the future value of an initial principal after applying a series of compound interest rates. * Use FVSCHEDULE to calculate the future value of an investment with a variable or adjustable rate. * * Excel Function: * FVSCHEDULE(principal,schedule) * * @param mixed $principal the present value * @param float[] $schedule an array of interest rates to apply * * @return float|string */ public static function futureValue($principal, $schedule) { $principal = Functions::flattenSingleValue($principal); $schedule = Functions::flattenArray($schedule); try { $principal = CashFlowValidations::validateFloat($principal); foreach ($schedule as $rate) { $rate = CashFlowValidations::validateFloat($rate); $principal *= 1 + $rate; } } catch (Exception $e) { return $e->getMessage(); } return $principal; } /** * PDURATION. * * Calculates the number of periods required for an investment to reach a specified value. * * @param mixed $rate Interest rate per period * @param mixed $presentValue Present Value * @param mixed $futureValue Future Value * * @return float|string Result, or a string containing an error */ public static function periods($rate, $presentValue, $futureValue) { $rate = Functions::flattenSingleValue($rate); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = Functions::flattenSingleValue($futureValue); try { $rate = CashFlowValidations::validateRate($rate); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($rate <= 0.0 || $presentValue <= 0.0 || $futureValue <= 0.0) { return ExcelError::NAN(); } return (log($futureValue) - log($presentValue)) / log(1 + $rate); } /** * RRI. * * Calculates the interest rate required for an investment to grow to a specified future value . * * @param float $periods The number of periods over which the investment is made * @param float $presentValue Present Value * @param float $futureValue Future Value * * @return float|string Result, or a string containing an error */ public static function interestRate($periods = 0.0, $presentValue = 0.0, $futureValue = 0.0) { $periods = Functions::flattenSingleValue($periods); $presentValue = Functions::flattenSingleValue($presentValue); $futureValue = Functions::flattenSingleValue($futureValue); try { $periods = CashFlowValidations::validateFloat($periods); $presentValue = CashFlowValidations::validatePresentValue($presentValue); $futureValue = CashFlowValidations::validateFutureValue($futureValue); } catch (Exception $e) { return $e->getMessage(); } // Validate parameters if ($periods <= 0.0 || $presentValue <= 0.0 || $futureValue < 0.0) { return ExcelError::NAN(); } return ($futureValue / $presentValue) ** (1 / $periods) - 1; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php 0000644 00000002506 15002227416 0025540 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Financial\FinancialValidations; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class CashFlowValidations extends FinancialValidations { /** * @param mixed $rate */ public static function validateRate($rate): float { $rate = self::validateFloat($rate); return $rate; } /** * @param mixed $type */ public static function validatePeriodType($type): int { $rate = self::validateInt($type); if ( $type !== FinancialConstants::PAYMENT_END_OF_PERIOD && $type !== FinancialConstants::PAYMENT_BEGINNING_OF_PERIOD ) { throw new Exception(ExcelError::NAN()); } return $rate; } /** * @param mixed $presentValue */ public static function validatePresentValue($presentValue): float { return self::validateFloat($presentValue); } /** * @param mixed $futureValue */ public static function validateFutureValue($futureValue): float { return self::validateFloat($futureValue); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php 0000644 00000025261 15002227416 0025575 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class NonPeriodic { const FINANCIAL_MAX_ITERATIONS = 128; const FINANCIAL_PRECISION = 1.0e-08; const DEFAULT_GUESS = 0.1; /** * XIRR. * * Returns the internal rate of return for a schedule of cash flows that is not necessarily periodic. * * Excel Function: * =XIRR(values,dates,guess) * * @param float[] $values A series of cash flow payments * The series of values must contain at least one positive value & one negative value * @param mixed[] $dates A series of payment dates * The first payment date indicates the beginning of the schedule of payments * All other dates must be later than this date, but they may occur in any order * @param mixed $guess An optional guess at the expected answer * * @return float|string */ public static function rate($values, $dates, $guess = self::DEFAULT_GUESS) { $rslt = self::xirrPart1($values, $dates); if ($rslt !== '') { return $rslt; } // create an initial range, with a root somewhere between 0 and guess $guess = Functions::flattenSingleValue($guess) ?? self::DEFAULT_GUESS; if (!is_numeric($guess)) { return ExcelError::VALUE(); } $guess = ($guess + 0.0) ?: self::DEFAULT_GUESS; $x1 = 0.0; $x2 = $guess + 0.0; $f1 = self::xnpvOrdered($x1, $values, $dates, false); $f2 = self::xnpvOrdered($x2, $values, $dates, false); $found = false; for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { if (!is_numeric($f1)) { return $f1; } if (!is_numeric($f2)) { return $f2; } $f1 = (float) $f1; $f2 = (float) $f2; if (($f1 * $f2) < 0.0) { $found = true; break; } elseif (abs($f1) < abs($f2)) { $x1 += 1.6 * ($x1 - $x2); $f1 = self::xnpvOrdered($x1, $values, $dates, false); } else { $x2 += 1.6 * ($x2 - $x1); $f2 = self::xnpvOrdered($x2, $values, $dates, false); } } if ($found) { return self::xirrPart3($values, $dates, $x1, $x2); } // Newton-Raphson didn't work - try bisection $x1 = $guess - 0.5; $x2 = $guess + 0.5; for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $f1 = self::xnpvOrdered($x1, $values, $dates, false, true); $f2 = self::xnpvOrdered($x2, $values, $dates, false, true); if (!is_numeric($f1) || !is_numeric($f2)) { break; } if ($f1 * $f2 <= 0) { $found = true; break; } $x1 -= 0.5; $x2 += 0.5; } if ($found) { return self::xirrBisection($values, $dates, $x1, $x2); } return ExcelError::NAN(); } /** * XNPV. * * Returns the net present value for a schedule of cash flows that is not necessarily periodic. * To calculate the net present value for a series of cash flows that is periodic, use the NPV function. * * Excel Function: * =XNPV(rate,values,dates) * * @param float $rate the discount rate to apply to the cash flows * @param float[] $values A series of cash flows that corresponds to a schedule of payments in dates. * The first payment is optional and corresponds to a cost or payment that occurs * at the beginning of the investment. * If the first value is a cost or payment, it must be a negative value. * All succeeding payments are discounted based on a 365-day year. * The series of values must contain at least one positive value and one negative value. * @param mixed[] $dates A schedule of payment dates that corresponds to the cash flow payments. * The first payment date indicates the beginning of the schedule of payments. * All other dates must be later than this date, but they may occur in any order. * * @return float|string */ public static function presentValue($rate, $values, $dates) { return self::xnpvOrdered($rate, $values, $dates, true); } private static function bothNegAndPos(bool $neg, bool $pos): bool { return $neg && $pos; } /** * @param mixed $values * @param mixed $dates */ private static function xirrPart1(&$values, &$dates): string { $values = Functions::flattenArray($values); $dates = Functions::flattenArray($dates); $valuesIsArray = count($values) > 1; $datesIsArray = count($dates) > 1; if (!$valuesIsArray && !$datesIsArray) { return ExcelError::NA(); } if (count($values) != count($dates)) { return ExcelError::NAN(); } $datesCount = count($dates); for ($i = 0; $i < $datesCount; ++$i) { try { $dates[$i] = DateTimeExcel\Helpers::getDateValue($dates[$i]); } catch (Exception $e) { return $e->getMessage(); } } return self::xirrPart2($values); } private static function xirrPart2(array &$values): string { $valCount = count($values); $foundpos = false; $foundneg = false; for ($i = 0; $i < $valCount; ++$i) { $fld = $values[$i]; if (!is_numeric($fld)) { return ExcelError::VALUE(); } elseif ($fld > 0) { $foundpos = true; } elseif ($fld < 0) { $foundneg = true; } } if (!self::bothNegAndPos($foundneg, $foundpos)) { return ExcelError::NAN(); } return ''; } /** * @return float|string */ private static function xirrPart3(array $values, array $dates, float $x1, float $x2) { $f = self::xnpvOrdered($x1, $values, $dates, false); if ($f < 0.0) { $rtb = $x1; $dx = $x2 - $x1; } else { $rtb = $x2; $dx = $x1 - $x2; } $rslt = ExcelError::VALUE(); for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $dx *= 0.5; $x_mid = $rtb + $dx; $f_mid = (float) self::xnpvOrdered($x_mid, $values, $dates, false); if ($f_mid <= 0.0) { $rtb = $x_mid; } if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { $rslt = $x_mid; break; } } return $rslt; } /** * @return float|string */ private static function xirrBisection(array $values, array $dates, float $x1, float $x2) { $rslt = ExcelError::NAN(); for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $rslt = ExcelError::NAN(); $f1 = self::xnpvOrdered($x1, $values, $dates, false, true); $f2 = self::xnpvOrdered($x2, $values, $dates, false, true); if (!is_numeric($f1) || !is_numeric($f2)) { break; } $f1 = (float) $f1; $f2 = (float) $f2; if (abs($f1) < self::FINANCIAL_PRECISION && abs($f2) < self::FINANCIAL_PRECISION) { break; } if ($f1 * $f2 > 0) { break; } $rslt = ($x1 + $x2) / 2; $f3 = self::xnpvOrdered($rslt, $values, $dates, false, true); if (!is_float($f3)) { break; } if ($f3 * $f1 < 0) { $x2 = $rslt; } else { $x1 = $rslt; } if (abs($f3) < self::FINANCIAL_PRECISION) { break; } } return $rslt; } /** * @param mixed $rate * @param mixed $values * @param mixed $dates * * @return float|string */ private static function xnpvOrdered($rate, $values, $dates, bool $ordered = true, bool $capAtNegative1 = false) { $rate = Functions::flattenSingleValue($rate); $values = Functions::flattenArray($values); $dates = Functions::flattenArray($dates); $valCount = count($values); try { self::validateXnpv($rate, $values, $dates); if ($capAtNegative1 && $rate <= -1) { $rate = -1.0 + 1.0E-10; } $date0 = DateTimeExcel\Helpers::getDateValue($dates[0]); } catch (Exception $e) { return $e->getMessage(); } $xnpv = 0.0; for ($i = 0; $i < $valCount; ++$i) { if (!is_numeric($values[$i])) { return ExcelError::VALUE(); } try { $datei = DateTimeExcel\Helpers::getDateValue($dates[$i]); } catch (Exception $e) { return $e->getMessage(); } if ($date0 > $datei) { $dif = $ordered ? ExcelError::NAN() : -((int) DateTimeExcel\Difference::interval($datei, $date0, 'd')); } else { $dif = Functions::scalar(DateTimeExcel\Difference::interval($date0, $datei, 'd')); } if (!is_numeric($dif)) { return $dif; } if ($rate <= -1.0) { $xnpv += -abs($values[$i]) / (-1 - $rate) ** ($dif / 365); } else { $xnpv += $values[$i] / (1 + $rate) ** ($dif / 365); } } return is_finite($xnpv) ? $xnpv : ExcelError::VALUE(); } /** * @param mixed $rate */ private static function validateXnpv($rate, array $values, array $dates): void { if (!is_numeric($rate)) { throw new Exception(ExcelError::VALUE()); } $valCount = count($values); if ($valCount != count($dates)) { throw new Exception(ExcelError::NAN()); } if ($valCount > 1 && ((min($values) > 0) || (max($values) < 0))) { throw new Exception(ExcelError::NAN()); } } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php 0000644 00000013074 15002227416 0025121 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial\CashFlow\Variable; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Periodic { const FINANCIAL_MAX_ITERATIONS = 128; const FINANCIAL_PRECISION = 1.0e-08; /** * IRR. * * Returns the internal rate of return for a series of cash flows represented by the numbers in values. * These cash flows do not have to be even, as they would be for an annuity. However, the cash flows must occur * at regular intervals, such as monthly or annually. The internal rate of return is the interest rate received * for an investment consisting of payments (negative values) and income (positive values) that occur at regular * periods. * * Excel Function: * IRR(values[,guess]) * * @param mixed $values An array or a reference to cells that contain numbers for which you want * to calculate the internal rate of return. * Values must contain at least one positive value and one negative value to * calculate the internal rate of return. * @param mixed $guess A number that you guess is close to the result of IRR * * @return float|string */ public static function rate($values, $guess = 0.1) { if (!is_array($values)) { return ExcelError::VALUE(); } $values = Functions::flattenArray($values); $guess = Functions::flattenSingleValue($guess); // create an initial range, with a root somewhere between 0 and guess $x1 = 0.0; $x2 = $guess; $f1 = self::presentValue($x1, $values); $f2 = self::presentValue($x2, $values); for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { if (($f1 * $f2) < 0.0) { break; } if (abs($f1) < abs($f2)) { $f1 = self::presentValue($x1 += 1.6 * ($x1 - $x2), $values); } else { $f2 = self::presentValue($x2 += 1.6 * ($x2 - $x1), $values); } } if (($f1 * $f2) > 0.0) { return ExcelError::VALUE(); } $f = self::presentValue($x1, $values); if ($f < 0.0) { $rtb = $x1; $dx = $x2 - $x1; } else { $rtb = $x2; $dx = $x1 - $x2; } for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { $dx *= 0.5; $x_mid = $rtb + $dx; $f_mid = self::presentValue($x_mid, $values); if ($f_mid <= 0.0) { $rtb = $x_mid; } if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { return $x_mid; } } return ExcelError::VALUE(); } /** * MIRR. * * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both * the cost of the investment and the interest received on reinvestment of cash. * * Excel Function: * MIRR(values,finance_rate, reinvestment_rate) * * @param mixed $values An array or a reference to cells that contain a series of payments and * income occurring at regular intervals. * Payments are negative value, income is positive values. * @param mixed $financeRate The interest rate you pay on the money used in the cash flows * @param mixed $reinvestmentRate The interest rate you receive on the cash flows as you reinvest them * * @return float|string Result, or a string containing an error */ public static function modifiedRate($values, $financeRate, $reinvestmentRate) { if (!is_array($values)) { return ExcelError::DIV0(); } $values = Functions::flattenArray($values); $financeRate = Functions::flattenSingleValue($financeRate); $reinvestmentRate = Functions::flattenSingleValue($reinvestmentRate); $n = count($values); $rr = 1.0 + $reinvestmentRate; $fr = 1.0 + $financeRate; $npvPos = $npvNeg = self::$zeroPointZero; foreach ($values as $i => $v) { if ($v >= 0) { $npvPos += $v / $rr ** $i; } else { $npvNeg += $v / $fr ** $i; } } if ($npvNeg === self::$zeroPointZero || $npvPos === self::$zeroPointZero) { return ExcelError::DIV0(); } $mirr = ((-$npvPos * $rr ** $n) / ($npvNeg * ($rr))) ** (1.0 / ($n - 1)) - 1.0; return is_finite($mirr) ? $mirr : ExcelError::NAN(); } /** * Sop to Scrutinizer. * * @var float */ private static $zeroPointZero = 0.0; /** * NPV. * * Returns the Net Present Value of a cash flow series given a discount rate. * * @param mixed $rate * @param array $args * * @return float */ public static function presentValue($rate, ...$args) { $returnValue = 0; $rate = Functions::flattenSingleValue($rate); $aArgs = Functions::flattenArray($args); // Calculate $countArgs = count($aArgs); for ($i = 1; $i <= $countArgs; ++$i) { // Is it a numeric value? if (is_numeric($aArgs[$i - 1])) { $returnValue += $aArgs[$i - 1] / (1 + $rate) ** $i; } } return $returnValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Constants.php 0000644 00000001046 15002227416 0022100 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; class Constants { public const BASIS_DAYS_PER_YEAR_NASD = 0; public const BASIS_DAYS_PER_YEAR_ACTUAL = 1; public const BASIS_DAYS_PER_YEAR_360 = 2; public const BASIS_DAYS_PER_YEAR_365 = 3; public const BASIS_DAYS_PER_YEAR_360_EUROPEAN = 4; public const FREQUENCY_ANNUAL = 1; public const FREQUENCY_SEMI_ANNUAL = 2; public const FREQUENCY_QUARTERLY = 4; public const PAYMENT_END_OF_PERIOD = 0; public const PAYMENT_BEGINNING_OF_PERIOD = 1; } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/FinancialValidations.php 0000644 00000007063 15002227416 0024213 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class FinancialValidations { /** * @param mixed $date */ public static function validateDate($date): float { return DateTimeExcel\Helpers::getDateValue($date); } /** * @param mixed $settlement */ public static function validateSettlementDate($settlement): float { return self::validateDate($settlement); } /** * @param mixed $maturity */ public static function validateMaturityDate($maturity): float { return self::validateDate($maturity); } /** * @param mixed $value */ public static function validateFloat($value): float { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (float) $value; } /** * @param mixed $value */ public static function validateInt($value): int { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (int) floor((float) $value); } /** * @param mixed $rate */ public static function validateRate($rate): float { $rate = self::validateFloat($rate); if ($rate < 0.0) { throw new Exception(ExcelError::NAN()); } return $rate; } /** * @param mixed $frequency */ public static function validateFrequency($frequency): int { $frequency = self::validateInt($frequency); if ( ($frequency !== FinancialConstants::FREQUENCY_ANNUAL) && ($frequency !== FinancialConstants::FREQUENCY_SEMI_ANNUAL) && ($frequency !== FinancialConstants::FREQUENCY_QUARTERLY) ) { throw new Exception(ExcelError::NAN()); } return $frequency; } /** * @param mixed $basis */ public static function validateBasis($basis): int { if (!is_numeric($basis)) { throw new Exception(ExcelError::VALUE()); } $basis = (int) $basis; if (($basis < 0) || ($basis > 4)) { throw new Exception(ExcelError::NAN()); } return $basis; } /** * @param mixed $price */ public static function validatePrice($price): float { $price = self::validateFloat($price); if ($price < 0.0) { throw new Exception(ExcelError::NAN()); } return $price; } /** * @param mixed $parValue */ public static function validateParValue($parValue): float { $parValue = self::validateFloat($parValue); if ($parValue < 0.0) { throw new Exception(ExcelError::NAN()); } return $parValue; } /** * @param mixed $yield */ public static function validateYield($yield): float { $yield = self::validateFloat($yield); if ($yield < 0.0) { throw new Exception(ExcelError::NAN()); } return $yield; } /** * @param mixed $discount */ public static function validateDiscount($discount): float { $discount = self::validateFloat($discount); if ($discount <= 0.0) { throw new Exception(ExcelError::NAN()); } return $discount; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Amortization.php 0000644 00000020472 15002227416 0022610 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class Amortization { /** * AMORDEGRC. * * Returns the depreciation for each accounting period. * This function is provided for the French accounting system. If an asset is purchased in * the middle of the accounting period, the prorated depreciation is taken into account. * The function is similar to AMORLINC, except that a depreciation coefficient is applied in * the calculation depending on the life of the assets. * This function will return the depreciation until the last period of the life of the assets * or until the cumulated value of depreciation is greater than the cost of the assets minus * the salvage value. * * Excel Function: * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * * @param mixed $cost The float cost of the asset * @param mixed $purchased Date of the purchase of the asset * @param mixed $firstPeriod Date of the end of the first period * @param mixed $salvage The salvage value at the end of the life of the asset * @param mixed $period the period (float) * @param mixed $rate rate of depreciation (float) * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string (string containing the error type if there is an error) */ public static function AMORDEGRC( $cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $cost = Functions::flattenSingleValue($cost); $purchased = Functions::flattenSingleValue($purchased); $firstPeriod = Functions::flattenSingleValue($firstPeriod); $salvage = Functions::flattenSingleValue($salvage); $period = Functions::flattenSingleValue($period); $rate = Functions::flattenSingleValue($rate); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $cost = FinancialValidations::validateFloat($cost); $purchased = FinancialValidations::validateDate($purchased); $firstPeriod = FinancialValidations::validateDate($firstPeriod); $salvage = FinancialValidations::validateFloat($salvage); $period = FinancialValidations::validateInt($period); $rate = FinancialValidations::validateFloat($rate); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $yearFracx = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis); if (is_string($yearFracx)) { return $yearFracx; } /** @var float */ $yearFrac = $yearFracx; $amortiseCoeff = self::getAmortizationCoefficient($rate); $rate *= $amortiseCoeff; $fNRate = round($yearFrac * $rate * $cost, 0); $cost -= $fNRate; $fRest = $cost - $salvage; for ($n = 0; $n < $period; ++$n) { $fNRate = round($rate * $cost, 0); $fRest -= $fNRate; if ($fRest < 0.0) { switch ($period - $n) { case 0: case 1: return round($cost * 0.5, 0); default: return 0.0; } } $cost -= $fNRate; } return $fNRate; } /** * AMORLINC. * * Returns the depreciation for each accounting period. * This function is provided for the French accounting system. If an asset is purchased in * the middle of the accounting period, the prorated depreciation is taken into account. * * Excel Function: * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * * @param mixed $cost The cost of the asset as a float * @param mixed $purchased Date of the purchase of the asset * @param mixed $firstPeriod Date of the end of the first period * @param mixed $salvage The salvage value at the end of the life of the asset * @param mixed $period The period as a float * @param mixed $rate Rate of depreciation as float * @param mixed $basis Integer indicating the type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string (string containing the error type if there is an error) */ public static function AMORLINC( $cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $cost = Functions::flattenSingleValue($cost); $purchased = Functions::flattenSingleValue($purchased); $firstPeriod = Functions::flattenSingleValue($firstPeriod); $salvage = Functions::flattenSingleValue($salvage); $period = Functions::flattenSingleValue($period); $rate = Functions::flattenSingleValue($rate); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $cost = FinancialValidations::validateFloat($cost); $purchased = FinancialValidations::validateDate($purchased); $firstPeriod = FinancialValidations::validateDate($firstPeriod); $salvage = FinancialValidations::validateFloat($salvage); $period = FinancialValidations::validateFloat($period); $rate = FinancialValidations::validateFloat($rate); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $fOneRate = $cost * $rate; $fCostDelta = $cost - $salvage; // Note, quirky variation for leap years on the YEARFRAC for this function $purchasedYear = DateTimeExcel\DateParts::year($purchased); $yearFracx = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis); if (is_string($yearFracx)) { return $yearFracx; } /** @var float */ $yearFrac = $yearFracx; if ( $basis == FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL && $yearFrac < 1 && DateTimeExcel\Helpers::isLeapYear(Functions::scalar($purchasedYear)) ) { $yearFrac *= 365 / 366; } $f0Rate = $yearFrac * $rate * $cost; $nNumOfFullPeriods = (int) (($cost - $salvage - $f0Rate) / $fOneRate); if ($period == 0) { return $f0Rate; } elseif ($period <= $nNumOfFullPeriods) { return $fOneRate; } elseif ($period == ($nNumOfFullPeriods + 1)) { return $fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate; } return 0.0; } private static function getAmortizationCoefficient(float $rate): float { // The depreciation coefficients are: // Life of assets (1/rate) Depreciation coefficient // Less than 3 years 1 // Between 3 and 4 years 1.5 // Between 5 and 6 years 2 // More than 6 years 2.5 $fUsePer = 1.0 / $rate; if ($fUsePer < 3.0) { return 1.0; } elseif ($fUsePer < 4.0) { return 1.5; } elseif ($fUsePer <= 6.0) { return 2.0; } return 2.5; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php 0000644 00000013504 15002227416 0022547 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class TreasuryBill { /** * TBILLEQ. * * Returns the bond-equivalent yield for a Treasury bill. * * @param mixed $settlement The Treasury bill's settlement date. * The Treasury bill's settlement date is the date after the issue date * when the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param mixed $discount The Treasury bill's discount rate * * @return float|string Result, or a string containing an error */ public static function bondEquivalentYield($settlement, $maturity, $discount) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $discount = Functions::flattenSingleValue($discount); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); $discount = FinancialValidations::validateFloat($discount); } catch (Exception $e) { return $e->getMessage(); } if ($discount <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = $maturity - $settlement; $daysPerYear = Helpers::daysPerYear( Functions::scalar(DateTimeExcel\DateParts::year($maturity)), FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL ); if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { return ExcelError::NAN(); } return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity); } /** * TBILLPRICE. * * Returns the price per $100 face value for a Treasury bill. * * @param mixed $settlement The Treasury bill's settlement date. * The Treasury bill's settlement date is the date after the issue date * when the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param mixed $discount The Treasury bill's discount rate * * @return float|string Result, or a string containing an error */ public static function price($settlement, $maturity, $discount) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $discount = Functions::flattenSingleValue($discount); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); $discount = FinancialValidations::validateFloat($discount); } catch (Exception $e) { return $e->getMessage(); } if ($discount <= 0) { return ExcelError::NAN(); } $daysBetweenSettlementAndMaturity = $maturity - $settlement; $daysPerYear = Helpers::daysPerYear( Functions::scalar(DateTimeExcel\DateParts::year($maturity)), FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL ); if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { return ExcelError::NAN(); } $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360)); if ($price < 0.0) { return ExcelError::NAN(); } return $price; } /** * TBILLYIELD. * * Returns the yield for a Treasury bill. * * @param mixed $settlement The Treasury bill's settlement date. * The Treasury bill's settlement date is the date after the issue date when * the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param mixed $price The Treasury bill's price per $100 face value * * @return float|string */ public static function yield($settlement, $maturity, $price) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $price = Functions::flattenSingleValue($price); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); $price = FinancialValidations::validatePrice($price); } catch (Exception $e) { return $e->getMessage(); } $daysBetweenSettlementAndMaturity = $maturity - $settlement; $daysPerYear = Helpers::daysPerYear( Functions::scalar(DateTimeExcel\DateParts::year($maturity)), FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL ); if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { return ExcelError::NAN(); } return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Coupons.php 0000644 00000044622 15002227416 0021561 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use DateTime; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Date; class Coupons { private const PERIOD_DATE_PREVIOUS = false; private const PERIOD_DATE_NEXT = true; /** * COUPDAYBS. * * Returns the number of days from the beginning of the coupon period to the settlement date. * * Excel Function: * COUPDAYBS(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year (int). * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string */ public static function COUPDAYBS( $settlement, $maturity, $frequency, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); if (is_string($daysPerYear)) { return ExcelError::VALUE(); } $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); if ($basis === FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL) { return abs((float) DateTimeExcel\Days::between($prev, $settlement)); } return (float) DateTimeExcel\YearFrac::fraction($prev, $settlement, $basis) * $daysPerYear; } /** * COUPDAYS. * * Returns the number of days in the coupon period that contains the settlement date. * * Excel Function: * COUPDAYS(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string */ public static function COUPDAYS( $settlement, $maturity, $frequency, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } switch ($basis) { case FinancialConstants::BASIS_DAYS_PER_YEAR_365: // Actual/365 return 365 / $frequency; case FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL: // Actual/actual if ($frequency == FinancialConstants::FREQUENCY_ANNUAL) { $daysPerYear = (int) Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); return $daysPerYear / $frequency; } $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); return $next - $prev; default: // US (NASD) 30/360, Actual/360 or European 30/360 return 360 / $frequency; } } /** * COUPDAYSNC. * * Returns the number of days from the settlement date to the next coupon date. * * Excel Function: * COUPDAYSNC(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int) . * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return float|string */ public static function COUPDAYSNC( $settlement, $maturity, $frequency, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); $basis = FinancialValidations::validateBasis($basis); } catch (Exception $e) { return $e->getMessage(); } /** @var int */ $daysPerYear = Helpers::daysPerYear(Functions::Scalar(DateTimeExcel\DateParts::year($settlement)), $basis); $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); if ($basis === FinancialConstants::BASIS_DAYS_PER_YEAR_NASD) { $settlementDate = Date::excelToDateTimeObject($settlement); $settlementEoM = Helpers::isLastDayOfMonth($settlementDate); if ($settlementEoM) { ++$settlement; } } return (float) DateTimeExcel\YearFrac::fraction($settlement, $next, $basis) * $daysPerYear; } /** * COUPNCD. * * Returns the next coupon date after the settlement date. * * Excel Function: * COUPNCD(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function COUPNCD( $settlement, $maturity, $frequency, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); $basis = FinancialValidations::validateBasis($basis); self::doNothing($basis); } catch (Exception $e) { return $e->getMessage(); } return self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); } /** * COUPNUM. * * Returns the number of coupons payable between the settlement date and maturity date, * rounded up to the nearest whole coupon. * * Excel Function: * COUPNUM(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return int|string */ public static function COUPNUM( $settlement, $maturity, $frequency, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); $basis = FinancialValidations::validateBasis($basis); self::doNothing($basis); } catch (Exception $e) { return $e->getMessage(); } $yearsBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction( $settlement, $maturity, FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ); return (int) ceil((float) $yearsBetweenSettlementAndMaturity * $frequency); } /** * COUPPCD. * * Returns the previous coupon date before the settlement date. * * Excel Function: * COUPPCD(settlement,maturity,frequency[,basis]) * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue * date when the security is traded to the buyer. * @param mixed $maturity The security's maturity date. * The maturity date is the date when the security expires. * @param mixed $frequency The number of coupon payments per year. * Valid frequency values are: * 1 Annual * 2 Semi-Annual * 4 Quarterly * @param mixed $basis The type of day count to use (int). * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function COUPPCD( $settlement, $maturity, $frequency, $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD ) { $settlement = Functions::flattenSingleValue($settlement); $maturity = Functions::flattenSingleValue($maturity); $frequency = Functions::flattenSingleValue($frequency); $basis = ($basis === null) ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD : Functions::flattenSingleValue($basis); try { $settlement = FinancialValidations::validateSettlementDate($settlement); $maturity = FinancialValidations::validateMaturityDate($maturity); self::validateCouponPeriod($settlement, $maturity); $frequency = FinancialValidations::validateFrequency($frequency); $basis = FinancialValidations::validateBasis($basis); self::doNothing($basis); } catch (Exception $e) { return $e->getMessage(); } return self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); } private static function monthsDiff(DateTime $result, int $months, string $plusOrMinus, int $day, bool $lastDayFlag): void { $result->setDate((int) $result->format('Y'), (int) $result->format('m'), 1); $result->modify("$plusOrMinus $months months"); $daysInMonth = (int) $result->format('t'); $result->setDate((int) $result->format('Y'), (int) $result->format('m'), $lastDayFlag ? $daysInMonth : min($day, $daysInMonth)); } private static function couponFirstPeriodDate(float $settlement, float $maturity, int $frequency, bool $next): float { $months = 12 / $frequency; $result = Date::excelToDateTimeObject($maturity); $day = (int) $result->format('d'); $lastDayFlag = Helpers::isLastDayOfMonth($result); while ($settlement < Date::PHPToExcel($result)) { self::monthsDiff($result, $months, '-', $day, $lastDayFlag); } if ($next === true) { self::monthsDiff($result, $months, '+', $day, $lastDayFlag); } return (float) Date::PHPToExcel($result); } private static function validateCouponPeriod(float $settlement, float $maturity): void { if ($settlement >= $maturity) { throw new Exception(ExcelError::NAN()); } } /** @param mixed $basis */ private static function doNothing($basis): bool { return $basis; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/InterestRate.php 0000644 00000004631 15002227416 0022540 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class InterestRate { /** * EFFECT. * * Returns the effective interest rate given the nominal rate and the number of * compounding payments per year. * * Excel Function: * EFFECT(nominal_rate,npery) * * @param mixed $nominalRate Nominal interest rate as a float * @param mixed $periodsPerYear Integer number of compounding payments per year * * @return float|string */ public static function effective($nominalRate = 0, $periodsPerYear = 0) { $nominalRate = Functions::flattenSingleValue($nominalRate); $periodsPerYear = Functions::flattenSingleValue($periodsPerYear); try { $nominalRate = FinancialValidations::validateFloat($nominalRate); $periodsPerYear = FinancialValidations::validateInt($periodsPerYear); } catch (Exception $e) { return $e->getMessage(); } if ($nominalRate <= 0 || $periodsPerYear < 1) { return ExcelError::NAN(); } return ((1 + $nominalRate / $periodsPerYear) ** $periodsPerYear) - 1; } /** * NOMINAL. * * Returns the nominal interest rate given the effective rate and the number of compounding payments per year. * * @param mixed $effectiveRate Effective interest rate as a float * @param mixed $periodsPerYear Integer number of compounding payments per year * * @return float|string Result, or a string containing an error */ public static function nominal($effectiveRate = 0, $periodsPerYear = 0) { $effectiveRate = Functions::flattenSingleValue($effectiveRate); $periodsPerYear = Functions::flattenSingleValue($periodsPerYear); try { $effectiveRate = FinancialValidations::validateFloat($effectiveRate); $periodsPerYear = FinancialValidations::validateInt($periodsPerYear); } catch (Exception $e) { return $e->getMessage(); } if ($effectiveRate <= 0 || $periodsPerYear < 1) { return ExcelError::NAN(); } // Calculate return $periodsPerYear * (($effectiveRate + 1) ** (1 / $periodsPerYear) - 1); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Dollar.php 0000644 00000011140 15002227416 0021335 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\TextData\Format; class Dollar { use ArrayEnabled; /** * DOLLAR. * * This function converts a number to text using currency format, with the decimals rounded to the specified place. * The format used is $#,##0.00_);($#,##0.00).. * * @param mixed $number The value to format, or can be an array of numbers * Or can be an array of values * @param mixed $precision The number of digits to display to the right of the decimal point (as an integer). * If precision is negative, number is rounded to the left of the decimal point. * If you omit precision, it is assumed to be 2 * Or can be an array of precision values * * @return array|string * If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function format($number, $precision = 2) { return Format::DOLLAR($number, $precision); } /** * DOLLARDE. * * Converts a dollar price expressed as an integer part and a fraction * part into a dollar price expressed as a decimal number. * Fractional dollar numbers are sometimes used for security prices. * * Excel Function: * DOLLARDE(fractional_dollar,fraction) * * @param mixed $fractionalDollar Fractional Dollar * Or can be an array of values * @param mixed $fraction Fraction * Or can be an array of values * * @return array|float|string */ public static function decimal($fractionalDollar = null, $fraction = 0) { if (is_array($fractionalDollar) || is_array($fraction)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $fractionalDollar, $fraction); } try { $fractionalDollar = FinancialValidations::validateFloat( Functions::flattenSingleValue($fractionalDollar) ?? 0.0 ); $fraction = FinancialValidations::validateInt(Functions::flattenSingleValue($fraction)); } catch (Exception $e) { return $e->getMessage(); } // Additional parameter validations if ($fraction < 0) { return ExcelError::NAN(); } if ($fraction == 0) { return ExcelError::DIV0(); } $dollars = ($fractionalDollar < 0) ? ceil($fractionalDollar) : floor($fractionalDollar); $cents = fmod($fractionalDollar, 1.0); $cents /= $fraction; $cents *= 10 ** ceil(log10($fraction)); return $dollars + $cents; } /** * DOLLARFR. * * Converts a dollar price expressed as a decimal number into a dollar price * expressed as a fraction. * Fractional dollar numbers are sometimes used for security prices. * * Excel Function: * DOLLARFR(decimal_dollar,fraction) * * @param mixed $decimalDollar Decimal Dollar * Or can be an array of values * @param mixed $fraction Fraction * Or can be an array of values * * @return array|float|string */ public static function fractional($decimalDollar = null, $fraction = 0) { if (is_array($decimalDollar) || is_array($fraction)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $decimalDollar, $fraction); } try { $decimalDollar = FinancialValidations::validateFloat( Functions::flattenSingleValue($decimalDollar) ?? 0.0 ); $fraction = FinancialValidations::validateInt(Functions::flattenSingleValue($fraction)); } catch (Exception $e) { return $e->getMessage(); } // Additional parameter validations if ($fraction < 0) { return ExcelError::NAN(); } if ($fraction == 0) { return ExcelError::DIV0(); } $dollars = ($decimalDollar < 0.0) ? ceil($decimalDollar) : floor($decimalDollar); $cents = fmod($decimalDollar, 1); $cents *= $fraction; $cents *= 10 ** (-ceil(log10($fraction))); return $dollars + $cents; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Depreciation.php 0000644 00000023227 15002227416 0022537 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Depreciation { /** @var float */ private static $zeroPointZero = 0.0; /** * DB. * * Returns the depreciation of an asset for a specified period using the * fixed-declining balance method. * This form of depreciation is used if you want to get a higher depreciation value * at the beginning of the depreciation (as opposed to linear depreciation). The * depreciation value is reduced with every depreciation period by the depreciation * already deducted from the initial cost. * * Excel Function: * DB(cost,salvage,life,period[,month]) * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation. * (Sometimes called the salvage value of the asset) * @param mixed $life Number of periods over which the asset is depreciated. * (Sometimes called the useful life of the asset) * @param mixed $period The period for which you want to calculate the * depreciation. Period must use the same units as life. * @param mixed $month Number of months in the first year. If month is omitted, * it defaults to 12. * * @return float|string */ public static function DB($cost, $salvage, $life, $period, $month = 12) { $cost = Functions::flattenSingleValue($cost); $salvage = Functions::flattenSingleValue($salvage); $life = Functions::flattenSingleValue($life); $period = Functions::flattenSingleValue($period); $month = Functions::flattenSingleValue($month); try { $cost = self::validateCost($cost); $salvage = self::validateSalvage($salvage); $life = self::validateLife($life); $period = self::validatePeriod($period); $month = self::validateMonth($month); } catch (Exception $e) { return $e->getMessage(); } if ($cost === self::$zeroPointZero) { return 0.0; } // Set Fixed Depreciation Rate $fixedDepreciationRate = 1 - ($salvage / $cost) ** (1 / $life); $fixedDepreciationRate = round($fixedDepreciationRate, 3); // Loop through each period calculating the depreciation // TODO Handle period value between 0 and 1 (e.g. 0.5) $previousDepreciation = 0; $depreciation = 0; for ($per = 1; $per <= $period; ++$per) { if ($per == 1) { $depreciation = $cost * $fixedDepreciationRate * $month / 12; } elseif ($per == ($life + 1)) { $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12; } else { $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate; } $previousDepreciation += $depreciation; } return $depreciation; } /** * DDB. * * Returns the depreciation of an asset for a specified period using the * double-declining balance method or some other method you specify. * * Excel Function: * DDB(cost,salvage,life,period[,factor]) * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation. * (Sometimes called the salvage value of the asset) * @param mixed $life Number of periods over which the asset is depreciated. * (Sometimes called the useful life of the asset) * @param mixed $period The period for which you want to calculate the * depreciation. Period must use the same units as life. * @param mixed $factor The rate at which the balance declines. * If factor is omitted, it is assumed to be 2 (the * double-declining balance method). * * @return float|string */ public static function DDB($cost, $salvage, $life, $period, $factor = 2.0) { $cost = Functions::flattenSingleValue($cost); $salvage = Functions::flattenSingleValue($salvage); $life = Functions::flattenSingleValue($life); $period = Functions::flattenSingleValue($period); $factor = Functions::flattenSingleValue($factor); try { $cost = self::validateCost($cost); $salvage = self::validateSalvage($salvage); $life = self::validateLife($life); $period = self::validatePeriod($period); $factor = self::validateFactor($factor); } catch (Exception $e) { return $e->getMessage(); } if ($period > $life) { return ExcelError::NAN(); } // Loop through each period calculating the depreciation // TODO Handling for fractional $period values $previousDepreciation = 0; $depreciation = 0; for ($per = 1; $per <= $period; ++$per) { $depreciation = min( ($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation) ); $previousDepreciation += $depreciation; } return $depreciation; } /** * SLN. * * Returns the straight-line depreciation of an asset for one period * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated * * @return float|string Result, or a string containing an error */ public static function SLN($cost, $salvage, $life) { $cost = Functions::flattenSingleValue($cost); $salvage = Functions::flattenSingleValue($salvage); $life = Functions::flattenSingleValue($life); try { $cost = self::validateCost($cost, true); $salvage = self::validateSalvage($salvage, true); $life = self::validateLife($life, true); } catch (Exception $e) { return $e->getMessage(); } if ($life === self::$zeroPointZero) { return ExcelError::DIV0(); } return ($cost - $salvage) / $life; } /** * SYD. * * Returns the sum-of-years' digits depreciation of an asset for a specified period. * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated * @param mixed $period Period * * @return float|string Result, or a string containing an error */ public static function SYD($cost, $salvage, $life, $period) { $cost = Functions::flattenSingleValue($cost); $salvage = Functions::flattenSingleValue($salvage); $life = Functions::flattenSingleValue($life); $period = Functions::flattenSingleValue($period); try { $cost = self::validateCost($cost, true); $salvage = self::validateSalvage($salvage); $life = self::validateLife($life); $period = self::validatePeriod($period); } catch (Exception $e) { return $e->getMessage(); } if ($period > $life) { return ExcelError::NAN(); } $syd = (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1)); return $syd; } /** @param mixed $cost */ private static function validateCost($cost, bool $negativeValueAllowed = false): float { $cost = FinancialValidations::validateFloat($cost); if ($cost < 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $cost; } /** @param mixed $salvage */ private static function validateSalvage($salvage, bool $negativeValueAllowed = false): float { $salvage = FinancialValidations::validateFloat($salvage); if ($salvage < 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $salvage; } /** @param mixed $life */ private static function validateLife($life, bool $negativeValueAllowed = false): float { $life = FinancialValidations::validateFloat($life); if ($life < 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $life; } /** @param mixed $period */ private static function validatePeriod($period, bool $negativeValueAllowed = false): float { $period = FinancialValidations::validateFloat($period); if ($period <= 0.0 && $negativeValueAllowed === false) { throw new Exception(ExcelError::NAN()); } return $period; } /** @param mixed $month */ private static function validateMonth($month): int { $month = FinancialValidations::validateInt($month); if ($month < 1) { throw new Exception(ExcelError::NAN()); } return $month; } /** @param mixed $factor */ private static function validateFactor($factor): float { $factor = FinancialValidations::validateFloat($factor); if ($factor <= 0.0) { throw new Exception(ExcelError::NAN()); } return $factor; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Helpers.php 0000644 00000003774 15002227416 0021540 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\Financial; use DateTimeInterface; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Financial\Constants as FinancialConstants; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Helpers { /** * daysPerYear. * * Returns the number of days in a specified year, as defined by the "basis" value * * @param int|string $year The year against which we're testing * @param int|string $basis The type of day count: * 0 or omitted US (NASD) 360 * 1 Actual (365 or 366 in a leap year) * 2 360 * 3 365 * 4 European 360 * * @return int|string Result, or a string containing an error */ public static function daysPerYear($year, $basis = 0) { if (!is_numeric($basis)) { return ExcelError::NAN(); } switch ($basis) { case FinancialConstants::BASIS_DAYS_PER_YEAR_NASD: case FinancialConstants::BASIS_DAYS_PER_YEAR_360: case FinancialConstants::BASIS_DAYS_PER_YEAR_360_EUROPEAN: return 360; case FinancialConstants::BASIS_DAYS_PER_YEAR_365: return 365; case FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL: return (DateTimeExcel\Helpers::isLeapYear($year)) ? 366 : 365; } return ExcelError::NAN(); } /** * isLastDayOfMonth. * * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month * * @param DateTimeInterface $date The date for testing */ public static function isLastDayOfMonth(DateTimeInterface $date): bool { return $date->format('d') === $date->format('t'); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData.php 0000644 00000030332 15002227416 0017756 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; use DateTimeInterface; /** * @deprecated 1.18.0 */ class TextData { /** * CHARACTER. * * @deprecated 1.18.0 * Use the character() method in the TextData\CharacterConvert class instead * @see TextData\CharacterConvert::character() * * @param string $character Value * * @return array|string */ public static function CHARACTER($character) { return TextData\CharacterConvert::character($character); } /** * TRIMNONPRINTABLE. * * @deprecated 1.18.0 * Use the nonPrintable() method in the TextData\Trim class instead * @see TextData\Trim::nonPrintable() * * @param mixed $stringValue Value to check * * @return null|array|string */ public static function TRIMNONPRINTABLE($stringValue = '') { return TextData\Trim::nonPrintable($stringValue); } /** * TRIMSPACES. * * @deprecated 1.18.0 * Use the spaces() method in the TextData\Trim class instead * @see TextData\Trim::spaces() * * @param mixed $stringValue Value to check * * @return array|string */ public static function TRIMSPACES($stringValue = '') { return TextData\Trim::spaces($stringValue); } /** * ASCIICODE. * * @deprecated 1.18.0 * Use the code() method in the TextData\CharacterConvert class instead * @see TextData\CharacterConvert::code() * * @param array|string $characters Value * * @return array|int|string A string if arguments are invalid */ public static function ASCIICODE($characters) { return TextData\CharacterConvert::code($characters); } /** * CONCATENATE. * * @deprecated 1.18.0 * Use the CONCATENATE() method in the TextData\Concatenate class instead * @see TextData\Concatenate::CONCATENATE() * * @param array $args * * @return string */ public static function CONCATENATE(...$args) { return TextData\Concatenate::CONCATENATE(...$args); } /** * DOLLAR. * * This function converts a number to text using currency format, with the decimals rounded to the specified place. * The format used is $#,##0.00_);($#,##0.00).. * * @deprecated 1.18.0 * Use the DOLLAR() method in the TextData\Format class instead * @see TextData\Format::DOLLAR() * * @param float $value The value to format * @param int $decimals The number of digits to display to the right of the decimal point. * If decimals is negative, number is rounded to the left of the decimal point. * If you omit decimals, it is assumed to be 2 * * @return array|string */ public static function DOLLAR($value = 0, $decimals = 2) { return TextData\Format::DOLLAR($value, $decimals); } /** * FIND. * * @deprecated 1.18.0 * Use the sensitive() method in the TextData\Search class instead * @see TextData\Search::sensitive() * * @param array|string $needle The string to look for * @param array|string $haystack The string in which to look * @param array|int $offset Offset within $haystack * * @return array|int|string */ public static function SEARCHSENSITIVE($needle, $haystack, $offset = 1) { return TextData\Search::sensitive($needle, $haystack, $offset); } /** * SEARCH. * * @deprecated 1.18.0 * Use the insensitive() method in the TextData\Search class instead * @see TextData\Search::insensitive() * * @param array|string $needle The string to look for * @param array|string $haystack The string in which to look * @param array|int $offset Offset within $haystack * * @return array|int|string */ public static function SEARCHINSENSITIVE($needle, $haystack, $offset = 1) { return TextData\Search::insensitive($needle, $haystack, $offset); } /** * FIXEDFORMAT. * * @deprecated 1.18.0 * Use the FIXEDFORMAT() method in the TextData\Format class instead * @see TextData\Format::FIXEDFORMAT() * * @param mixed $value Value to check * @param int $decimals * @param bool $no_commas * * @return array|string */ public static function FIXEDFORMAT($value, $decimals = 2, $no_commas = false) { return TextData\Format::FIXEDFORMAT($value, $decimals, $no_commas); } /** * LEFT. * * @deprecated 1.18.0 * Use the left() method in the TextData\Extract class instead * @see TextData\Extract::left() * * @param array|string $value Value * @param array|int $chars Number of characters * * @return array|string */ public static function LEFT($value = '', $chars = 1) { return TextData\Extract::left($value, $chars); } /** * MID. * * @deprecated 1.18.0 * Use the mid() method in the TextData\Extract class instead * @see TextData\Extract::mid() * * @param array|string $value Value * @param array|int $start Start character * @param array|int $chars Number of characters * * @return array|string */ public static function MID($value = '', $start = 1, $chars = null) { return TextData\Extract::mid($value, $start, $chars); } /** * RIGHT. * * @deprecated 1.18.0 * Use the right() method in the TextData\Extract class instead * @see TextData\Extract::right() * * @param array|string $value Value * @param array|int $chars Number of characters * * @return array|string */ public static function RIGHT($value = '', $chars = 1) { return TextData\Extract::right($value, $chars); } /** * STRINGLENGTH. * * @deprecated 1.18.0 * Use the length() method in the TextData\Text class instead * @see TextData\Text::length() * * @param string $value Value * * @return array|int */ public static function STRINGLENGTH($value = '') { return TextData\Text::length($value); } /** * LOWERCASE. * * Converts a string value to lower case. * * @deprecated 1.18.0 * Use the lower() method in the TextData\CaseConvert class instead * @see TextData\CaseConvert::lower() * * @param array|string $mixedCaseString * * @return array|string */ public static function LOWERCASE($mixedCaseString) { return TextData\CaseConvert::lower($mixedCaseString); } /** * UPPERCASE. * * Converts a string value to upper case. * * @deprecated 1.18.0 * Use the upper() method in the TextData\CaseConvert class instead * @see TextData\CaseConvert::upper() * * @param string $mixedCaseString * * @return array|string */ public static function UPPERCASE($mixedCaseString) { return TextData\CaseConvert::upper($mixedCaseString); } /** * PROPERCASE. * * Converts a string value to proper/title case. * * @deprecated 1.18.0 * Use the proper() method in the TextData\CaseConvert class instead * @see TextData\CaseConvert::proper() * * @param array|string $mixedCaseString * * @return array|string */ public static function PROPERCASE($mixedCaseString) { return TextData\CaseConvert::proper($mixedCaseString); } /** * REPLACE. * * @deprecated 1.18.0 * Use the replace() method in the TextData\Replace class instead * @see TextData\Replace::replace() * * @param string $oldText String to modify * @param int $start Start character * @param int $chars Number of characters * @param string $newText String to replace in defined position * * @return array|string */ public static function REPLACE($oldText, $start, $chars, $newText) { return TextData\Replace::replace($oldText, $start, $chars, $newText); } /** * SUBSTITUTE. * * @deprecated 1.18.0 * Use the substitute() method in the TextData\Replace class instead * @see TextData\Replace::substitute() * * @param string $text Value * @param string $fromText From Value * @param string $toText To Value * @param int $instance Instance Number * * @return array|string */ public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0) { return TextData\Replace::substitute($text, $fromText, $toText, $instance); } /** * RETURNSTRING. * * @deprecated 1.18.0 * Use the test() method in the TextData\Text class instead * @see TextData\Text::test() * * @param mixed $testValue Value to check * * @return null|array|string */ public static function RETURNSTRING($testValue = '') { return TextData\Text::test($testValue); } /** * TEXTFORMAT. * * @deprecated 1.18.0 * Use the TEXTFORMAT() method in the TextData\Format class instead * @see TextData\Format::TEXTFORMAT() * * @param mixed $value Value to check * @param string $format Format mask to use * * @return array|string */ public static function TEXTFORMAT($value, $format) { return TextData\Format::TEXTFORMAT($value, $format); } /** * VALUE. * * @deprecated 1.18.0 * Use the VALUE() method in the TextData\Format class instead * @see TextData\Format::VALUE() * * @param mixed $value Value to check * * @return array|DateTimeInterface|float|int|string A string if arguments are invalid */ public static function VALUE($value = '') { return TextData\Format::VALUE($value); } /** * NUMBERVALUE. * * @deprecated 1.18.0 * Use the NUMBERVALUE() method in the TextData\Format class instead * @see TextData\Format::NUMBERVALUE() * * @param mixed $value Value to check * @param string $decimalSeparator decimal separator, defaults to locale defined value * @param string $groupSeparator group/thosands separator, defaults to locale defined value * * @return array|float|string */ public static function NUMBERVALUE($value = '', $decimalSeparator = null, $groupSeparator = null) { return TextData\Format::NUMBERVALUE($value, $decimalSeparator, $groupSeparator); } /** * Compares two text strings and returns TRUE if they are exactly the same, FALSE otherwise. * EXACT is case-sensitive but ignores formatting differences. * Use EXACT to test text being entered into a document. * * @deprecated 1.18.0 * Use the exact() method in the TextData\Text class instead * @see TextData\Text::exact() * * @param mixed $value1 * @param mixed $value2 * * @return array|bool */ public static function EXACT($value1, $value2) { return TextData\Text::exact($value1, $value2); } /** * TEXTJOIN. * * @deprecated 1.18.0 * Use the TEXTJOIN() method in the TextData\Concatenate class instead * @see TextData\Concatenate::TEXTJOIN() * * @param mixed $delimiter * @param mixed $ignoreEmpty * @param mixed $args * * @return array|string */ public static function TEXTJOIN($delimiter, $ignoreEmpty, ...$args) { return TextData\Concatenate::TEXTJOIN($delimiter, $ignoreEmpty, ...$args); } /** * REPT. * * Returns the result of builtin function repeat after validating args. * * @deprecated 1.18.0 * Use the builtinREPT() method in the TextData\Concatenate class instead * @see TextData\Concatenate::builtinREPT() * * @param array|string $str Should be numeric * @param mixed $number Should be int * * @return array|string */ public static function builtinREPT($str, $number) { return TextData\Concatenate::builtinREPT($str, $number); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Search.php 0000644 00000007055 15002227416 0021171 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Search { use ArrayEnabled; /** * FIND (case sensitive search). * * @param mixed $needle The string to look for * Or can be an array of values * @param mixed $haystack The string in which to look * Or can be an array of values * @param mixed $offset Integer offset within $haystack to start searching from * Or can be an array of values * * @return array|int|string The offset where the first occurrence of needle was found in the haystack * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function sensitive($needle, $haystack, $offset = 1) { if (is_array($needle) || is_array($haystack) || is_array($offset)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $needle, $haystack, $offset); } try { $needle = Helpers::extractString($needle); $haystack = Helpers::extractString($haystack); $offset = Helpers::extractInt($offset, 1, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } if (StringHelper::countCharacters($haystack) >= $offset) { if (StringHelper::countCharacters($needle) === 0) { return $offset; } $pos = mb_strpos($haystack, $needle, --$offset, 'UTF-8'); if ($pos !== false) { return ++$pos; } } return ExcelError::VALUE(); } /** * SEARCH (case insensitive search). * * @param mixed $needle The string to look for * Or can be an array of values * @param mixed $haystack The string in which to look * Or can be an array of values * @param mixed $offset Integer offset within $haystack to start searching from * Or can be an array of values * * @return array|int|string The offset where the first occurrence of needle was found in the haystack * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function insensitive($needle, $haystack, $offset = 1) { if (is_array($needle) || is_array($haystack) || is_array($offset)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $needle, $haystack, $offset); } try { $needle = Helpers::extractString($needle); $haystack = Helpers::extractString($haystack); $offset = Helpers::extractInt($offset, 1, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } if (StringHelper::countCharacters($haystack) >= $offset) { if (StringHelper::countCharacters($needle) === 0) { return $offset; } $pos = mb_stripos($haystack, $needle, --$offset, 'UTF-8'); if ($pos !== false) { return ++$pos; } } return ExcelError::VALUE(); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Replace.php 0000644 00000011463 15002227416 0021335 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Replace { use ArrayEnabled; /** * REPLACE. * * @param mixed $oldText The text string value to modify * Or can be an array of values * @param mixed $start Integer offset for start character of the replacement * Or can be an array of values * @param mixed $chars Integer number of characters to replace from the start offset * Or can be an array of values * @param mixed $newText String to replace in the defined position * Or can be an array of values * * @return array|string * If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function replace($oldText, $start, $chars, $newText) { if (is_array($oldText) || is_array($start) || is_array($chars) || is_array($newText)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $oldText, $start, $chars, $newText); } try { $start = Helpers::extractInt($start, 1, 0, true); $chars = Helpers::extractInt($chars, 0, 0, true); $oldText = Helpers::extractString($oldText, true); $newText = Helpers::extractString($newText, true); $left = StringHelper::substring($oldText, 0, $start - 1); $right = StringHelper::substring($oldText, $start + $chars - 1, null); } catch (CalcExp $e) { return $e->getMessage(); } $returnValue = $left . $newText . $right; if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::VALUE(); } return $returnValue; } /** * SUBSTITUTE. * * @param mixed $text The text string value to modify * Or can be an array of values * @param mixed $fromText The string value that we want to replace in $text * Or can be an array of values * @param mixed $toText The string value that we want to replace with in $text * Or can be an array of values * @param mixed $instance Integer instance Number for the occurrence of frmText to change * Or can be an array of values * * @return array|string * If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function substitute($text = '', $fromText = '', $toText = '', $instance = null) { if (is_array($text) || is_array($fromText) || is_array($toText) || is_array($instance)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $text, $fromText, $toText, $instance); } try { $text = Helpers::extractString($text, true); $fromText = Helpers::extractString($fromText, true); $toText = Helpers::extractString($toText, true); if ($instance === null) { $returnValue = str_replace($fromText, $toText, $text); } else { if (is_bool($instance)) { if ($instance === false || Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE) { return ExcelError::Value(); } $instance = 1; } $instance = Helpers::extractInt($instance, 1, 0, true); $returnValue = self::executeSubstitution($text, $fromText, $toText, $instance); } } catch (CalcExp $e) { return $e->getMessage(); } if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::VALUE(); } return $returnValue; } private static function executeSubstitution(string $text, string $fromText, string $toText, int $instance): string { $pos = -1; while ($instance > 0) { $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8'); if ($pos === false) { return $text; } --$instance; } return Functions::scalar(self::REPLACE($text, ++$pos, StringHelper::countCharacters($fromText), $toText)); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php 0000644 00000027566 15002227416 0021407 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Extract { use ArrayEnabled; /** * LEFT. * * @param mixed $value String value from which to extract characters * Or can be an array of values * @param mixed $chars The number of characters to extract (as an integer) * Or can be an array of values * * @return array|string The joined string * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function left($value, $chars = 1) { if (is_array($value) || is_array($chars)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $chars); } try { $value = Helpers::extractString($value); $chars = Helpers::extractInt($chars, 0, 1); } catch (CalcExp $e) { return $e->getMessage(); } return mb_substr($value, 0, $chars, 'UTF-8'); } /** * MID. * * @param mixed $value String value from which to extract characters * Or can be an array of values * @param mixed $start Integer offset of the first character that we want to extract * Or can be an array of values * @param mixed $chars The number of characters to extract (as an integer) * Or can be an array of values * * @return array|string The joined string * If an array of values is passed for the $value, $start or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function mid($value, $start, $chars) { if (is_array($value) || is_array($start) || is_array($chars)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $start, $chars); } try { $value = Helpers::extractString($value); $start = Helpers::extractInt($start, 1); $chars = Helpers::extractInt($chars, 0); } catch (CalcExp $e) { return $e->getMessage(); } return mb_substr($value, --$start, $chars, 'UTF-8'); } /** * RIGHT. * * @param mixed $value String value from which to extract characters * Or can be an array of values * @param mixed $chars The number of characters to extract (as an integer) * Or can be an array of values * * @return array|string The joined string * If an array of values is passed for the $value or $chars arguments, then the returned result * will also be an array with matching dimensions */ public static function right($value, $chars = 1) { if (is_array($value) || is_array($chars)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $chars); } try { $value = Helpers::extractString($value); $chars = Helpers::extractInt($chars, 0, 1); } catch (CalcExp $e) { return $e->getMessage(); } return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8'); } /** * TEXTBEFORE. * * @param mixed $text the text that you're searching * Or can be an array of values * @param null|array|string $delimiter the text that marks the point before which you want to extract * Multiple delimiters can be passed as an array of string values * @param mixed $instance The instance of the delimiter after which you want to extract the text. * By default, this is the first instance (1). * A negative value means start searching from the end of the text string. * Or can be an array of values * @param mixed $matchMode Determines whether the match is case-sensitive or not. * 0 - Case-sensitive * 1 - Case-insensitive * Or can be an array of values * @param mixed $matchEnd Treats the end of text as a delimiter. * 0 - Don't match the delimiter against the end of the text. * 1 - Match the delimiter against the end of the text. * Or can be an array of values * @param mixed $ifNotFound value to return if no match is found * The default is a #N/A Error * Or can be an array of values * * @return mixed|mixed[] the string extracted from text before the delimiter; or the $ifNotFound value * If an array of values is passed for any of the arguments, then the returned result * will also be an array with matching dimensions */ public static function before($text, $delimiter, $instance = 1, $matchMode = 0, $matchEnd = 0, $ifNotFound = '#N/A') { if (is_array($text) || is_array($instance) || is_array($matchMode) || is_array($matchEnd) || is_array($ifNotFound)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); } $text = Helpers::extractString($text ?? ''); $instance = (int) $instance; $matchMode = (int) $matchMode; $matchEnd = (int) $matchEnd; $split = self::validateTextBeforeAfter($text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); if (is_string($split)) { return $split; } if (Helpers::extractString(Functions::flattenSingleValue($delimiter ?? '')) === '') { return ($instance > 0) ? '' : $text; } // Adjustment for a match as the first element of the split $flags = self::matchFlags($matchMode); $delimiter = self::buildDelimiter($delimiter); $adjust = preg_match('/^' . $delimiter . "\$/{$flags}", $split[0]); $oddReverseAdjustment = count($split) % 2; $split = ($instance < 0) ? array_slice($split, 0, max(count($split) - (abs($instance) * 2 - 1) - $adjust - $oddReverseAdjustment, 0)) : array_slice($split, 0, $instance * 2 - 1 - $adjust); return implode('', $split); } /** * TEXTAFTER. * * @param mixed $text the text that you're searching * @param null|array|string $delimiter the text that marks the point before which you want to extract * Multiple delimiters can be passed as an array of string values * @param mixed $instance The instance of the delimiter after which you want to extract the text. * By default, this is the first instance (1). * A negative value means start searching from the end of the text string. * Or can be an array of values * @param mixed $matchMode Determines whether the match is case-sensitive or not. * 0 - Case-sensitive * 1 - Case-insensitive * Or can be an array of values * @param mixed $matchEnd Treats the end of text as a delimiter. * 0 - Don't match the delimiter against the end of the text. * 1 - Match the delimiter against the end of the text. * Or can be an array of values * @param mixed $ifNotFound value to return if no match is found * The default is a #N/A Error * Or can be an array of values * * @return mixed|mixed[] the string extracted from text before the delimiter; or the $ifNotFound value * If an array of values is passed for any of the arguments, then the returned result * will also be an array with matching dimensions */ public static function after($text, $delimiter, $instance = 1, $matchMode = 0, $matchEnd = 0, $ifNotFound = '#N/A') { if (is_array($text) || is_array($instance) || is_array($matchMode) || is_array($matchEnd) || is_array($ifNotFound)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); } $text = Helpers::extractString($text ?? ''); $instance = (int) $instance; $matchMode = (int) $matchMode; $matchEnd = (int) $matchEnd; $split = self::validateTextBeforeAfter($text, $delimiter, $instance, $matchMode, $matchEnd, $ifNotFound); if (is_string($split)) { return $split; } if (Helpers::extractString(Functions::flattenSingleValue($delimiter ?? '')) === '') { return ($instance < 0) ? '' : $text; } // Adjustment for a match as the first element of the split $flags = self::matchFlags($matchMode); $delimiter = self::buildDelimiter($delimiter); $adjust = preg_match('/^' . $delimiter . "\$/{$flags}", $split[0]); $oddReverseAdjustment = count($split) % 2; $split = ($instance < 0) ? array_slice($split, count($split) - ((int) abs($instance + 1) * 2) - $adjust - $oddReverseAdjustment) : array_slice($split, $instance * 2 - $adjust); return implode('', $split); } /** * @param null|array|string $delimiter * @param int $matchMode * @param int $matchEnd * @param mixed $ifNotFound * * @return array|string */ private static function validateTextBeforeAfter(string $text, $delimiter, int $instance, $matchMode, $matchEnd, $ifNotFound) { $flags = self::matchFlags($matchMode); $delimiter = self::buildDelimiter($delimiter); if (preg_match('/' . $delimiter . "/{$flags}", $text) === 0 && $matchEnd === 0) { return $ifNotFound; } $split = preg_split('/' . $delimiter . "/{$flags}", $text, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); if ($split === false) { return ExcelError::NA(); } if ($instance === 0 || abs($instance) > StringHelper::countCharacters($text)) { return ExcelError::VALUE(); } if ($matchEnd === 0 && (abs($instance) > floor(count($split) / 2))) { return ExcelError::NA(); } elseif ($matchEnd !== 0 && (abs($instance) - 1 > ceil(count($split) / 2))) { return ExcelError::NA(); } return $split; } /** * @param null|array|string $delimiter the text that marks the point before which you want to extract * Multiple delimiters can be passed as an array of string values */ private static function buildDelimiter($delimiter): string { if (is_array($delimiter)) { $delimiter = Functions::flattenArray($delimiter); $quotedDelimiters = array_map( function ($delimiter) { return preg_quote($delimiter ?? '', '/'); }, $delimiter ); $delimiters = implode('|', $quotedDelimiters); return '(' . $delimiters . ')'; } return '(' . preg_quote($delimiter ?? '', '/') . ')'; } private static function matchFlags(int $matchMode): string { return ($matchMode === 0) ? 'mu' : 'miu'; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php 0000644 00000026770 15002227416 0021221 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use DateTimeInterface; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class Format { use ArrayEnabled; /** * DOLLAR. * * This function converts a number to text using currency format, with the decimals rounded to the specified place. * The format used is $#,##0.00_);($#,##0.00).. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $decimals The number of digits to display to the right of the decimal point (as an integer). * If decimals is negative, number is rounded to the left of the decimal point. * If you omit decimals, it is assumed to be 2 * Or can be an array of values * * @return array|string * If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function DOLLAR($value = 0, $decimals = 2) { if (is_array($value) || is_array($decimals)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $decimals); } try { $value = Helpers::extractFloat($value); $decimals = Helpers::extractInt($decimals, -100, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } $mask = '$#,##0'; if ($decimals > 0) { $mask .= '.' . str_repeat('0', $decimals); } else { $round = 10 ** abs($decimals); if ($value < 0) { $round = 0 - $round; } $value = MathTrig\Round::multiple($value, $round); } $mask = "{$mask};-{$mask}"; return NumberFormat::toFormattedString($value, $mask); } /** * FIXED. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $decimals Integer value for the number of decimal places that should be formatted * Or can be an array of values * @param mixed $noCommas Boolean value indicating whether the value should have thousands separators or not * Or can be an array of values * * @return array|string * If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function FIXEDFORMAT($value, $decimals = 2, $noCommas = false) { if (is_array($value) || is_array($decimals) || is_array($noCommas)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $decimals, $noCommas); } try { $value = Helpers::extractFloat($value); $decimals = Helpers::extractInt($decimals, -100, 0, true); } catch (CalcExp $e) { return $e->getMessage(); } $valueResult = round($value, $decimals); if ($decimals < 0) { $decimals = 0; } if ($noCommas === false) { $valueResult = number_format( $valueResult, $decimals, StringHelper::getDecimalSeparator(), StringHelper::getThousandsSeparator() ); } return (string) $valueResult; } /** * TEXT. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $format A string with the Format mask that should be used * Or can be an array of values * * @return array|string * If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function TEXTFORMAT($value, $format) { if (is_array($value) || is_array($format)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $format); } $value = Helpers::extractString($value); $format = Helpers::extractString($format); if (!is_numeric($value) && Date::isDateTimeFormatCode($format)) { $value = DateTimeExcel\DateValue::fromString($value) + DateTimeExcel\TimeValue::fromString($value); } return (string) NumberFormat::toFormattedString($value, $format); } /** * @param mixed $value Value to check * * @return mixed */ private static function convertValue($value, bool $spacesMeanZero = false) { $value = $value ?? 0; if (is_bool($value)) { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $value = (int) $value; } else { throw new CalcExp(ExcelError::VALUE()); } } if (is_string($value)) { $value = trim($value); if ($spacesMeanZero && $value === '') { $value = 0; } } return $value; } /** * VALUE. * * @param mixed $value Value to check * Or can be an array of values * * @return array|DateTimeInterface|float|int|string A string if arguments are invalid * If an array of values is passed for the argument, then the returned result * will also be an array with matching dimensions */ public static function VALUE($value = '') { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = self::convertValue($value); } catch (CalcExp $e) { return $e->getMessage(); } if (!is_numeric($value)) { $numberValue = str_replace( StringHelper::getThousandsSeparator(), '', trim($value, " \t\n\r\0\x0B" . StringHelper::getCurrencyCode()) ); if ($numberValue === '') { return ExcelError::VALUE(); } if (is_numeric($numberValue)) { return (float) $numberValue; } $dateSetting = Functions::getReturnDateType(); Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); if (strpos($value, ':') !== false) { $timeValue = Functions::scalar(DateTimeExcel\TimeValue::fromString($value)); if ($timeValue !== ExcelError::VALUE()) { Functions::setReturnDateType($dateSetting); return $timeValue; } } $dateValue = Functions::scalar(DateTimeExcel\DateValue::fromString($value)); if ($dateValue !== ExcelError::VALUE()) { Functions::setReturnDateType($dateSetting); return $dateValue; } Functions::setReturnDateType($dateSetting); return ExcelError::VALUE(); } return (float) $value; } /** * TEXT. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $format * * @return array|string * If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function valueToText($value, $format = false) { if (is_array($value) || is_array($format)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $format); } $format = (bool) $format; if (is_object($value) && $value instanceof RichText) { $value = $value->getPlainText(); } if (is_string($value)) { $value = ($format === true) ? Calculation::wrapResult($value) : $value; $value = str_replace("\n", '', $value); } elseif (is_bool($value)) { $value = Calculation::getLocaleBoolean($value ? 'TRUE' : 'FALSE'); } return (string) $value; } /** * @param mixed $decimalSeparator */ private static function getDecimalSeparator($decimalSeparator): string { return empty($decimalSeparator) ? StringHelper::getDecimalSeparator() : (string) $decimalSeparator; } /** * @param mixed $groupSeparator */ private static function getGroupSeparator($groupSeparator): string { return empty($groupSeparator) ? StringHelper::getThousandsSeparator() : (string) $groupSeparator; } /** * NUMBERVALUE. * * @param mixed $value The value to format * Or can be an array of values * @param mixed $decimalSeparator A string with the decimal separator to use, defaults to locale defined value * Or can be an array of values * @param mixed $groupSeparator A string with the group/thousands separator to use, defaults to locale defined value * Or can be an array of values * * @return array|float|string */ public static function NUMBERVALUE($value = '', $decimalSeparator = null, $groupSeparator = null) { if (is_array($value) || is_array($decimalSeparator) || is_array($groupSeparator)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $decimalSeparator, $groupSeparator); } try { $value = self::convertValue($value, true); $decimalSeparator = self::getDecimalSeparator($decimalSeparator); $groupSeparator = self::getGroupSeparator($groupSeparator); } catch (CalcExp $e) { return $e->getMessage(); } if (!is_numeric($value)) { $decimalPositions = preg_match_all('/' . preg_quote($decimalSeparator, '/') . '/', $value, $matches, PREG_OFFSET_CAPTURE); if ($decimalPositions > 1) { return ExcelError::VALUE(); } $decimalOffset = array_pop($matches[0])[1] ?? null; if ($decimalOffset === null || strpos($value, $groupSeparator, $decimalOffset) !== false) { return ExcelError::VALUE(); } $value = str_replace([$groupSeparator, $decimalSeparator], ['', '.'], $value); // Handle the special case of trailing % signs $percentageString = rtrim($value, '%'); if (!is_numeric($percentageString)) { return ExcelError::VALUE(); } $percentageAdjustment = strlen($value) - strlen($percentageString); if ($percentageAdjustment) { $value = (float) $percentageString; $value /= 10 ** ($percentageAdjustment * 2); } } return is_array($value) ? ExcelError::VALUE() : (float) $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Text.php 0000644 00000021216 15002227416 0020703 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; class Text { use ArrayEnabled; /** * LEN. * * @param mixed $value String Value * Or can be an array of values * * @return array|int * If an array of values is passed for the argument, then the returned result * will also be an array with matching dimensions */ public static function length($value = '') { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } $value = Helpers::extractString($value); return mb_strlen($value, 'UTF-8'); } /** * Compares two text strings and returns TRUE if they are exactly the same, FALSE otherwise. * EXACT is case-sensitive but ignores formatting differences. * Use EXACT to test text being entered into a document. * * @param mixed $value1 String Value * Or can be an array of values * @param mixed $value2 String Value * Or can be an array of values * * @return array|bool * If an array of values is passed for either of the arguments, then the returned result * will also be an array with matching dimensions */ public static function exact($value1, $value2) { if (is_array($value1) || is_array($value2)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value1, $value2); } $value1 = Helpers::extractString($value1); $value2 = Helpers::extractString($value2); return $value2 === $value1; } /** * T. * * @param mixed $testValue Value to check * Or can be an array of values * * @return array|string * If an array of values is passed for the argument, then the returned result * will also be an array with matching dimensions */ public static function test($testValue = '') { if (is_array($testValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $testValue); } if (is_string($testValue)) { return $testValue; } return ''; } /** * TEXTSPLIT. * * @param mixed $text the text that you're searching * @param null|array|string $columnDelimiter The text that marks the point where to spill the text across columns. * Multiple delimiters can be passed as an array of string values * @param null|array|string $rowDelimiter The text that marks the point where to spill the text down rows. * Multiple delimiters can be passed as an array of string values * @param bool $ignoreEmpty Specify FALSE to create an empty cell when two delimiters are consecutive. * true = create empty cells * false = skip empty cells * Defaults to TRUE, which creates an empty cell * @param bool $matchMode Determines whether the match is case-sensitive or not. * true = case-sensitive * false = case-insensitive * By default, a case-sensitive match is done. * @param mixed $padding The value with which to pad the result. * The default is #N/A. * * @return array the array built from the text, split by the row and column delimiters */ public static function split($text, $columnDelimiter = null, $rowDelimiter = null, bool $ignoreEmpty = false, bool $matchMode = true, $padding = '#N/A') { $text = Functions::flattenSingleValue($text); $flags = self::matchFlags($matchMode); if ($rowDelimiter !== null) { $delimiter = self::buildDelimiter($rowDelimiter); $rows = ($delimiter === '()') ? [$text] : preg_split("/{$delimiter}/{$flags}", $text); } else { $rows = [$text]; } /** @var array $rows */ if ($ignoreEmpty === true) { $rows = array_values(array_filter( $rows, function ($row) { return $row !== ''; } )); } if ($columnDelimiter !== null) { $delimiter = self::buildDelimiter($columnDelimiter); array_walk( $rows, function (&$row) use ($delimiter, $flags, $ignoreEmpty): void { $row = ($delimiter === '()') ? [$row] : preg_split("/{$delimiter}/{$flags}", $row); /** @var array $row */ if ($ignoreEmpty === true) { $row = array_values(array_filter( $row, function ($value) { return $value !== ''; } )); } } ); if ($ignoreEmpty === true) { $rows = array_values(array_filter( $rows, function ($row) { return $row !== [] && $row !== ['']; } )); } } return self::applyPadding($rows, $padding); } /** * @param mixed $padding */ private static function applyPadding(array $rows, $padding): array { $columnCount = array_reduce( $rows, function (int $counter, array $row): int { return max($counter, count($row)); }, 0 ); return array_map( function (array $row) use ($columnCount, $padding): array { return (count($row) < $columnCount) ? array_merge($row, array_fill(0, $columnCount - count($row), $padding)) : $row; }, $rows ); } /** * @param null|array|string $delimiter the text that marks the point before which you want to split * Multiple delimiters can be passed as an array of string values */ private static function buildDelimiter($delimiter): string { $valueSet = Functions::flattenArray($delimiter); if (is_array($delimiter) && count($valueSet) > 1) { $quotedDelimiters = array_map( function ($delimiter) { return preg_quote($delimiter ?? '', '/'); }, $valueSet ); $delimiters = implode('|', $quotedDelimiters); return '(' . $delimiters . ')'; } return '(' . preg_quote(/** @scrutinizer ignore-type */ Functions::flattenSingleValue($delimiter), '/') . ')'; } private static function matchFlags(bool $matchMode): string { return ($matchMode === true) ? 'miu' : 'mu'; } public static function fromArray(array $array, int $format = 0): string { $result = []; foreach ($array as $row) { $cells = []; foreach ($row as $cellValue) { $value = ($format === 1) ? self::formatValueMode1($cellValue) : self::formatValueMode0($cellValue); $cells[] = $value; } $result[] = implode(($format === 1) ? ',' : ', ', $cells); } $result = implode(($format === 1) ? ';' : ', ', $result); return ($format === 1) ? '{' . $result . '}' : $result; } /** * @param mixed $cellValue */ private static function formatValueMode0($cellValue): string { if (is_bool($cellValue)) { return Calculation::getLocaleBoolean($cellValue ? 'TRUE' : 'FALSE'); } return (string) $cellValue; } /** * @param mixed $cellValue */ private static function formatValueMode1($cellValue): string { if (is_string($cellValue) && ErrorValue::isError($cellValue) === false) { return Calculation::FORMULA_STRING_QUOTE . $cellValue . Calculation::FORMULA_STRING_QUOTE; } elseif (is_bool($cellValue)) { return Calculation::getLocaleBoolean($cellValue ? 'TRUE' : 'FALSE'); } return (string) $cellValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/CharacterConvert.php 0000644 00000005051 15002227416 0023213 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class CharacterConvert { use ArrayEnabled; /** * CHAR. * * @param mixed $character Integer Value to convert to its character representation * Or can be an array of values * * @return array|string The character string * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function character($character) { if (is_array($character)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $character); } $character = Helpers::validateInt($character); $min = Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE ? 0 : 1; if ($character < $min || $character > 255) { return ExcelError::VALUE(); } $result = iconv('UCS-4LE', 'UTF-8', pack('V', $character)); return ($result === false) ? '' : $result; } /** * CODE. * * @param mixed $characters String character to convert to its ASCII value * Or can be an array of values * * @return array|int|string A string if arguments are invalid * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function code($characters) { if (is_array($characters)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $characters); } $characters = Helpers::extractString($characters); if ($characters === '') { return ExcelError::VALUE(); } $character = $characters; if (mb_strlen($characters, 'UTF-8') > 1) { $character = mb_substr($characters, 0, 1, 'UTF-8'); } return self::unicodeToOrd($character); } private static function unicodeToOrd(string $character): int { $retVal = 0; $iconv = iconv('UTF-8', 'UCS-4LE', $character); if ($iconv !== false) { $result = unpack('V', $iconv); if (is_array($result) && isset($result[1])) { $retVal = $result[1]; } } return $retVal; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Helpers.php 0000644 00000005031 15002227416 0021356 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Helpers { public static function convertBooleanValue(bool $value): string { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { return $value ? '1' : '0'; } return ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); } /** * @param mixed $value String value from which to extract characters */ public static function extractString($value, bool $throwIfError = false): string { if (is_bool($value)) { return self::convertBooleanValue($value); } if ($throwIfError && is_string($value) && ErrorValue::isError($value)) { throw new CalcExp($value); } return (string) $value; } /** * @param mixed $value */ public static function extractInt($value, int $minValue, int $gnumericNull = 0, bool $ooBoolOk = false): int { if ($value === null) { // usually 0, but sometimes 1 for Gnumeric $value = (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_GNUMERIC) ? $gnumericNull : 0; } if (is_bool($value) && ($ooBoolOk || Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE)) { $value = (int) $value; } if (!is_numeric($value)) { throw new CalcExp(ExcelError::VALUE()); } $value = (int) $value; if ($value < $minValue) { throw new CalcExp(ExcelError::VALUE()); } return (int) $value; } /** * @param mixed $value */ public static function extractFloat($value): float { if ($value === null) { $value = 0.0; } if (is_bool($value)) { $value = (float) $value; } if (!is_numeric($value)) { throw new CalcExp(ExcelError::VALUE()); } return (float) $value; } /** * @param mixed $value */ public static function validateInt($value): int { if ($value === null) { $value = 0; } elseif (is_bool($value)) { $value = (int) $value; } return (int) $value; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php 0000644 00000004740 15002227416 0022176 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class CaseConvert { use ArrayEnabled; /** * LOWERCASE. * * Converts a string value to upper case. * * @param mixed $mixedCaseValue The string value to convert to lower case * Or can be an array of values * * @return array|string * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function lower($mixedCaseValue) { if (is_array($mixedCaseValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $mixedCaseValue); } $mixedCaseValue = Helpers::extractString($mixedCaseValue); return StringHelper::strToLower($mixedCaseValue); } /** * UPPERCASE. * * Converts a string value to upper case. * * @param mixed $mixedCaseValue The string value to convert to upper case * Or can be an array of values * * @return array|string * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function upper($mixedCaseValue) { if (is_array($mixedCaseValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $mixedCaseValue); } $mixedCaseValue = Helpers::extractString($mixedCaseValue); return StringHelper::strToUpper($mixedCaseValue); } /** * PROPERCASE. * * Converts a string value to proper or title case. * * @param mixed $mixedCaseValue The string value to convert to title case * Or can be an array of values * * @return array|string * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function proper($mixedCaseValue) { if (is_array($mixedCaseValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $mixedCaseValue); } $mixedCaseValue = Helpers::extractString($mixedCaseValue); return StringHelper::strToTitle($mixedCaseValue); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Concatenate.php 0000644 00000011041 15002227416 0022176 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Concatenate { use ArrayEnabled; /** * CONCATENATE. * * @param array $args */ public static function CONCATENATE(...$args): string { $returnValue = ''; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { $value = Helpers::extractString($arg); if (ErrorValue::isError($value)) { $returnValue = $value; break; } $returnValue .= Helpers::extractString($arg); if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::CALC(); break; } } return $returnValue; } /** * TEXTJOIN. * * @param mixed $delimiter The delimter to use between the joined arguments * Or can be an array of values * @param mixed $ignoreEmpty true/false Flag indicating whether empty arguments should be skipped * Or can be an array of values * @param mixed $args The values to join * * @return array|string The joined string * If an array of values is passed for the $delimiter or $ignoreEmpty arguments, then the returned result * will also be an array with matching dimensions */ public static function TEXTJOIN($delimiter = '', $ignoreEmpty = true, ...$args) { if (is_array($delimiter) || is_array($ignoreEmpty)) { return self::evaluateArrayArgumentsSubset( [self::class, __FUNCTION__], 2, $delimiter, $ignoreEmpty, ...$args ); } $delimiter ??= ''; $ignoreEmpty ??= true; $aArgs = Functions::flattenArray($args); $returnValue = self::evaluateTextJoinArray($ignoreEmpty, $aArgs); $returnValue ??= implode($delimiter, $aArgs); if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::CALC(); } return $returnValue; } private static function evaluateTextJoinArray(bool $ignoreEmpty, array &$aArgs): ?string { foreach ($aArgs as $key => &$arg) { $value = Helpers::extractString($arg); if (ErrorValue::isError($value)) { return $value; } if ($ignoreEmpty === true && ((is_string($arg) && trim($arg) === '') || $arg === null)) { unset($aArgs[$key]); } elseif (is_bool($arg)) { $arg = Helpers::convertBooleanValue($arg); } } return null; } /** * REPT. * * Returns the result of builtin function round after validating args. * * @param mixed $stringValue The value to repeat * Or can be an array of values * @param mixed $repeatCount The number of times the string value should be repeated * Or can be an array of values * * @return array|string The repeated string * If an array of values is passed for the $stringValue or $repeatCount arguments, then the returned result * will also be an array with matching dimensions */ public static function builtinREPT($stringValue, $repeatCount) { if (is_array($stringValue) || is_array($repeatCount)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $stringValue, $repeatCount); } $stringValue = Helpers::extractString($stringValue); if (!is_numeric($repeatCount) || $repeatCount < 0) { $returnValue = ExcelError::VALUE(); } elseif (ErrorValue::isError($stringValue)) { $returnValue = $stringValue; } else { $returnValue = str_repeat($stringValue, (int) $repeatCount); if (StringHelper::countCharacters($returnValue) > DataType::MAX_STRING_LENGTH) { $returnValue = ExcelError::VALUE(); // note VALUE not CALC } } return $returnValue; } } phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Trim.php 0000644 00000003036 15002227416 0020672 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation\TextData; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; class Trim { use ArrayEnabled; /** * CLEAN. * * @param mixed $stringValue String Value to check * Or can be an array of values * * @return array|string * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function nonPrintable($stringValue = '') { if (is_array($stringValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $stringValue); } $stringValue = Helpers::extractString($stringValue); return (string) preg_replace('/[\\x00-\\x1f]/', '', "$stringValue"); } /** * TRIM. * * @param mixed $stringValue String Value to check * Or can be an array of values * * @return array|string * If an array of values is passed as the argument, then the returned result will also be an array * with the same dimensions */ public static function spaces($stringValue = '') { if (is_array($stringValue)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $stringValue); } $stringValue = Helpers::extractString($stringValue); return trim(preg_replace('/ +/', ' ', trim("$stringValue", ' ')) ?? '', ' '); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical.php 0000644 00000026626 15002227416 0017625 0 ustar 00 <?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean; /** * @deprecated 1.17.0 */ class Logical { /** * TRUE. * * Returns the boolean TRUE. * * Excel Function: * =TRUE() * * @deprecated 1.17.0 * Use the TRUE() method in the Logical\Boolean class instead * @see Logical\Boolean::TRUE() * * @return bool True */ public static function true(): bool { return Boolean::true(); } /** * FALSE. * * Returns the boolean FALSE. * * Excel Function: * =FALSE() * * @deprecated 1.17.0 * Use the FALSE() method in the Logical\Boolean class instead * @see Logical\Boolean::FALSE() * * @return bool False */ public static function false(): bool { return Boolean::false(); } /** * LOGICAL_AND. * * Returns boolean TRUE if all its arguments are TRUE; returns FALSE if one or more argument is FALSE. * * Excel Function: * =AND(logical1[,logical2[, ...]]) * * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays * or references that contain logical values. * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @deprecated 1.17.0 * Use the logicalAnd() method in the Logical\Operations class instead * @see Logical\Operations::logicalAnd() * * @param mixed ...$args Data values * * @return bool|string the logical AND of the arguments */ public static function logicalAnd(...$args) { return Logical\Operations::logicalAnd(...$args); } /** * LOGICAL_OR. * * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE. * * Excel Function: * =OR(logical1[,logical2[, ...]]) * * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays * or references that contain logical values. * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @deprecated 1.17.0 * Use the logicalOr() method in the Logical\Operations class instead * @see Logical\Operations::logicalOr() * * @param mixed $args Data values * * @return bool|string the logical OR of the arguments */ public static function logicalOr(...$args) { return Logical\Operations::logicalOr(...$args); } /** * LOGICAL_XOR. * * Returns the Exclusive Or logical operation for one or more supplied conditions. * i.e. the Xor function returns TRUE if an odd number of the supplied conditions evaluate to TRUE, * and FALSE otherwise. * * Excel Function: * =XOR(logical1[,logical2[, ...]]) * * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays * or references that contain logical values. * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @deprecated 1.17.0 * Use the logicalXor() method in the Logical\Operations class instead * @see Logical\Operations::logicalXor() * * @param mixed $args Data values * * @return bool|string the logical XOR of the arguments */ public static function logicalXor(...$args) { return Logical\Operations::logicalXor(...$args); } /** * NOT. * * Returns the boolean inverse of the argument. * * Excel Function: * =NOT(logical) * * The argument must evaluate to a logical value such as TRUE or FALSE * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * * @deprecated 1.17.0 * Use the NOT() method in the Logical\Operations class instead * @see Logical\Operations::NOT() * * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE * * @return array|bool|string the boolean inverse of the argument */ public static function NOT($logical = false) { return Logical\Operations::NOT($logical); } /** * STATEMENT_IF. * * Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE. * * Excel Function: * =IF(condition[,returnIfTrue[,returnIfFalse]]) * * Condition is any value or expression that can be evaluated to TRUE or FALSE. * For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100, * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE. * This argument can use any comparison calculation operator. * ReturnIfTrue is the value that is returned if condition evaluates to TRUE. * For example, if this argument is the text string "Within budget" and the condition argument * evaluates to TRUE, then the IF function returns the text "Within budget" * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). * To display the word TRUE, use the logical value TRUE for this argument. * ReturnIfTrue can be another formula. * ReturnIfFalse is the value that is returned if condition evaluates to FALSE. * For example, if this argument is the text string "Over budget" and the condition argument * evaluates to FALSE, then the IF function returns the text "Over budget". * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned. * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned. * ReturnIfFalse can be another formula. * * @deprecated 1.17.0 * Use the statementIf() method in the Logical\Conditional class instead * @see Logical\Conditional::statementIf() * * @param mixed $condition Condition to evaluate * @param mixed $returnIfTrue Value to return when condition is true * @param mixed $returnIfFalse Optional value to return when condition is false * * @return mixed The value of returnIfTrue or returnIfFalse determined by condition */ public static function statementIf($condition = true, $returnIfTrue = 0, $returnIfFalse = false) { return Logical\Conditional::statementIf($condition, $returnIfTrue, $returnIfFalse); } /** * STATEMENT_SWITCH. * * Returns corresponding with first match (any data type such as a string, numeric, date, etc). * * Excel Function: * =SWITCH (expression, value1, result1, value2, result2, ... value_n, result_n [, default]) * * Expression * The expression to compare to a list of values. * value1, value2, ... value_n * A list of values that are compared to expression. * The SWITCH function is looking for the first value that matches the expression. * result1, result2, ... result_n * A list of results. The SWITCH function returns the corresponding result when a value * matches expression. * default * Optional. It is the default to return if expression does not match any of the values * (value1, value2, ... value_n). * * @deprecated 1.17.0 * Use the statementSwitch() method in the Logical\Conditional class instead * @see Logical\Conditional::statementSwitch() * * @param mixed $arguments Statement arguments * * @return mixed The value of matched expression */ public static function statementSwitch(...$arguments) { return Logical\Conditional::statementSwitch(...$arguments); } /** * IFERROR. * * Excel Function: * =IFERROR(testValue,errorpart) * * @deprecated 1.17.0 * Use the IFERROR() method in the Logical\Conditional class instead * @see Logical\Conditional::IFERROR() * * @param mixed $testValue Value to check, is also the value returned when no error * @param mixed $errorpart Value to return when testValue is an error condition * * @return mixed The value of errorpart or testValue determined by error condition */ public static function IFERROR($testValue = '', $errorpart = '') { return Logical\Conditional::IFERROR($testValue, $errorpart); } /** * IFNA. * * Excel Function: * =IFNA(testValue,napart) * * @deprecated 1.17.0 * Use the IFNA() method in the Logical\Conditional class instead * @see Logical\Conditional::IFNA() * * @param mixed $testValue Value to check, is also the value returned when not an NA * @param mixed $napart Value to return when testValue is an NA condition * * @return mixed The value of errorpart or testValue determined by error condition */ public static function IFNA($testValue = '', $napart = '') { return Logical\Conditional::IFNA($testValue, $napart); } /** * IFS. * * Excel Function: * =IFS(testValue1;returnIfTrue1;testValue2;returnIfTrue2;...;testValue_n;returnIfTrue_n) * * testValue1 ... testValue_n * Conditions to Evaluate * returnIfTrue1 ... returnIfTrue_n * Value returned if corresponding testValue (nth) was true * * @deprecated 1.17.0 * Use the IFS() method in the Logical\Conditional class instead * @see Logical\Conditional::IFS() * * @param mixed ...$arguments Statement arguments * * @return mixed|string The value of returnIfTrue_n, if testValue_n was true. #N/A if none of testValues was true */ public static function IFS(...$arguments) { return Logical\Conditional::IFS(...$arguments); } } phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/bg/functions 0000644 00000147436 15002227416 0021327 0 ustar 00 ## ## PhpSpreadsheet ## ## ## Data in this file derived from information provided by web-junior (http://www.web-junior.net/) ## ## ## ## Add-in and Automation functions Функции надстроек и автоматизации ## GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ ## Возвращает данные, хранящиеся в отчете сводной таблицы. ## ## Cube functions Функции Куб ## CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП ## Возвращает свойство ключевого индикатора производительности «(КИП)» и отображает имя «КИП» в ячейке. «КИП» представляет собой количественную величину, такую как ежемесячная валовая прибыль или ежеквартальная текучесть кадров, используемой для контроля эффективности работы организации. CUBEMEMBER = КУБЭЛЕМЕНТ ## Возвращает элемент или кортеж из куба. Используется для проверки существования элемента или кортежа в кубе. CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА ## Возвращает значение свойства элемента из куба. Используется для проверки существования имени элемента в кубе и возвращает указанное свойство для этого элемента. CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ ## Возвращает n-ый или ранжированный элемент в множество. Используется для возвращения одного или нескольких элементов в множество, например, лучшего продавца или 10 лучших студентов. CUBESET = КУБМНОЖ ## Определяет вычислительное множество элементов или кортежей, отправляя на сервер выражение, которое создает множество, а затем возвращает его в Microsoft Office Excel. CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ ## Возвращает число элементов множества. CUBEVALUE = КУБЗНАЧЕНИЕ ## Возвращает обобщенное значение из куба. ## ## Database functions Функции для работы с базами данных ## DAVERAGE = ДСРЗНАЧ ## Возвращает среднее значение выбранных записей базы данных. DCOUNT = БСЧЁТ ## Подсчитывает количество числовых ячеек в базе данных. DCOUNTA = БСЧЁТА ## Подсчитывает количество непустых ячеек в базе данных. DGET = БИЗВЛЕЧЬ ## Извлекает из базы данных одну запись, удовлетворяющую заданному условию. DMAX = ДМАКС ## Возвращает максимальное значение среди выделенных записей базы данных. DMIN = ДМИН ## Возвращает минимальное значение среди выделенных записей базы данных. DPRODUCT = БДПРОИЗВЕД ## Перемножает значения определенного поля в записях базы данных, удовлетворяющих условию. DSTDEV = ДСТАНДОТКЛ ## Оценивает стандартное отклонение по выборке для выделенных записей базы данных. DSTDEVP = ДСТАНДОТКЛП ## Вычисляет стандартное отклонение по генеральной совокупности для выделенных записей базы данных DSUM = БДСУММ ## Суммирует числа в поле для записей базы данных, удовлетворяющих условию. DVAR = БДДИСП ## Оценивает дисперсию по выборке из выделенных записей базы данных DVARP = БДДИСПП ## Вычисляет дисперсию по генеральной совокупности для выделенных записей базы данных ## ## Date and time functions Функции даты и времени ## DATE = ДАТА ## Возвращает заданную дату в числовом формате. DATEVALUE = ДАТАЗНАЧ ## Преобразует дату из текстового формата в числовой формат. DAY = ДЕНЬ ## Преобразует дату в числовом формате в день месяца. DAYS360 = ДНЕЙ360 ## Вычисляет количество дней между двумя датами на основе 360-дневного года. EDATE = ДАТАМЕС ## Возвращает дату в числовом формате, отстоящую на заданное число месяцев вперед или назад от начальной даты. EOMONTH = КОНМЕСЯЦА ## Возвращает дату в числовом формате для последнего дня месяца, отстоящего вперед или назад на заданное число месяцев. HOUR = ЧАС ## Преобразует дату в числовом формате в часы. MINUTE = МИНУТЫ ## Преобразует дату в числовом формате в минуты. MONTH = МЕСЯЦ ## Преобразует дату в числовом формате в месяцы. NETWORKDAYS = ЧИСТРАБДНИ ## Возвращает количество рабочих дней между двумя датами. NOW = ТДАТА ## Возвращает текущую дату и время в числовом формате. SECOND = СЕКУНДЫ ## Преобразует дату в числовом формате в секунды. TIME = ВРЕМЯ ## Возвращает заданное время в числовом формате. TIMEVALUE = ВРЕМЗНАЧ ## Преобразует время из текстового формата в числовой формат. TODAY = СЕГОДНЯ ## Возвращает текущую дату в числовом формате. WEEKDAY = ДЕНЬНЕД ## Преобразует дату в числовом формате в день недели. WEEKNUM = НОМНЕДЕЛИ ## Преобразует числовое представление в число, которое указывает, на какую неделю года приходится указанная дата. WORKDAY = РАБДЕНЬ ## Возвращает дату в числовом формате, отстоящую вперед или назад на заданное количество рабочих дней. YEAR = ГОД ## Преобразует дату в числовом формате в год. YEARFRAC = ДОЛЯГОДА ## Возвращает долю года, которую составляет количество дней между начальной и конечной датами. ## ## Engineering functions Инженерные функции ## BESSELI = БЕССЕЛЬ.I ## Возвращает модифицированную функцию Бесселя In(x). BESSELJ = БЕССЕЛЬ.J ## Возвращает функцию Бесселя Jn(x). BESSELK = БЕССЕЛЬ.K ## Возвращает модифицированную функцию Бесселя Kn(x). BESSELY = БЕССЕЛЬ.Y ## Возвращает функцию Бесселя Yn(x). BIN2DEC = ДВ.В.ДЕС ## Преобразует двоичное число в десятичное. BIN2HEX = ДВ.В.ШЕСТН ## Преобразует двоичное число в шестнадцатеричное. BIN2OCT = ДВ.В.ВОСЬМ ## Преобразует двоичное число в восьмеричное. COMPLEX = КОМПЛЕКСН ## Преобразует коэффициенты при вещественной и мнимой частях комплексного числа в комплексное число. CONVERT = ПРЕОБР ## Преобразует число из одной системы единиц измерения в другую. DEC2BIN = ДЕС.В.ДВ ## Преобразует десятичное число в двоичное. DEC2HEX = ДЕС.В.ШЕСТН ## Преобразует десятичное число в шестнадцатеричное. DEC2OCT = ДЕС.В.ВОСЬМ ## Преобразует десятичное число в восьмеричное. DELTA = ДЕЛЬТА ## Проверяет равенство двух значений. ERF = ФОШ ## Возвращает функцию ошибки. ERFC = ДФОШ ## Возвращает дополнительную функцию ошибки. GESTEP = ПОРОГ ## Проверяет, не превышает ли данное число порогового значения. HEX2BIN = ШЕСТН.В.ДВ ## Преобразует шестнадцатеричное число в двоичное. HEX2DEC = ШЕСТН.В.ДЕС ## Преобразует шестнадцатеричное число в десятичное. HEX2OCT = ШЕСТН.В.ВОСЬМ ## Преобразует шестнадцатеричное число в восьмеричное. IMABS = МНИМ.ABS ## Возвращает абсолютную величину (модуль) комплексного числа. IMAGINARY = МНИМ.ЧАСТЬ ## Возвращает коэффициент при мнимой части комплексного числа. IMARGUMENT = МНИМ.АРГУМЕНТ ## Возвращает значение аргумента комплексного числа (тета) — угол, выраженный в радианах. IMCONJUGATE = МНИМ.СОПРЯЖ ## Возвращает комплексно-сопряженное комплексное число. IMCOS = МНИМ.COS ## Возвращает косинус комплексного числа. IMDIV = МНИМ.ДЕЛ ## Возвращает частное от деления двух комплексных чисел. IMEXP = МНИМ.EXP ## Возвращает экспоненту комплексного числа. IMLN = МНИМ.LN ## Возвращает натуральный логарифм комплексного числа. IMLOG10 = МНИМ.LOG10 ## Возвращает обычный (десятичный) логарифм комплексного числа. IMLOG2 = МНИМ.LOG2 ## Возвращает двоичный логарифм комплексного числа. IMPOWER = МНИМ.СТЕПЕНЬ ## Возвращает комплексное число, возведенное в целую степень. IMPRODUCT = МНИМ.ПРОИЗВЕД ## Возвращает произведение от 2 до 29 комплексных чисел. IMREAL = МНИМ.ВЕЩ ## Возвращает коэффициент при вещественной части комплексного числа. IMSIN = МНИМ.SIN ## Возвращает синус комплексного числа. IMSQRT = МНИМ.КОРЕНЬ ## Возвращает значение квадратного корня из комплексного числа. IMSUB = МНИМ.РАЗН ## Возвращает разность двух комплексных чисел. IMSUM = МНИМ.СУММ ## Возвращает сумму комплексных чисел. OCT2BIN = ВОСЬМ.В.ДВ ## Преобразует восьмеричное число в двоичное. OCT2DEC = ВОСЬМ.В.ДЕС ## Преобразует восьмеричное число в десятичное. OCT2HEX = ВОСЬМ.В.ШЕСТН ## Преобразует восьмеричное число в шестнадцатеричное. ## ## Financial functions Финансовые функции ## ACCRINT = НАКОПДОХОД ## Возвращает накопленный процент по ценным бумагам с периодической выплатой процентов. ACCRINTM = НАКОПДОХОДПОГАШ ## Возвращает накопленный процент по ценным бумагам, проценты по которым выплачиваются в срок погашения. AMORDEGRC = АМОРУМ ## Возвращает величину амортизации для каждого периода, используя коэффициент амортизации. AMORLINC = АМОРУВ ## Возвращает величину амортизации для каждого периода. COUPDAYBS = ДНЕЙКУПОНДО ## Возвращает количество дней от начала действия купона до даты соглашения. COUPDAYS = ДНЕЙКУПОН ## Возвращает число дней в периоде купона, содержащем дату соглашения. COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ ## Возвращает число дней от даты соглашения до срока следующего купона. COUPNCD = ДАТАКУПОНПОСЛЕ ## Возвращает следующую дату купона после даты соглашения. COUPNUM = ЧИСЛКУПОН ## Возвращает количество купонов, которые могут быть оплачены между датой соглашения и сроком вступления в силу. COUPPCD = ДАТАКУПОНДО ## Возвращает предыдущую дату купона перед датой соглашения. CUMIPMT = ОБЩПЛАТ ## Возвращает общую выплату, произведенную между двумя периодическими выплатами. CUMPRINC = ОБЩДОХОД ## Возвращает общую выплату по займу между двумя периодами. DB = ФУО ## Возвращает величину амортизации актива для заданного периода, рассчитанную методом фиксированного уменьшения остатка. DDB = ДДОБ ## Возвращает величину амортизации актива за данный период, используя метод двойного уменьшения остатка или иной явно указанный метод. DISC = СКИДКА ## Возвращает норму скидки для ценных бумаг. DOLLARDE = РУБЛЬ.ДЕС ## Преобразует цену в рублях, выраженную в виде дроби, в цену в рублях, выраженную десятичным числом. DOLLARFR = РУБЛЬ.ДРОБЬ ## Преобразует цену в рублях, выраженную десятичным числом, в цену в рублях, выраженную в виде дроби. DURATION = ДЛИТ ## Возвращает ежегодную продолжительность действия ценных бумаг с периодическими выплатами по процентам. EFFECT = ЭФФЕКТ ## Возвращает действующие ежегодные процентные ставки. FV = БС ## Возвращает будущую стоимость инвестиции. FVSCHEDULE = БЗРАСПИС ## Возвращает будущую стоимость первоначальной основной суммы после начисления ряда сложных процентов. INTRATE = ИНОРМА ## Возвращает процентную ставку для полностью инвестированных ценных бумаг. IPMT = ПРПЛТ ## Возвращает величину выплаты прибыли на вложения за данный период. IRR = ВСД ## Возвращает внутреннюю ставку доходности для ряда потоков денежных средств. ISPMT = ПРОЦПЛАТ ## Вычисляет выплаты за указанный период инвестиции. MDURATION = МДЛИТ ## Возвращает модифицированную длительность Маколея для ценных бумаг с предполагаемой номинальной стоимостью 100 рублей. MIRR = МВСД ## Возвращает внутреннюю ставку доходности, при которой положительные и отрицательные денежные потоки имеют разные значения ставки. NOMINAL = НОМИНАЛ ## Возвращает номинальную годовую процентную ставку. NPER = КПЕР ## Возвращает общее количество периодов выплаты для данного вклада. NPV = ЧПС ## Возвращает чистую приведенную стоимость инвестиции, основанной на серии периодических денежных потоков и ставке дисконтирования. ODDFPRICE = ЦЕНАПЕРВНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным первым периодом. ODDFYIELD = ДОХОДПЕРВНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным первым периодом. ODDLPRICE = ЦЕНАПОСЛНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным последним периодом. ODDLYIELD = ДОХОДПОСЛНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным последним периодом. PMT = ПЛТ ## Возвращает величину выплаты за один период аннуитета. PPMT = ОСПЛТ ## Возвращает величину выплат в погашение основной суммы по инвестиции за заданный период. PRICE = ЦЕНА ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг, по которым производится периодическая выплата процентов. PRICEDISC = ЦЕНАСКИДКА ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, на которые сделана скидка. PRICEMAT = ЦЕНАПОГАШ ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, проценты по которым выплачиваются в срок погашения. PV = ПС ## Возвращает приведенную (к текущему моменту) стоимость инвестиции. RATE = СТАВКА ## Возвращает процентную ставку по аннуитету за один период. RECEIVED = ПОЛУЧЕНО ## Возвращает сумму, полученную к сроку погашения полностью обеспеченных ценных бумаг. SLN = АПЛ ## Возвращает величину линейной амортизации актива за один период. SYD = АСЧ ## Возвращает величину амортизации актива за данный период, рассчитанную методом суммы годовых чисел. TBILLEQ = РАВНОКЧЕК ## Возвращает эквивалентный облигации доход по казначейскому чеку. TBILLPRICE = ЦЕНАКЧЕК ## Возвращает цену за 100 рублей нарицательной стоимости для казначейского чека. TBILLYIELD = ДОХОДКЧЕК ## Возвращает доход по казначейскому чеку. VDB = ПУО ## Возвращает величину амортизации актива для указанного или частичного периода при использовании метода сокращающегося баланса. XIRR = ЧИСТВНДОХ ## Возвращает внутреннюю ставку доходности для графика денежных потоков, которые не обязательно носят периодический характер. XNPV = ЧИСТНЗ ## Возвращает чистую приведенную стоимость для денежных потоков, которые не обязательно являются периодическими. YIELD = ДОХОД ## Возвращает доход от ценных бумаг, по которым производятся периодические выплаты процентов. YIELDDISC = ДОХОДСКИДКА ## Возвращает годовой доход по ценным бумагам, на которые сделана скидка (пример — казначейские чеки). YIELDMAT = ДОХОДПОГАШ ## Возвращает годовой доход от ценных бумаг, проценты по которым выплачиваются в срок погашения. ## ## Information functions Информационные функции ## CELL = ЯЧЕЙКА ## Возвращает информацию о формате, расположении или содержимом ячейки. ERROR.TYPE = ТИП.ОШИБКИ ## Возвращает числовой код, соответствующий типу ошибки. INFO = ИНФОРМ ## Возвращает информацию о текущей операционной среде. ISBLANK = ЕПУСТО ## Возвращает значение ИСТИНА, если аргумент является ссылкой на пустую ячейку. ISERR = ЕОШ ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки, кроме #Н/Д. ISERROR = ЕОШИБКА ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки. ISEVEN = ЕЧЁТН ## Возвращает значение ИСТИНА, если значение аргумента является четным числом. ISLOGICAL = ЕЛОГИЧ ## Возвращает значение ИСТИНА, если аргумент ссылается на логическое значение. ISNA = ЕНД ## Возвращает значение ИСТИНА, если аргумент ссылается на значение ошибки #Н/Д. ISNONTEXT = ЕНЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента не является текстом. ISNUMBER = ЕЧИСЛО ## Возвращает значение ИСТИНА, если аргумент ссылается на число. ISODD = ЕНЕЧЁТ ## Возвращает значение ИСТИНА, если значение аргумента является нечетным числом. ISREF = ЕССЫЛКА ## Возвращает значение ИСТИНА, если значение аргумента является ссылкой. ISTEXT = ЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента является текстом. N = Ч ## Возвращает значение, преобразованное в число. NA = НД ## Возвращает значение ошибки #Н/Д. TYPE = ТИП ## Возвращает число, обозначающее тип данных значения. ## ## Logical functions Логические функции ## AND = И ## Renvoie VRAI si tous ses arguments sont VRAI. FALSE = ЛОЖЬ ## Возвращает логическое значение ЛОЖЬ. IF = ЕСЛИ ## Выполняет проверку условия. IFERROR = ЕСЛИОШИБКА ## Возвращает введённое значение, если вычисление по формуле вызывает ошибку; в противном случае функция возвращает результат вычисления. NOT = НЕ ## Меняет логическое значение своего аргумента на противоположное. OR = ИЛИ ## Возвращает значение ИСТИНА, если хотя бы один аргумент имеет значение ИСТИНА. TRUE = ИСТИНА ## Возвращает логическое значение ИСТИНА. ## ## Lookup and reference functions Функции ссылки и поиска ## ADDRESS = АДРЕС ## Возвращает ссылку на отдельную ячейку листа в виде текста. AREAS = ОБЛАСТИ ## Возвращает количество областей в ссылке. CHOOSE = ВЫБОР ## Выбирает значение из списка значений по индексу. COLUMN = СТОЛБЕЦ ## Возвращает номер столбца, на который указывает ссылка. COLUMNS = ЧИСЛСТОЛБ ## Возвращает количество столбцов в ссылке. HLOOKUP = ГПР ## Ищет в первой строке массива и возвращает значение отмеченной ячейки HYPERLINK = ГИПЕРССЫЛКА ## Создает ссылку, открывающую документ, который находится на сервере сети, в интрасети или в Интернете. INDEX = ИНДЕКС ## Использует индекс для выбора значения из ссылки или массива. INDIRECT = ДВССЫЛ ## Возвращает ссылку, заданную текстовым значением. LOOKUP = ПРОСМОТР ## Ищет значения в векторе или массиве. MATCH = ПОИСКПОЗ ## Ищет значения в ссылке или массиве. OFFSET = СМЕЩ ## Возвращает смещение ссылки относительно заданной ссылки. ROW = СТРОКА ## Возвращает номер строки, определяемой ссылкой. ROWS = ЧСТРОК ## Возвращает количество строк в ссылке. RTD = ДРВ ## Извлекает данные реального времени из программ, поддерживающих автоматизацию COM (Программирование объектов. Стандартное средство для работы с объектами некоторого приложения из другого приложения или средства разработки. Программирование объектов (ранее называемое программированием OLE) является функцией модели COM (Component Object Model, модель компонентных объектов).). TRANSPOSE = ТРАНСП ## Возвращает транспонированный массив. VLOOKUP = ВПР ## Ищет значение в первом столбце массива и возвращает значение из ячейки в найденной строке и указанном столбце. ## ## Math and trigonometry functions Математические и тригонометрические функции ## ABS = ABS ## Возвращает модуль (абсолютную величину) числа. ACOS = ACOS ## Возвращает арккосинус числа. ACOSH = ACOSH ## Возвращает гиперболический арккосинус числа. ASIN = ASIN ## Возвращает арксинус числа. ASINH = ASINH ## Возвращает гиперболический арксинус числа. ATAN = ATAN ## Возвращает арктангенс числа. ATAN2 = ATAN2 ## Возвращает арктангенс для заданных координат x и y. ATANH = ATANH ## Возвращает гиперболический арктангенс числа. CEILING = ОКРВВЕРХ ## Округляет число до ближайшего целого или до ближайшего кратного указанному значению. COMBIN = ЧИСЛКОМБ ## Возвращает количество комбинаций для заданного числа объектов. COS = COS ## Возвращает косинус числа. COSH = COSH ## Возвращает гиперболический косинус числа. DEGREES = ГРАДУСЫ ## Преобразует радианы в градусы. EVEN = ЧЁТН ## Округляет число до ближайшего четного целого. EXP = EXP ## Возвращает число e, возведенное в указанную степень. FACT = ФАКТР ## Возвращает факториал числа. FACTDOUBLE = ДВФАКТР ## Возвращает двойной факториал числа. FLOOR = ОКРВНИЗ ## Округляет число до ближайшего меньшего по модулю значения. GCD = НОД ## Возвращает наибольший общий делитель. INT = ЦЕЛОЕ ## Округляет число до ближайшего меньшего целого. LCM = НОК ## Возвращает наименьшее общее кратное. LN = LN ## Возвращает натуральный логарифм числа. LOG = LOG ## Возвращает логарифм числа по заданному основанию. LOG10 = LOG10 ## Возвращает десятичный логарифм числа. MDETERM = МОПРЕД ## Возвращает определитель матрицы массива. MINVERSE = МОБР ## Возвращает обратную матрицу массива. MMULT = МУМНОЖ ## Возвращает произведение матриц двух массивов. MOD = ОСТАТ ## Возвращает остаток от деления. MROUND = ОКРУГЛТ ## Возвращает число, округленное с требуемой точностью. MULTINOMIAL = МУЛЬТИНОМ ## Возвращает мультиномиальный коэффициент множества чисел. ODD = НЕЧЁТ ## Округляет число до ближайшего нечетного целого. PI = ПИ ## Возвращает число пи. POWER = СТЕПЕНЬ ## Возвращает результат возведения числа в степень. PRODUCT = ПРОИЗВЕД ## Возвращает произведение аргументов. QUOTIENT = ЧАСТНОЕ ## Возвращает целую часть частного при делении. RADIANS = РАДИАНЫ ## Преобразует градусы в радианы. RAND = СЛЧИС ## Возвращает случайное число в интервале от 0 до 1. RANDBETWEEN = СЛУЧМЕЖДУ ## Возвращает случайное число в интервале между двумя заданными числами. ROMAN = РИМСКОЕ ## Преобразует арабские цифры в римские в виде текста. ROUND = ОКРУГЛ ## Округляет число до указанного количества десятичных разрядов. ROUNDDOWN = ОКРУГЛВНИЗ ## Округляет число до ближайшего меньшего по модулю значения. ROUNDUP = ОКРУГЛВВЕРХ ## Округляет число до ближайшего большего по модулю значения. SERIESSUM = РЯД.СУММ ## Возвращает сумму степенного ряда, вычисленную по формуле. SIGN = ЗНАК ## Возвращает знак числа. SIN = SIN ## Возвращает синус заданного угла. SINH = SINH ## Возвращает гиперболический синус числа. SQRT = КОРЕНЬ ## Возвращает положительное значение квадратного корня. SQRTPI = КОРЕНЬПИ ## Возвращает квадратный корень из значения выражения (число * ПИ). SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ ## Возвращает промежуточный итог в списке или базе данных. SUM = СУММ ## Суммирует аргументы. SUMIF = СУММЕСЛИ ## Суммирует ячейки, удовлетворяющие заданному условию. SUMIFS = СУММЕСЛИМН ## Суммирует диапазон ячеек, удовлетворяющих нескольким условиям. SUMPRODUCT = СУММПРОИЗВ ## Возвращает сумму произведений соответствующих элементов массивов. SUMSQ = СУММКВ ## Возвращает сумму квадратов аргументов. SUMX2MY2 = СУММРАЗНКВ ## Возвращает сумму разностей квадратов соответствующих значений в двух массивах. SUMX2PY2 = СУММСУММКВ ## Возвращает сумму сумм квадратов соответствующих элементов двух массивов. SUMXMY2 = СУММКВРАЗН ## Возвращает сумму квадратов разностей соответствующих значений в двух массивах. TAN = TAN ## Возвращает тангенс числа. TANH = TANH ## Возвращает гиперболический тангенс числа. TRUNC = ОТБР ## Отбрасывает дробную часть числа. ## ## Statistical functions Статистические функции ## AVEDEV = СРОТКЛ ## Возвращает среднее арифметическое абсолютных значений отклонений точек данных от среднего. AVERAGE = СРЗНАЧ ## Возвращает среднее арифметическое аргументов. AVERAGEA = СРЗНАЧА ## Возвращает среднее арифметическое аргументов, включая числа, текст и логические значения. AVERAGEIF = СРЗНАЧЕСЛИ ## Возвращает среднее значение (среднее арифметическое) всех ячеек в диапазоне, которые удовлетворяют данному условию. AVERAGEIFS = СРЗНАЧЕСЛИМН ## Возвращает среднее значение (среднее арифметическое) всех ячеек, которые удовлетворяют нескольким условиям. BETADIST = БЕТАРАСП ## Возвращает интегральную функцию бета-распределения. BETAINV = БЕТАОБР ## Возвращает обратную интегральную функцию указанного бета-распределения. BINOMDIST = БИНОМРАСП ## Возвращает отдельное значение биномиального распределения. CHIDIST = ХИ2РАСП ## Возвращает одностороннюю вероятность распределения хи-квадрат. CHIINV = ХИ2ОБР ## Возвращает обратное значение односторонней вероятности распределения хи-квадрат. CHITEST = ХИ2ТЕСТ ## Возвращает тест на независимость. CONFIDENCE = ДОВЕРИТ ## Возвращает доверительный интервал для среднего значения по генеральной совокупности. CORREL = КОРРЕЛ ## Возвращает коэффициент корреляции между двумя множествами данных. COUNT = СЧЁТ ## Подсчитывает количество чисел в списке аргументов. COUNTA = СЧЁТЗ ## Подсчитывает количество значений в списке аргументов. COUNTBLANK = СЧИТАТЬПУСТОТЫ ## Подсчитывает количество пустых ячеек в диапазоне COUNTIF = СЧЁТЕСЛИ ## Подсчитывает количество ячеек в диапазоне, удовлетворяющих заданному условию COUNTIFS = СЧЁТЕСЛИМН ## Подсчитывает количество ячеек внутри диапазона, удовлетворяющих нескольким условиям. COVAR = КОВАР ## Возвращает ковариацию, среднее произведений парных отклонений CRITBINOM = КРИТБИНОМ ## Возвращает наименьшее значение, для которого интегральное биномиальное распределение меньше или равно заданному критерию. DEVSQ = КВАДРОТКЛ ## Возвращает сумму квадратов отклонений. EXPONDIST = ЭКСПРАСП ## Возвращает экспоненциальное распределение. FDIST = FРАСП ## Возвращает F-распределение вероятности. FINV = FРАСПОБР ## Возвращает обратное значение для F-распределения вероятности. FISHER = ФИШЕР ## Возвращает преобразование Фишера. FISHERINV = ФИШЕРОБР ## Возвращает обратное преобразование Фишера. FORECAST = ПРЕДСКАЗ ## Возвращает значение линейного тренда. FREQUENCY = ЧАСТОТА ## Возвращает распределение частот в виде вертикального массива. FTEST = ФТЕСТ ## Возвращает результат F-теста. GAMMADIST = ГАММАРАСП ## Возвращает гамма-распределение. GAMMAINV = ГАММАОБР ## Возвращает обратное гамма-распределение. GAMMALN = ГАММАНЛОГ ## Возвращает натуральный логарифм гамма функции, Γ(x). GEOMEAN = СРГЕОМ ## Возвращает среднее геометрическое. GROWTH = РОСТ ## Возвращает значения в соответствии с экспоненциальным трендом. HARMEAN = СРГАРМ ## Возвращает среднее гармоническое. HYPGEOMDIST = ГИПЕРГЕОМЕТ ## Возвращает гипергеометрическое распределение. INTERCEPT = ОТРЕЗОК ## Возвращает отрезок, отсекаемый на оси линией линейной регрессии. KURT = ЭКСЦЕСС ## Возвращает эксцесс множества данных. LARGE = НАИБОЛЬШИЙ ## Возвращает k-ое наибольшее значение в множестве данных. LINEST = ЛИНЕЙН ## Возвращает параметры линейного тренда. LOGEST = ЛГРФПРИБЛ ## Возвращает параметры экспоненциального тренда. LOGINV = ЛОГНОРМОБР ## Возвращает обратное логарифмическое нормальное распределение. LOGNORMDIST = ЛОГНОРМРАСП ## Возвращает интегральное логарифмическое нормальное распределение. MAX = МАКС ## Возвращает наибольшее значение в списке аргументов. MAXA = МАКСА ## Возвращает наибольшее значение в списке аргументов, включая числа, текст и логические значения. MEDIAN = МЕДИАНА ## Возвращает медиану заданных чисел. MIN = МИН ## Возвращает наименьшее значение в списке аргументов. MINA = МИНА ## Возвращает наименьшее значение в списке аргументов, включая числа, текст и логические значения. MODE = МОДА ## Возвращает значение моды множества данных. NEGBINOMDIST = ОТРБИНОМРАСП ## Возвращает отрицательное биномиальное распределение. NORMDIST = НОРМРАСП ## Возвращает нормальную функцию распределения. NORMINV = НОРМОБР ## Возвращает обратное нормальное распределение. NORMSDIST = НОРМСТРАСП ## Возвращает стандартное нормальное интегральное распределение. NORMSINV = НОРМСТОБР ## Возвращает обратное значение стандартного нормального распределения. PEARSON = ПИРСОН ## Возвращает коэффициент корреляции Пирсона. PERCENTILE = ПЕРСЕНТИЛЬ ## Возвращает k-ую персентиль для значений диапазона. PERCENTRANK = ПРОЦЕНТРАНГ ## Возвращает процентную норму значения в множестве данных. PERMUT = ПЕРЕСТ ## Возвращает количество перестановок для заданного числа объектов. POISSON = ПУАССОН ## Возвращает распределение Пуассона. PROB = ВЕРОЯТНОСТЬ ## Возвращает вероятность того, что значение из диапазона находится внутри заданных пределов. QUARTILE = КВАРТИЛЬ ## Возвращает квартиль множества данных. RANK = РАНГ ## Возвращает ранг числа в списке чисел. RSQ = КВПИРСОН ## Возвращает квадрат коэффициента корреляции Пирсона. SKEW = СКОС ## Возвращает асимметрию распределения. SLOPE = НАКЛОН ## Возвращает наклон линии линейной регрессии. SMALL = НАИМЕНЬШИЙ ## Возвращает k-ое наименьшее значение в множестве данных. STANDARDIZE = НОРМАЛИЗАЦИЯ ## Возвращает нормализованное значение. STDEV = СТАНДОТКЛОН ## Оценивает стандартное отклонение по выборке. STDEVA = СТАНДОТКЛОНА ## Оценивает стандартное отклонение по выборке, включая числа, текст и логические значения. STDEVP = СТАНДОТКЛОНП ## Вычисляет стандартное отклонение по генеральной совокупности. STDEVPA = СТАНДОТКЛОНПА ## Вычисляет стандартное отклонение по генеральной совокупности, включая числа, текст и логические значения. STEYX = СТОШYX ## Возвращает стандартную ошибку предсказанных значений y для каждого значения x в регрессии. TDIST = СТЬЮДРАСП ## Возвращает t-распределение Стьюдента. TINV = СТЬЮДРАСПОБР ## Возвращает обратное t-распределение Стьюдента. TREND = ТЕНДЕНЦИЯ ## Возвращает значения в соответствии с линейным трендом. TRIMMEAN = УРЕЗСРЕДНЕЕ ## Возвращает среднее внутренности множества данных. TTEST = ТТЕСТ ## Возвращает вероятность, соответствующую критерию Стьюдента. VAR = ДИСП ## Оценивает дисперсию по выборке. VARA = ДИСПА ## Оценивает дисперсию по выборке, включая числа, текст и логические значения. VARP = ДИСПР ## Вычисляет дисперсию для генеральной совокупности. VARPA = ДИСПРА ## Вычисляет дисперсию для генеральной совокупности, включая числа, текст и логические значения. WEIBULL = ВЕЙБУЛЛ ## Возвращает распределение Вейбулла. ZTEST = ZТЕСТ ## Возвращает двустороннее P-значение z-теста. ## ## Text functions Текстовые функции ## ASC = ASC ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полноширинные (двухбайтовые) знаки в полуширинные (однобайтовые). BAHTTEXT = БАТТЕКСТ ## Преобразует число в текст, используя денежный формат ß (БАТ). CHAR = СИМВОЛ ## Возвращает знак с заданным кодом. CLEAN = ПЕЧСИМВ ## Удаляет все непечатаемые знаки из текста. CODE = КОДСИМВ ## Возвращает числовой код первого знака в текстовой строке. CONCATENATE = СЦЕПИТЬ ## Объединяет несколько текстовых элементов в один. DOLLAR = РУБЛЬ ## Преобразует число в текст, используя денежный формат. EXACT = СОВПАД ## Проверяет идентичность двух текстовых значений. FIND = НАЙТИ ## Ищет вхождения одного текстового значения в другом (с учетом регистра). FINDB = НАЙТИБ ## Ищет вхождения одного текстового значения в другом (с учетом регистра). FIXED = ФИКСИРОВАННЫЙ ## Форматирует число и преобразует его в текст с заданным числом десятичных знаков. JIS = JIS ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полуширинные (однобайтовые) знаки в текстовой строке в полноширинные (двухбайтовые). LEFT = ЛЕВСИМВ ## Возвращает крайние слева знаки текстового значения. LEFTB = ЛЕВБ ## Возвращает крайние слева знаки текстового значения. LEN = ДЛСТР ## Возвращает количество знаков в текстовой строке. LENB = ДЛИНБ ## Возвращает количество знаков в текстовой строке. LOWER = СТРОЧН ## Преобразует все буквы текста в строчные. MID = ПСТР ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции. MIDB = ПСТРБ ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции. PHONETIC = PHONETIC ## Извлекает фонетические (фуригана) знаки из текстовой строки. PROPER = ПРОПНАЧ ## Преобразует первую букву в каждом слове текста в прописную. REPLACE = ЗАМЕНИТЬ ## Заменяет знаки в тексте. REPLACEB = ЗАМЕНИТЬБ ## Заменяет знаки в тексте. REPT = ПОВТОР ## Повторяет текст заданное число раз. RIGHT = ПРАВСИМВ ## Возвращает крайние справа знаки текстовой строки. RIGHTB = ПРАВБ ## Возвращает крайние справа знаки текстовой строки. SEARCH = ПОИСК ## Ищет вхождения одного текстового значения в другом (без учета регистра). SEARCHB = ПОИСКБ ## Ищет вхождения одного текстового значения в другом (без учета регистра). SUBSTITUTE = ПОДСТАВИТЬ ## Заменяет в текстовой строке старый текст новым. T = Т ## Преобразует аргументы в текст. TEXT = ТЕКСТ ## Форматирует число и преобразует его в текст. TRIM = СЖПРОБЕЛЫ ## Удаляет из текста пробелы. UPPER = ПРОПИСН ## Преобразует все буквы текста в прописные. VALUE = ЗНАЧЕН ## Преобразует текстовый аргумент в число. phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/bg/config 0000644 00000000430 15002227416 0020542 0 ustar 00 ## ## PhpSpreadsheet ## ## ## ArgumentSeparator = ; ## ## (For future use) ## currencySymbol = лв ## ## Excel Error Codes (For future use) ## NULL = #ПРАЗНО! DIV0 = #ДЕЛ/0! VALUE = #СТОЙНОСТ! REF = #РЕФ! NAME = #ИМЕ? NUM = #ЧИСЛО! NA = #Н/Д phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/functions 0000644 00000024714 15002227416 0021337 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Español (Spanish) ## ############################################################ ## ## Funciones de cubo (Cube Functions) ## CUBEKPIMEMBER = MIEMBROKPICUBO CUBEMEMBER = MIEMBROCUBO CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO CUBERANKEDMEMBER = MIEMBRORANGOCUBO CUBESET = CONJUNTOCUBO CUBESETCOUNT = RECUENTOCONJUNTOCUBO CUBEVALUE = VALORCUBO ## ## Funciones de base de datos (Database Functions) ## DAVERAGE = BDPROMEDIO DCOUNT = BDCONTAR DCOUNTA = BDCONTARA DGET = BDEXTRAER DMAX = BDMAX DMIN = BDMIN DPRODUCT = BDPRODUCTO DSTDEV = BDDESVEST DSTDEVP = BDDESVESTP DSUM = BDSUMA DVAR = BDVAR DVARP = BDVARP ## ## Funciones de fecha y hora (Date & Time Functions) ## DATE = FECHA DATEDIF = SIFECHA DATESTRING = CADENA.FECHA DATEVALUE = FECHANUMERO DAY = DIA DAYS = DIAS DAYS360 = DIAS360 EDATE = FECHA.MES EOMONTH = FIN.MES HOUR = HORA ISOWEEKNUM = ISO.NUM.DE.SEMANA MINUTE = MINUTO MONTH = MES NETWORKDAYS = DIAS.LAB NETWORKDAYS.INTL = DIAS.LAB.INTL NOW = AHORA SECOND = SEGUNDO THAIDAYOFWEEK = DIASEMTAI THAIMONTHOFYEAR = MESAÑOTAI THAIYEAR = AÑOTAI TIME = NSHORA TIMEVALUE = HORANUMERO TODAY = HOY WEEKDAY = DIASEM WEEKNUM = NUM.DE.SEMANA WORKDAY = DIA.LAB WORKDAY.INTL = DIA.LAB.INTL YEAR = AÑO YEARFRAC = FRAC.AÑO ## ## Funciones de ingeniería (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN.A.DEC BIN2HEX = BIN.A.HEX BIN2OCT = BIN.A.OCT BITAND = BIT.Y BITLSHIFT = BIT.DESPLIZQDA BITOR = BIT.O BITRSHIFT = BIT.DESPLDCHA BITXOR = BIT.XO COMPLEX = COMPLEJO CONVERT = CONVERTIR DEC2BIN = DEC.A.BIN DEC2HEX = DEC.A.HEX DEC2OCT = DEC.A.OCT DELTA = DELTA ERF = FUN.ERROR ERF.PRECISE = FUN.ERROR.EXACTO ERFC = FUN.ERROR.COMPL ERFC.PRECISE = FUN.ERROR.COMPL.EXACTO GESTEP = MAYOR.O.IGUAL HEX2BIN = HEX.A.BIN HEX2DEC = HEX.A.DEC HEX2OCT = HEX.A.OCT IMABS = IM.ABS IMAGINARY = IMAGINARIO IMARGUMENT = IM.ANGULO IMCONJUGATE = IM.CONJUGADA IMCOS = IM.COS IMCOSH = IM.COSH IMCOT = IM.COT IMCSC = IM.CSC IMCSCH = IM.CSCH IMDIV = IM.DIV IMEXP = IM.EXP IMLN = IM.LN IMLOG10 = IM.LOG10 IMLOG2 = IM.LOG2 IMPOWER = IM.POT IMPRODUCT = IM.PRODUCT IMREAL = IM.REAL IMSEC = IM.SEC IMSECH = IM.SECH IMSIN = IM.SENO IMSINH = IM.SENOH IMSQRT = IM.RAIZ2 IMSUB = IM.SUSTR IMSUM = IM.SUM IMTAN = IM.TAN OCT2BIN = OCT.A.BIN OCT2DEC = OCT.A.DEC OCT2HEX = OCT.A.HEX ## ## Funciones financieras (Financial Functions) ## ACCRINT = INT.ACUM ACCRINTM = INT.ACUM.V AMORDEGRC = AMORTIZ.PROGRE AMORLINC = AMORTIZ.LIN COUPDAYBS = CUPON.DIAS.L1 COUPDAYS = CUPON.DIAS COUPDAYSNC = CUPON.DIAS.L2 COUPNCD = CUPON.FECHA.L2 COUPNUM = CUPON.NUM COUPPCD = CUPON.FECHA.L1 CUMIPMT = PAGO.INT.ENTRE CUMPRINC = PAGO.PRINC.ENTRE DB = DB DDB = DDB DISC = TASA.DESC DOLLARDE = MONEDA.DEC DOLLARFR = MONEDA.FRAC DURATION = DURACION EFFECT = INT.EFECTIVO FV = VF FVSCHEDULE = VF.PLAN INTRATE = TASA.INT IPMT = PAGOINT IRR = TIR ISPMT = INT.PAGO.DIR MDURATION = DURACION.MODIF MIRR = TIRM NOMINAL = TASA.NOMINAL NPER = NPER NPV = VNA ODDFPRICE = PRECIO.PER.IRREGULAR.1 ODDFYIELD = RENDTO.PER.IRREGULAR.1 ODDLPRICE = PRECIO.PER.IRREGULAR.2 ODDLYIELD = RENDTO.PER.IRREGULAR.2 PDURATION = P.DURACION PMT = PAGO PPMT = PAGOPRIN PRICE = PRECIO PRICEDISC = PRECIO.DESCUENTO PRICEMAT = PRECIO.VENCIMIENTO PV = VA RATE = TASA RECEIVED = CANTIDAD.RECIBIDA RRI = RRI SLN = SLN SYD = SYD TBILLEQ = LETRA.DE.TEST.EQV.A.BONO TBILLPRICE = LETRA.DE.TES.PRECIO TBILLYIELD = LETRA.DE.TES.RENDTO VDB = DVS XIRR = TIR.NO.PER XNPV = VNA.NO.PER YIELD = RENDTO YIELDDISC = RENDTO.DESC YIELDMAT = RENDTO.VENCTO ## ## Funciones de información (Information Functions) ## CELL = CELDA ERROR.TYPE = TIPO.DE.ERROR INFO = INFO ISBLANK = ESBLANCO ISERR = ESERR ISERROR = ESERROR ISEVEN = ES.PAR ISFORMULA = ESFORMULA ISLOGICAL = ESLOGICO ISNA = ESNOD ISNONTEXT = ESNOTEXTO ISNUMBER = ESNUMERO ISODD = ES.IMPAR ISREF = ESREF ISTEXT = ESTEXTO N = N NA = NOD SHEET = HOJA SHEETS = HOJAS TYPE = TIPO ## ## Funciones lógicas (Logical Functions) ## AND = Y FALSE = FALSO IF = SI IFERROR = SI.ERROR IFNA = SI.ND IFS = SI.CONJUNTO NOT = NO OR = O SWITCH = CAMBIAR TRUE = VERDADERO XOR = XO ## ## Funciones de búsqueda y referencia (Lookup & Reference Functions) ## ADDRESS = DIRECCION AREAS = AREAS CHOOSE = ELEGIR COLUMN = COLUMNA COLUMNS = COLUMNAS FORMULATEXT = FORMULATEXTO GETPIVOTDATA = IMPORTARDATOSDINAMICOS HLOOKUP = BUSCARH HYPERLINK = HIPERVINCULO INDEX = INDICE INDIRECT = INDIRECTO LOOKUP = BUSCAR MATCH = COINCIDIR OFFSET = DESREF ROW = FILA ROWS = FILAS RTD = RDTR TRANSPOSE = TRANSPONER VLOOKUP = BUSCARV *RC = FC ## ## Funciones matemáticas y trigonométricas (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGREGAR ARABIC = NUMERO.ARABE ASIN = ASENO ASINH = ASENOH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = BASE CEILING.MATH = MULTIPLO.SUPERIOR.MAT CEILING.PRECISE = MULTIPLO.SUPERIOR.EXACTO COMBIN = COMBINAT COMBINA = COMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = CONV.DECIMAL DEGREES = GRADOS ECMA.CEILING = MULTIPLO.SUPERIOR.ECMA EVEN = REDONDEA.PAR EXP = EXP FACT = FACT FACTDOUBLE = FACT.DOBLE FLOOR.MATH = MULTIPLO.INFERIOR.MAT FLOOR.PRECISE = MULTIPLO.INFERIOR.EXACTO GCD = M.C.D INT = ENTERO ISO.CEILING = MULTIPLO.SUPERIOR.ISO LCM = M.C.M LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = MINVERSA MMULT = MMULT MOD = RESIDUO MROUND = REDOND.MULT MULTINOMIAL = MULTINOMIAL MUNIT = M.UNIDAD ODD = REDONDEA.IMPAR PI = PI POWER = POTENCIA PRODUCT = PRODUCTO QUOTIENT = COCIENTE RADIANS = RADIANES RAND = ALEATORIO RANDBETWEEN = ALEATORIO.ENTRE ROMAN = NUMERO.ROMANO ROUND = REDONDEAR ROUNDBAHTDOWN = REDONDEAR.BAHT.MAS ROUNDBAHTUP = REDONDEAR.BAHT.MENOS ROUNDDOWN = REDONDEAR.MENOS ROUNDUP = REDONDEAR.MAS SEC = SEC SECH = SECH SERIESSUM = SUMA.SERIES SIGN = SIGNO SIN = SENO SINH = SENOH SQRT = RAIZ SQRTPI = RAIZ2PI SUBTOTAL = SUBTOTALES SUM = SUMA SUMIF = SUMAR.SI SUMIFS = SUMAR.SI.CONJUNTO SUMPRODUCT = SUMAPRODUCTO SUMSQ = SUMA.CUADRADOS SUMX2MY2 = SUMAX2MENOSY2 SUMX2PY2 = SUMAX2MASY2 SUMXMY2 = SUMAXMENOSY2 TAN = TAN TANH = TANH TRUNC = TRUNCAR ## ## Funciones estadísticas (Statistical Functions) ## AVEDEV = DESVPROM AVERAGE = PROMEDIO AVERAGEA = PROMEDIOA AVERAGEIF = PROMEDIO.SI AVERAGEIFS = PROMEDIO.SI.CONJUNTO BETA.DIST = DISTR.BETA.N BETA.INV = INV.BETA.N BINOM.DIST = DISTR.BINOM.N BINOM.DIST.RANGE = DISTR.BINOM.SERIE BINOM.INV = INV.BINOM CHISQ.DIST = DISTR.CHICUAD CHISQ.DIST.RT = DISTR.CHICUAD.CD CHISQ.INV = INV.CHICUAD CHISQ.INV.RT = INV.CHICUAD.CD CHISQ.TEST = PRUEBA.CHICUAD CONFIDENCE.NORM = INTERVALO.CONFIANZA.NORM CONFIDENCE.T = INTERVALO.CONFIANZA.T CORREL = COEF.DE.CORREL COUNT = CONTAR COUNTA = CONTARA COUNTBLANK = CONTAR.BLANCO COUNTIF = CONTAR.SI COUNTIFS = CONTAR.SI.CONJUNTO COVARIANCE.P = COVARIANCE.P COVARIANCE.S = COVARIANZA.M DEVSQ = DESVIA2 EXPON.DIST = DISTR.EXP.N F.DIST = DISTR.F.N F.DIST.RT = DISTR.F.CD F.INV = INV.F F.INV.RT = INV.F.CD F.TEST = PRUEBA.F.N FISHER = FISHER FISHERINV = PRUEBA.FISHER.INV FORECAST.ETS = PRONOSTICO.ETS FORECAST.ETS.CONFINT = PRONOSTICO.ETS.CONFINT FORECAST.ETS.SEASONALITY = PRONOSTICO.ETS.ESTACIONALIDAD FORECAST.ETS.STAT = PRONOSTICO.ETS.STAT FORECAST.LINEAR = PRONOSTICO.LINEAL FREQUENCY = FRECUENCIA GAMMA = GAMMA GAMMA.DIST = DISTR.GAMMA.N GAMMA.INV = INV.GAMMA GAMMALN = GAMMA.LN GAMMALN.PRECISE = GAMMA.LN.EXACTO GAUSS = GAUSS GEOMEAN = MEDIA.GEOM GROWTH = CRECIMIENTO HARMEAN = MEDIA.ARMO HYPGEOM.DIST = DISTR.HIPERGEOM.N INTERCEPT = INTERSECCION.EJE KURT = CURTOSIS LARGE = K.ESIMO.MAYOR LINEST = ESTIMACION.LINEAL LOGEST = ESTIMACION.LOGARITMICA LOGNORM.DIST = DISTR.LOGNORM LOGNORM.INV = INV.LOGNORM MAX = MAX MAXA = MAXA MAXIFS = MAX.SI.CONJUNTO MEDIAN = MEDIANA MIN = MIN MINA = MINA MINIFS = MIN.SI.CONJUNTO MODE.MULT = MODA.VARIOS MODE.SNGL = MODA.UNO NEGBINOM.DIST = NEGBINOM.DIST NORM.DIST = DISTR.NORM.N NORM.INV = INV.NORM NORM.S.DIST = DISTR.NORM.ESTAND.N NORM.S.INV = INV.NORM.ESTAND PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = RANGO.PERCENTIL.EXC PERCENTRANK.INC = RANGO.PERCENTIL.INC PERMUT = PERMUTACIONES PERMUTATIONA = PERMUTACIONES.A PHI = FI POISSON.DIST = POISSON.DIST PROB = PROBABILIDAD QUARTILE.EXC = CUARTIL.EXC QUARTILE.INC = CUARTIL.INC RANK.AVG = JERARQUIA.MEDIA RANK.EQ = JERARQUIA.EQV RSQ = COEFICIENTE.R2 SKEW = COEFICIENTE.ASIMETRIA SKEW.P = COEFICIENTE.ASIMETRIA.P SLOPE = PENDIENTE SMALL = K.ESIMO.MENOR STANDARDIZE = NORMALIZACION STDEV.P = DESVEST.P STDEV.S = DESVEST.M STDEVA = DESVESTA STDEVPA = DESVESTPA STEYX = ERROR.TIPICO.XY T.DIST = DISTR.T.N T.DIST.2T = DISTR.T.2C T.DIST.RT = DISTR.T.CD T.INV = INV.T T.INV.2T = INV.T.2C T.TEST = PRUEBA.T.N TREND = TENDENCIA TRIMMEAN = MEDIA.ACOTADA VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = DISTR.WEIBULL Z.TEST = PRUEBA.Z.N ## ## Funciones de texto (Text Functions) ## BAHTTEXT = TEXTOBAHT CHAR = CARACTER CLEAN = LIMPIAR CODE = CODIGO CONCAT = CONCAT DOLLAR = MONEDA EXACT = IGUAL FIND = ENCONTRAR FIXED = DECIMAL ISTHAIDIGIT = ESDIGITOTAI LEFT = IZQUIERDA LEN = LARGO LOWER = MINUSC MID = EXTRAE NUMBERSTRING = CADENA.NUMERO NUMBERVALUE = VALOR.NUMERO PHONETIC = FONETICO PROPER = NOMPROPIO REPLACE = REEMPLAZAR REPT = REPETIR RIGHT = DERECHA SEARCH = HALLAR SUBSTITUTE = SUSTITUIR T = T TEXT = TEXTO TEXTJOIN = UNIRCADENAS THAIDIGIT = DIGITOTAI THAINUMSOUND = SONNUMTAI THAINUMSTRING = CADENANUMTAI THAISTRINGLENGTH = LONGCADENATAI TRIM = ESPACIOS UNICHAR = UNICAR UNICODE = UNICODE UPPER = MAYUSC VALUE = VALOR ## ## Funciones web (Web Functions) ## ENCODEURL = URLCODIF FILTERXML = XMLFILTRO WEBSERVICE = SERVICIOWEB ## ## Funciones de compatibilidad (Compatibility Functions) ## BETADIST = DISTR.BETA BETAINV = DISTR.BETA.INV BINOMDIST = DISTR.BINOM CEILING = MULTIPLO.SUPERIOR CHIDIST = DISTR.CHI CHIINV = PRUEBA.CHI.INV CHITEST = PRUEBA.CHI CONCATENATE = CONCATENAR CONFIDENCE = INTERVALO.CONFIANZA COVAR = COVAR CRITBINOM = BINOM.CRIT EXPONDIST = DISTR.EXP FDIST = DISTR.F FINV = DISTR.F.INV FLOOR = MULTIPLO.INFERIOR FORECAST = PRONOSTICO FTEST = PRUEBA.F GAMMADIST = DISTR.GAMMA GAMMAINV = DISTR.GAMMA.INV HYPGEOMDIST = DISTR.HIPERGEOM LOGINV = DISTR.LOG.INV LOGNORMDIST = DISTR.LOG.NORM MODE = MODA NEGBINOMDIST = NEGBINOMDIST NORMDIST = DISTR.NORM NORMINV = DISTR.NORM.INV NORMSDIST = DISTR.NORM.ESTAND NORMSINV = DISTR.NORM.ESTAND.INV PERCENTILE = PERCENTIL PERCENTRANK = RANGO.PERCENTIL POISSON = POISSON QUARTILE = CUARTIL RANK = JERARQUIA STDEV = DESVEST STDEVP = DESVESTP TDIST = DISTR.T TINV = DISTR.T.INV TTEST = PRUEBA.T VAR = VAR VARP = VARP WEIBULL = DIST.WEIBULL ZTEST = PRUEBA.Z phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/config 0000644 00000000516 15002227416 0020566 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Español (Spanish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #¡NULO! DIV0 = #¡DIV/0! VALUE = #¡VALOR! REF = #¡REF! NAME = #¿NOMBRE? NUM = #¡NUM! NA phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/functions 0000644 00000023777 15002227416 0021363 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Português (Portuguese) ## ############################################################ ## ## Funções de cubo (Cube Functions) ## CUBEKPIMEMBER = MEMBROKPICUBO CUBEMEMBER = MEMBROCUBO CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO CUBESET = CONJUNTOCUBO CUBESETCOUNT = CONTARCONJUNTOCUBO CUBEVALUE = VALORCUBO ## ## Funções de base de dados (Database Functions) ## DAVERAGE = BDMÉDIA DCOUNT = BDCONTAR DCOUNTA = BDCONTAR.VAL DGET = BDOBTER DMAX = BDMÁX DMIN = BDMÍN DPRODUCT = BDMULTIPL DSTDEV = BDDESVPAD DSTDEVP = BDDESVPADP DSUM = BDSOMA DVAR = BDVAR DVARP = BDVARP ## ## Funções de data e hora (Date & Time Functions) ## DATE = DATA DATEDIF = DATADIF DATESTRING = DATA.CADEIA DATEVALUE = DATA.VALOR DAY = DIA DAYS = DIAS DAYS360 = DIAS360 EDATE = DATAM EOMONTH = FIMMÊS HOUR = HORA ISOWEEKNUM = NUMSEMANAISO MINUTE = MINUTO MONTH = MÊS NETWORKDAYS = DIATRABALHOTOTAL NETWORKDAYS.INTL = DIATRABALHOTOTAL.INTL NOW = AGORA SECOND = SEGUNDO THAIDAYOFWEEK = DIA.DA.SEMANA.TAILANDÊS THAIMONTHOFYEAR = MÊS.DO.ANO.TAILANDÊS THAIYEAR = ANO.TAILANDÊS TIME = TEMPO TIMEVALUE = VALOR.TEMPO TODAY = HOJE WEEKDAY = DIA.SEMANA WEEKNUM = NÚMSEMANA WORKDAY = DIATRABALHO WORKDAY.INTL = DIATRABALHO.INTL YEAR = ANO YEARFRAC = FRAÇÃOANO ## ## Funções de engenharia (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BINADEC BIN2HEX = BINAHEX BIN2OCT = BINAOCT BITAND = BIT.E BITLSHIFT = BITDESL.ESQ BITOR = BIT.OU BITRSHIFT = BITDESL.DIR BITXOR = BIT.XOU COMPLEX = COMPLEXO CONVERT = CONVERTER DEC2BIN = DECABIN DEC2HEX = DECAHEX DEC2OCT = DECAOCT DELTA = DELTA ERF = FUNCERRO ERF.PRECISE = FUNCERRO.PRECISO ERFC = FUNCERROCOMPL ERFC.PRECISE = FUNCERROCOMPL.PRECISO GESTEP = DEGRAU HEX2BIN = HEXABIN HEX2DEC = HEXADEC HEX2OCT = HEXAOCT IMABS = IMABS IMAGINARY = IMAGINÁRIO IMARGUMENT = IMARG IMCONJUGATE = IMCONJ IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCSC IMCSCH = IMCSCH IMDIV = IMDIV IMEXP = IMEXP IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMPOT IMPRODUCT = IMPROD IMREAL = IMREAL IMSEC = IMSEC IMSECH = IMSECH IMSIN = IMSENO IMSINH = IMSENOH IMSQRT = IMRAIZ IMSUB = IMSUBTR IMSUM = IMSOMA IMTAN = IMTAN OCT2BIN = OCTABIN OCT2DEC = OCTADEC OCT2HEX = OCTAHEX ## ## Funções financeiras (Financial Functions) ## ACCRINT = JUROSACUM ACCRINTM = JUROSACUMV AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = CUPDIASINLIQ COUPDAYS = CUPDIAS COUPDAYSNC = CUPDIASPRÓX COUPNCD = CUPDATAPRÓX COUPNUM = CUPNÚM COUPPCD = CUPDATAANT CUMIPMT = PGTOJURACUM CUMPRINC = PGTOCAPACUM DB = BD DDB = BDD DISC = DESC DOLLARDE = MOEDADEC DOLLARFR = MOEDAFRA DURATION = DURAÇÃO EFFECT = EFETIVA FV = VF FVSCHEDULE = VFPLANO INTRATE = TAXAJUROS IPMT = IPGTO IRR = TIR ISPMT = É.PGTO MDURATION = MDURAÇÃO MIRR = MTIR NOMINAL = NOMINAL NPER = NPER NPV = VAL ODDFPRICE = PREÇOPRIMINC ODDFYIELD = LUCROPRIMINC ODDLPRICE = PREÇOÚLTINC ODDLYIELD = LUCROÚLTINC PDURATION = PDURAÇÃO PMT = PGTO PPMT = PPGTO PRICE = PREÇO PRICEDISC = PREÇODESC PRICEMAT = PREÇOVENC PV = VA RATE = TAXA RECEIVED = RECEBER RRI = DEVOLVERTAXAJUROS SLN = AMORT SYD = AMORTD TBILLEQ = OTN TBILLPRICE = OTNVALOR TBILLYIELD = OTNLUCRO VDB = BDV XIRR = XTIR XNPV = XVAL YIELD = LUCRO YIELDDISC = LUCRODESC YIELDMAT = LUCROVENC ## ## Funções de informação (Information Functions) ## CELL = CÉL ERROR.TYPE = TIPO.ERRO INFO = INFORMAÇÃO ISBLANK = É.CÉL.VAZIA ISERR = É.ERROS ISERROR = É.ERRO ISEVEN = ÉPAR ISFORMULA = É.FORMULA ISLOGICAL = É.LÓGICO ISNA = É.NÃO.DISP ISNONTEXT = É.NÃO.TEXTO ISNUMBER = É.NÚM ISODD = ÉÍMPAR ISREF = É.REF ISTEXT = É.TEXTO N = N NA = NÃO.DISP SHEET = FOLHA SHEETS = FOLHAS TYPE = TIPO ## ## Funções lógicas (Logical Functions) ## AND = E FALSE = FALSO IF = SE IFERROR = SE.ERRO IFNA = SEND IFS = SE.S NOT = NÃO OR = OU SWITCH = PARÂMETRO TRUE = VERDADEIRO XOR = XOU ## ## Funções de pesquisa e referência (Lookup & Reference Functions) ## ADDRESS = ENDEREÇO AREAS = ÁREAS CHOOSE = SELECIONAR COLUMN = COL COLUMNS = COLS FORMULATEXT = FÓRMULA.TEXTO GETPIVOTDATA = OBTERDADOSDIN HLOOKUP = PROCH HYPERLINK = HIPERLIGAÇÃO INDEX = ÍNDICE INDIRECT = INDIRETO LOOKUP = PROC MATCH = CORRESP OFFSET = DESLOCAMENTO ROW = LIN ROWS = LINS RTD = RTD TRANSPOSE = TRANSPOR VLOOKUP = PROCV *RC = LC ## ## Funções matemáticas e trigonométricas (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGREGAR ARABIC = ÁRABE ASIN = ASEN ASINH = ASENH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = BASE CEILING.MATH = ARRED.EXCESSO.MAT CEILING.PRECISE = ARRED.EXCESSO.PRECISO COMBIN = COMBIN COMBINA = COMBIN.R COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMAL DEGREES = GRAUS ECMA.CEILING = ARRED.EXCESSO.ECMA EVEN = PAR EXP = EXP FACT = FATORIAL FACTDOUBLE = FATDUPLO FLOOR.MATH = ARRED.DEFEITO.MAT FLOOR.PRECISE = ARRED.DEFEITO.PRECISO GCD = MDC INT = INT ISO.CEILING = ARRED.EXCESSO.ISO LCM = MMC LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MATRIZ.DETERM MINVERSE = MATRIZ.INVERSA MMULT = MATRIZ.MULT MOD = RESTO MROUND = MARRED MULTINOMIAL = POLINOMIAL MUNIT = UNIDM ODD = ÍMPAR PI = PI POWER = POTÊNCIA PRODUCT = PRODUTO QUOTIENT = QUOCIENTE RADIANS = RADIANOS RAND = ALEATÓRIO RANDBETWEEN = ALEATÓRIOENTRE ROMAN = ROMANO ROUND = ARRED ROUNDBAHTDOWN = ARREDOND.BAHT.BAIXO ROUNDBAHTUP = ARREDOND.BAHT.CIMA ROUNDDOWN = ARRED.PARA.BAIXO ROUNDUP = ARRED.PARA.CIMA SEC = SEC SECH = SECH SERIESSUM = SOMASÉRIE SIGN = SINAL SIN = SEN SINH = SENH SQRT = RAIZQ SQRTPI = RAIZPI SUBTOTAL = SUBTOTAL SUM = SOMA SUMIF = SOMA.SE SUMIFS = SOMA.SE.S SUMPRODUCT = SOMARPRODUTO SUMSQ = SOMARQUAD SUMX2MY2 = SOMAX2DY2 SUMX2PY2 = SOMAX2SY2 SUMXMY2 = SOMAXMY2 TAN = TAN TANH = TANH TRUNC = TRUNCAR ## ## Funções estatísticas (Statistical Functions) ## AVEDEV = DESV.MÉDIO AVERAGE = MÉDIA AVERAGEA = MÉDIAA AVERAGEIF = MÉDIA.SE AVERAGEIFS = MÉDIA.SE.S BETA.DIST = DIST.BETA BETA.INV = INV.BETA BINOM.DIST = DISTR.BINOM BINOM.DIST.RANGE = DIST.BINOM.INTERVALO BINOM.INV = INV.BINOM CHISQ.DIST = DIST.CHIQ CHISQ.DIST.RT = DIST.CHIQ.DIR CHISQ.INV = INV.CHIQ CHISQ.INV.RT = INV.CHIQ.DIR CHISQ.TEST = TESTE.CHIQ CONFIDENCE.NORM = INT.CONFIANÇA.NORM CONFIDENCE.T = INT.CONFIANÇA.T CORREL = CORREL COUNT = CONTAR COUNTA = CONTAR.VAL COUNTBLANK = CONTAR.VAZIO COUNTIF = CONTAR.SE COUNTIFS = CONTAR.SE.S COVARIANCE.P = COVARIÂNCIA.P COVARIANCE.S = COVARIÂNCIA.S DEVSQ = DESVQ EXPON.DIST = DIST.EXPON F.DIST = DIST.F F.DIST.RT = DIST.F.DIR F.INV = INV.F F.INV.RT = INV.F.DIR F.TEST = TESTE.F FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PREVISÃO.ETS FORECAST.ETS.CONFINT = PREVISÃO.ETS.CONFINT FORECAST.ETS.SEASONALITY = PREVISÃO.ETS.SAZONALIDADE FORECAST.ETS.STAT = PREVISÃO.ETS.ESTATÍSTICA FORECAST.LINEAR = PREVISÃO.LINEAR FREQUENCY = FREQUÊNCIA GAMMA = GAMA GAMMA.DIST = DIST.GAMA GAMMA.INV = INV.GAMA GAMMALN = LNGAMA GAMMALN.PRECISE = LNGAMA.PRECISO GAUSS = GAUSS GEOMEAN = MÉDIA.GEOMÉTRICA GROWTH = CRESCIMENTO HARMEAN = MÉDIA.HARMÓNICA HYPGEOM.DIST = DIST.HIPGEOM INTERCEPT = INTERCETAR KURT = CURT LARGE = MAIOR LINEST = PROJ.LIN LOGEST = PROJ.LOG LOGNORM.DIST = DIST.NORMLOG LOGNORM.INV = INV.NORMALLOG MAX = MÁXIMO MAXA = MÁXIMOA MAXIFS = MÁXIMO.SE.S MEDIAN = MED MIN = MÍNIMO MINA = MÍNIMOA MINIFS = MÍNIMO.SE.S MODE.MULT = MODO.MÚLT MODE.SNGL = MODO.SIMPLES NEGBINOM.DIST = DIST.BINOM.NEG NORM.DIST = DIST.NORMAL NORM.INV = INV.NORMAL NORM.S.DIST = DIST.S.NORM NORM.S.INV = INV.S.NORM PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = ORDEM.PERCENTUAL.EXC PERCENTRANK.INC = ORDEM.PERCENTUAL.INC PERMUT = PERMUTAR PERMUTATIONA = PERMUTAR.R PHI = PHI POISSON.DIST = DIST.POISSON PROB = PROB QUARTILE.EXC = QUARTIL.EXC QUARTILE.INC = QUARTIL.INC RANK.AVG = ORDEM.MÉD RANK.EQ = ORDEM.EQ RSQ = RQUAD SKEW = DISTORÇÃO SKEW.P = DISTORÇÃO.P SLOPE = DECLIVE SMALL = MENOR STANDARDIZE = NORMALIZAR STDEV.P = DESVPAD.P STDEV.S = DESVPAD.S STDEVA = DESVPADA STDEVPA = DESVPADPA STEYX = EPADYX T.DIST = DIST.T T.DIST.2T = DIST.T.2C T.DIST.RT = DIST.T.DIR T.INV = INV.T T.INV.2T = INV.T.2C T.TEST = TESTE.T TREND = TENDÊNCIA TRIMMEAN = MÉDIA.INTERNA VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = DIST.WEIBULL Z.TEST = TESTE.Z ## ## Funções de texto (Text Functions) ## BAHTTEXT = TEXTO.BAHT CHAR = CARÁT CLEAN = LIMPARB CODE = CÓDIGO CONCAT = CONCAT DOLLAR = MOEDA EXACT = EXATO FIND = LOCALIZAR FIXED = FIXA ISTHAIDIGIT = É.DÍGITO.TAILANDÊS LEFT = ESQUERDA LEN = NÚM.CARAT LOWER = MINÚSCULAS MID = SEG.TEXTO NUMBERSTRING = NÚMERO.CADEIA NUMBERVALUE = VALOR.NÚMERO PHONETIC = FONÉTICA PROPER = INICIAL.MAIÚSCULA REPLACE = SUBSTITUIR REPT = REPETIR RIGHT = DIREITA SEARCH = PROCURAR SUBSTITUTE = SUBST T = T TEXT = TEXTO TEXTJOIN = UNIRTEXTO THAIDIGIT = DÍGITO.TAILANDÊS THAINUMSOUND = SOM.NÚM.TAILANDÊS THAINUMSTRING = CADEIA.NÚM.TAILANDÊS THAISTRINGLENGTH = COMP.CADEIA.TAILANDÊS TRIM = COMPACTAR UNICHAR = UNICARÁT UNICODE = UNICODE UPPER = MAIÚSCULAS VALUE = VALOR ## ## Funções da Web (Web Functions) ## ENCODEURL = CODIFICAÇÃOURL FILTERXML = FILTRARXML WEBSERVICE = SERVIÇOWEB ## ## Funções de compatibilidade (Compatibility Functions) ## BETADIST = DISTBETA BETAINV = BETA.ACUM.INV BINOMDIST = DISTRBINOM CEILING = ARRED.EXCESSO CHIDIST = DIST.CHI CHIINV = INV.CHI CHITEST = TESTE.CHI CONCATENATE = CONCATENAR CONFIDENCE = INT.CONFIANÇA COVAR = COVAR CRITBINOM = CRIT.BINOM EXPONDIST = DISTEXPON FDIST = DISTF FINV = INVF FLOOR = ARRED.DEFEITO FORECAST = PREVISÃO FTEST = TESTEF GAMMADIST = DISTGAMA GAMMAINV = INVGAMA HYPGEOMDIST = DIST.HIPERGEOM LOGINV = INVLOG LOGNORMDIST = DIST.NORMALLOG MODE = MODA NEGBINOMDIST = DIST.BIN.NEG NORMDIST = DIST.NORM NORMINV = INV.NORM NORMSDIST = DIST.NORMP NORMSINV = INV.NORMP PERCENTILE = PERCENTIL PERCENTRANK = ORDEM.PERCENTUAL POISSON = POISSON QUARTILE = QUARTIL RANK = ORDEM STDEV = DESVPAD STDEVP = DESVPADP TDIST = DISTT TINV = INVT TTEST = TESTET VAR = VAR VARP = VARP WEIBULL = WEIBULL ZTEST = TESTEZ phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/functions 0000644 00000023147 15002227416 0021755 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Português Brasileiro (Brazilian Portuguese) ## ############################################################ ## ## Funções de cubo (Cube Functions) ## CUBEKPIMEMBER = MEMBROKPICUBO CUBEMEMBER = MEMBROCUBO CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO CUBESET = CONJUNTOCUBO CUBESETCOUNT = CONTAGEMCONJUNTOCUBO CUBEVALUE = VALORCUBO ## ## Funções de banco de dados (Database Functions) ## DAVERAGE = BDMÉDIA DCOUNT = BDCONTAR DCOUNTA = BDCONTARA DGET = BDEXTRAIR DMAX = BDMÁX DMIN = BDMÍN DPRODUCT = BDMULTIPL DSTDEV = BDEST DSTDEVP = BDDESVPA DSUM = BDSOMA DVAR = BDVAREST DVARP = BDVARP ## ## Funções de data e hora (Date & Time Functions) ## DATE = DATA DATEDIF = DATADIF DATESTRING = DATA.SÉRIE DATEVALUE = DATA.VALOR DAY = DIA DAYS = DIAS DAYS360 = DIAS360 EDATE = DATAM EOMONTH = FIMMÊS HOUR = HORA ISOWEEKNUM = NÚMSEMANAISO MINUTE = MINUTO MONTH = MÊS NETWORKDAYS = DIATRABALHOTOTAL NETWORKDAYS.INTL = DIATRABALHOTOTAL.INTL NOW = AGORA SECOND = SEGUNDO TIME = TEMPO TIMEVALUE = VALOR.TEMPO TODAY = HOJE WEEKDAY = DIA.DA.SEMANA WEEKNUM = NÚMSEMANA WORKDAY = DIATRABALHO WORKDAY.INTL = DIATRABALHO.INTL YEAR = ANO YEARFRAC = FRAÇÃOANO ## ## Funções de engenharia (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BINADEC BIN2HEX = BINAHEX BIN2OCT = BINAOCT BITAND = BITAND BITLSHIFT = DESLOCESQBIT BITOR = BITOR BITRSHIFT = DESLOCDIRBIT BITXOR = BITXOR COMPLEX = COMPLEXO CONVERT = CONVERTER DEC2BIN = DECABIN DEC2HEX = DECAHEX DEC2OCT = DECAOCT DELTA = DELTA ERF = FUNERRO ERF.PRECISE = FUNERRO.PRECISO ERFC = FUNERROCOMPL ERFC.PRECISE = FUNERROCOMPL.PRECISO GESTEP = DEGRAU HEX2BIN = HEXABIN HEX2DEC = HEXADEC HEX2OCT = HEXAOCT IMABS = IMABS IMAGINARY = IMAGINÁRIO IMARGUMENT = IMARG IMCONJUGATE = IMCONJ IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCOSEC IMCSCH = IMCOSECH IMDIV = IMDIV IMEXP = IMEXP IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMPOT IMPRODUCT = IMPROD IMREAL = IMREAL IMSEC = IMSEC IMSECH = IMSECH IMSIN = IMSENO IMSINH = IMSENH IMSQRT = IMRAIZ IMSUB = IMSUBTR IMSUM = IMSOMA IMTAN = IMTAN OCT2BIN = OCTABIN OCT2DEC = OCTADEC OCT2HEX = OCTAHEX ## ## Funções financeiras (Financial Functions) ## ACCRINT = JUROSACUM ACCRINTM = JUROSACUMV AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = CUPDIASINLIQ COUPDAYS = CUPDIAS COUPDAYSNC = CUPDIASPRÓX COUPNCD = CUPDATAPRÓX COUPNUM = CUPNÚM COUPPCD = CUPDATAANT CUMIPMT = PGTOJURACUM CUMPRINC = PGTOCAPACUM DB = BD DDB = BDD DISC = DESC DOLLARDE = MOEDADEC DOLLARFR = MOEDAFRA DURATION = DURAÇÃO EFFECT = EFETIVA FV = VF FVSCHEDULE = VFPLANO INTRATE = TAXAJUROS IPMT = IPGTO IRR = TIR ISPMT = ÉPGTO MDURATION = MDURAÇÃO MIRR = MTIR NOMINAL = NOMINAL NPER = NPER NPV = VPL ODDFPRICE = PREÇOPRIMINC ODDFYIELD = LUCROPRIMINC ODDLPRICE = PREÇOÚLTINC ODDLYIELD = LUCROÚLTINC PDURATION = DURAÇÃOP PMT = PGTO PPMT = PPGTO PRICE = PREÇO PRICEDISC = PREÇODESC PRICEMAT = PREÇOVENC PV = VP RATE = TAXA RECEIVED = RECEBER RRI = TAXAJURO SLN = DPD SYD = SDA TBILLEQ = OTN TBILLPRICE = OTNVALOR TBILLYIELD = OTNLUCRO VDB = BDV XIRR = XTIR XNPV = XVPL YIELD = LUCRO YIELDDISC = LUCRODESC YIELDMAT = LUCROVENC ## ## Funções de informação (Information Functions) ## CELL = CÉL ERROR.TYPE = TIPO.ERRO INFO = INFORMAÇÃO ISBLANK = ÉCÉL.VAZIA ISERR = ÉERRO ISERROR = ÉERROS ISEVEN = ÉPAR ISFORMULA = ÉFÓRMULA ISLOGICAL = ÉLÓGICO ISNA = É.NÃO.DISP ISNONTEXT = É.NÃO.TEXTO ISNUMBER = ÉNÚM ISODD = ÉIMPAR ISREF = ÉREF ISTEXT = ÉTEXTO N = N NA = NÃO.DISP SHEET = PLAN SHEETS = PLANS TYPE = TIPO ## ## Funções lógicas (Logical Functions) ## AND = E FALSE = FALSO IF = SE IFERROR = SEERRO IFNA = SENÃODISP IFS = SES NOT = NÃO OR = OU SWITCH = PARÂMETRO TRUE = VERDADEIRO XOR = XOR ## ## Funções de pesquisa e referência (Lookup & Reference Functions) ## ADDRESS = ENDEREÇO AREAS = ÁREAS CHOOSE = ESCOLHER COLUMN = COL COLUMNS = COLS FORMULATEXT = FÓRMULATEXTO GETPIVOTDATA = INFODADOSTABELADINÂMICA HLOOKUP = PROCH HYPERLINK = HIPERLINK INDEX = ÍNDICE INDIRECT = INDIRETO LOOKUP = PROC MATCH = CORRESP OFFSET = DESLOC ROW = LIN ROWS = LINS RTD = RTD TRANSPOSE = TRANSPOR VLOOKUP = PROCV *RC = LC ## ## Funções matemáticas e trigonométricas (Math & Trig Functions) ## ABS = ABS ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGREGAR ARABIC = ARÁBICO ASIN = ASEN ASINH = ASENH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = BASE CEILING.MATH = TETO.MAT CEILING.PRECISE = TETO.PRECISO COMBIN = COMBIN COMBINA = COMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = COSEC CSCH = COSECH DECIMAL = DECIMAL DEGREES = GRAUS ECMA.CEILING = ECMA.TETO EVEN = PAR EXP = EXP FACT = FATORIAL FACTDOUBLE = FATDUPLO FLOOR.MATH = ARREDMULTB.MAT FLOOR.PRECISE = ARREDMULTB.PRECISO GCD = MDC INT = INT ISO.CEILING = ISO.TETO LCM = MMC LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MATRIZ.DETERM MINVERSE = MATRIZ.INVERSO MMULT = MATRIZ.MULT MOD = MOD MROUND = MARRED MULTINOMIAL = MULTINOMIAL MUNIT = MUNIT ODD = ÍMPAR PI = PI POWER = POTÊNCIA PRODUCT = MULT QUOTIENT = QUOCIENTE RADIANS = RADIANOS RAND = ALEATÓRIO RANDBETWEEN = ALEATÓRIOENTRE ROMAN = ROMANO ROUND = ARRED ROUNDDOWN = ARREDONDAR.PARA.BAIXO ROUNDUP = ARREDONDAR.PARA.CIMA SEC = SEC SECH = SECH SERIESSUM = SOMASEQÜÊNCIA SIGN = SINAL SIN = SEN SINH = SENH SQRT = RAIZ SQRTPI = RAIZPI SUBTOTAL = SUBTOTAL SUM = SOMA SUMIF = SOMASE SUMIFS = SOMASES SUMPRODUCT = SOMARPRODUTO SUMSQ = SOMAQUAD SUMX2MY2 = SOMAX2DY2 SUMX2PY2 = SOMAX2SY2 SUMXMY2 = SOMAXMY2 TAN = TAN TANH = TANH TRUNC = TRUNCAR ## ## Funções estatísticas (Statistical Functions) ## AVEDEV = DESV.MÉDIO AVERAGE = MÉDIA AVERAGEA = MÉDIAA AVERAGEIF = MÉDIASE AVERAGEIFS = MÉDIASES BETA.DIST = DIST.BETA BETA.INV = INV.BETA BINOM.DIST = DISTR.BINOM BINOM.DIST.RANGE = INTERV.DISTR.BINOM BINOM.INV = INV.BINOM CHISQ.DIST = DIST.QUIQUA CHISQ.DIST.RT = DIST.QUIQUA.CD CHISQ.INV = INV.QUIQUA CHISQ.INV.RT = INV.QUIQUA.CD CHISQ.TEST = TESTE.QUIQUA CONFIDENCE.NORM = INT.CONFIANÇA.NORM CONFIDENCE.T = INT.CONFIANÇA.T CORREL = CORREL COUNT = CONT.NÚM COUNTA = CONT.VALORES COUNTBLANK = CONTAR.VAZIO COUNTIF = CONT.SE COUNTIFS = CONT.SES COVARIANCE.P = COVARIAÇÃO.P COVARIANCE.S = COVARIAÇÃO.S DEVSQ = DESVQ EXPON.DIST = DISTR.EXPON F.DIST = DIST.F F.DIST.RT = DIST.F.CD F.INV = INV.F F.INV.RT = INV.F.CD F.TEST = TESTE.F FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PREVISÃO.ETS FORECAST.ETS.CONFINT = PREVISÃO.ETS.CONFINT FORECAST.ETS.SEASONALITY = PREVISÃO.ETS.SAZONALIDADE FORECAST.ETS.STAT = PREVISÃO.ETS.STAT FORECAST.LINEAR = PREVISÃO.LINEAR FREQUENCY = FREQÜÊNCIA GAMMA = GAMA GAMMA.DIST = DIST.GAMA GAMMA.INV = INV.GAMA GAMMALN = LNGAMA GAMMALN.PRECISE = LNGAMA.PRECISO GAUSS = GAUSS GEOMEAN = MÉDIA.GEOMÉTRICA GROWTH = CRESCIMENTO HARMEAN = MÉDIA.HARMÔNICA HYPGEOM.DIST = DIST.HIPERGEOM.N INTERCEPT = INTERCEPÇÃO KURT = CURT LARGE = MAIOR LINEST = PROJ.LIN LOGEST = PROJ.LOG LOGNORM.DIST = DIST.LOGNORMAL.N LOGNORM.INV = INV.LOGNORMAL MAX = MÁXIMO MAXA = MÁXIMOA MAXIFS = MÁXIMOSES MEDIAN = MED MIN = MÍNIMO MINA = MÍNIMOA MINIFS = MÍNIMOSES MODE.MULT = MODO.MULT MODE.SNGL = MODO.ÚNICO NEGBINOM.DIST = DIST.BIN.NEG.N NORM.DIST = DIST.NORM.N NORM.INV = INV.NORM.N NORM.S.DIST = DIST.NORMP.N NORM.S.INV = INV.NORMP.N PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = ORDEM.PORCENTUAL.EXC PERCENTRANK.INC = ORDEM.PORCENTUAL.INC PERMUT = PERMUT PERMUTATIONA = PERMUTAS PHI = PHI POISSON.DIST = DIST.POISSON PROB = PROB QUARTILE.EXC = QUARTIL.EXC QUARTILE.INC = QUARTIL.INC RANK.AVG = ORDEM.MÉD RANK.EQ = ORDEM.EQ RSQ = RQUAD SKEW = DISTORÇÃO SKEW.P = DISTORÇÃO.P SLOPE = INCLINAÇÃO SMALL = MENOR STANDARDIZE = PADRONIZAR STDEV.P = DESVPAD.P STDEV.S = DESVPAD.A STDEVA = DESVPADA STDEVPA = DESVPADPA STEYX = EPADYX T.DIST = DIST.T T.DIST.2T = DIST.T.BC T.DIST.RT = DIST.T.CD T.INV = INV.T T.INV.2T = INV.T.BC T.TEST = TESTE.T TREND = TENDÊNCIA TRIMMEAN = MÉDIA.INTERNA VAR.P = VAR.P VAR.S = VAR.A VARA = VARA VARPA = VARPA WEIBULL.DIST = DIST.WEIBULL Z.TEST = TESTE.Z ## ## Funções de texto (Text Functions) ## BAHTTEXT = BAHTTEXT CHAR = CARACT CLEAN = TIRAR CODE = CÓDIGO CONCAT = CONCAT DOLLAR = MOEDA EXACT = EXATO FIND = PROCURAR FIXED = DEF.NÚM.DEC LEFT = ESQUERDA LEN = NÚM.CARACT LOWER = MINÚSCULA MID = EXT.TEXTO NUMBERSTRING = SEQÜÊNCIA.NÚMERO NUMBERVALUE = VALORNUMÉRICO PHONETIC = FONÉTICA PROPER = PRI.MAIÚSCULA REPLACE = MUDAR REPT = REPT RIGHT = DIREITA SEARCH = LOCALIZAR SUBSTITUTE = SUBSTITUIR T = T TEXT = TEXTO TEXTJOIN = UNIRTEXTO TRIM = ARRUMAR UNICHAR = CARACTUNICODE UNICODE = UNICODE UPPER = MAIÚSCULA VALUE = VALOR ## ## Funções da Web (Web Functions) ## ENCODEURL = CODIFURL FILTERXML = FILTROXML WEBSERVICE = SERVIÇOWEB ## ## Funções de compatibilidade (Compatibility Functions) ## BETADIST = DISTBETA BETAINV = BETA.ACUM.INV BINOMDIST = DISTRBINOM CEILING = TETO CHIDIST = DIST.QUI CHIINV = INV.QUI CHITEST = TESTE.QUI CONCATENATE = CONCATENAR CONFIDENCE = INT.CONFIANÇA COVAR = COVAR CRITBINOM = CRIT.BINOM EXPONDIST = DISTEXPON FDIST = DISTF FINV = INVF FLOOR = ARREDMULTB FORECAST = PREVISÃO FTEST = TESTEF GAMMADIST = DISTGAMA GAMMAINV = INVGAMA HYPGEOMDIST = DIST.HIPERGEOM LOGINV = INVLOG LOGNORMDIST = DIST.LOGNORMAL MODE = MODO NEGBINOMDIST = DIST.BIN.NEG NORMDIST = DISTNORM NORMINV = INV.NORM NORMSDIST = DISTNORMP NORMSINV = INV.NORMP PERCENTILE = PERCENTIL PERCENTRANK = ORDEM.PORCENTUAL POISSON = POISSON QUARTILE = QUARTIL RANK = ORDEM STDEV = DESVPAD STDEVP = DESVPADP TDIST = DISTT TINV = INVT TTEST = TESTET VAR = VAR VARP = VARP WEIBULL = WEIBULL ZTEST = TESTEZ phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/config 0000644 00000000520 15002227416 0021200 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Português Brasileiro (Brazilian Portuguese) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NULO! DIV0 VALUE = #VALOR! REF NAME = #NOME? NUM = #NÚM! NA = #N/D phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/config 0000644 00000000473 15002227416 0020604 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Português (Portuguese) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #NULO! DIV0 VALUE = #VALOR! REF NAME = #NOME? NUM = #NÚM! NA = #N/D phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/functions 0000644 00000026262 15002227416 0021326 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Suomi (Finnish) ## ############################################################ ## ## Kuutiofunktiot (Cube Functions) ## CUBEKPIMEMBER = KUUTIOKPIJÄSEN CUBEMEMBER = KUUTIONJÄSEN CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN CUBESET = KUUTIOJOUKKO CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ CUBEVALUE = KUUTIONARVO ## ## Tietokantafunktiot (Database Functions) ## DAVERAGE = TKESKIARVO DCOUNT = TLASKE DCOUNTA = TLASKEA DGET = TNOUDA DMAX = TMAKS DMIN = TMIN DPRODUCT = TTULO DSTDEV = TKESKIHAJONTA DSTDEVP = TKESKIHAJONTAP DSUM = TSUMMA DVAR = TVARIANSSI DVARP = TVARIANSSIP ## ## Päivämäärä- ja aikafunktiot (Date & Time Functions) ## DATE = PÄIVÄYS DATEDIF = PVMERO DATESTRING = PVMMERKKIJONO DATEVALUE = PÄIVÄYSARVO DAY = PÄIVÄ DAYS = PÄIVÄT DAYS360 = PÄIVÄT360 EDATE = PÄIVÄ.KUUKAUSI EOMONTH = KUUKAUSI.LOPPU HOUR = TUNNIT ISOWEEKNUM = VIIKKO.ISO.NRO MINUTE = MINUUTIT MONTH = KUUKAUSI NETWORKDAYS = TYÖPÄIVÄT NETWORKDAYS.INTL = TYÖPÄIVÄT.KANSVÄL NOW = NYT SECOND = SEKUNNIT THAIDAYOFWEEK = THAI.VIIKONPÄIVÄ THAIMONTHOFYEAR = THAI.KUUKAUSI THAIYEAR = THAI.VUOSI TIME = AIKA TIMEVALUE = AIKA_ARVO TODAY = TÄMÄ.PÄIVÄ WEEKDAY = VIIKONPÄIVÄ WEEKNUM = VIIKKO.NRO WORKDAY = TYÖPÄIVÄ WORKDAY.INTL = TYÖPÄIVÄ.KANSVÄL YEAR = VUOSI YEARFRAC = VUOSI.OSA ## ## Tekniset funktiot (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BINDES BIN2HEX = BINHEKSA BIN2OCT = BINOKT BITAND = BITTI.JA BITLSHIFT = BITTI.SIIRTO.V BITOR = BITTI.TAI BITRSHIFT = BITTI.SIIRTO.O BITXOR = BITTI.EHDOTON.TAI COMPLEX = KOMPLEKSI CONVERT = MUUNNA DEC2BIN = DESBIN DEC2HEX = DESHEKSA DEC2OCT = DESOKT DELTA = SAMA.ARVO ERF = VIRHEFUNKTIO ERF.PRECISE = VIRHEFUNKTIO.TARKKA ERFC = VIRHEFUNKTIO.KOMPLEMENTTI ERFC.PRECISE = VIRHEFUNKTIO.KOMPLEMENTTI.TARKKA GESTEP = RAJA HEX2BIN = HEKSABIN HEX2DEC = HEKSADES HEX2OCT = HEKSAOKT IMABS = KOMPLEKSI.ABS IMAGINARY = KOMPLEKSI.IMAG IMARGUMENT = KOMPLEKSI.ARG IMCONJUGATE = KOMPLEKSI.KONJ IMCOS = KOMPLEKSI.COS IMCOSH = IMCOSH IMCOT = KOMPLEKSI.COT IMCSC = KOMPLEKSI.KOSEK IMCSCH = KOMPLEKSI.KOSEKH IMDIV = KOMPLEKSI.OSAM IMEXP = KOMPLEKSI.EKSP IMLN = KOMPLEKSI.LN IMLOG10 = KOMPLEKSI.LOG10 IMLOG2 = KOMPLEKSI.LOG2 IMPOWER = KOMPLEKSI.POT IMPRODUCT = KOMPLEKSI.TULO IMREAL = KOMPLEKSI.REAALI IMSEC = KOMPLEKSI.SEK IMSECH = KOMPLEKSI.SEKH IMSIN = KOMPLEKSI.SIN IMSINH = KOMPLEKSI.SINH IMSQRT = KOMPLEKSI.NELIÖJ IMSUB = KOMPLEKSI.EROTUS IMSUM = KOMPLEKSI.SUM IMTAN = KOMPLEKSI.TAN OCT2BIN = OKTBIN OCT2DEC = OKTDES OCT2HEX = OKTHEKSA ## ## Rahoitusfunktiot (Financial Functions) ## ACCRINT = KERTYNYT.KORKO ACCRINTM = KERTYNYT.KORKO.LOPUSSA AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = KORKOPÄIVÄT.ALUSTA COUPDAYS = KORKOPÄIVÄT COUPDAYSNC = KORKOPÄIVÄT.SEURAAVA COUPNCD = KORKOPÄIVÄ.SEURAAVA COUPNUM = KORKOPÄIVÄ.JAKSOT COUPPCD = KORKOPÄIVÄ.EDELLINEN CUMIPMT = MAKSETTU.KORKO CUMPRINC = MAKSETTU.LYHENNYS DB = DB DDB = DDB DISC = DISKONTTOKORKO DOLLARDE = VALUUTTA.DES DOLLARFR = VALUUTTA.MURTO DURATION = KESTO EFFECT = KORKO.EFEKT FV = TULEVA.ARVO FVSCHEDULE = TULEVA.ARVO.ERIKORKO INTRATE = KORKO.ARVOPAPERI IPMT = IPMT IRR = SISÄINEN.KORKO ISPMT = ISPMT MDURATION = KESTO.MUUNN MIRR = MSISÄINEN NOMINAL = KORKO.VUOSI NPER = NJAKSO NPV = NNA ODDFPRICE = PARITON.ENS.NIMELLISARVO ODDFYIELD = PARITON.ENS.TUOTTO ODDLPRICE = PARITON.VIIM.NIMELLISARVO ODDLYIELD = PARITON.VIIM.TUOTTO PDURATION = KESTO.JAKSO PMT = MAKSU PPMT = PPMT PRICE = HINTA PRICEDISC = HINTA.DISK PRICEMAT = HINTA.LUNASTUS PV = NA RATE = KORKO RECEIVED = SAATU.HINTA RRI = TOT.ROI SLN = STP SYD = VUOSIPOISTO TBILLEQ = OBLIG.TUOTTOPROS TBILLPRICE = OBLIG.HINTA TBILLYIELD = OBLIG.TUOTTO VDB = VDB XIRR = SISÄINEN.KORKO.JAKSOTON XNPV = NNA.JAKSOTON YIELD = TUOTTO YIELDDISC = TUOTTO.DISK YIELDMAT = TUOTTO.ERÄP ## ## Tietofunktiot (Information Functions) ## CELL = SOLU ERROR.TYPE = VIRHEEN.LAJI INFO = KUVAUS ISBLANK = ONTYHJÄ ISERR = ONVIRH ISERROR = ONVIRHE ISEVEN = ONPARILLINEN ISFORMULA = ONKAAVA ISLOGICAL = ONTOTUUS ISNA = ONPUUTTUU ISNONTEXT = ONEI_TEKSTI ISNUMBER = ONLUKU ISODD = ONPARITON ISREF = ONVIITT ISTEXT = ONTEKSTI N = N NA = PUUTTUU SHEET = TAULUKKO SHEETS = TAULUKOT TYPE = TYYPPI ## ## Loogiset funktiot (Logical Functions) ## AND = JA FALSE = EPÄTOSI IF = JOS IFERROR = JOSVIRHE IFNA = JOSPUUTTUU IFS = JOSS NOT = EI OR = TAI SWITCH = MUUTA TRUE = TOSI XOR = EHDOTON.TAI ## ## Haku- ja viitefunktiot (Lookup & Reference Functions) ## ADDRESS = OSOITE AREAS = ALUEET CHOOSE = VALITSE.INDEKSI COLUMN = SARAKE COLUMNS = SARAKKEET FORMULATEXT = KAAVA.TEKSTI GETPIVOTDATA = NOUDA.PIVOT.TIEDOT HLOOKUP = VHAKU HYPERLINK = HYPERLINKKI INDEX = INDEKSI INDIRECT = EPÄSUORA LOOKUP = HAKU MATCH = VASTINE OFFSET = SIIRTYMÄ ROW = RIVI ROWS = RIVIT RTD = RTD TRANSPOSE = TRANSPONOI VLOOKUP = PHAKU *RC = RS ## ## Matemaattiset ja trigonometriset funktiot (Math & Trig Functions) ## ABS = ITSEISARVO ACOS = ACOS ACOSH = ACOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = KOOSTE ARABIC = ARABIA ASIN = ASIN ASINH = ASINH ATAN = ATAN ATAN2 = ATAN2 ATANH = ATANH BASE = PERUS CEILING.MATH = PYÖRISTÄ.KERR.YLÖS.MATEMAATTINEN CEILING.PRECISE = PYÖRISTÄ.KERR.YLÖS.TARKKA COMBIN = KOMBINAATIO COMBINA = KOMBINAATIOA COS = COS COSH = COSH COT = COT COTH = COTH CSC = KOSEK CSCH = KOSEKH DECIMAL = DESIMAALI DEGREES = ASTEET ECMA.CEILING = ECMA.PYÖRISTÄ.KERR.YLÖS EVEN = PARILLINEN EXP = EKSPONENTTI FACT = KERTOMA FACTDOUBLE = KERTOMA.OSA FLOOR.MATH = PYÖRISTÄ.KERR.ALAS.MATEMAATTINEN FLOOR.PRECISE = PYÖRISTÄ.KERR.ALAS.TARKKA GCD = SUURIN.YHT.TEKIJÄ INT = KOKONAISLUKU ISO.CEILING = ISO.PYÖRISTÄ.KERR.YLÖS LCM = PIENIN.YHT.JAETTAVA LN = LUONNLOG LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = MKÄÄNTEINEN MMULT = MKERRO MOD = JAKOJ MROUND = PYÖRISTÄ.KERR MULTINOMIAL = MULTINOMI MUNIT = YKSIKKÖM ODD = PARITON PI = PII POWER = POTENSSI PRODUCT = TULO QUOTIENT = OSAMÄÄRÄ RADIANS = RADIAANIT RAND = SATUNNAISLUKU RANDBETWEEN = SATUNNAISLUKU.VÄLILTÄ ROMAN = ROMAN ROUND = PYÖRISTÄ ROUNDBAHTDOWN = PYÖRISTÄ.BAHT.ALAS ROUNDBAHTUP = PYÖRISTÄ.BAHT.YLÖS ROUNDDOWN = PYÖRISTÄ.DES.ALAS ROUNDUP = PYÖRISTÄ.DES.YLÖS SEC = SEK SECH = SEKH SERIESSUM = SARJA.SUMMA SIGN = ETUMERKKI SIN = SIN SINH = SINH SQRT = NELIÖJUURI SQRTPI = NELIÖJUURI.PII SUBTOTAL = VÄLISUMMA SUM = SUMMA SUMIF = SUMMA.JOS SUMIFS = SUMMA.JOS.JOUKKO SUMPRODUCT = TULOJEN.SUMMA SUMSQ = NELIÖSUMMA SUMX2MY2 = NELIÖSUMMIEN.EROTUS SUMX2PY2 = NELIÖSUMMIEN.SUMMA SUMXMY2 = EROTUSTEN.NELIÖSUMMA TAN = TAN TANH = TANH TRUNC = KATKAISE ## ## Tilastolliset funktiot (Statistical Functions) ## AVEDEV = KESKIPOIKKEAMA AVERAGE = KESKIARVO AVERAGEA = KESKIARVOA AVERAGEIF = KESKIARVO.JOS AVERAGEIFS = KESKIARVO.JOS.JOUKKO BETA.DIST = BEETA.JAKAUMA BETA.INV = BEETA.KÄÄNT BINOM.DIST = BINOMI.JAKAUMA BINOM.DIST.RANGE = BINOMI.JAKAUMA.ALUE BINOM.INV = BINOMIJAKAUMA.KÄÄNT CHISQ.DIST = CHINELIÖ.JAKAUMA CHISQ.DIST.RT = CHINELIÖ.JAKAUMA.OH CHISQ.INV = CHINELIÖ.KÄÄNT CHISQ.INV.RT = CHINELIÖ.KÄÄNT.OH CHISQ.TEST = CHINELIÖ.TESTI CONFIDENCE.NORM = LUOTTAMUSVÄLI.NORM CONFIDENCE.T = LUOTTAMUSVÄLI.T CORREL = KORRELAATIO COUNT = LASKE COUNTA = LASKE.A COUNTBLANK = LASKE.TYHJÄT COUNTIF = LASKE.JOS COUNTIFS = LASKE.JOS.JOUKKO COVARIANCE.P = KOVARIANSSI.P COVARIANCE.S = KOVARIANSSI.S DEVSQ = OIKAISTU.NELIÖSUMMA EXPON.DIST = EKSPONENTIAALI.JAKAUMA F.DIST = F.JAKAUMA F.DIST.RT = F.JAKAUMA.OH F.INV = F.KÄÄNT F.INV.RT = F.KÄÄNT.OH F.TEST = F.TESTI FISHER = FISHER FISHERINV = FISHER.KÄÄNT FORECAST.ETS = ENNUSTE.ETS FORECAST.ETS.CONFINT = ENNUSTE.ETS.CONFINT FORECAST.ETS.SEASONALITY = ENNUSTE.ETS.KAUSIVAIHTELU FORECAST.ETS.STAT = ENNUSTE.ETS.STAT FORECAST.LINEAR = ENNUSTE.LINEAARINEN FREQUENCY = TAAJUUS GAMMA = GAMMA GAMMA.DIST = GAMMA.JAKAUMA GAMMA.INV = GAMMA.JAKAUMA.KÄÄNT GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.TARKKA GAUSS = GAUSS GEOMEAN = KESKIARVO.GEOM GROWTH = KASVU HARMEAN = KESKIARVO.HARM HYPGEOM.DIST = HYPERGEOM_JAKAUMA INTERCEPT = LEIKKAUSPISTE KURT = KURT LARGE = SUURI LINEST = LINREGR LOGEST = LOGREGR LOGNORM.DIST = LOGNORM_JAKAUMA LOGNORM.INV = LOGNORM.KÄÄNT MAX = MAKS MAXA = MAKSA MAXIFS = MAKS.JOS MEDIAN = MEDIAANI MIN = MIN MINA = MINA MINIFS = MIN.JOS MODE.MULT = MOODI.USEA MODE.SNGL = MOODI.YKSI NEGBINOM.DIST = BINOMI.JAKAUMA.NEG NORM.DIST = NORMAALI.JAKAUMA NORM.INV = NORMAALI.JAKAUMA.KÄÄNT NORM.S.DIST = NORM_JAKAUMA.NORMIT NORM.S.INV = NORM_JAKAUMA.KÄÄNT PEARSON = PEARSON PERCENTILE.EXC = PROSENTTIPISTE.ULK PERCENTILE.INC = PROSENTTIPISTE.SIS PERCENTRANK.EXC = PROSENTTIJÄRJESTYS.ULK PERCENTRANK.INC = PROSENTTIJÄRJESTYS.SIS PERMUT = PERMUTAATIO PERMUTATIONA = PERMUTAATIOA PHI = FII POISSON.DIST = POISSON.JAKAUMA PROB = TODENNÄKÖISYYS QUARTILE.EXC = NELJÄNNES.ULK QUARTILE.INC = NELJÄNNES.SIS RANK.AVG = ARVON.MUKAAN.KESKIARVO RANK.EQ = ARVON.MUKAAN.TASAN RSQ = PEARSON.NELIÖ SKEW = JAKAUMAN.VINOUS SKEW.P = JAKAUMAN.VINOUS.POP SLOPE = KULMAKERROIN SMALL = PIENI STANDARDIZE = NORMITA STDEV.P = KESKIHAJONTA.P STDEV.S = KESKIHAJONTA.S STDEVA = KESKIHAJONTAA STDEVPA = KESKIHAJONTAPA STEYX = KESKIVIRHE T.DIST = T.JAKAUMA T.DIST.2T = T.JAKAUMA.2S T.DIST.RT = T.JAKAUMA.OH T.INV = T.KÄÄNT T.INV.2T = T.KÄÄNT.2S T.TEST = T.TESTI TREND = SUUNTAUS TRIMMEAN = KESKIARVO.TASATTU VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = WEIBULL.JAKAUMA Z.TEST = Z.TESTI ## ## Tekstifunktiot (Text Functions) ## BAHTTEXT = BAHTTEKSTI CHAR = MERKKI CLEAN = SIIVOA CODE = KOODI CONCAT = YHDISTÄ DOLLAR = VALUUTTA EXACT = VERTAA FIND = ETSI FIXED = KIINTEÄ ISTHAIDIGIT = ON.THAI.NUMERO LEFT = VASEN LEN = PITUUS LOWER = PIENET MID = POIMI.TEKSTI NUMBERSTRING = NROMERKKIJONO NUMBERVALUE = NROARVO PHONETIC = FONEETTINEN PROPER = ERISNIMI REPLACE = KORVAA REPT = TOISTA RIGHT = OIKEA SEARCH = KÄY.LÄPI SUBSTITUTE = VAIHDA T = T TEXT = TEKSTI TEXTJOIN = TEKSTI.YHDISTÄ THAIDIGIT = THAI.NUMERO THAINUMSOUND = THAI.LUKU.ÄÄNI THAINUMSTRING = THAI.LUKU.MERKKIJONO THAISTRINGLENGTH = THAI.MERKKIJONON.PITUUS TRIM = POISTA.VÄLIT UNICHAR = UNICODEMERKKI UNICODE = UNICODE UPPER = ISOT VALUE = ARVO ## ## Verkkofunktiot (Web Functions) ## ENCODEURL = URLKOODAUS FILTERXML = SUODATA.XML WEBSERVICE = VERKKOPALVELU ## ## Yhteensopivuusfunktiot (Compatibility Functions) ## BETADIST = BEETAJAKAUMA BETAINV = BEETAJAKAUMA.KÄÄNT BINOMDIST = BINOMIJAKAUMA CEILING = PYÖRISTÄ.KERR.YLÖS CHIDIST = CHIJAKAUMA CHIINV = CHIJAKAUMA.KÄÄNT CHITEST = CHITESTI CONCATENATE = KETJUTA CONFIDENCE = LUOTTAMUSVÄLI COVAR = KOVARIANSSI CRITBINOM = BINOMIJAKAUMA.KRIT EXPONDIST = EKSPONENTIAALIJAKAUMA FDIST = FJAKAUMA FINV = FJAKAUMA.KÄÄNT FLOOR = PYÖRISTÄ.KERR.ALAS FORECAST = ENNUSTE FTEST = FTESTI GAMMADIST = GAMMAJAKAUMA GAMMAINV = GAMMAJAKAUMA.KÄÄNT HYPGEOMDIST = HYPERGEOM.JAKAUMA LOGINV = LOGNORM.JAKAUMA.KÄÄNT LOGNORMDIST = LOGNORM.JAKAUMA MODE = MOODI NEGBINOMDIST = BINOMIJAKAUMA.NEG NORMDIST = NORM.JAKAUMA NORMINV = NORM.JAKAUMA.KÄÄNT NORMSDIST = NORM.JAKAUMA.NORMIT NORMSINV = NORM.JAKAUMA.NORMIT.KÄÄNT PERCENTILE = PROSENTTIPISTE PERCENTRANK = PROSENTTIJÄRJESTYS POISSON = POISSON QUARTILE = NELJÄNNES RANK = ARVON.MUKAAN STDEV = KESKIHAJONTA STDEVP = KESKIHAJONTAP TDIST = TJAKAUMA TINV = TJAKAUMA.KÄÄNT TTEST = TTESTI VAR = VAR VARP = VARP WEIBULL = WEIBULL ZTEST = ZTESTI phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/config 0000644 00000000521 15002227416 0020551 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Suomi (Finnish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #TYHJÄ! DIV0 = #JAKO/0! VALUE = #ARVO! REF = #VIITTAUS! NAME = #NIMI? NUM = #LUKU! NA = #PUUTTUU! phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/functions 0000644 00000023241 15002227416 0021352 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Svenska (Swedish) ## ############################################################ ## ## Kubfunktioner (Cube Functions) ## CUBEKPIMEMBER = KUBKPIMEDLEM CUBEMEMBER = KUBMEDLEM CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM CUBESET = KUBUPPSÄTTNING CUBESETCOUNT = KUBUPPSÄTTNINGANTAL CUBEVALUE = KUBVÄRDE ## ## Databasfunktioner (Database Functions) ## DAVERAGE = DMEDEL DCOUNT = DANTAL DCOUNTA = DANTALV DGET = DHÄMTA DMAX = DMAX DMIN = DMIN DPRODUCT = DPRODUKT DSTDEV = DSTDAV DSTDEVP = DSTDAVP DSUM = DSUMMA DVAR = DVARIANS DVARP = DVARIANSP ## ## Tid- och datumfunktioner (Date & Time Functions) ## DATE = DATUM DATEVALUE = DATUMVÄRDE DAY = DAG DAYS = DAGAR DAYS360 = DAGAR360 EDATE = EDATUM EOMONTH = SLUTMÅNAD HOUR = TIMME ISOWEEKNUM = ISOVECKONR MINUTE = MINUT MONTH = MÅNAD NETWORKDAYS = NETTOARBETSDAGAR NETWORKDAYS.INTL = NETTOARBETSDAGAR.INT NOW = NU SECOND = SEKUND THAIDAYOFWEEK = THAIVECKODAG THAIMONTHOFYEAR = THAIMÅNAD THAIYEAR = THAIÅR TIME = KLOCKSLAG TIMEVALUE = TIDVÄRDE TODAY = IDAG WEEKDAY = VECKODAG WEEKNUM = VECKONR WORKDAY = ARBETSDAGAR WORKDAY.INTL = ARBETSDAGAR.INT YEAR = ÅR YEARFRAC = ÅRDEL ## ## Tekniska funktioner (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN.TILL.DEC BIN2HEX = BIN.TILL.HEX BIN2OCT = BIN.TILL.OKT BITAND = BITOCH BITLSHIFT = BITVSKIFT BITOR = BITELLER BITRSHIFT = BITHSKIFT BITXOR = BITXELLER COMPLEX = KOMPLEX CONVERT = KONVERTERA DEC2BIN = DEC.TILL.BIN DEC2HEX = DEC.TILL.HEX DEC2OCT = DEC.TILL.OKT DELTA = DELTA ERF = FELF ERF.PRECISE = FELF.EXAKT ERFC = FELFK ERFC.PRECISE = FELFK.EXAKT GESTEP = SLSTEG HEX2BIN = HEX.TILL.BIN HEX2DEC = HEX.TILL.DEC HEX2OCT = HEX.TILL.OKT IMABS = IMABS IMAGINARY = IMAGINÄR IMARGUMENT = IMARGUMENT IMCONJUGATE = IMKONJUGAT IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCSC IMCSCH = IMCSCH IMDIV = IMDIV IMEXP = IMEUPPHÖJT IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMUPPHÖJT IMPRODUCT = IMPRODUKT IMREAL = IMREAL IMSEC = IMSEK IMSECH = IMSEKH IMSIN = IMSIN IMSINH = IMSINH IMSQRT = IMROT IMSUB = IMDIFF IMSUM = IMSUM IMTAN = IMTAN OCT2BIN = OKT.TILL.BIN OCT2DEC = OKT.TILL.DEC OCT2HEX = OKT.TILL.HEX ## ## Finansiella funktioner (Financial Functions) ## ACCRINT = UPPLRÄNTA ACCRINTM = UPPLOBLRÄNTA AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = KUPDAGBB COUPDAYS = KUPDAGB COUPDAYSNC = KUPDAGNK COUPNCD = KUPNKD COUPNUM = KUPANT COUPPCD = KUPFKD CUMIPMT = KUMRÄNTA CUMPRINC = KUMPRIS DB = DB DDB = DEGAVSKR DISC = DISK DOLLARDE = DECTAL DOLLARFR = BRÅK DURATION = LÖPTID EFFECT = EFFRÄNTA FV = SLUTVÄRDE FVSCHEDULE = FÖRRÄNTNING INTRATE = ÅRSRÄNTA IPMT = RBETALNING IRR = IR ISPMT = RALÅN MDURATION = MLÖPTID MIRR = MODIR NOMINAL = NOMRÄNTA NPER = PERIODER NPV = NETNUVÄRDE ODDFPRICE = UDDAFPRIS ODDFYIELD = UDDAFAVKASTNING ODDLPRICE = UDDASPRIS ODDLYIELD = UDDASAVKASTNING PDURATION = PLÖPTID PMT = BETALNING PPMT = AMORT PRICE = PRIS PRICEDISC = PRISDISK PRICEMAT = PRISFÖRF PV = NUVÄRDE RATE = RÄNTA RECEIVED = BELOPP RRI = AVKPÅINVEST SLN = LINAVSKR SYD = ÅRSAVSKR TBILLEQ = SSVXEKV TBILLPRICE = SSVXPRIS TBILLYIELD = SSVXRÄNTA VDB = VDEGRAVSKR XIRR = XIRR XNPV = XNUVÄRDE YIELD = NOMAVK YIELDDISC = NOMAVKDISK YIELDMAT = NOMAVKFÖRF ## ## Informationsfunktioner (Information Functions) ## CELL = CELL ERROR.TYPE = FEL.TYP INFO = INFO ISBLANK = ÄRTOM ISERR = ÄRF ISERROR = ÄRFEL ISEVEN = ÄRJÄMN ISFORMULA = ÄRFORMEL ISLOGICAL = ÄRLOGISK ISNA = ÄRSAKNAD ISNONTEXT = ÄREJTEXT ISNUMBER = ÄRTAL ISODD = ÄRUDDA ISREF = ÄRREF ISTEXT = ÄRTEXT N = N NA = SAKNAS SHEET = BLAD SHEETS = ANTALBLAD TYPE = VÄRDETYP ## ## Logiska funktioner (Logical Functions) ## AND = OCH FALSE = FALSKT IF = OM IFERROR = OMFEL IFNA = OMSAKNAS IFS = IFS NOT = ICKE OR = ELLER SWITCH = VÄXLA TRUE = SANT XOR = XELLER ## ## Sök- och referensfunktioner (Lookup & Reference Functions) ## ADDRESS = ADRESS AREAS = OMRÅDEN CHOOSE = VÄLJ COLUMN = KOLUMN COLUMNS = KOLUMNER FORMULATEXT = FORMELTEXT GETPIVOTDATA = HÄMTA.PIVOTDATA HLOOKUP = LETAKOLUMN HYPERLINK = HYPERLÄNK INDEX = INDEX INDIRECT = INDIREKT LOOKUP = LETAUPP MATCH = PASSA OFFSET = FÖRSKJUTNING ROW = RAD ROWS = RADER RTD = RTD TRANSPOSE = TRANSPONERA VLOOKUP = LETARAD *RC = RK ## ## Matematiska och trigonometriska funktioner (Math & Trig Functions) ## ABS = ABS ACOS = ARCCOS ACOSH = ARCCOSH ACOT = ARCCOT ACOTH = ARCCOTH AGGREGATE = MÄNGD ARABIC = ARABISKA ASIN = ARCSIN ASINH = ARCSINH ATAN = ARCTAN ATAN2 = ARCTAN2 ATANH = ARCTANH BASE = BAS CEILING.MATH = RUNDA.UPP.MATEMATISKT CEILING.PRECISE = RUNDA.UPP.EXAKT COMBIN = KOMBIN COMBINA = KOMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMAL DEGREES = GRADER ECMA.CEILING = ECMA.RUNDA.UPP EVEN = JÄMN EXP = EXP FACT = FAKULTET FACTDOUBLE = DUBBELFAKULTET FLOOR.MATH = RUNDA.NER.MATEMATISKT FLOOR.PRECISE = RUNDA.NER.EXAKT GCD = SGD INT = HELTAL ISO.CEILING = ISO.RUNDA.UPP LCM = MGM LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MDETERM MINVERSE = MINVERT MMULT = MMULT MOD = REST MROUND = MAVRUNDA MULTINOMIAL = MULTINOMIAL MUNIT = MENHET ODD = UDDA PI = PI POWER = UPPHÖJT.TILL PRODUCT = PRODUKT QUOTIENT = KVOT RADIANS = RADIANER RAND = SLUMP RANDBETWEEN = SLUMP.MELLAN ROMAN = ROMERSK ROUND = AVRUNDA ROUNDBAHTDOWN = AVRUNDABAHTNEDÅT ROUNDBAHTUP = AVRUNDABAHTUPPÅT ROUNDDOWN = AVRUNDA.NEDÅT ROUNDUP = AVRUNDA.UPPÅT SEC = SEK SECH = SEKH SERIESSUM = SERIESUMMA SIGN = TECKEN SIN = SIN SINH = SINH SQRT = ROT SQRTPI = ROTPI SUBTOTAL = DELSUMMA SUM = SUMMA SUMIF = SUMMA.OM SUMIFS = SUMMA.OMF SUMPRODUCT = PRODUKTSUMMA SUMSQ = KVADRATSUMMA SUMX2MY2 = SUMMAX2MY2 SUMX2PY2 = SUMMAX2PY2 SUMXMY2 = SUMMAXMY2 TAN = TAN TANH = TANH TRUNC = AVKORTA ## ## Statistiska funktioner (Statistical Functions) ## AVEDEV = MEDELAVV AVERAGE = MEDEL AVERAGEA = AVERAGEA AVERAGEIF = MEDEL.OM AVERAGEIFS = MEDEL.OMF BETA.DIST = BETA.FÖRD BETA.INV = BETA.INV BINOM.DIST = BINOM.FÖRD BINOM.DIST.RANGE = BINOM.FÖRD.INTERVALL BINOM.INV = BINOM.INV CHISQ.DIST = CHI2.FÖRD CHISQ.DIST.RT = CHI2.FÖRD.RT CHISQ.INV = CHI2.INV CHISQ.INV.RT = CHI2.INV.RT CHISQ.TEST = CHI2.TEST CONFIDENCE.NORM = KONFIDENS.NORM CONFIDENCE.T = KONFIDENS.T CORREL = KORREL COUNT = ANTAL COUNTA = ANTALV COUNTBLANK = ANTAL.TOMMA COUNTIF = ANTAL.OM COUNTIFS = ANTAL.OMF COVARIANCE.P = KOVARIANS.P COVARIANCE.S = KOVARIANS.S DEVSQ = KVADAVV EXPON.DIST = EXPON.FÖRD F.DIST = F.FÖRD F.DIST.RT = F.FÖRD.RT F.INV = F.INV F.INV.RT = F.INV.RT F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = PROGNOS.ETS FORECAST.ETS.CONFINT = PROGNOS.ETS.KONFINT FORECAST.ETS.SEASONALITY = PROGNOS.ETS.SÄSONGSBEROENDE FORECAST.ETS.STAT = PROGNOS.ETS.STAT FORECAST.LINEAR = PROGNOS.LINJÄR FREQUENCY = FREKVENS GAMMA = GAMMA GAMMA.DIST = GAMMA.FÖRD GAMMA.INV = GAMMA.INV GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.EXAKT GAUSS = GAUSS GEOMEAN = GEOMEDEL GROWTH = EXPTREND HARMEAN = HARMMEDEL HYPGEOM.DIST = HYPGEOM.FÖRD INTERCEPT = SKÄRNINGSPUNKT KURT = TOPPIGHET LARGE = STÖRSTA LINEST = REGR LOGEST = EXPREGR LOGNORM.DIST = LOGNORM.FÖRD LOGNORM.INV = LOGNORM.INV MAX = MAX MAXA = MAXA MAXIFS = MAXIFS MEDIAN = MEDIAN MIN = MIN MINA = MINA MINIFS = MINIFS MODE.MULT = TYPVÄRDE.FLERA MODE.SNGL = TYPVÄRDE.ETT NEGBINOM.DIST = NEGBINOM.FÖRD NORM.DIST = NORM.FÖRD NORM.INV = NORM.INV NORM.S.DIST = NORM.S.FÖRD NORM.S.INV = NORM.S.INV PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXK PERCENTILE.INC = PERCENTIL.INK PERCENTRANK.EXC = PROCENTRANG.EXK PERCENTRANK.INC = PROCENTRANG.INK PERMUT = PERMUT PERMUTATIONA = PERMUTATIONA PHI = PHI POISSON.DIST = POISSON.FÖRD PROB = SANNOLIKHET QUARTILE.EXC = KVARTIL.EXK QUARTILE.INC = KVARTIL.INK RANK.AVG = RANG.MED RANK.EQ = RANG.EKV RSQ = RKV SKEW = SNEDHET SKEW.P = SNEDHET.P SLOPE = LUTNING SMALL = MINSTA STANDARDIZE = STANDARDISERA STDEV.P = STDAV.P STDEV.S = STDAV.S STDEVA = STDEVA STDEVPA = STDEVPA STEYX = STDFELYX T.DIST = T.FÖRD T.DIST.2T = T.FÖRD.2T T.DIST.RT = T.FÖRD.RT T.INV = T.INV T.INV.2T = T.INV.2T T.TEST = T.TEST TREND = TREND TRIMMEAN = TRIMMEDEL VAR.P = VARIANS.P VAR.S = VARIANS.S VARA = VARA VARPA = VARPA WEIBULL.DIST = WEIBULL.FÖRD Z.TEST = Z.TEST ## ## Textfunktioner (Text Functions) ## BAHTTEXT = BAHTTEXT CHAR = TECKENKOD CLEAN = STÄDA CODE = KOD CONCAT = SAMMAN DOLLAR = VALUTA EXACT = EXAKT FIND = HITTA FIXED = FASTTAL LEFT = VÄNSTER LEN = LÄNGD LOWER = GEMENER MID = EXTEXT NUMBERVALUE = TALVÄRDE PROPER = INITIAL REPLACE = ERSÄTT REPT = REP RIGHT = HÖGER SEARCH = SÖK SUBSTITUTE = BYT.UT T = T TEXT = TEXT TEXTJOIN = TEXTJOIN THAIDIGIT = THAISIFFRA THAINUMSOUND = THAITALLJUD THAINUMSTRING = THAITALSTRÄNG THAISTRINGLENGTH = THAISTRÄNGLÄNGD TRIM = RENSA UNICHAR = UNITECKENKOD UNICODE = UNICODE UPPER = VERSALER VALUE = TEXTNUM ## ## Webbfunktioner (Web Functions) ## ENCODEURL = KODAWEBBADRESS FILTERXML = FILTRERAXML WEBSERVICE = WEBBTJÄNST ## ## Kompatibilitetsfunktioner (Compatibility Functions) ## BETADIST = BETAFÖRD BETAINV = BETAINV BINOMDIST = BINOMFÖRD CEILING = RUNDA.UPP CHIDIST = CHI2FÖRD CHIINV = CHI2INV CHITEST = CHI2TEST CONCATENATE = SAMMANFOGA CONFIDENCE = KONFIDENS COVAR = KOVAR CRITBINOM = KRITBINOM EXPONDIST = EXPONFÖRD FDIST = FFÖRD FINV = FINV FLOOR = RUNDA.NER FORECAST = PREDIKTION FTEST = FTEST GAMMADIST = GAMMAFÖRD GAMMAINV = GAMMAINV HYPGEOMDIST = HYPGEOMFÖRD LOGINV = LOGINV LOGNORMDIST = LOGNORMFÖRD MODE = TYPVÄRDE NEGBINOMDIST = NEGBINOMFÖRD NORMDIST = NORMFÖRD NORMINV = NORMINV NORMSDIST = NORMSFÖRD NORMSINV = NORMSINV PERCENTILE = PERCENTIL PERCENTRANK = PROCENTRANG POISSON = POISSON QUARTILE = KVARTIL RANK = RANG STDEV = STDAV STDEVP = STDAVP TDIST = TFÖRD TINV = TINV TTEST = TTEST VAR = VARIANS VARP = VARIANSP WEIBULL = WEIBULL ZTEST = ZTEST phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/config 0000644 00000000542 15002227416 0020606 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Svenska (Swedish) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL = #SKÄRNING! DIV0 = #DIVISION/0! VALUE = #VÄRDEFEL! REF = #REFERENS! NAME = #NAMN? NUM = #OGILTIGT! NA = #SAKNAS! phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/functions 0000644 00000022455 15002227416 0021335 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Ceština (Czech) ## ############################################################ ## ## Funkce pro práci s datovými krychlemi (Cube Functions) ## CUBEKPIMEMBER = CUBEKPIMEMBER CUBEMEMBER = CUBEMEMBER CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY CUBERANKEDMEMBER = CUBERANKEDMEMBER CUBESET = CUBESET CUBESETCOUNT = CUBESETCOUNT CUBEVALUE = CUBEVALUE ## ## Funkce databáze (Database Functions) ## DAVERAGE = DPRŮMĚR DCOUNT = DPOČET DCOUNTA = DPOČET2 DGET = DZÍSKAT DMAX = DMAX DMIN = DMIN DPRODUCT = DSOUČIN DSTDEV = DSMODCH.VÝBĚR DSTDEVP = DSMODCH DSUM = DSUMA DVAR = DVAR.VÝBĚR DVARP = DVAR ## ## Funkce data a času (Date & Time Functions) ## DATE = DATUM DATEVALUE = DATUMHODN DAY = DEN DAYS = DAYS DAYS360 = ROK360 EDATE = EDATE EOMONTH = EOMONTH HOUR = HODINA ISOWEEKNUM = ISOWEEKNUM MINUTE = MINUTA MONTH = MĚSÍC NETWORKDAYS = NETWORKDAYS NETWORKDAYS.INTL = NETWORKDAYS.INTL NOW = NYNÍ SECOND = SEKUNDA TIME = ČAS TIMEVALUE = ČASHODN TODAY = DNES WEEKDAY = DENTÝDNE WEEKNUM = WEEKNUM WORKDAY = WORKDAY WORKDAY.INTL = WORKDAY.INTL YEAR = ROK YEARFRAC = YEARFRAC ## ## Inženýrské funkce (Engineering Functions) ## BESSELI = BESSELI BESSELJ = BESSELJ BESSELK = BESSELK BESSELY = BESSELY BIN2DEC = BIN2DEC BIN2HEX = BIN2HEX BIN2OCT = BIN2OCT BITAND = BITAND BITLSHIFT = BITLSHIFT BITOR = BITOR BITRSHIFT = BITRSHIFT BITXOR = BITXOR COMPLEX = COMPLEX CONVERT = CONVERT DEC2BIN = DEC2BIN DEC2HEX = DEC2HEX DEC2OCT = DEC2OCT DELTA = DELTA ERF = ERF ERF.PRECISE = ERF.PRECISE ERFC = ERFC ERFC.PRECISE = ERFC.PRECISE GESTEP = GESTEP HEX2BIN = HEX2BIN HEX2DEC = HEX2DEC HEX2OCT = HEX2OCT IMABS = IMABS IMAGINARY = IMAGINARY IMARGUMENT = IMARGUMENT IMCONJUGATE = IMCONJUGATE IMCOS = IMCOS IMCOSH = IMCOSH IMCOT = IMCOT IMCSC = IMCSC IMCSCH = IMCSCH IMDIV = IMDIV IMEXP = IMEXP IMLN = IMLN IMLOG10 = IMLOG10 IMLOG2 = IMLOG2 IMPOWER = IMPOWER IMPRODUCT = IMPRODUCT IMREAL = IMREAL IMSEC = IMSEC IMSECH = IMSECH IMSIN = IMSIN IMSINH = IMSINH IMSQRT = IMSQRT IMSUB = IMSUB IMSUM = IMSUM IMTAN = IMTAN OCT2BIN = OCT2BIN OCT2DEC = OCT2DEC OCT2HEX = OCT2HEX ## ## Finanční funkce (Financial Functions) ## ACCRINT = ACCRINT ACCRINTM = ACCRINTM AMORDEGRC = AMORDEGRC AMORLINC = AMORLINC COUPDAYBS = COUPDAYBS COUPDAYS = COUPDAYS COUPDAYSNC = COUPDAYSNC COUPNCD = COUPNCD COUPNUM = COUPNUM COUPPCD = COUPPCD CUMIPMT = CUMIPMT CUMPRINC = CUMPRINC DB = ODPIS.ZRYCH DDB = ODPIS.ZRYCH2 DISC = DISC DOLLARDE = DOLLARDE DOLLARFR = DOLLARFR DURATION = DURATION EFFECT = EFFECT FV = BUDHODNOTA FVSCHEDULE = FVSCHEDULE INTRATE = INTRATE IPMT = PLATBA.ÚROK IRR = MÍRA.VÝNOSNOSTI ISPMT = ISPMT MDURATION = MDURATION MIRR = MOD.MÍRA.VÝNOSNOSTI NOMINAL = NOMINAL NPER = POČET.OBDOBÍ NPV = ČISTÁ.SOUČHODNOTA ODDFPRICE = ODDFPRICE ODDFYIELD = ODDFYIELD ODDLPRICE = ODDLPRICE ODDLYIELD = ODDLYIELD PDURATION = PDURATION PMT = PLATBA PPMT = PLATBA.ZÁKLAD PRICE = PRICE PRICEDISC = PRICEDISC PRICEMAT = PRICEMAT PV = SOUČHODNOTA RATE = ÚROKOVÁ.MÍRA RECEIVED = RECEIVED RRI = RRI SLN = ODPIS.LIN SYD = ODPIS.NELIN TBILLEQ = TBILLEQ TBILLPRICE = TBILLPRICE TBILLYIELD = TBILLYIELD VDB = ODPIS.ZA.INT XIRR = XIRR XNPV = XNPV YIELD = YIELD YIELDDISC = YIELDDISC YIELDMAT = YIELDMAT ## ## Informační funkce (Information Functions) ## CELL = POLÍČKO ERROR.TYPE = CHYBA.TYP INFO = O.PROSTŘEDÍ ISBLANK = JE.PRÁZDNÉ ISERR = JE.CHYBA ISERROR = JE.CHYBHODN ISEVEN = ISEVEN ISFORMULA = ISFORMULA ISLOGICAL = JE.LOGHODN ISNA = JE.NEDEF ISNONTEXT = JE.NETEXT ISNUMBER = JE.ČISLO ISODD = ISODD ISREF = JE.ODKAZ ISTEXT = JE.TEXT N = N NA = NEDEF SHEET = SHEET SHEETS = SHEETS TYPE = TYP ## ## Logické funkce (Logical Functions) ## AND = A FALSE = NEPRAVDA IF = KDYŽ IFERROR = IFERROR IFNA = IFNA IFS = IFS NOT = NE OR = NEBO SWITCH = SWITCH TRUE = PRAVDA XOR = XOR ## ## Vyhledávací funkce a funkce pro odkazy (Lookup & Reference Functions) ## ADDRESS = ODKAZ AREAS = POČET.BLOKŮ CHOOSE = ZVOLIT COLUMN = SLOUPEC COLUMNS = SLOUPCE FORMULATEXT = FORMULATEXT GETPIVOTDATA = ZÍSKATKONTDATA HLOOKUP = VVYHLEDAT HYPERLINK = HYPERTEXTOVÝ.ODKAZ INDEX = INDEX INDIRECT = NEPŘÍMÝ.ODKAZ LOOKUP = VYHLEDAT MATCH = POZVYHLEDAT OFFSET = POSUN ROW = ŘÁDEK ROWS = ŘÁDKY RTD = RTD TRANSPOSE = TRANSPOZICE VLOOKUP = SVYHLEDAT ## ## Matematické a trigonometrické funkce (Math & Trig Functions) ## ABS = ABS ACOS = ARCCOS ACOSH = ARCCOSH ACOT = ACOT ACOTH = ACOTH AGGREGATE = AGGREGATE ARABIC = ARABIC ASIN = ARCSIN ASINH = ARCSINH ATAN = ARCTG ATAN2 = ARCTG2 ATANH = ARCTGH BASE = BASE CEILING.MATH = CEILING.MATH COMBIN = KOMBINACE COMBINA = COMBINA COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMAL DEGREES = DEGREES EVEN = ZAOKROUHLIT.NA.SUDÉ EXP = EXP FACT = FAKTORIÁL FACTDOUBLE = FACTDOUBLE FLOOR.MATH = FLOOR.MATH GCD = GCD INT = CELÁ.ČÁST LCM = LCM LN = LN LOG = LOGZ LOG10 = LOG MDETERM = DETERMINANT MINVERSE = INVERZE MMULT = SOUČIN.MATIC MOD = MOD MROUND = MROUND MULTINOMIAL = MULTINOMIAL MUNIT = MUNIT ODD = ZAOKROUHLIT.NA.LICHÉ PI = PI POWER = POWER PRODUCT = SOUČIN QUOTIENT = QUOTIENT RADIANS = RADIANS RAND = NÁHČÍSLO RANDBETWEEN = RANDBETWEEN ROMAN = ROMAN ROUND = ZAOKROUHLIT ROUNDDOWN = ROUNDDOWN ROUNDUP = ROUNDUP SEC = SEC SECH = SECH SERIESSUM = SERIESSUM SIGN = SIGN SIN = SIN SINH = SINH SQRT = ODMOCNINA SQRTPI = SQRTPI SUBTOTAL = SUBTOTAL SUM = SUMA SUMIF = SUMIF SUMIFS = SUMIFS SUMPRODUCT = SOUČIN.SKALÁRNÍ SUMSQ = SUMA.ČTVERCŮ SUMX2MY2 = SUMX2MY2 SUMX2PY2 = SUMX2PY2 SUMXMY2 = SUMXMY2 TAN = TG TANH = TGH TRUNC = USEKNOUT ## ## Statistické funkce (Statistical Functions) ## AVEDEV = PRŮMODCHYLKA AVERAGE = PRŮMĚR AVERAGEA = AVERAGEA AVERAGEIF = AVERAGEIF AVERAGEIFS = AVERAGEIFS BETA.DIST = BETA.DIST BETA.INV = BETA.INV BINOM.DIST = BINOM.DIST BINOM.DIST.RANGE = BINOM.DIST.RANGE BINOM.INV = BINOM.INV CHISQ.DIST = CHISQ.DIST CHISQ.DIST.RT = CHISQ.DIST.RT CHISQ.INV = CHISQ.INV CHISQ.INV.RT = CHISQ.INV.RT CHISQ.TEST = CHISQ.TEST CONFIDENCE.NORM = CONFIDENCE.NORM CONFIDENCE.T = CONFIDENCE.T CORREL = CORREL COUNT = POČET COUNTA = POČET2 COUNTBLANK = COUNTBLANK COUNTIF = COUNTIF COUNTIFS = COUNTIFS COVARIANCE.P = COVARIANCE.P COVARIANCE.S = COVARIANCE.S DEVSQ = DEVSQ EXPON.DIST = EXPON.DIST F.DIST = F.DIST F.DIST.RT = F.DIST.RT F.INV = F.INV F.INV.RT = F.INV.RT F.TEST = F.TEST FISHER = FISHER FISHERINV = FISHERINV FORECAST.ETS = FORECAST.ETS FORECAST.ETS.CONFINT = FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY = FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT = FORECAST.ETS.STAT FORECAST.LINEAR = FORECAST.LINEAR FREQUENCY = ČETNOSTI GAMMA = GAMMA GAMMA.DIST = GAMMA.DIST GAMMA.INV = GAMMA.INV GAMMALN = GAMMALN GAMMALN.PRECISE = GAMMALN.PRECISE GAUSS = GAUSS GEOMEAN = GEOMEAN GROWTH = LOGLINTREND HARMEAN = HARMEAN HYPGEOM.DIST = HYPGEOM.DIST INTERCEPT = INTERCEPT KURT = KURT LARGE = LARGE LINEST = LINREGRESE LOGEST = LOGLINREGRESE LOGNORM.DIST = LOGNORM.DIST LOGNORM.INV = LOGNORM.INV MAX = MAX MAXA = MAXA MAXIFS = MAXIFS MEDIAN = MEDIAN MIN = MIN MINA = MINA MINIFS = MINIFS MODE.MULT = MODE.MULT MODE.SNGL = MODE.SNGL NEGBINOM.DIST = NEGBINOM.DIST NORM.DIST = NORM.DIST NORM.INV = NORM.INV NORM.S.DIST = NORM.S.DIST NORM.S.INV = NORM.S.INV PEARSON = PEARSON PERCENTILE.EXC = PERCENTIL.EXC PERCENTILE.INC = PERCENTIL.INC PERCENTRANK.EXC = PERCENTRANK.EXC PERCENTRANK.INC = PERCENTRANK.INC PERMUT = PERMUTACE PERMUTATIONA = PERMUTATIONA PHI = PHI POISSON.DIST = POISSON.DIST PROB = PROB QUARTILE.EXC = QUARTIL.EXC QUARTILE.INC = QUARTIL.INC RANK.AVG = RANK.AVG RANK.EQ = RANK.EQ RSQ = RKQ SKEW = SKEW SKEW.P = SKEW.P SLOPE = SLOPE SMALL = SMALL STANDARDIZE = STANDARDIZE STDEV.P = SMODCH.P STDEV.S = SMODCH.VÝBĚR.S STDEVA = STDEVA STDEVPA = STDEVPA STEYX = STEYX T.DIST = T.DIST T.DIST.2T = T.DIST.2T T.DIST.RT = T.DIST.RT T.INV = T.INV T.INV.2T = T.INV.2T T.TEST = T.TEST TREND = LINTREND TRIMMEAN = TRIMMEAN VAR.P = VAR.P VAR.S = VAR.S VARA = VARA VARPA = VARPA WEIBULL.DIST = WEIBULL.DIST Z.TEST = Z.TEST ## ## Textové funkce (Text Functions) ## BAHTTEXT = BAHTTEXT CHAR = ZNAK CLEAN = VYČISTIT CODE = KÓD CONCAT = CONCAT DOLLAR = KČ EXACT = STEJNÉ FIND = NAJÍT FIXED = ZAOKROUHLIT.NA.TEXT LEFT = ZLEVA LEN = DÉLKA LOWER = MALÁ MID = ČÁST NUMBERVALUE = NUMBERVALUE PHONETIC = ZVUKOVÉ PROPER = VELKÁ2 REPLACE = NAHRADIT REPT = OPAKOVAT RIGHT = ZPRAVA SEARCH = HLEDAT SUBSTITUTE = DOSADIT T = T TEXT = HODNOTA.NA.TEXT TEXTJOIN = TEXTJOIN TRIM = PROČISTIT UNICHAR = UNICHAR UNICODE = UNICODE UPPER = VELKÁ VALUE = HODNOTA ## ## Webové funkce (Web Functions) ## ENCODEURL = ENCODEURL FILTERXML = FILTERXML WEBSERVICE = WEBSERVICE ## ## Funkce pro kompatibilitu (Compatibility Functions) ## BETADIST = BETADIST BETAINV = BETAINV BINOMDIST = BINOMDIST CEILING = ZAOKR.NAHORU CHIDIST = CHIDIST CHIINV = CHIINV CHITEST = CHITEST CONCATENATE = CONCATENATE CONFIDENCE = CONFIDENCE COVAR = COVAR CRITBINOM = CRITBINOM EXPONDIST = EXPONDIST FDIST = FDIST FINV = FINV FLOOR = ZAOKR.DOLŮ FORECAST = FORECAST FTEST = FTEST GAMMADIST = GAMMADIST GAMMAINV = GAMMAINV HYPGEOMDIST = HYPGEOMDIST LOGINV = LOGINV LOGNORMDIST = LOGNORMDIST MODE = MODE NEGBINOMDIST = NEGBINOMDIST NORMDIST = NORMDIST NORMINV = NORMINV NORMSDIST = NORMSDIST NORMSINV = NORMSINV PERCENTILE = PERCENTIL PERCENTRANK = PERCENTRANK POISSON = POISSON QUARTILE = QUARTIL RANK = RANK STDEV = SMODCH.VÝBĚR STDEVP = SMODCH TDIST = TDIST TINV = TINV TTEST = TTEST VAR = VAR.VÝBĚR VARP = VAR WEIBULL = WEIBULL ZTEST = ZTEST phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/config 0000644 00000000535 15002227416 0020565 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Ceština (Czech) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL DIV0 = #DĚLENÍ_NULOU! VALUE = #HODNOTA! REF = #ODKAZ! NAME = #NÁZEV? NUM = #ČÍSLO! NA = #NENÍ_K_DISPOZICI phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/functions 0000644 00000025234 15002227416 0021342 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - function name translations ## ## Italiano (Italian) ## ############################################################ ## ## Funzioni cubo (Cube Functions) ## CUBEKPIMEMBER = MEMBRO.KPI.CUBO CUBEMEMBER = MEMBRO.CUBO CUBEMEMBERPROPERTY = PROPRIETÀ.MEMBRO.CUBO CUBERANKEDMEMBER = MEMBRO.CUBO.CON.RANGO CUBESET = SET.CUBO CUBESETCOUNT = CONTA.SET.CUBO CUBEVALUE = VALORE.CUBO ## ## Funzioni di database (Database Functions) ## DAVERAGE = DB.MEDIA DCOUNT = DB.CONTA.NUMERI DCOUNTA = DB.CONTA.VALORI DGET = DB.VALORI DMAX = DB.MAX DMIN = DB.MIN DPRODUCT = DB.PRODOTTO DSTDEV = DB.DEV.ST DSTDEVP = DB.DEV.ST.POP DSUM = DB.SOMMA DVAR = DB.VAR DVARP = DB.VAR.POP ## ## Funzioni data e ora (Date & Time Functions) ## DATE = DATA DATEDIF = DATA.DIFF DATESTRING = DATA.STRINGA DATEVALUE = DATA.VALORE DAY = GIORNO DAYS = GIORNI DAYS360 = GIORNO360 EDATE = DATA.MESE EOMONTH = FINE.MESE HOUR = ORA ISOWEEKNUM = NUM.SETTIMANA.ISO MINUTE = MINUTO MONTH = MESE NETWORKDAYS = GIORNI.LAVORATIVI.TOT NETWORKDAYS.INTL = GIORNI.LAVORATIVI.TOT.INTL NOW = ADESSO SECOND = SECONDO THAIDAYOFWEEK = THAIGIORNODELLASETTIMANA THAIMONTHOFYEAR = THAIMESEDELLANNO THAIYEAR = THAIANNO TIME = ORARIO TIMEVALUE = ORARIO.VALORE TODAY = OGGI WEEKDAY = GIORNO.SETTIMANA WEEKNUM = NUM.SETTIMANA WORKDAY = GIORNO.LAVORATIVO WORKDAY.INTL = GIORNO.LAVORATIVO.INTL YEAR = ANNO YEARFRAC = FRAZIONE.ANNO ## ## Funzioni ingegneristiche (Engineering Functions) ## BESSELI = BESSEL.I BESSELJ = BESSEL.J BESSELK = BESSEL.K BESSELY = BESSEL.Y BIN2DEC = BINARIO.DECIMALE BIN2HEX = BINARIO.HEX BIN2OCT = BINARIO.OCT BITAND = BITAND BITLSHIFT = BIT.SPOSTA.SX BITOR = BITOR BITRSHIFT = BIT.SPOSTA.DX BITXOR = BITXOR COMPLEX = COMPLESSO CONVERT = CONVERTI DEC2BIN = DECIMALE.BINARIO DEC2HEX = DECIMALE.HEX DEC2OCT = DECIMALE.OCT DELTA = DELTA ERF = FUNZ.ERRORE ERF.PRECISE = FUNZ.ERRORE.PRECISA ERFC = FUNZ.ERRORE.COMP ERFC.PRECISE = FUNZ.ERRORE.COMP.PRECISA GESTEP = SOGLIA HEX2BIN = HEX.BINARIO HEX2DEC = HEX.DECIMALE HEX2OCT = HEX.OCT IMABS = COMP.MODULO IMAGINARY = COMP.IMMAGINARIO IMARGUMENT = COMP.ARGOMENTO IMCONJUGATE = COMP.CONIUGATO IMCOS = COMP.COS IMCOSH = COMP.COSH IMCOT = COMP.COT IMCSC = COMP.CSC IMCSCH = COMP.CSCH IMDIV = COMP.DIV IMEXP = COMP.EXP IMLN = COMP.LN IMLOG10 = COMP.LOG10 IMLOG2 = COMP.LOG2 IMPOWER = COMP.POTENZA IMPRODUCT = COMP.PRODOTTO IMREAL = COMP.PARTE.REALE IMSEC = COMP.SEC IMSECH = COMP.SECH IMSIN = COMP.SEN IMSINH = COMP.SENH IMSQRT = COMP.RADQ IMSUB = COMP.DIFF IMSUM = COMP.SOMMA IMTAN = COMP.TAN OCT2BIN = OCT.BINARIO OCT2DEC = OCT.DECIMALE OCT2HEX = OCT.HEX ## ## Funzioni finanziarie (Financial Functions) ## ACCRINT = INT.MATURATO.PER ACCRINTM = INT.MATURATO.SCAD AMORDEGRC = AMMORT.DEGR AMORLINC = AMMORT.PER COUPDAYBS = GIORNI.CED.INIZ.LIQ COUPDAYS = GIORNI.CED COUPDAYSNC = GIORNI.CED.NUOVA COUPNCD = DATA.CED.SUCC COUPNUM = NUM.CED COUPPCD = DATA.CED.PREC CUMIPMT = INT.CUMUL CUMPRINC = CAP.CUM DB = AMMORT.FISSO DDB = AMMORT DISC = TASSO.SCONTO DOLLARDE = VALUTA.DEC DOLLARFR = VALUTA.FRAZ DURATION = DURATA EFFECT = EFFETTIVO FV = VAL.FUT FVSCHEDULE = VAL.FUT.CAPITALE INTRATE = TASSO.INT IPMT = INTERESSI IRR = TIR.COST ISPMT = INTERESSE.RATA MDURATION = DURATA.M MIRR = TIR.VAR NOMINAL = NOMINALE NPER = NUM.RATE NPV = VAN ODDFPRICE = PREZZO.PRIMO.IRR ODDFYIELD = REND.PRIMO.IRR ODDLPRICE = PREZZO.ULTIMO.IRR ODDLYIELD = REND.ULTIMO.IRR PDURATION = DURATA.P PMT = RATA PPMT = P.RATA PRICE = PREZZO PRICEDISC = PREZZO.SCONT PRICEMAT = PREZZO.SCAD PV = VA RATE = TASSO RECEIVED = RICEV.SCAD RRI = RIT.INVEST.EFFETT SLN = AMMORT.COST SYD = AMMORT.ANNUO TBILLEQ = BOT.EQUIV TBILLPRICE = BOT.PREZZO TBILLYIELD = BOT.REND VDB = AMMORT.VAR XIRR = TIR.X XNPV = VAN.X YIELD = REND YIELDDISC = REND.TITOLI.SCONT YIELDMAT = REND.SCAD ## ## Funzioni relative alle informazioni (Information Functions) ## CELL = CELLA ERROR.TYPE = ERRORE.TIPO INFO = AMBIENTE.INFO ISBLANK = VAL.VUOTO ISERR = VAL.ERR ISERROR = VAL.ERRORE ISEVEN = VAL.PARI ISFORMULA = VAL.FORMULA ISLOGICAL = VAL.LOGICO ISNA = VAL.NON.DISP ISNONTEXT = VAL.NON.TESTO ISNUMBER = VAL.NUMERO ISODD = VAL.DISPARI ISREF = VAL.RIF ISTEXT = VAL.TESTO N = NUM NA = NON.DISP SHEET = FOGLIO SHEETS = FOGLI TYPE = TIPO ## ## Funzioni logiche (Logical Functions) ## AND = E FALSE = FALSO IF = SE IFERROR = SE.ERRORE IFNA = SE.NON.DISP. IFS = PIÙ.SE NOT = NON OR = O SWITCH = SWITCH TRUE = VERO XOR = XOR ## ## Funzioni di ricerca e di riferimento (Lookup & Reference Functions) ## ADDRESS = INDIRIZZO AREAS = AREE CHOOSE = SCEGLI COLUMN = RIF.COLONNA COLUMNS = COLONNE FORMULATEXT = TESTO.FORMULA GETPIVOTDATA = INFO.DATI.TAB.PIVOT HLOOKUP = CERCA.ORIZZ HYPERLINK = COLLEG.IPERTESTUALE INDEX = INDICE INDIRECT = INDIRETTO LOOKUP = CERCA MATCH = CONFRONTA OFFSET = SCARTO ROW = RIF.RIGA ROWS = RIGHE RTD = DATITEMPOREALE TRANSPOSE = MATR.TRASPOSTA VLOOKUP = CERCA.VERT ## ## Funzioni matematiche e trigonometriche (Math & Trig Functions) ## ABS = ASS ACOS = ARCCOS ACOSH = ARCCOSH ACOT = ARCCOT ACOTH = ARCCOTH AGGREGATE = AGGREGA ARABIC = ARABO ASIN = ARCSEN ASINH = ARCSENH ATAN = ARCTAN ATAN2 = ARCTAN.2 ATANH = ARCTANH BASE = BASE CEILING.MATH = ARROTONDA.ECCESSO.MAT CEILING.PRECISE = ARROTONDA.ECCESSO.PRECISA COMBIN = COMBINAZIONE COMBINA = COMBINAZIONE.VALORI COS = COS COSH = COSH COT = COT COTH = COTH CSC = CSC CSCH = CSCH DECIMAL = DECIMALE DEGREES = GRADI ECMA.CEILING = ECMA.ARROTONDA.ECCESSO EVEN = PARI EXP = EXP FACT = FATTORIALE FACTDOUBLE = FATT.DOPPIO FLOOR.MATH = ARROTONDA.DIFETTO.MAT FLOOR.PRECISE = ARROTONDA.DIFETTO.PRECISA GCD = MCD INT = INT ISO.CEILING = ISO.ARROTONDA.ECCESSO LCM = MCM LN = LN LOG = LOG LOG10 = LOG10 MDETERM = MATR.DETERM MINVERSE = MATR.INVERSA MMULT = MATR.PRODOTTO MOD = RESTO MROUND = ARROTONDA.MULTIPLO MULTINOMIAL = MULTINOMIALE MUNIT = MATR.UNIT ODD = DISPARI PI = PI.GRECO POWER = POTENZA PRODUCT = PRODOTTO QUOTIENT = QUOZIENTE RADIANS = RADIANTI RAND = CASUALE RANDBETWEEN = CASUALE.TRA ROMAN = ROMANO ROUND = ARROTONDA ROUNDBAHTDOWN = ARROTBAHTGIU ROUNDBAHTUP = ARROTBAHTSU ROUNDDOWN = ARROTONDA.PER.DIF ROUNDUP = ARROTONDA.PER.ECC SEC = SEC SECH = SECH SERIESSUM = SOMMA.SERIE SIGN = SEGNO SIN = SEN SINH = SENH SQRT = RADQ SQRTPI = RADQ.PI.GRECO SUBTOTAL = SUBTOTALE SUM = SOMMA SUMIF = SOMMA.SE SUMIFS = SOMMA.PIÙ.SE SUMPRODUCT = MATR.SOMMA.PRODOTTO SUMSQ = SOMMA.Q SUMX2MY2 = SOMMA.DIFF.Q SUMX2PY2 = SOMMA.SOMMA.Q SUMXMY2 = SOMMA.Q.DIFF TAN = TAN TANH = TANH TRUNC = TRONCA ## ## Funzioni statistiche (Statistical Functions) ## AVEDEV = MEDIA.DEV AVERAGE = MEDIA AVERAGEA = MEDIA.VALORI AVERAGEIF = MEDIA.SE AVERAGEIFS = MEDIA.PIÙ.SE BETA.DIST = DISTRIB.BETA.N BETA.INV = INV.BETA.N BINOM.DIST = DISTRIB.BINOM.N BINOM.DIST.RANGE = INTERVALLO.DISTRIB.BINOM.N. BINOM.INV = INV.BINOM CHISQ.DIST = DISTRIB.CHI.QUAD CHISQ.DIST.RT = DISTRIB.CHI.QUAD.DS CHISQ.INV = INV.CHI.QUAD CHISQ.INV.RT = INV.CHI.QUAD.DS CHISQ.TEST = TEST.CHI.QUAD CONFIDENCE.NORM = CONFIDENZA.NORM CONFIDENCE.T = CONFIDENZA.T CORREL = CORRELAZIONE COUNT = CONTA.NUMERI COUNTA = CONTA.VALORI COUNTBLANK = CONTA.VUOTE COUNTIF = CONTA.SE COUNTIFS = CONTA.PIÙ.SE COVARIANCE.P = COVARIANZA.P COVARIANCE.S = COVARIANZA.C DEVSQ = DEV.Q EXPON.DIST = DISTRIB.EXP.N F.DIST = DISTRIBF F.DIST.RT = DISTRIB.F.DS F.INV = INVF F.INV.RT = INV.F.DS F.TEST = TESTF FISHER = FISHER FISHERINV = INV.FISHER FORECAST.ETS = PREVISIONE.ETS FORECAST.ETS.CONFINT = PREVISIONE.ETS.INTCONF FORECAST.ETS.SEASONALITY = PREVISIONE.ETS.STAGIONALITÀ FORECAST.ETS.STAT = PREVISIONE.ETS.STAT FORECAST.LINEAR = PREVISIONE.LINEARE FREQUENCY = FREQUENZA GAMMA = GAMMA GAMMA.DIST = DISTRIB.GAMMA.N GAMMA.INV = INV.GAMMA.N GAMMALN = LN.GAMMA GAMMALN.PRECISE = LN.GAMMA.PRECISA GAUSS = GAUSS GEOMEAN = MEDIA.GEOMETRICA GROWTH = CRESCITA HARMEAN = MEDIA.ARMONICA HYPGEOM.DIST = DISTRIB.IPERGEOM.N INTERCEPT = INTERCETTA KURT = CURTOSI LARGE = GRANDE LINEST = REGR.LIN LOGEST = REGR.LOG LOGNORM.DIST = DISTRIB.LOGNORM.N LOGNORM.INV = INV.LOGNORM.N MAX = MAX MAXA = MAX.VALORI MAXIFS = MAX.PIÙ.SE MEDIAN = MEDIANA MIN = MIN MINA = MIN.VALORI MINIFS = MIN.PIÙ.SE MODE.MULT = MODA.MULT MODE.SNGL = MODA.SNGL NEGBINOM.DIST = DISTRIB.BINOM.NEG.N NORM.DIST = DISTRIB.NORM.N NORM.INV = INV.NORM.N NORM.S.DIST = DISTRIB.NORM.ST.N NORM.S.INV = INV.NORM.S PEARSON = PEARSON PERCENTILE.EXC = ESC.PERCENTILE PERCENTILE.INC = INC.PERCENTILE PERCENTRANK.EXC = ESC.PERCENT.RANGO PERCENTRANK.INC = INC.PERCENT.RANGO PERMUT = PERMUTAZIONE PERMUTATIONA = PERMUTAZIONE.VALORI PHI = PHI POISSON.DIST = DISTRIB.POISSON PROB = PROBABILITÀ QUARTILE.EXC = ESC.QUARTILE QUARTILE.INC = INC.QUARTILE RANK.AVG = RANGO.MEDIA RANK.EQ = RANGO.UG RSQ = RQ SKEW = ASIMMETRIA SKEW.P = ASIMMETRIA.P SLOPE = PENDENZA SMALL = PICCOLO STANDARDIZE = NORMALIZZA STDEV.P = DEV.ST.P STDEV.S = DEV.ST.C STDEVA = DEV.ST.VALORI STDEVPA = DEV.ST.POP.VALORI STEYX = ERR.STD.YX T.DIST = DISTRIB.T.N T.DIST.2T = DISTRIB.T.2T T.DIST.RT = DISTRIB.T.DS T.INV = INVT T.INV.2T = INV.T.2T T.TEST = TESTT TREND = TENDENZA TRIMMEAN = MEDIA.TRONCATA VAR.P = VAR.P VAR.S = VAR.C VARA = VAR.VALORI VARPA = VAR.POP.VALORI WEIBULL.DIST = DISTRIB.WEIBULL Z.TEST = TESTZ ## ## Funzioni di testo (Text Functions) ## BAHTTEXT = BAHTTESTO CHAR = CODICE.CARATT CLEAN = LIBERA CODE = CODICE CONCAT = CONCAT DOLLAR = VALUTA EXACT = IDENTICO FIND = TROVA FIXED = FISSO ISTHAIDIGIT = ÈTHAICIFRA LEFT = SINISTRA LEN = LUNGHEZZA LOWER = MINUSC MID = STRINGA.ESTRAI NUMBERSTRING = NUMERO.STRINGA NUMBERVALUE = NUMERO.VALORE PHONETIC = FURIGANA PROPER = MAIUSC.INIZ REPLACE = RIMPIAZZA REPT = RIPETI RIGHT = DESTRA SEARCH = RICERCA SUBSTITUTE = SOSTITUISCI T = T TEXT = TESTO TEXTJOIN = TESTO.UNISCI THAIDIGIT = THAICIFRA THAINUMSOUND = THAINUMSUONO THAINUMSTRING = THAISZÁMKAR THAISTRINGLENGTH = THAILUNGSTRINGA TRIM = ANNULLA.SPAZI UNICHAR = CARATT.UNI UNICODE = UNICODE UPPER = MAIUSC VALUE = VALORE ## ## Funzioni Web (Web Functions) ## ENCODEURL = CODIFICA.URL FILTERXML = FILTRO.XML WEBSERVICE = SERVIZIO.WEB ## ## Funzioni di compatibilità (Compatibility Functions) ## BETADIST = DISTRIB.BETA BETAINV = INV.BETA BINOMDIST = DISTRIB.BINOM CEILING = ARROTONDA.ECCESSO CHIDIST = DISTRIB.CHI CHIINV = INV.CHI CHITEST = TEST.CHI CONCATENATE = CONCATENA CONFIDENCE = CONFIDENZA COVAR = COVARIANZA CRITBINOM = CRIT.BINOM EXPONDIST = DISTRIB.EXP FDIST = DISTRIB.F FINV = INV.F FLOOR = ARROTONDA.DIFETTO FORECAST = PREVISIONE FTEST = TEST.F GAMMADIST = DISTRIB.GAMMA GAMMAINV = INV.GAMMA HYPGEOMDIST = DISTRIB.IPERGEOM LOGINV = INV.LOGNORM LOGNORMDIST = DISTRIB.LOGNORM MODE = MODA NEGBINOMDIST = DISTRIB.BINOM.NEG NORMDIST = DISTRIB.NORM NORMINV = INV.NORM NORMSDIST = DISTRIB.NORM.ST NORMSINV = INV.NORM.ST PERCENTILE = PERCENTILE PERCENTRANK = PERCENT.RANGO POISSON = POISSON QUARTILE = QUARTILE RANK = RANGO STDEV = DEV.ST STDEVP = DEV.ST.POP TDIST = DISTRIB.T TINV = INV.T TTEST = TEST.T VAR = VAR VARP = VAR.POP WEIBULL = WEIBULL ZTEST = TEST.Z phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/config 0000644 00000000455 15002227416 0020575 0 ustar 00 ############################################################ ## ## PhpSpreadsheet - locale settings ## ## Italiano (Italian) ## ############################################################ ArgumentSeparator = ; ## ## Error Codes ## NULL DIV0 VALUE = #VALORE! REF = #RIF! NAME = #NOME? NUM NA = #N/D phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/en/uk/config 0000644 00000000107 15002227416 0021174 0 ustar 00 ## ## PhpSpreadsheet ## ## ## (For future use) ## currencySymbol = £ phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/Translations.xlsx 0000644 00000324313 15002227416 0022374 0 ustar 00 PK ! ����� � [Content_Types].xml �(� Ėˎ�@E������gQٞ�L�LF�����i�~�����`,'� �Hـ��{n�����ޖ�"�f�!�����q�����=�"$�rUz3q O��� �p�Ù(��W)Q`f>��/K�"~�+�^�������8J����,զ��۞_7NƉ�W�fB�P���ʭ���~�4r�7��3T� �2�01�'�B^dF(q�UƑ�1,L�O���ܓǿD��� *�u���O^�hrH^U�����})w>�ޯ��"C�^��*�ډ�����o#���x�O>��z�T�2�#J�����"*B�F|LW�8��𡽭����Z�<Uт��h���}lYLa����؞�v�ػ}������?�P6���j"�� ,�ml(I�:(��1�ik��L�0�{��s]`�Br�}�> ��ëH�K��4�D2pꦗ�Ɖ�w��z��� e� ��w��pY�i� �� PK ! ��, t _rels/.rels �(� ���N�0�;�徦Bh�.i7��x��Um�(�`{{��`�FAbǶ�:?��d���x�r�,�\ t�L��R�,GwRDg�#���b������;��S\5>�T��R����RQ��B�ȣK_* 8=�Zy�-Ԩ�y~��q 9��sS�07WR,�>�����"��)�ȇ$ܤ^�B�\JC�)���D��R�� �F�Tq��*��F��,�~�� ��at��3�փ;vl�^"�������>d���Xħ���юF�]�C��sZ�:2�_6�����I�oϠF����ݕ�; �� PK ! vn�h t xl/workbook.xml�Vmo�:�>���Ӽ�����R����~A��c�&qf;�j��qBh)W�ر������?o��x�B2^E�9��A+�3V=F��Ej��!�2\�F�J�y�ϧ� O+Ο �d�r��в$�i���i�5%V����ř�)Uea��X%f�Bq _�� 'MI+ՁZ`�˜ղG+�)p%OMm^� �bS/-(2J^>V\�Uno�� ��sl�&]U2"��ku�Vg�m9�A��18 ɳ}f:�{�D�A��=V� ���� �Z�����{�\49_���u�5p]ť�T��K5˘�Y����z�!�:nXR��cdM�t�#�k�jD��2�`�Z�qQ(**��W x���o9�bOs7n� ��_a�$�+9�*7QDh.�G�������4��}-������JfYp��|�e|\8�fLt�,�Q�G��>^�{�Ε0�2�����g�!0%ە�%$�<TD��Ïx4� ��t{��N3����y~<K�a��?����F�;zh�y��#�5��������}L=�z�O�n�w�n�+����*�C�/�j87��e*�� :m������u�� �nt���x4F&�=�^�����FG�ؤ36����c�7ֶ��ng�j+h�%�0�43�l;+�t�ֹ�!B}�����ɴ��D��o� �s[��7�-�NOm�ǎ�U$ݪ+�&�0�x����]H����3��8<�Oҁ?t���Ou��)�j����jOS��A]~�:�c���o���]��%�I���ӿS��nAOTN�NT�~�^\��{5[<ܧ�*_\���N���X�8(�>�V��a� �� PK ! �� � xl/_rels/workbook.xml.rels �(� ���N�0E�H���=q� T���-����C��G��Q �J��Xε|����z�i:�[g%ϒ�3�ڕ��%�=]�s�Q�Ru�= ���g�T�Oش�X����?���0q,�T.���J�U "Oӕ�=x1�d�R�-�9��:��vU�jxt�̀�GZ�H\@�*�%�Q���8C~N��� ĉ� �^�%��a�Y�cZ�*&�1��݉,��]xZ>g�0����$nϙ6*@�m>N43y ��0������C��^�n�� �� PK ! {-ؼ' �/ xl/worksheets/sheet1.xml��]o�0��'�?D�'���DZ1Z�I����k�85�3��i�}ljMؘ&\�@��|�ǰ�=֕��DW�&E��Ú��e�Mї���9��MN+ް���}�8p�����.E;)۹�uَմsy��RpQS ���Z�h�o�+��~�մl�@��k�(ʌ��l_�F�**!�nW����x�����s��p����E|u� ��B���!��,/�#�:�&њ��};p�mʪ�/}�ȩ���m��TБ#i�< ����饧�C�ىtYɫ08�{.��Fy]���"#,x%,:�T��|_�)�y��A�It/'�2�M�Ux?yG����:��_�f���=��#X��%�/�8D�͢�ג�3�Q���I]� �|`��a��SmMd�M�G�#+�UU�V!rh&�g� ;R��R���d?��+����?���)~� �o��a�>���� �86.!�L��_�Σ��ީ綩ͺ?�����+���JΡ�W�����2v(�(����N]�C&���P�r��!��L��a�\�*�}پ��}�wi�@��X5e�N�a4��g@�=Vø�?x��j� n�%i����k����,��(��g���@��uD�q��EK0�֠04'�%��Ed��G$��S@{%��e���2L�S{Ec�e���]��(`�e������2��l1��(A���5I�M/e�V�Ĝ6��B\�'6�$F��[c}h�Ze�R�=����2��؇c���;�vsO�l�1B��|��u� �� �����n�8�_���%K��� [>��Y>�� �iS�����/�,b���b�������QZ篏�/����z~����;�����Y��s3���t������r��?<�>��o�x>=~yw�Si�]ڸ���g��χ�����j���tlN&�I�DRd��" ��٤f�R_ y^�|�&������39#)J��{SMl��ii*Z��r! ʃ(3�0,%DY��!XJ�Ʊ���MR1�]��qڈ�S�� �M�`+Z��;�����!|:�����籺���]�4?� :� ��2��H��]��H�l�.sX�$��&�2��C��e$�`i,�Ny�i"ZB O�8E��\��<�Ù�v7,%>:�B��/��'!�&�B���IקY�qwAa��!h�-���Db�����+aw�B!���y\a���3��az���ѱIQ�F��$����&K_t1�$� P C��$d�Xڝb7�I��g7����O��n&YJ�`)�!�Q�n ���\�$� ���@ ��.l��Ȃ�h !؉�k��T�/�ί�y� �Ǖˁ� w����c?��x�� ݧ���ňgO"%H��i�B��F.��)w!�]H�҅�r!�]H�i�B:��Ҵ�e$p�n�ݶ�w���7����� [��T6ܻ���N_�����I�8�:�T����3�,��� 0Ob�虣��Ƿ�)`�I9`�FK�8bV�qn�oÛ۞&�?nC�`��[+`(��������'�K2r9����@R>��hR%�9X� C�`H>