diff --git a/lib/phpspreadsheet/vendor/autoload.php b/lib/phpspreadsheet/vendor/autoload.php
index ae97c5a8ef9..afaa78f0390 100644
--- a/lib/phpspreadsheet/vendor/autoload.php
+++ b/lib/phpspreadsheet/vendor/autoload.php
@@ -4,4 +4,4 @@
require_once __DIR__ . '/composer/autoload_real.php';
-return ComposerAutoloaderInit596026141085fc6d905fff9fde42dc1b::getLoader();
+return ComposerAutoloaderInit47a82a2b792e78d18b5f54d474d822dc::getLoader();
diff --git a/lib/phpspreadsheet/vendor/composer/ClassLoader.php b/lib/phpspreadsheet/vendor/composer/ClassLoader.php
index 1a58957d25d..afef3fa2ad8 100644
--- a/lib/phpspreadsheet/vendor/composer/ClassLoader.php
+++ b/lib/phpspreadsheet/vendor/composer/ClassLoader.php
@@ -42,21 +42,75 @@ namespace Composer\Autoload;
*/
class ClassLoader
{
+ /** @var ?string */
+ private $vendorDir;
+
// PSR-4
+ /**
+ * @var array[]
+ * @psalm-var array>
+ */
private $prefixLengthsPsr4 = array();
+ /**
+ * @var array[]
+ * @psalm-var array>
+ */
private $prefixDirsPsr4 = array();
+ /**
+ * @var array[]
+ * @psalm-var array
+ */
private $fallbackDirsPsr4 = array();
// PSR-0
+ /**
+ * @var array[]
+ * @psalm-var array>
+ */
private $prefixesPsr0 = array();
+ /**
+ * @var array[]
+ * @psalm-var array
+ */
private $fallbackDirsPsr0 = array();
+ /** @var bool */
private $useIncludePath = false;
+
+ /**
+ * @var string[]
+ * @psalm-var array
+ */
private $classMap = array();
+
+ /** @var bool */
private $classMapAuthoritative = false;
+
+ /**
+ * @var bool[]
+ * @psalm-var array
+ */
private $missingClasses = array();
+
+ /** @var ?string */
private $apcuPrefix;
+ /**
+ * @var self[]
+ */
+ private static $registeredLoaders = array();
+
+ /**
+ * @param ?string $vendorDir
+ */
+ public function __construct($vendorDir = null)
+ {
+ $this->vendorDir = $vendorDir;
+ }
+
+ /**
+ * @return string[]
+ */
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
@@ -66,28 +120,47 @@ class ClassLoader
return array();
}
+ /**
+ * @return array[]
+ * @psalm-return array>
+ */
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
+ /**
+ * @return array[]
+ * @psalm-return array
+ */
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
+ /**
+ * @return array[]
+ * @psalm-return array
+ */
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
+ /**
+ * @return string[] Array of classname => path
+ * @psalm-return array
+ */
public function getClassMap()
{
return $this->classMap;
}
/**
- * @param array $classMap Class to filename map
+ * @param string[] $classMap Class to filename map
+ * @psalm-param array $classMap
+ *
+ * @return void
*/
public function addClassMap(array $classMap)
{
@@ -102,9 +175,11 @@ class ClassLoader
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
- * @param string $prefix The prefix
- * @param array|string $paths The PSR-0 root directories
- * @param bool $prepend Whether to prepend the directories
+ * @param string $prefix The prefix
+ * @param string[]|string $paths The PSR-0 root directories
+ * @param bool $prepend Whether to prepend the directories
+ *
+ * @return void
*/
public function add($prefix, $paths, $prepend = false)
{
@@ -147,11 +222,13 @@ class ClassLoader
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
- * @param string $prefix The prefix/namespace, with trailing '\\'
- * @param array|string $paths The PSR-4 base directories
- * @param bool $prepend Whether to prepend the directories
+ * @param string $prefix The prefix/namespace, with trailing '\\'
+ * @param string[]|string $paths The PSR-4 base directories
+ * @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
+ *
+ * @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
@@ -195,8 +272,10 @@ class ClassLoader
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
- * @param string $prefix The prefix
- * @param array|string $paths The PSR-0 base directories
+ * @param string $prefix The prefix
+ * @param string[]|string $paths The PSR-0 base directories
+ *
+ * @return void
*/
public function set($prefix, $paths)
{
@@ -211,10 +290,12 @@ class ClassLoader
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
- * @param string $prefix The prefix/namespace, with trailing '\\'
- * @param array|string $paths The PSR-4 base directories
+ * @param string $prefix The prefix/namespace, with trailing '\\'
+ * @param string[]|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
+ *
+ * @return void
*/
public function setPsr4($prefix, $paths)
{
@@ -234,6 +315,8 @@ class ClassLoader
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
+ *
+ * @return void
*/
public function setUseIncludePath($useIncludePath)
{
@@ -256,6 +339,8 @@ class ClassLoader
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
+ *
+ * @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
@@ -276,6 +361,8 @@ class ClassLoader
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
+ *
+ * @return void
*/
public function setApcuPrefix($apcuPrefix)
{
@@ -296,25 +383,44 @@ class ClassLoader
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
+ *
+ * @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
+
+ if (null === $this->vendorDir) {
+ return;
+ }
+
+ if ($prepend) {
+ self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
+ } else {
+ unset(self::$registeredLoaders[$this->vendorDir]);
+ self::$registeredLoaders[$this->vendorDir] = $this;
+ }
}
/**
* Unregisters this instance as an autoloader.
+ *
+ * @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
+
+ if (null !== $this->vendorDir) {
+ unset(self::$registeredLoaders[$this->vendorDir]);
+ }
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
- * @return bool|null True if loaded, null otherwise
+ * @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
@@ -323,6 +429,8 @@ class ClassLoader
return true;
}
+
+ return null;
}
/**
@@ -367,6 +475,21 @@ class ClassLoader
return $file;
}
+ /**
+ * Returns the currently registered loaders indexed by their corresponding vendor directories.
+ *
+ * @return self[]
+ */
+ public static function getRegisteredLoaders()
+ {
+ return self::$registeredLoaders;
+ }
+
+ /**
+ * @param string $class
+ * @param string $ext
+ * @return string|false
+ */
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
@@ -438,6 +561,10 @@ class ClassLoader
* Scope isolated include.
*
* Prevents access to $this/self from included files.
+ *
+ * @param string $file
+ * @return void
+ * @private
*/
function includeFile($file)
{
diff --git a/lib/phpspreadsheet/vendor/composer/InstalledVersions.php b/lib/phpspreadsheet/vendor/composer/InstalledVersions.php
index fe344fe10ce..d50e0c9fcc4 100644
--- a/lib/phpspreadsheet/vendor/composer/InstalledVersions.php
+++ b/lib/phpspreadsheet/vendor/composer/InstalledVersions.php
@@ -1,318 +1,350 @@
+ * Jordi Boggiano
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
namespace Composer;
+use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
-
-
-
-
-
+/**
+ * This class is copied in every Composer installed project and available to all
+ *
+ * See also https://getcomposer.org/doc/07-runtime.md#installed-versions
+ *
+ * To require its presence, you can require `composer-runtime-api ^2.0`
+ */
class InstalledVersions
{
-private static $installed = array (
- 'root' =>
- array (
- 'pretty_version' => 'dev-master',
- 'version' => 'dev-master',
- 'aliases' =>
- array (
- ),
- 'reference' => '70d1b7d67bc280b21f450db41728869bd1bda8d8',
- 'name' => '__root__',
- ),
- 'versions' =>
- array (
- '__root__' =>
- array (
- 'pretty_version' => 'dev-master',
- 'version' => 'dev-master',
- 'aliases' =>
- array (
- ),
- 'reference' => '70d1b7d67bc280b21f450db41728869bd1bda8d8',
- ),
- 'ezyang/htmlpurifier' =>
- array (
- 'pretty_version' => 'v4.13.0',
- 'version' => '4.13.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '08e27c97e4c6ed02f37c5b2b20488046c8d90d75',
- ),
- 'maennchen/zipstream-php' =>
- array (
- 'pretty_version' => '2.1.0',
- 'version' => '2.1.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => 'c4c5803cc1f93df3d2448478ef79394a5981cc58',
- ),
- 'markbaker/complex' =>
- array (
- 'pretty_version' => '2.0.0',
- 'version' => '2.0.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '9999f1432fae467bc93c53f357105b4c31bb994c',
- ),
- 'markbaker/matrix' =>
- array (
- 'pretty_version' => '2.0.0',
- 'version' => '2.0.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '9567d9c4c519fbe40de01dbd1e4469dbbb66f46a',
- ),
- 'myclabs/php-enum' =>
- array (
- 'pretty_version' => '1.7.7',
- 'version' => '1.7.7.0',
- 'aliases' =>
- array (
- ),
- 'reference' => 'd178027d1e679832db9f38248fcc7200647dc2b7',
- ),
- 'phpoffice/phpspreadsheet' =>
- array (
- 'pretty_version' => '1.16.0',
- 'version' => '1.16.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '76d4323b85129d0c368149c831a07a3e258b2b50',
- ),
- 'psr/http-client' =>
- array (
- 'pretty_version' => '1.0.1',
- 'version' => '1.0.1.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '2dfb5f6c5eff0e91e20e913f8c5452ed95b86621',
- ),
- 'psr/http-factory' =>
- array (
- 'pretty_version' => '1.0.1',
- 'version' => '1.0.1.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '12ac7fcd07e5b077433f5f2bee95b3a771bf61be',
- ),
- 'psr/http-message' =>
- array (
- 'pretty_version' => '1.0.1',
- 'version' => '1.0.1.0',
- 'aliases' =>
- array (
- ),
- 'reference' => 'f6561bf28d520154e4b0ec72be95418abe6d9363',
- ),
- 'psr/simple-cache' =>
- array (
- 'pretty_version' => '1.0.1',
- 'version' => '1.0.1.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '408d5eafb83c57f6365a3ca330ff23aa4a5fa39b',
- ),
- 'symfony/polyfill-mbstring' =>
- array (
- 'pretty_version' => 'v1.22.0',
- 'version' => '1.22.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => 'f377a3dd1fde44d37b9831d68dc8dea3ffd28e13',
- ),
- ),
-);
+ /**
+ * @var mixed[]|null
+ * @psalm-var array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array}|array{}|null
+ */
+ private static $installed;
+ /**
+ * @var bool|null
+ */
+ private static $canGetVendors;
+ /**
+ * @var array[]
+ * @psalm-var array}>
+ */
+ private static $installedByVendor = array();
+ /**
+ * Returns a list of all package names which are present, either by being installed, replaced or provided
+ *
+ * @return string[]
+ * @psalm-return list
+ */
+ public static function getInstalledPackages()
+ {
+ $packages = array();
+ foreach (self::getInstalled() as $installed) {
+ $packages[] = array_keys($installed['versions']);
+ }
+ if (1 === \count($packages)) {
+ return $packages[0];
+ }
+ return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
+ }
+ /**
+ * Returns a list of all package names with a specific type e.g. 'library'
+ *
+ * @param string $type
+ * @return string[]
+ * @psalm-return list
+ */
+ public static function getInstalledPackagesByType($type)
+ {
+ $packagesByType = array();
-public static function getInstalledPackages()
-{
-return array_keys(self::$installed['versions']);
-}
-
-
-
-
-
-
-
-
-
-public static function isInstalled($packageName)
-{
-return isset(self::$installed['versions'][$packageName]);
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-public static function satisfies(VersionParser $parser, $packageName, $constraint)
-{
-$constraint = $parser->parseConstraints($constraint);
-$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
-
-return $provided->matches($constraint);
-}
-
-
-
-
-
-
-
-
-
-
-public static function getVersionRanges($packageName)
-{
-if (!isset(self::$installed['versions'][$packageName])) {
-throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
-}
-
-$ranges = array();
-if (isset(self::$installed['versions'][$packageName]['pretty_version'])) {
-$ranges[] = self::$installed['versions'][$packageName]['pretty_version'];
-}
-if (array_key_exists('aliases', self::$installed['versions'][$packageName])) {
-$ranges = array_merge($ranges, self::$installed['versions'][$packageName]['aliases']);
-}
-if (array_key_exists('replaced', self::$installed['versions'][$packageName])) {
-$ranges = array_merge($ranges, self::$installed['versions'][$packageName]['replaced']);
-}
-if (array_key_exists('provided', self::$installed['versions'][$packageName])) {
-$ranges = array_merge($ranges, self::$installed['versions'][$packageName]['provided']);
-}
-
-return implode(' || ', $ranges);
-}
-
-
-
-
-
-public static function getVersion($packageName)
-{
-if (!isset(self::$installed['versions'][$packageName])) {
-throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
-}
-
-if (!isset(self::$installed['versions'][$packageName]['version'])) {
-return null;
-}
-
-return self::$installed['versions'][$packageName]['version'];
-}
-
-
-
-
-
-public static function getPrettyVersion($packageName)
-{
-if (!isset(self::$installed['versions'][$packageName])) {
-throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
-}
-
-if (!isset(self::$installed['versions'][$packageName]['pretty_version'])) {
-return null;
-}
-
-return self::$installed['versions'][$packageName]['pretty_version'];
-}
-
-
-
-
-
-public static function getReference($packageName)
-{
-if (!isset(self::$installed['versions'][$packageName])) {
-throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
-}
-
-if (!isset(self::$installed['versions'][$packageName]['reference'])) {
-return null;
-}
-
-return self::$installed['versions'][$packageName]['reference'];
-}
-
-
-
-
-
-public static function getRootPackage()
-{
-return self::$installed['root'];
-}
-
-
-
-
-
-
-
-public static function getRawData()
-{
-return self::$installed;
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-public static function reload($data)
-{
-self::$installed = $data;
-}
+ foreach (self::getInstalled() as $installed) {
+ foreach ($installed['versions'] as $name => $package) {
+ if (isset($package['type']) && $package['type'] === $type) {
+ $packagesByType[] = $name;
+ }
+ }
+ }
+
+ return $packagesByType;
+ }
+
+ /**
+ * Checks whether the given package is installed
+ *
+ * This also returns true if the package name is provided or replaced by another package
+ *
+ * @param string $packageName
+ * @param bool $includeDevRequirements
+ * @return bool
+ */
+ public static function isInstalled($packageName, $includeDevRequirements = true)
+ {
+ foreach (self::getInstalled() as $installed) {
+ if (isset($installed['versions'][$packageName])) {
+ return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']);
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Checks whether the given package satisfies a version constraint
+ *
+ * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
+ *
+ * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
+ *
+ * @param VersionParser $parser Install composer/semver to have access to this class and functionality
+ * @param string $packageName
+ * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
+ * @return bool
+ */
+ public static function satisfies(VersionParser $parser, $packageName, $constraint)
+ {
+ $constraint = $parser->parseConstraints($constraint);
+ $provided = $parser->parseConstraints(self::getVersionRanges($packageName));
+
+ return $provided->matches($constraint);
+ }
+
+ /**
+ * Returns a version constraint representing all the range(s) which are installed for a given package
+ *
+ * It is easier to use this via isInstalled() with the $constraint argument if you need to check
+ * whether a given version of a package is installed, and not just whether it exists
+ *
+ * @param string $packageName
+ * @return string Version constraint usable with composer/semver
+ */
+ public static function getVersionRanges($packageName)
+ {
+ foreach (self::getInstalled() as $installed) {
+ if (!isset($installed['versions'][$packageName])) {
+ continue;
+ }
+
+ $ranges = array();
+ if (isset($installed['versions'][$packageName]['pretty_version'])) {
+ $ranges[] = $installed['versions'][$packageName]['pretty_version'];
+ }
+ if (array_key_exists('aliases', $installed['versions'][$packageName])) {
+ $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
+ }
+ if (array_key_exists('replaced', $installed['versions'][$packageName])) {
+ $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
+ }
+ if (array_key_exists('provided', $installed['versions'][$packageName])) {
+ $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
+ }
+
+ return implode(' || ', $ranges);
+ }
+
+ throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
+ }
+
+ /**
+ * @param string $packageName
+ * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
+ */
+ public static function getVersion($packageName)
+ {
+ foreach (self::getInstalled() as $installed) {
+ if (!isset($installed['versions'][$packageName])) {
+ continue;
+ }
+
+ if (!isset($installed['versions'][$packageName]['version'])) {
+ return null;
+ }
+
+ return $installed['versions'][$packageName]['version'];
+ }
+
+ throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
+ }
+
+ /**
+ * @param string $packageName
+ * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
+ */
+ public static function getPrettyVersion($packageName)
+ {
+ foreach (self::getInstalled() as $installed) {
+ if (!isset($installed['versions'][$packageName])) {
+ continue;
+ }
+
+ if (!isset($installed['versions'][$packageName]['pretty_version'])) {
+ return null;
+ }
+
+ return $installed['versions'][$packageName]['pretty_version'];
+ }
+
+ throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
+ }
+
+ /**
+ * @param string $packageName
+ * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
+ */
+ public static function getReference($packageName)
+ {
+ foreach (self::getInstalled() as $installed) {
+ if (!isset($installed['versions'][$packageName])) {
+ continue;
+ }
+
+ if (!isset($installed['versions'][$packageName]['reference'])) {
+ return null;
+ }
+
+ return $installed['versions'][$packageName]['reference'];
+ }
+
+ throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
+ }
+
+ /**
+ * @param string $packageName
+ * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
+ */
+ public static function getInstallPath($packageName)
+ {
+ foreach (self::getInstalled() as $installed) {
+ if (!isset($installed['versions'][$packageName])) {
+ continue;
+ }
+
+ return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
+ }
+
+ throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
+ }
+
+ /**
+ * @return array
+ * @psalm-return array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}
+ */
+ public static function getRootPackage()
+ {
+ $installed = self::getInstalled();
+
+ return $installed[0]['root'];
+ }
+
+ /**
+ * Returns the raw installed.php data for custom implementations
+ *
+ * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
+ * @return array[]
+ * @psalm-return array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array}
+ */
+ public static function getRawData()
+ {
+ @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
+
+ if (null === self::$installed) {
+ // only require the installed.php file if this file is loaded from its dumped location,
+ // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
+ if (substr(__DIR__, -8, 1) !== 'C') {
+ self::$installed = include __DIR__ . '/installed.php';
+ } else {
+ self::$installed = array();
+ }
+ }
+
+ return self::$installed;
+ }
+
+ /**
+ * Returns the raw data of all installed.php which are currently loaded for custom implementations
+ *
+ * @return array[]
+ * @psalm-return list}>
+ */
+ public static function getAllRawData()
+ {
+ return self::getInstalled();
+ }
+
+ /**
+ * Lets you reload the static array from another file
+ *
+ * This is only useful for complex integrations in which a project needs to use
+ * this class but then also needs to execute another project's autoloader in process,
+ * and wants to ensure both projects have access to their version of installed.php.
+ *
+ * A typical case would be PHPUnit, where it would need to make sure it reads all
+ * the data it needs from this class, then call reload() with
+ * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
+ * the project in which it runs can then also use this class safely, without
+ * interference between PHPUnit's dependencies and the project's dependencies.
+ *
+ * @param array[] $data A vendor/composer/installed.php data set
+ * @return void
+ *
+ * @psalm-param array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array} $data
+ */
+ public static function reload($data)
+ {
+ self::$installed = $data;
+ self::$installedByVendor = array();
+ }
+
+ /**
+ * @return array[]
+ * @psalm-return list}>
+ */
+ private static function getInstalled()
+ {
+ if (null === self::$canGetVendors) {
+ self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
+ }
+
+ $installed = array();
+
+ if (self::$canGetVendors) {
+ foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
+ if (isset(self::$installedByVendor[$vendorDir])) {
+ $installed[] = self::$installedByVendor[$vendorDir];
+ } elseif (is_file($vendorDir.'/composer/installed.php')) {
+ $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
+ if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
+ self::$installed = $installed[count($installed) - 1];
+ }
+ }
+ }
+ }
+
+ if (null === self::$installed) {
+ // only require the installed.php file if this file is loaded from its dumped location,
+ // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
+ if (substr(__DIR__, -8, 1) !== 'C') {
+ self::$installed = require __DIR__ . '/installed.php';
+ } else {
+ self::$installed = array();
+ }
+ }
+ $installed[] = self::$installed;
+
+ return $installed;
+ }
}
diff --git a/lib/phpspreadsheet/vendor/composer/autoload_files.php b/lib/phpspreadsheet/vendor/composer/autoload_files.php
deleted file mode 100644
index fb9363c7250..00000000000
--- a/lib/phpspreadsheet/vendor/composer/autoload_files.php
+++ /dev/null
@@ -1,67 +0,0 @@
- $vendorDir . '/markbaker/matrix/classes/src/functions/adjoint.php',
- '6e78d1bdea6248d6aa117229efae50f2' => $vendorDir . '/markbaker/matrix/classes/src/functions/antidiagonal.php',
- '4623d87924d94f5412fe5afbf1cef31d' => $vendorDir . '/markbaker/matrix/classes/src/functions/cofactors.php',
- '901fd1f6950a637ca85f66b701a45e13' => $vendorDir . '/markbaker/matrix/classes/src/functions/determinant.php',
- '83057abc0e4acc99ba80154ee5d02a49' => $vendorDir . '/markbaker/matrix/classes/src/functions/diagonal.php',
- '07b7fd7a434451149b4fd477fca0ce06' => $vendorDir . '/markbaker/matrix/classes/src/functions/identity.php',
- 'c8d43b340583e07ae89f2a3baef2cf89' => $vendorDir . '/markbaker/matrix/classes/src/functions/inverse.php',
- '499bb10ed7a3aee2ba4c09a31a85e8d1' => $vendorDir . '/markbaker/matrix/classes/src/functions/minors.php',
- '1cad2e6414d652e8b1c64e8967f6f37d' => $vendorDir . '/markbaker/matrix/classes/src/functions/trace.php',
- '95a7f134ac17161d07def442b3b737e8' => $vendorDir . '/markbaker/matrix/classes/src/functions/transpose.php',
- 'b3a6bc628377118d4b4b8ba08d1eb949' => $vendorDir . '/markbaker/matrix/classes/src/operations/add.php',
- '5fef6d0e407f3f8887266dfa4a6c534c' => $vendorDir . '/markbaker/matrix/classes/src/operations/directsum.php',
- '684ba247e1385946e3babdaa054119de' => $vendorDir . '/markbaker/matrix/classes/src/operations/subtract.php',
- 'aa53dcba601214d17ad405b7c291b7e8' => $vendorDir . '/markbaker/matrix/classes/src/operations/multiply.php',
- '75c79eb1b25749b05a47976f32b0d8a2' => $vendorDir . '/markbaker/matrix/classes/src/operations/divideby.php',
- '6ab8ad87a734f276a6bcd5a0fe1289be' => $vendorDir . '/markbaker/matrix/classes/src/operations/divideinto.php',
- 'abede361264e2ae69ec1eee813a101af' => $vendorDir . '/markbaker/complex/classes/src/functions/abs.php',
- '21a5860fbef5be28db5ddfbc3cca67c4' => $vendorDir . '/markbaker/complex/classes/src/functions/acos.php',
- '1546e3f9d127f2a9bb2d1b6c31c26ef1' => $vendorDir . '/markbaker/complex/classes/src/functions/acosh.php',
- 'd2516f7f4fba5ea5905f494b4a8262e0' => $vendorDir . '/markbaker/complex/classes/src/functions/acot.php',
- '4511163d560956219b96882c0980b65e' => $vendorDir . '/markbaker/complex/classes/src/functions/acoth.php',
- 'c361f5616dc2a8da4fa3e137077cd4ea' => $vendorDir . '/markbaker/complex/classes/src/functions/acsc.php',
- '02d68920fc98da71991ce569c91df0f6' => $vendorDir . '/markbaker/complex/classes/src/functions/acsch.php',
- '88e19525eae308b4a6aa3419364875d3' => $vendorDir . '/markbaker/complex/classes/src/functions/argument.php',
- '60e8e2d0827b58bfc904f13957e51849' => $vendorDir . '/markbaker/complex/classes/src/functions/asec.php',
- '13d2f040713999eab66c359b4d79871d' => $vendorDir . '/markbaker/complex/classes/src/functions/asech.php',
- '838ab38beb32c68a79d3cd2c007d5a04' => $vendorDir . '/markbaker/complex/classes/src/functions/asin.php',
- 'bb28eccd0f8f008333a1b3c163d604ac' => $vendorDir . '/markbaker/complex/classes/src/functions/asinh.php',
- '9e483de83558c98f7d3feaa402c78cb3' => $vendorDir . '/markbaker/complex/classes/src/functions/atan.php',
- '36b74b5b765ded91ee58c8ee3c0e85e3' => $vendorDir . '/markbaker/complex/classes/src/functions/atanh.php',
- '05c15ee9510da7fd6bf6136f436500c0' => $vendorDir . '/markbaker/complex/classes/src/functions/conjugate.php',
- 'd3208dfbce2505e370788f9f22f6785f' => $vendorDir . '/markbaker/complex/classes/src/functions/cos.php',
- '141cf1fb3a3046f8b64534b0ebab33ca' => $vendorDir . '/markbaker/complex/classes/src/functions/cosh.php',
- 'be660df75fd0dbe7fa7c03b7434b3294' => $vendorDir . '/markbaker/complex/classes/src/functions/cot.php',
- '01e31ea298a51bc9e91517e3ce6b9e76' => $vendorDir . '/markbaker/complex/classes/src/functions/coth.php',
- '803ddd97f7b1da68982a7b087c3476f6' => $vendorDir . '/markbaker/complex/classes/src/functions/csc.php',
- '3001cdfd101ec3c32da34ee43c2e149b' => $vendorDir . '/markbaker/complex/classes/src/functions/csch.php',
- '77b2d7629ef2a93fabb8c56754a91051' => $vendorDir . '/markbaker/complex/classes/src/functions/exp.php',
- '4a4471296dec796c21d4f4b6552396a9' => $vendorDir . '/markbaker/complex/classes/src/functions/inverse.php',
- 'c3e9897e1744b88deb56fcdc39d34d85' => $vendorDir . '/markbaker/complex/classes/src/functions/ln.php',
- 'a83cacf2de942cff288de15a83afd26d' => $vendorDir . '/markbaker/complex/classes/src/functions/log2.php',
- '6a861dacc9ee2f3061241d4c7772fa21' => $vendorDir . '/markbaker/complex/classes/src/functions/log10.php',
- '4d2522d968c8ba78d6c13548a1b4200e' => $vendorDir . '/markbaker/complex/classes/src/functions/negative.php',
- 'fd587ca933fc0447fa5ab4843bdd97f7' => $vendorDir . '/markbaker/complex/classes/src/functions/pow.php',
- '383ef01c62028fc78cd4388082fce3c2' => $vendorDir . '/markbaker/complex/classes/src/functions/rho.php',
- '150fbd1b95029dc47292da97ecab9375' => $vendorDir . '/markbaker/complex/classes/src/functions/sec.php',
- '549abd9bae174286d660bdaa07407c68' => $vendorDir . '/markbaker/complex/classes/src/functions/sech.php',
- '6bfbf5eaea6b17a0ed85cb21ba80370c' => $vendorDir . '/markbaker/complex/classes/src/functions/sin.php',
- '22efe13f1a497b8e199540ae2d9dc59c' => $vendorDir . '/markbaker/complex/classes/src/functions/sinh.php',
- 'e90135ab8e787795a509ed7147de207d' => $vendorDir . '/markbaker/complex/classes/src/functions/sqrt.php',
- 'bb0a7923ffc6a90919cd64ec54ff06bc' => $vendorDir . '/markbaker/complex/classes/src/functions/tan.php',
- '2d302f32ce0fd4e433dd91c5bb404a28' => $vendorDir . '/markbaker/complex/classes/src/functions/tanh.php',
- '24dd4658a952171a4ee79218c4f9fd06' => $vendorDir . '/markbaker/complex/classes/src/functions/theta.php',
- 'e49b7876281d6f5bc39536dde96d1f4a' => $vendorDir . '/markbaker/complex/classes/src/operations/add.php',
- '47596e02b43cd6da7700134fd08f88cf' => $vendorDir . '/markbaker/complex/classes/src/operations/subtract.php',
- '883af48563631547925fa4c3b48ead07' => $vendorDir . '/markbaker/complex/classes/src/operations/multiply.php',
- 'f190e3308e6ca23234a2875edc985c03' => $vendorDir . '/markbaker/complex/classes/src/operations/divideby.php',
- 'ac9e33ce6841aa5bf5d16d465a2f03a7' => $vendorDir . '/markbaker/complex/classes/src/operations/divideinto.php',
-);
diff --git a/lib/phpspreadsheet/vendor/composer/autoload_namespaces.php b/lib/phpspreadsheet/vendor/composer/autoload_namespaces.php
index 97f041d5b3a..b7fc0125dbc 100644
--- a/lib/phpspreadsheet/vendor/composer/autoload_namespaces.php
+++ b/lib/phpspreadsheet/vendor/composer/autoload_namespaces.php
@@ -5,4 +5,5 @@
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
-return array();
+return array(
+);
diff --git a/lib/phpspreadsheet/vendor/composer/autoload_psr4.php b/lib/phpspreadsheet/vendor/composer/autoload_psr4.php
index def19d8baa9..a86a0028118 100644
--- a/lib/phpspreadsheet/vendor/composer/autoload_psr4.php
+++ b/lib/phpspreadsheet/vendor/composer/autoload_psr4.php
@@ -6,13 +6,10 @@ $vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
- 'ZipStream\\' => array($vendorDir . '/maennchen/zipstream-php/src'),
- 'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src', $vendorDir . '/psr/http-factory/src'),
'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'),
'PhpOffice\\PhpSpreadsheet\\' => array($vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet'),
- 'MyCLabs\\Enum\\' => array($vendorDir . '/myclabs/php-enum/src'),
'Matrix\\' => array($vendorDir . '/markbaker/matrix/classes/src'),
'Complex\\' => array($vendorDir . '/markbaker/complex/classes/src'),
);
diff --git a/lib/phpspreadsheet/vendor/composer/autoload_real.php b/lib/phpspreadsheet/vendor/composer/autoload_real.php
index 9a3431ed05d..0745ab34d43 100644
--- a/lib/phpspreadsheet/vendor/composer/autoload_real.php
+++ b/lib/phpspreadsheet/vendor/composer/autoload_real.php
@@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer
-class ComposerAutoloaderInit596026141085fc6d905fff9fde42dc1b
+class ComposerAutoloaderInit47a82a2b792e78d18b5f54d474d822dc
{
private static $loader;
@@ -24,15 +24,15 @@ class ComposerAutoloaderInit596026141085fc6d905fff9fde42dc1b
require __DIR__ . '/platform_check.php';
- spl_autoload_register(array('ComposerAutoloaderInit596026141085fc6d905fff9fde42dc1b', 'loadClassLoader'), true, true);
- self::$loader = $loader = new \Composer\Autoload\ClassLoader();
- spl_autoload_unregister(array('ComposerAutoloaderInit596026141085fc6d905fff9fde42dc1b', 'loadClassLoader'));
+ spl_autoload_register(array('ComposerAutoloaderInit47a82a2b792e78d18b5f54d474d822dc', 'loadClassLoader'), true, true);
+ self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(\dirname(__FILE__)));
+ spl_autoload_unregister(array('ComposerAutoloaderInit47a82a2b792e78d18b5f54d474d822dc', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require __DIR__ . '/autoload_static.php';
- call_user_func(\Composer\Autoload\ComposerStaticInit596026141085fc6d905fff9fde42dc1b::getInitializer($loader));
+ call_user_func(\Composer\Autoload\ComposerStaticInit47a82a2b792e78d18b5f54d474d822dc::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
@@ -52,24 +52,6 @@ class ComposerAutoloaderInit596026141085fc6d905fff9fde42dc1b
$loader->register(true);
- if ($useStaticLoader) {
- $includeFiles = Composer\Autoload\ComposerStaticInit596026141085fc6d905fff9fde42dc1b::$files;
- } else {
- $includeFiles = require __DIR__ . '/autoload_files.php';
- }
- foreach ($includeFiles as $fileIdentifier => $file) {
- composerRequire596026141085fc6d905fff9fde42dc1b($fileIdentifier, $file);
- }
-
return $loader;
}
}
-
-function composerRequire596026141085fc6d905fff9fde42dc1b($fileIdentifier, $file)
-{
- if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
- require $file;
-
- $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
- }
-}
diff --git a/lib/phpspreadsheet/vendor/composer/autoload_static.php b/lib/phpspreadsheet/vendor/composer/autoload_static.php
index ec49ef17ee3..bdc8de8fb9e 100644
--- a/lib/phpspreadsheet/vendor/composer/autoload_static.php
+++ b/lib/phpspreadsheet/vendor/composer/autoload_static.php
@@ -4,78 +4,9 @@
namespace Composer\Autoload;
-class ComposerStaticInit596026141085fc6d905fff9fde42dc1b
+class ComposerStaticInit47a82a2b792e78d18b5f54d474d822dc
{
- public static $files = array (
- '9d8e013a5160a09477beb8e44f8ae97b' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/adjoint.php',
- '6e78d1bdea6248d6aa117229efae50f2' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/antidiagonal.php',
- '4623d87924d94f5412fe5afbf1cef31d' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/cofactors.php',
- '901fd1f6950a637ca85f66b701a45e13' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/determinant.php',
- '83057abc0e4acc99ba80154ee5d02a49' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/diagonal.php',
- '07b7fd7a434451149b4fd477fca0ce06' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/identity.php',
- 'c8d43b340583e07ae89f2a3baef2cf89' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/inverse.php',
- '499bb10ed7a3aee2ba4c09a31a85e8d1' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/minors.php',
- '1cad2e6414d652e8b1c64e8967f6f37d' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/trace.php',
- '95a7f134ac17161d07def442b3b737e8' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/transpose.php',
- 'b3a6bc628377118d4b4b8ba08d1eb949' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/add.php',
- '5fef6d0e407f3f8887266dfa4a6c534c' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/directsum.php',
- '684ba247e1385946e3babdaa054119de' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/subtract.php',
- 'aa53dcba601214d17ad405b7c291b7e8' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/multiply.php',
- '75c79eb1b25749b05a47976f32b0d8a2' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/divideby.php',
- '6ab8ad87a734f276a6bcd5a0fe1289be' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/divideinto.php',
- 'abede361264e2ae69ec1eee813a101af' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/abs.php',
- '21a5860fbef5be28db5ddfbc3cca67c4' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acos.php',
- '1546e3f9d127f2a9bb2d1b6c31c26ef1' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acosh.php',
- 'd2516f7f4fba5ea5905f494b4a8262e0' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acot.php',
- '4511163d560956219b96882c0980b65e' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acoth.php',
- 'c361f5616dc2a8da4fa3e137077cd4ea' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acsc.php',
- '02d68920fc98da71991ce569c91df0f6' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acsch.php',
- '88e19525eae308b4a6aa3419364875d3' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/argument.php',
- '60e8e2d0827b58bfc904f13957e51849' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/asec.php',
- '13d2f040713999eab66c359b4d79871d' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/asech.php',
- '838ab38beb32c68a79d3cd2c007d5a04' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/asin.php',
- 'bb28eccd0f8f008333a1b3c163d604ac' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/asinh.php',
- '9e483de83558c98f7d3feaa402c78cb3' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/atan.php',
- '36b74b5b765ded91ee58c8ee3c0e85e3' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/atanh.php',
- '05c15ee9510da7fd6bf6136f436500c0' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/conjugate.php',
- 'd3208dfbce2505e370788f9f22f6785f' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/cos.php',
- '141cf1fb3a3046f8b64534b0ebab33ca' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/cosh.php',
- 'be660df75fd0dbe7fa7c03b7434b3294' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/cot.php',
- '01e31ea298a51bc9e91517e3ce6b9e76' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/coth.php',
- '803ddd97f7b1da68982a7b087c3476f6' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/csc.php',
- '3001cdfd101ec3c32da34ee43c2e149b' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/csch.php',
- '77b2d7629ef2a93fabb8c56754a91051' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/exp.php',
- '4a4471296dec796c21d4f4b6552396a9' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/inverse.php',
- 'c3e9897e1744b88deb56fcdc39d34d85' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/ln.php',
- 'a83cacf2de942cff288de15a83afd26d' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/log2.php',
- '6a861dacc9ee2f3061241d4c7772fa21' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/log10.php',
- '4d2522d968c8ba78d6c13548a1b4200e' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/negative.php',
- 'fd587ca933fc0447fa5ab4843bdd97f7' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/pow.php',
- '383ef01c62028fc78cd4388082fce3c2' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/rho.php',
- '150fbd1b95029dc47292da97ecab9375' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/sec.php',
- '549abd9bae174286d660bdaa07407c68' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/sech.php',
- '6bfbf5eaea6b17a0ed85cb21ba80370c' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/sin.php',
- '22efe13f1a497b8e199540ae2d9dc59c' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/sinh.php',
- 'e90135ab8e787795a509ed7147de207d' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/sqrt.php',
- 'bb0a7923ffc6a90919cd64ec54ff06bc' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/tan.php',
- '2d302f32ce0fd4e433dd91c5bb404a28' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/tanh.php',
- '24dd4658a952171a4ee79218c4f9fd06' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/theta.php',
- 'e49b7876281d6f5bc39536dde96d1f4a' => __DIR__ . '/..' . '/markbaker/complex/classes/src/operations/add.php',
- '47596e02b43cd6da7700134fd08f88cf' => __DIR__ . '/..' . '/markbaker/complex/classes/src/operations/subtract.php',
- '883af48563631547925fa4c3b48ead07' => __DIR__ . '/..' . '/markbaker/complex/classes/src/operations/multiply.php',
- 'f190e3308e6ca23234a2875edc985c03' => __DIR__ . '/..' . '/markbaker/complex/classes/src/operations/divideby.php',
- 'ac9e33ce6841aa5bf5d16d465a2f03a7' => __DIR__ . '/..' . '/markbaker/complex/classes/src/operations/divideinto.php',
- );
-
public static $prefixLengthsPsr4 = array (
- 'Z' =>
- array (
- 'ZipStream\\' => 10,
- ),
- 'S' =>
- array (
- 'Symfony\\Polyfill\\Mbstring\\' => 26,
- ),
'P' =>
array (
'Psr\\SimpleCache\\' => 16,
@@ -85,7 +16,6 @@ class ComposerStaticInit596026141085fc6d905fff9fde42dc1b
),
'M' =>
array (
- 'MyCLabs\\Enum\\' => 13,
'Matrix\\' => 7,
),
'C' =>
@@ -95,14 +25,6 @@ class ComposerStaticInit596026141085fc6d905fff9fde42dc1b
);
public static $prefixDirsPsr4 = array (
- 'ZipStream\\' =>
- array (
- 0 => __DIR__ . '/..' . '/maennchen/zipstream-php/src',
- ),
- 'Symfony\\Polyfill\\Mbstring\\' =>
- array (
- 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
- ),
'Psr\\SimpleCache\\' =>
array (
0 => __DIR__ . '/..' . '/psr/simple-cache/src',
@@ -120,10 +42,6 @@ class ComposerStaticInit596026141085fc6d905fff9fde42dc1b
array (
0 => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet',
),
- 'MyCLabs\\Enum\\' =>
- array (
- 0 => __DIR__ . '/..' . '/myclabs/php-enum/src',
- ),
'Matrix\\' =>
array (
0 => __DIR__ . '/..' . '/markbaker/matrix/classes/src',
@@ -134,16 +52,6 @@ class ComposerStaticInit596026141085fc6d905fff9fde42dc1b
),
);
- public static $prefixesPsr0 = array (
- 'H' =>
- array (
- 'HTMLPurifier' =>
- array (
- 0 => __DIR__ . '/..' . '/ezyang/htmlpurifier/library',
- ),
- ),
- );
-
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
);
@@ -151,10 +59,9 @@ class ComposerStaticInit596026141085fc6d905fff9fde42dc1b
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
- $loader->prefixLengthsPsr4 = ComposerStaticInit596026141085fc6d905fff9fde42dc1b::$prefixLengthsPsr4;
- $loader->prefixDirsPsr4 = ComposerStaticInit596026141085fc6d905fff9fde42dc1b::$prefixDirsPsr4;
- $loader->prefixesPsr0 = ComposerStaticInit596026141085fc6d905fff9fde42dc1b::$prefixesPsr0;
- $loader->classMap = ComposerStaticInit596026141085fc6d905fff9fde42dc1b::$classMap;
+ $loader->prefixLengthsPsr4 = ComposerStaticInit47a82a2b792e78d18b5f54d474d822dc::$prefixLengthsPsr4;
+ $loader->prefixDirsPsr4 = ComposerStaticInit47a82a2b792e78d18b5f54d474d822dc::$prefixDirsPsr4;
+ $loader->classMap = ComposerStaticInit47a82a2b792e78d18b5f54d474d822dc::$classMap;
}, null, ClassLoader::class);
}
diff --git a/lib/phpspreadsheet/vendor/composer/installed.json b/lib/phpspreadsheet/vendor/composer/installed.json
index aac52851b06..e9a76b7b20d 100644
--- a/lib/phpspreadsheet/vendor/composer/installed.json
+++ b/lib/phpspreadsheet/vendor/composer/installed.json
@@ -1,149 +1,18 @@
{
"packages": [
- {
- "name": "ezyang/htmlpurifier",
- "version": "v4.13.0",
- "version_normalized": "4.13.0.0",
- "source": {
- "type": "git",
- "url": "https://github.com/ezyang/htmlpurifier.git",
- "reference": "08e27c97e4c6ed02f37c5b2b20488046c8d90d75"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/ezyang/htmlpurifier/zipball/08e27c97e4c6ed02f37c5b2b20488046c8d90d75",
- "reference": "08e27c97e4c6ed02f37c5b2b20488046c8d90d75",
- "shasum": ""
- },
- "require": {
- "php": ">=5.2"
- },
- "require-dev": {
- "simpletest/simpletest": "dev-master#72de02a7b80c6bb8864ef9bf66d41d2f58f826bd"
- },
- "time": "2020-06-29T00:56:53+00:00",
- "type": "library",
- "installation-source": "dist",
- "autoload": {
- "psr-0": {
- "HTMLPurifier": "library/"
- },
- "files": [
- "library/HTMLPurifier.composer.php"
- ],
- "exclude-from-classmap": [
- "/library/HTMLPurifier/Language/"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "LGPL-2.1-or-later"
- ],
- "authors": [
- {
- "name": "Edward Z. Yang",
- "email": "admin@htmlpurifier.org",
- "homepage": "http://ezyang.com"
- }
- ],
- "description": "Standards compliant HTML filter written in PHP",
- "homepage": "http://htmlpurifier.org/",
- "keywords": [
- "html"
- ],
- "support": {
- "issues": "https://github.com/ezyang/htmlpurifier/issues",
- "source": "https://github.com/ezyang/htmlpurifier/tree/master"
- },
- "install-path": "../ezyang/htmlpurifier"
- },
- {
- "name": "maennchen/zipstream-php",
- "version": "2.1.0",
- "version_normalized": "2.1.0.0",
- "source": {
- "type": "git",
- "url": "https://github.com/maennchen/ZipStream-PHP.git",
- "reference": "c4c5803cc1f93df3d2448478ef79394a5981cc58"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/maennchen/ZipStream-PHP/zipball/c4c5803cc1f93df3d2448478ef79394a5981cc58",
- "reference": "c4c5803cc1f93df3d2448478ef79394a5981cc58",
- "shasum": ""
- },
- "require": {
- "myclabs/php-enum": "^1.5",
- "php": ">= 7.1",
- "psr/http-message": "^1.0",
- "symfony/polyfill-mbstring": "^1.0"
- },
- "require-dev": {
- "ext-zip": "*",
- "guzzlehttp/guzzle": ">= 6.3",
- "mikey179/vfsstream": "^1.6",
- "phpunit/phpunit": ">= 7.5"
- },
- "time": "2020-05-30T13:11:16+00:00",
- "type": "library",
- "installation-source": "dist",
- "autoload": {
- "psr-4": {
- "ZipStream\\": "src/"
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Paul Duncan",
- "email": "pabs@pablotron.org"
- },
- {
- "name": "Jonatan Männchen",
- "email": "jonatan@maennchen.ch"
- },
- {
- "name": "Jesse Donat",
- "email": "donatj@gmail.com"
- },
- {
- "name": "András Kolesár",
- "email": "kolesar@kolesar.hu"
- }
- ],
- "description": "ZipStream is a library for dynamically streaming dynamic zip files from PHP without writing to the disk at all on the server.",
- "keywords": [
- "stream",
- "zip"
- ],
- "support": {
- "issues": "https://github.com/maennchen/ZipStream-PHP/issues",
- "source": "https://github.com/maennchen/ZipStream-PHP/tree/master"
- },
- "funding": [
- {
- "url": "https://opencollective.com/zipstream",
- "type": "open_collective"
- }
- ],
- "install-path": "../maennchen/zipstream-php"
- },
{
"name": "markbaker/complex",
- "version": "2.0.0",
- "version_normalized": "2.0.0.0",
+ "version": "3.0.1",
+ "version_normalized": "3.0.1.0",
"source": {
"type": "git",
"url": "https://github.com/MarkBaker/PHPComplex.git",
- "reference": "9999f1432fae467bc93c53f357105b4c31bb994c"
+ "reference": "ab8bc271e404909db09ff2d5ffa1e538085c0f22"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/MarkBaker/PHPComplex/zipball/9999f1432fae467bc93c53f357105b4c31bb994c",
- "reference": "9999f1432fae467bc93c53f357105b4c31bb994c",
+ "url": "https://api.github.com/repos/MarkBaker/PHPComplex/zipball/ab8bc271e404909db09ff2d5ffa1e538085c0f22",
+ "reference": "ab8bc271e404909db09ff2d5ffa1e538085c0f22",
"shasum": ""
},
"require": {
@@ -152,64 +21,16 @@
"require-dev": {
"dealerdirect/phpcodesniffer-composer-installer": "^0.7.0",
"phpcompatibility/php-compatibility": "^9.0",
- "phpdocumentor/phpdocumentor": "2.*",
- "phploc/phploc": "^4.0",
- "phpmd/phpmd": "2.*",
"phpunit/phpunit": "^7.0 || ^8.0 || ^9.3",
- "sebastian/phpcpd": "^4.0",
"squizlabs/php_codesniffer": "^3.4"
},
- "time": "2020-08-26T10:42:07+00:00",
+ "time": "2021-06-29T15:32:53+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Complex\\": "classes/src/"
- },
- "files": [
- "classes/src/functions/abs.php",
- "classes/src/functions/acos.php",
- "classes/src/functions/acosh.php",
- "classes/src/functions/acot.php",
- "classes/src/functions/acoth.php",
- "classes/src/functions/acsc.php",
- "classes/src/functions/acsch.php",
- "classes/src/functions/argument.php",
- "classes/src/functions/asec.php",
- "classes/src/functions/asech.php",
- "classes/src/functions/asin.php",
- "classes/src/functions/asinh.php",
- "classes/src/functions/atan.php",
- "classes/src/functions/atanh.php",
- "classes/src/functions/conjugate.php",
- "classes/src/functions/cos.php",
- "classes/src/functions/cosh.php",
- "classes/src/functions/cot.php",
- "classes/src/functions/coth.php",
- "classes/src/functions/csc.php",
- "classes/src/functions/csch.php",
- "classes/src/functions/exp.php",
- "classes/src/functions/inverse.php",
- "classes/src/functions/ln.php",
- "classes/src/functions/log2.php",
- "classes/src/functions/log10.php",
- "classes/src/functions/negative.php",
- "classes/src/functions/pow.php",
- "classes/src/functions/rho.php",
- "classes/src/functions/sec.php",
- "classes/src/functions/sech.php",
- "classes/src/functions/sin.php",
- "classes/src/functions/sinh.php",
- "classes/src/functions/sqrt.php",
- "classes/src/functions/tan.php",
- "classes/src/functions/tanh.php",
- "classes/src/functions/theta.php",
- "classes/src/operations/add.php",
- "classes/src/operations/subtract.php",
- "classes/src/operations/multiply.php",
- "classes/src/operations/divideby.php",
- "classes/src/operations/divideinto.php"
- ]
+ }
},
"notification-url": "https://packagist.org/downloads/",
"license": [
@@ -229,27 +50,27 @@
],
"support": {
"issues": "https://github.com/MarkBaker/PHPComplex/issues",
- "source": "https://github.com/MarkBaker/PHPComplex/tree/PHP8"
+ "source": "https://github.com/MarkBaker/PHPComplex/tree/3.0.1"
},
"install-path": "../markbaker/complex"
},
{
"name": "markbaker/matrix",
- "version": "2.0.0",
- "version_normalized": "2.0.0.0",
+ "version": "3.0.0",
+ "version_normalized": "3.0.0.0",
"source": {
"type": "git",
"url": "https://github.com/MarkBaker/PHPMatrix.git",
- "reference": "9567d9c4c519fbe40de01dbd1e4469dbbb66f46a"
+ "reference": "c66aefcafb4f6c269510e9ac46b82619a904c576"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/MarkBaker/PHPMatrix/zipball/9567d9c4c519fbe40de01dbd1e4469dbbb66f46a",
- "reference": "9567d9c4c519fbe40de01dbd1e4469dbbb66f46a",
+ "url": "https://api.github.com/repos/MarkBaker/PHPMatrix/zipball/c66aefcafb4f6c269510e9ac46b82619a904c576",
+ "reference": "c66aefcafb4f6c269510e9ac46b82619a904c576",
"shasum": ""
},
"require": {
- "php": "^7.2 || ^8.0"
+ "php": "^7.1 || ^8.0"
},
"require-dev": {
"dealerdirect/phpcodesniffer-composer-installer": "^0.7.0",
@@ -261,31 +82,13 @@
"sebastian/phpcpd": "^4.0",
"squizlabs/php_codesniffer": "^3.4"
},
- "time": "2020-08-28T17:11:00+00:00",
+ "time": "2021-07-01T19:01:15+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Matrix\\": "classes/src/"
- },
- "files": [
- "classes/src/functions/adjoint.php",
- "classes/src/functions/antidiagonal.php",
- "classes/src/functions/cofactors.php",
- "classes/src/functions/determinant.php",
- "classes/src/functions/diagonal.php",
- "classes/src/functions/identity.php",
- "classes/src/functions/inverse.php",
- "classes/src/functions/minors.php",
- "classes/src/functions/trace.php",
- "classes/src/functions/transpose.php",
- "classes/src/operations/add.php",
- "classes/src/operations/directsum.php",
- "classes/src/operations/subtract.php",
- "classes/src/operations/multiply.php",
- "classes/src/operations/divideby.php",
- "classes/src/operations/divideinto.php"
- ]
+ }
},
"notification-url": "https://packagist.org/downloads/",
"license": [
@@ -306,86 +109,23 @@
],
"support": {
"issues": "https://github.com/MarkBaker/PHPMatrix/issues",
- "source": "https://github.com/MarkBaker/PHPMatrix/tree/PHP8"
+ "source": "https://github.com/MarkBaker/PHPMatrix/tree/3.0.0"
},
"install-path": "../markbaker/matrix"
},
- {
- "name": "myclabs/php-enum",
- "version": "1.7.7",
- "version_normalized": "1.7.7.0",
- "source": {
- "type": "git",
- "url": "https://github.com/myclabs/php-enum.git",
- "reference": "d178027d1e679832db9f38248fcc7200647dc2b7"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/myclabs/php-enum/zipball/d178027d1e679832db9f38248fcc7200647dc2b7",
- "reference": "d178027d1e679832db9f38248fcc7200647dc2b7",
- "shasum": ""
- },
- "require": {
- "ext-json": "*",
- "php": ">=7.1"
- },
- "require-dev": {
- "phpunit/phpunit": "^7",
- "squizlabs/php_codesniffer": "1.*",
- "vimeo/psalm": "^3.8"
- },
- "time": "2020-11-14T18:14:52+00:00",
- "type": "library",
- "installation-source": "dist",
- "autoload": {
- "psr-4": {
- "MyCLabs\\Enum\\": "src/"
- }
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "PHP Enum contributors",
- "homepage": "https://github.com/myclabs/php-enum/graphs/contributors"
- }
- ],
- "description": "PHP Enum implementation",
- "homepage": "http://github.com/myclabs/php-enum",
- "keywords": [
- "enum"
- ],
- "support": {
- "issues": "https://github.com/myclabs/php-enum/issues",
- "source": "https://github.com/myclabs/php-enum/tree/1.7.7"
- },
- "funding": [
- {
- "url": "https://github.com/mnapoli",
- "type": "github"
- },
- {
- "url": "https://tidelift.com/funding/github/packagist/myclabs/php-enum",
- "type": "tidelift"
- }
- ],
- "install-path": "../myclabs/php-enum"
- },
{
"name": "phpoffice/phpspreadsheet",
- "version": "1.16.0",
- "version_normalized": "1.16.0.0",
+ "version": "1.21.0",
+ "version_normalized": "1.21.0.0",
"source": {
"type": "git",
"url": "https://github.com/PHPOffice/PhpSpreadsheet.git",
- "reference": "76d4323b85129d0c368149c831a07a3e258b2b50"
+ "reference": "1a359d2ccbb89c05f5dffb32711a95f4afc67964"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/76d4323b85129d0c368149c831a07a3e258b2b50",
- "reference": "76d4323b85129d0c368149c831a07a3e258b2b50",
+ "url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/1a359d2ccbb89c05f5dffb32711a95f4afc67964",
+ "reference": "1a359d2ccbb89c05f5dffb32711a95f4afc67964",
"shasum": ""
},
"require": {
@@ -404,22 +144,25 @@
"ext-zlib": "*",
"ezyang/htmlpurifier": "^4.13",
"maennchen/zipstream-php": "^2.1",
- "markbaker/complex": "^1.5||^2.0",
- "markbaker/matrix": "^1.2||^2.0",
- "php": "^7.2||^8.0",
+ "markbaker/complex": "^3.0",
+ "markbaker/matrix": "^3.0",
+ "php": "^7.3 || ^8.0",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0",
"psr/simple-cache": "^1.0"
},
"require-dev": {
- "dompdf/dompdf": "^0.8.5",
- "friendsofphp/php-cs-fixer": "^2.16",
+ "dealerdirect/phpcodesniffer-composer-installer": "dev-master",
+ "dompdf/dompdf": "^1.0",
+ "friendsofphp/php-cs-fixer": "^3.2",
"jpgraph/jpgraph": "^4.0",
"mpdf/mpdf": "^8.0",
"phpcompatibility/php-compatibility": "^9.3",
- "phpunit/phpunit": "^8.5||^9.3",
- "squizlabs/php_codesniffer": "^3.5",
- "tecnickcom/tcpdf": "^6.3"
+ "phpstan/phpstan": "^1.1",
+ "phpstan/phpstan-phpunit": "^1.0",
+ "phpunit/phpunit": "^8.5 || ^9.0",
+ "squizlabs/php_codesniffer": "^3.6",
+ "tecnickcom/tcpdf": "^6.4"
},
"suggest": {
"dompdf/dompdf": "Option for rendering PDF with PDF Writer (doesn't yet support PHP8)",
@@ -427,7 +170,7 @@
"mpdf/mpdf": "Option for rendering PDF with PDF Writer",
"tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer (doesn't yet support PHP8)"
},
- "time": "2020-12-31T18:03:49+00:00",
+ "time": "2022-01-06T11:10:08+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
@@ -473,7 +216,7 @@
],
"support": {
"issues": "https://github.com/PHPOffice/PhpSpreadsheet/issues",
- "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/1.16.0"
+ "source": "https://github.com/PHPOffice/PhpSpreadsheet/tree/1.21.0"
},
"install-path": "../phpoffice/phpspreadsheet"
},
@@ -699,89 +442,6 @@
"source": "https://github.com/php-fig/simple-cache/tree/master"
},
"install-path": "../psr/simple-cache"
- },
- {
- "name": "symfony/polyfill-mbstring",
- "version": "v1.22.0",
- "version_normalized": "1.22.0.0",
- "source": {
- "type": "git",
- "url": "https://github.com/symfony/polyfill-mbstring.git",
- "reference": "f377a3dd1fde44d37b9831d68dc8dea3ffd28e13"
- },
- "dist": {
- "type": "zip",
- "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/f377a3dd1fde44d37b9831d68dc8dea3ffd28e13",
- "reference": "f377a3dd1fde44d37b9831d68dc8dea3ffd28e13",
- "shasum": ""
- },
- "require": {
- "php": ">=7.1"
- },
- "suggest": {
- "ext-mbstring": "For best performance"
- },
- "time": "2021-01-07T16:49:33+00:00",
- "type": "library",
- "extra": {
- "branch-alias": {
- "dev-main": "1.22-dev"
- },
- "thanks": {
- "name": "symfony/polyfill",
- "url": "https://github.com/symfony/polyfill"
- }
- },
- "installation-source": "dist",
- "autoload": {
- "psr-4": {
- "Symfony\\Polyfill\\Mbstring\\": ""
- },
- "files": [
- "bootstrap.php"
- ]
- },
- "notification-url": "https://packagist.org/downloads/",
- "license": [
- "MIT"
- ],
- "authors": [
- {
- "name": "Nicolas Grekas",
- "email": "p@tchwork.com"
- },
- {
- "name": "Symfony Community",
- "homepage": "https://symfony.com/contributors"
- }
- ],
- "description": "Symfony polyfill for the Mbstring extension",
- "homepage": "https://symfony.com",
- "keywords": [
- "compatibility",
- "mbstring",
- "polyfill",
- "portable",
- "shim"
- ],
- "support": {
- "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.22.0"
- },
- "funding": [
- {
- "url": "https://symfony.com/sponsor",
- "type": "custom"
- },
- {
- "url": "https://github.com/fabpot",
- "type": "github"
- },
- {
- "url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
- "type": "tidelift"
- }
- ],
- "install-path": "../symfony/polyfill-mbstring"
}
],
"dev": true,
diff --git a/lib/phpspreadsheet/vendor/composer/installed.php b/lib/phpspreadsheet/vendor/composer/installed.php
index 1ca76964218..91c054a37b6 100644
--- a/lib/phpspreadsheet/vendor/composer/installed.php
+++ b/lib/phpspreadsheet/vendor/composer/installed.php
@@ -1,123 +1,110 @@
-
- array (
- 'pretty_version' => 'dev-master',
- 'version' => 'dev-master',
- 'aliases' =>
- array (
+ array(
+ 'pretty_version' => '1.0.0+no-version-set',
+ 'version' => '1.0.0.0',
+ 'type' => 'library',
+ 'install_path' => __DIR__ . '/../../',
+ 'aliases' => array(),
+ 'reference' => NULL,
+ 'name' => '__root__',
+ 'dev' => true,
),
- 'reference' => '70d1b7d67bc280b21f450db41728869bd1bda8d8',
- 'name' => '__root__',
- ),
- 'versions' =>
- array (
- '__root__' =>
- array (
- 'pretty_version' => 'dev-master',
- 'version' => 'dev-master',
- 'aliases' =>
- array (
- ),
- 'reference' => '70d1b7d67bc280b21f450db41728869bd1bda8d8',
+ 'versions' => array(
+ '__root__' => array(
+ 'pretty_version' => '1.0.0+no-version-set',
+ 'version' => '1.0.0.0',
+ 'type' => 'library',
+ 'install_path' => __DIR__ . '/../../',
+ 'aliases' => array(),
+ 'reference' => NULL,
+ 'dev_requirement' => false,
+ ),
+ 'ezyang/htmlpurifier' => array(
+ 'dev_requirement' => false,
+ 'replaced' => array(
+ 0 => '*',
+ ),
+ ),
+ 'maennchen/zipstream-php' => array(
+ 'dev_requirement' => false,
+ 'replaced' => array(
+ 0 => '*',
+ ),
+ ),
+ 'markbaker/complex' => array(
+ 'pretty_version' => '3.0.1',
+ 'version' => '3.0.1.0',
+ 'type' => 'library',
+ 'install_path' => __DIR__ . '/../markbaker/complex',
+ 'aliases' => array(),
+ 'reference' => 'ab8bc271e404909db09ff2d5ffa1e538085c0f22',
+ 'dev_requirement' => false,
+ ),
+ 'markbaker/matrix' => array(
+ 'pretty_version' => '3.0.0',
+ 'version' => '3.0.0.0',
+ 'type' => 'library',
+ 'install_path' => __DIR__ . '/../markbaker/matrix',
+ 'aliases' => array(),
+ 'reference' => 'c66aefcafb4f6c269510e9ac46b82619a904c576',
+ 'dev_requirement' => false,
+ ),
+ 'myclabs/php-enum' => array(
+ 'dev_requirement' => false,
+ 'replaced' => array(
+ 0 => '*',
+ ),
+ ),
+ 'phpoffice/phpspreadsheet' => array(
+ 'pretty_version' => '1.21.0',
+ 'version' => '1.21.0.0',
+ 'type' => 'library',
+ 'install_path' => __DIR__ . '/../phpoffice/phpspreadsheet',
+ 'aliases' => array(),
+ 'reference' => '1a359d2ccbb89c05f5dffb32711a95f4afc67964',
+ 'dev_requirement' => false,
+ ),
+ 'psr/http-client' => array(
+ 'pretty_version' => '1.0.1',
+ 'version' => '1.0.1.0',
+ 'type' => 'library',
+ 'install_path' => __DIR__ . '/../psr/http-client',
+ 'aliases' => array(),
+ 'reference' => '2dfb5f6c5eff0e91e20e913f8c5452ed95b86621',
+ 'dev_requirement' => false,
+ ),
+ 'psr/http-factory' => array(
+ 'pretty_version' => '1.0.1',
+ 'version' => '1.0.1.0',
+ 'type' => 'library',
+ 'install_path' => __DIR__ . '/../psr/http-factory',
+ 'aliases' => array(),
+ 'reference' => '12ac7fcd07e5b077433f5f2bee95b3a771bf61be',
+ 'dev_requirement' => false,
+ ),
+ 'psr/http-message' => array(
+ 'pretty_version' => '1.0.1',
+ 'version' => '1.0.1.0',
+ 'type' => 'library',
+ 'install_path' => __DIR__ . '/../psr/http-message',
+ 'aliases' => array(),
+ 'reference' => 'f6561bf28d520154e4b0ec72be95418abe6d9363',
+ 'dev_requirement' => false,
+ ),
+ 'psr/simple-cache' => array(
+ 'pretty_version' => '1.0.1',
+ 'version' => '1.0.1.0',
+ 'type' => 'library',
+ 'install_path' => __DIR__ . '/../psr/simple-cache',
+ 'aliases' => array(),
+ 'reference' => '408d5eafb83c57f6365a3ca330ff23aa4a5fa39b',
+ 'dev_requirement' => false,
+ ),
+ 'symfony/polyfill-mbstring' => array(
+ 'dev_requirement' => false,
+ 'replaced' => array(
+ 0 => '*',
+ ),
+ ),
),
- 'ezyang/htmlpurifier' =>
- array (
- 'pretty_version' => 'v4.13.0',
- 'version' => '4.13.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '08e27c97e4c6ed02f37c5b2b20488046c8d90d75',
- ),
- 'maennchen/zipstream-php' =>
- array (
- 'pretty_version' => '2.1.0',
- 'version' => '2.1.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => 'c4c5803cc1f93df3d2448478ef79394a5981cc58',
- ),
- 'markbaker/complex' =>
- array (
- 'pretty_version' => '2.0.0',
- 'version' => '2.0.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '9999f1432fae467bc93c53f357105b4c31bb994c',
- ),
- 'markbaker/matrix' =>
- array (
- 'pretty_version' => '2.0.0',
- 'version' => '2.0.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '9567d9c4c519fbe40de01dbd1e4469dbbb66f46a',
- ),
- 'myclabs/php-enum' =>
- array (
- 'pretty_version' => '1.7.7',
- 'version' => '1.7.7.0',
- 'aliases' =>
- array (
- ),
- 'reference' => 'd178027d1e679832db9f38248fcc7200647dc2b7',
- ),
- 'phpoffice/phpspreadsheet' =>
- array (
- 'pretty_version' => '1.16.0',
- 'version' => '1.16.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '76d4323b85129d0c368149c831a07a3e258b2b50',
- ),
- 'psr/http-client' =>
- array (
- 'pretty_version' => '1.0.1',
- 'version' => '1.0.1.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '2dfb5f6c5eff0e91e20e913f8c5452ed95b86621',
- ),
- 'psr/http-factory' =>
- array (
- 'pretty_version' => '1.0.1',
- 'version' => '1.0.1.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '12ac7fcd07e5b077433f5f2bee95b3a771bf61be',
- ),
- 'psr/http-message' =>
- array (
- 'pretty_version' => '1.0.1',
- 'version' => '1.0.1.0',
- 'aliases' =>
- array (
- ),
- 'reference' => 'f6561bf28d520154e4b0ec72be95418abe6d9363',
- ),
- 'psr/simple-cache' =>
- array (
- 'pretty_version' => '1.0.1',
- 'version' => '1.0.1.0',
- 'aliases' =>
- array (
- ),
- 'reference' => '408d5eafb83c57f6365a3ca330ff23aa4a5fa39b',
- ),
- 'symfony/polyfill-mbstring' =>
- array (
- 'pretty_version' => 'v1.22.0',
- 'version' => '1.22.0.0',
- 'aliases' =>
- array (
- ),
- 'reference' => 'f377a3dd1fde44d37b9831d68dc8dea3ffd28e13',
- ),
- ),
);
diff --git a/lib/phpspreadsheet/vendor/composer/platform_check.php b/lib/phpspreadsheet/vendor/composer/platform_check.php
index 589e9e770b9..92370c5a0c9 100644
--- a/lib/phpspreadsheet/vendor/composer/platform_check.php
+++ b/lib/phpspreadsheet/vendor/composer/platform_check.php
@@ -4,8 +4,8 @@
$issues = array();
-if (!(PHP_VERSION_ID >= 70200)) {
- $issues[] = 'Your Composer dependencies require a PHP version ">= 7.2.0". You are running ' . PHP_VERSION . '.';
+if (!(PHP_VERSION_ID >= 70300)) {
+ $issues[] = 'Your Composer dependencies require a PHP version ">= 7.3.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/README.md b/lib/phpspreadsheet/vendor/markbaker/complex/README.md
index c306394eeb6..27afc59c4eb 100644
--- a/lib/phpspreadsheet/vendor/markbaker/complex/README.md
+++ b/lib/phpspreadsheet/vendor/markbaker/complex/README.md
@@ -3,11 +3,13 @@ PHPComplex
---
-PHP Class for handling Complex numbers
+PHP Class Library for working with Complex numbers
-Master: [](http://travis-ci.org/MarkBaker/PHPComplex)
+[](https://github.com/MarkBaker/PHPComplex/actions)
+[](https://packagist.org/packages/markbaker/complex)
+[](https://packagist.org/packages/markbaker/complex)
+[](https://packagist.org/packages/markbaker/complex)
-Develop: [](http://travis-ci.org/MarkBaker/PHPComplex)
[](https://xkcd.com/2028/)
@@ -63,19 +65,37 @@ together with functions for
---
+# Installation
+
+```shell
+composer require markbaker/complex:^3.0
+```
+
+# Important BC Note
+
+If you've previously been using procedural calls to functions and operations using this library, then from version 3.0 you should use [MarkBaker/PHPComplexFunctions](https://github.com/MarkBaker/PHPComplexFunctions) instead (available on packagist as [markbaker/complex-functions](https://packagist.org/packages/markbaker/complex-functions)).
+
+You'll need to replace `markbaker/complex`in your `composer.json` file with the new library, but otherwise there should be no difference in the namespacing, or in the way that you have called the Complex functions in the past, so no actual code changes are required.
+
+```shell
+composer require markbaker/complex-functions:^1.0
+```
+
+You should not reference this library (`markbaker/complex`) in your `composer.json`, composer wil take care of that for you.
+
# Usage
To create a new complex object, you can provide either the real, imaginary and suffix parts as individual values, or as an array of values passed passed to the constructor; or a string representing the value. e.g
-```
+```php
$real = 1.23;
$imaginary = -4.56;
$suffix = 'i';
$complexObject = new Complex\Complex($real, $imaginary, $suffix);
```
-or
-```
+or as an array
+```php
$real = 1.23;
$imaginary = -4.56;
$suffix = 'i';
@@ -84,8 +104,8 @@ $arguments = [$real, $imaginary, $suffix];
$complexObject = new Complex\Complex($arguments);
```
-or
-```
+or as a string
+```php
$complexString = '1.23-4.56i';
$complexObject = new Complex\Complex($complexString);
@@ -98,57 +118,54 @@ This also allows you to chain multiple methods as you would for a fluent interfa
To perform mathematical operations with Complex values, you can call the appropriate method against a complex value, passing other values as arguments
-```
+```php
$complexString1 = '1.23-4.56i';
$complexString2 = '2.34+5.67i';
$complexObject = new Complex\Complex($complexString1);
echo $complexObject->add($complexString2);
```
-or pass all values to the appropriate function
-```
+
+or use the static Operation methods
+```php
$complexString1 = '1.23-4.56i';
$complexString2 = '2.34+5.67i';
-echo Complex\add($complexString1, $complexString2);
+echo Complex\Operations::add($complexString1, $complexString2);
```
If you want to perform the same operation against multiple values (e.g. to add three or more complex numbers), then you can pass multiple arguments to any of the operations.
-You can pass these arguments as Complex objects, or as an array or string that will parse to a complex object.
+You can pass these arguments as Complex objects, or as an array, or string that will parse to a complex object.
## Using functions
When calling any of the available functions for a complex value, you can either call the relevant method for the Complex object
-```
+```php
$complexString = '1.23-4.56i';
$complexObject = new Complex\Complex($complexString);
echo $complexObject->sinh();
```
-or you can call the function as you would in procedural code, passing the Complex object as an argument
+
+or use the static Functions methods
+```php
+$complexString = '1.23-4.56i';
+
+echo Complex\Functions::sinh($complexString);
```
+As with operations, you can pass these arguments as Complex objects, or as an array or string that will parse to a complex object.
+
+
+In the case of the `pow()` function (the only implemented function that requires an additional argument) you need to pass both arguments when calling the function
+
+```php
$complexString = '1.23-4.56i';
$complexObject = new Complex\Complex($complexString);
-echo Complex\sinh($complexObject);
-```
-When called procedurally using the function, you can pass in the argument as a Complex object, or as an array or string that will parse to a complex object.
-```
-$complexString = '1.23-4.56i';
-
-echo Complex\sinh($complexString);
-```
-
-In the case of the `pow()` function (the only implemented function that requires an additional argument) you need to pass both arguments when calling the function procedurally
-
-```
-$complexString = '1.23-4.56i';
-
-$complexObject = new Complex\Complex($complexString);
-echo Complex\pow($complexObject, 2);
+echo Complex\Functions::pow($complexObject, 2);
```
or pass the additional argument when calling the method
-```
+```php
$complexString = '1.23-4.56i';
$complexObject = new Complex\Complex($complexString);
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/Autoloader.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/Autoloader.php
deleted file mode 100644
index 792ecef0d97..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/Autoloader.php
+++ /dev/null
@@ -1,53 +0,0 @@
-regex = $regex;
- parent::__construct($it, $regex);
- }
-}
-
-class FilenameFilter extends FilesystemRegexFilter
-{
- // Filter files against the regex
- public function accept()
- {
- return (!$this->isFile() || preg_match($this->regex, $this->getFilename()));
- }
-}
-
-
-$srcFolder = __DIR__ . DIRECTORY_SEPARATOR . 'src';
-$srcDirectory = new RecursiveDirectoryIterator($srcFolder);
-
-$filteredFileList = new FilenameFilter($srcDirectory, '/(?:php)$/i');
-$filteredFileList = new FilenameFilter($filteredFileList, '/^(?!.*(Complex|Exception)\.php).*$/i');
-
-foreach (new RecursiveIteratorIterator($filteredFileList) as $file) {
- if ($file->isFile()) {
- include_once $file;
- }
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/Complex.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/Complex.php
index f7ba162188b..25414ee612e 100644
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/Complex.php
+++ b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/Complex.php
@@ -186,7 +186,7 @@ class Complex
// Set parsed values in our properties
$this->realPart = (float) $realPart;
$this->imaginaryPart = (float) $imaginaryPart;
- $this->suffix = strtolower($suffix);
+ $this->suffix = strtolower($suffix ?? '');
}
/**
@@ -377,13 +377,11 @@ class Complex
// Test for function calls
if (in_array($functionName, self::$functions, true)) {
- $functionName = "\\" . __NAMESPACE__ . "\\{$functionName}";
- return $functionName($this, ...$arguments);
+ return Functions::$functionName($this, ...$arguments);
}
// Test for operation calls
if (in_array($functionName, self::$operations, true)) {
- $functionName = "\\" . __NAMESPACE__ . "\\{$functionName}";
- return $functionName($this, ...$arguments);
+ return Operations::$functionName($this, ...$arguments);
}
throw new Exception('Complex Function or Operation does not exist');
}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/Functions.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/Functions.php
new file mode 100644
index 00000000000..ba593ac3683
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/Functions.php
@@ -0,0 +1,805 @@
+getReal() - $invsqrt->getImaginary(),
+ $complex->getImaginary() + $invsqrt->getReal()
+ );
+ $log = self::ln($adjust);
+
+ return new Complex(
+ $log->getImaginary(),
+ -1 * $log->getReal()
+ );
+ }
+
+ /**
+ * Returns the inverse hyperbolic cosine of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse hyperbolic cosine of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function acosh($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->isReal() && ($complex->getReal() > 1)) {
+ return new Complex(\acosh($complex->getReal()));
+ }
+
+ $acosh = self::acos($complex)
+ ->reverse();
+ if ($acosh->getReal() < 0.0) {
+ $acosh = $acosh->invertReal();
+ }
+
+ return $acosh;
+ }
+
+ /**
+ * Returns the inverse cotangent of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse cotangent of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function acot($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ return self::atan(self::inverse($complex));
+ }
+
+ /**
+ * Returns the inverse hyperbolic cotangent of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse hyperbolic cotangent of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function acoth($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ return self::atanh(self::inverse($complex));
+ }
+
+ /**
+ * Returns the inverse cosecant of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse cosecant of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function acsc($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ return new Complex(INF);
+ }
+
+ return self::asin(self::inverse($complex));
+ }
+
+ /**
+ * Returns the inverse hyperbolic cosecant of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse hyperbolic cosecant of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function acsch($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ return new Complex(INF);
+ }
+
+ return self::asinh(self::inverse($complex));
+ }
+
+ /**
+ * Returns the argument of a complex number.
+ * Also known as the theta of the complex number, i.e. the angle in radians
+ * from the real axis to the representation of the number in polar coordinates.
+ *
+ * This function is a synonym for theta()
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return float The argument (or theta) value of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ *
+ * @see theta
+ */
+ public static function argument($complex): float
+ {
+ return self::theta($complex);
+ }
+
+ /**
+ * Returns the inverse secant of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse secant of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function asec($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ return new Complex(INF);
+ }
+
+ return self::acos(self::inverse($complex));
+ }
+
+ /**
+ * Returns the inverse hyperbolic secant of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse hyperbolic secant of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function asech($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ return new Complex(INF);
+ }
+
+ return self::acosh(self::inverse($complex));
+ }
+
+ /**
+ * Returns the inverse sine of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse sine of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function asin($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ $square = Operations::multiply($complex, $complex);
+ $invsqrt = new Complex(1.0);
+ $invsqrt = Operations::subtract($invsqrt, $square);
+ $invsqrt = self::sqrt($invsqrt);
+ $adjust = new Complex(
+ $invsqrt->getReal() - $complex->getImaginary(),
+ $invsqrt->getImaginary() + $complex->getReal()
+ );
+ $log = self::ln($adjust);
+
+ return new Complex(
+ $log->getImaginary(),
+ -1 * $log->getReal()
+ );
+ }
+
+ /**
+ * Returns the inverse hyperbolic sine of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse hyperbolic sine of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function asinh($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->isReal() && ($complex->getReal() > 1)) {
+ return new Complex(\asinh($complex->getReal()));
+ }
+
+ $asinh = clone $complex;
+ $asinh = $asinh->reverse()
+ ->invertReal();
+ $asinh = self::asin($asinh);
+
+ return $asinh->reverse()
+ ->invertImaginary();
+ }
+
+ /**
+ * Returns the inverse tangent of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse tangent of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function atan($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->isReal()) {
+ return new Complex(\atan($complex->getReal()));
+ }
+
+ $t1Value = new Complex(-1 * $complex->getImaginary(), $complex->getReal());
+ $uValue = new Complex(1, 0);
+
+ $d1Value = clone $uValue;
+ $d1Value = Operations::subtract($d1Value, $t1Value);
+ $d2Value = Operations::add($t1Value, $uValue);
+ $uResult = $d1Value->divideBy($d2Value);
+ $uResult = self::ln($uResult);
+
+ return new Complex(
+ (($uResult->getImaginary() == M_PI) ? -M_PI : $uResult->getImaginary()) * -0.5,
+ $uResult->getReal() * 0.5,
+ $complex->getSuffix()
+ );
+ }
+
+ /**
+ * Returns the inverse hyperbolic tangent of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse hyperbolic tangent of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function atanh($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->isReal()) {
+ $real = $complex->getReal();
+ if ($real >= -1.0 && $real <= 1.0) {
+ return new Complex(\atanh($real));
+ } else {
+ return new Complex(\atanh(1 / $real), (($real < 0.0) ? M_PI_2 : -1 * M_PI_2));
+ }
+ }
+
+ $iComplex = clone $complex;
+ $iComplex = $iComplex->invertImaginary()
+ ->reverse();
+ return self::atan($iComplex)
+ ->invertReal()
+ ->reverse();
+ }
+
+ /**
+ * Returns the complex conjugate of a complex number
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The conjugate of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function conjugate($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ return new Complex(
+ $complex->getReal(),
+ -1 * $complex->getImaginary(),
+ $complex->getSuffix()
+ );
+ }
+
+ /**
+ * Returns the cosine of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The cosine of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function cos($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->isReal()) {
+ return new Complex(\cos($complex->getReal()));
+ }
+
+ return self::conjugate(
+ new Complex(
+ \cos($complex->getReal()) * \cosh($complex->getImaginary()),
+ \sin($complex->getReal()) * \sinh($complex->getImaginary()),
+ $complex->getSuffix()
+ )
+ );
+ }
+
+ /**
+ * Returns the hyperbolic cosine of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The hyperbolic cosine of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function cosh($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->isReal()) {
+ return new Complex(\cosh($complex->getReal()));
+ }
+
+ return new Complex(
+ \cosh($complex->getReal()) * \cos($complex->getImaginary()),
+ \sinh($complex->getReal()) * \sin($complex->getImaginary()),
+ $complex->getSuffix()
+ );
+ }
+
+ /**
+ * Returns the cotangent of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The cotangent of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function cot($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ return new Complex(INF);
+ }
+
+ return self::inverse(self::tan($complex));
+ }
+
+ /**
+ * Returns the hyperbolic cotangent of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The hyperbolic cotangent of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function coth($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ return self::inverse(self::tanh($complex));
+ }
+
+ /**
+ * Returns the cosecant of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The cosecant of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function csc($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ return new Complex(INF);
+ }
+
+ return self::inverse(self::sin($complex));
+ }
+
+ /**
+ * Returns the hyperbolic cosecant of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The hyperbolic cosecant of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function csch($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ return new Complex(INF);
+ }
+
+ return self::inverse(self::sinh($complex));
+ }
+
+ /**
+ * Returns the exponential of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The exponential of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function exp($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if (($complex->getReal() == 0.0) && (\abs($complex->getImaginary()) == M_PI)) {
+ return new Complex(-1.0, 0.0);
+ }
+
+ $rho = \exp($complex->getReal());
+
+ return new Complex(
+ $rho * \cos($complex->getImaginary()),
+ $rho * \sin($complex->getImaginary()),
+ $complex->getSuffix()
+ );
+ }
+
+ /**
+ * Returns the inverse of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The inverse of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws InvalidArgumentException If function would result in a division by zero
+ */
+ public static function inverse($complex): Complex
+ {
+ $complex = clone Complex::validateComplexArgument($complex);
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ throw new InvalidArgumentException('Division by zero');
+ }
+
+ return $complex->divideInto(1.0);
+ }
+
+ /**
+ * Returns the natural logarithm of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The natural logarithm of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws InvalidArgumentException If the real and the imaginary parts are both zero
+ */
+ public static function ln($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if (($complex->getReal() == 0.0) && ($complex->getImaginary() == 0.0)) {
+ throw new InvalidArgumentException();
+ }
+
+ return new Complex(
+ \log(self::rho($complex)),
+ self::theta($complex),
+ $complex->getSuffix()
+ );
+ }
+
+ /**
+ * Returns the base-2 logarithm of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The base-2 logarithm of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws InvalidArgumentException If the real and the imaginary parts are both zero
+ */
+ public static function log2($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if (($complex->getReal() == 0.0) && ($complex->getImaginary() == 0.0)) {
+ throw new InvalidArgumentException();
+ } elseif (($complex->getReal() > 0.0) && ($complex->getImaginary() == 0.0)) {
+ return new Complex(\log($complex->getReal(), 2), 0.0, $complex->getSuffix());
+ }
+
+ return self::ln($complex)
+ ->multiply(\log(Complex::EULER, 2));
+ }
+
+ /**
+ * Returns the common logarithm (base 10) of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The common logarithm (base 10) of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws InvalidArgumentException If the real and the imaginary parts are both zero
+ */
+ public static function log10($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if (($complex->getReal() == 0.0) && ($complex->getImaginary() == 0.0)) {
+ throw new InvalidArgumentException();
+ } elseif (($complex->getReal() > 0.0) && ($complex->getImaginary() == 0.0)) {
+ return new Complex(\log10($complex->getReal()), 0.0, $complex->getSuffix());
+ }
+
+ return self::ln($complex)
+ ->multiply(\log10(Complex::EULER));
+ }
+
+ /**
+ * Returns the negative of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The negative value of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ *
+ * @see rho
+ *
+ */
+ public static function negative($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ return new Complex(
+ -1 * $complex->getReal(),
+ -1 * $complex->getImaginary(),
+ $complex->getSuffix()
+ );
+ }
+
+ /**
+ * Returns a complex number raised to a power.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @param float|integer $power The power to raise this value to
+ * @return Complex The complex argument raised to the real power.
+ * @throws Exception If the power argument isn't a valid real
+ */
+ public static function pow($complex, $power): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if (!is_numeric($power)) {
+ throw new Exception('Power argument must be a real number');
+ }
+
+ if ($complex->getImaginary() == 0.0 && $complex->getReal() >= 0.0) {
+ return new Complex(\pow($complex->getReal(), $power));
+ }
+
+ $rValue = \sqrt(($complex->getReal() * $complex->getReal()) + ($complex->getImaginary() * $complex->getImaginary()));
+ $rPower = \pow($rValue, $power);
+ $theta = $complex->argument() * $power;
+ if ($theta == 0) {
+ return new Complex(1);
+ }
+
+ return new Complex($rPower * \cos($theta), $rPower * \sin($theta), $complex->getSuffix());
+ }
+
+ /**
+ * Returns the rho of a complex number.
+ * This is the distance/radius from the centrepoint to the representation of the number in polar coordinates.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return float The rho value of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function rho($complex): float
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ return \sqrt(
+ ($complex->getReal() * $complex->getReal()) +
+ ($complex->getImaginary() * $complex->getImaginary())
+ );
+ }
+
+ /**
+ * Returns the secant of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The secant of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function sec($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ return self::inverse(self::cos($complex));
+ }
+
+ /**
+ * Returns the hyperbolic secant of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The hyperbolic secant of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function sech($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ return self::inverse(self::cosh($complex));
+ }
+
+ /**
+ * Returns the sine of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The sine of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function sin($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->isReal()) {
+ return new Complex(\sin($complex->getReal()));
+ }
+
+ return new Complex(
+ \sin($complex->getReal()) * \cosh($complex->getImaginary()),
+ \cos($complex->getReal()) * \sinh($complex->getImaginary()),
+ $complex->getSuffix()
+ );
+ }
+
+ /**
+ * Returns the hyperbolic sine of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The hyperbolic sine of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function sinh($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->isReal()) {
+ return new Complex(\sinh($complex->getReal()));
+ }
+
+ return new Complex(
+ \sinh($complex->getReal()) * \cos($complex->getImaginary()),
+ \cosh($complex->getReal()) * \sin($complex->getImaginary()),
+ $complex->getSuffix()
+ );
+ }
+
+ /**
+ * Returns the square root of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The Square root of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function sqrt($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ $theta = self::theta($complex);
+ $delta1 = \cos($theta / 2);
+ $delta2 = \sin($theta / 2);
+ $rho = \sqrt(self::rho($complex));
+
+ return new Complex($delta1 * $rho, $delta2 * $rho, $complex->getSuffix());
+ }
+
+ /**
+ * Returns the tangent of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The tangent of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws InvalidArgumentException If function would result in a division by zero
+ */
+ public static function tan($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->isReal()) {
+ return new Complex(\tan($complex->getReal()));
+ }
+
+ $real = $complex->getReal();
+ $imaginary = $complex->getImaginary();
+ $divisor = 1 + \pow(\tan($real), 2) * \pow(\tanh($imaginary), 2);
+ if ($divisor == 0.0) {
+ throw new InvalidArgumentException('Division by zero');
+ }
+
+ return new Complex(
+ \pow(self::sech($imaginary)->getReal(), 2) * \tan($real) / $divisor,
+ \pow(self::sec($real)->getReal(), 2) * \tanh($imaginary) / $divisor,
+ $complex->getSuffix()
+ );
+ }
+
+ /**
+ * Returns the hyperbolic tangent of a complex number.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return Complex The hyperbolic tangent of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ * @throws \InvalidArgumentException If function would result in a division by zero
+ */
+ public static function tanh($complex): Complex
+ {
+ $complex = Complex::validateComplexArgument($complex);
+ $real = $complex->getReal();
+ $imaginary = $complex->getImaginary();
+ $divisor = \cos($imaginary) * \cos($imaginary) + \sinh($real) * \sinh($real);
+ if ($divisor == 0.0) {
+ throw new InvalidArgumentException('Division by zero');
+ }
+
+ return new Complex(
+ \sinh($real) * \cosh($real) / $divisor,
+ 0.5 * \sin(2 * $imaginary) / $divisor,
+ $complex->getSuffix()
+ );
+ }
+
+ /**
+ * Returns the theta of a complex number.
+ * This is the angle in radians from the real axis to the representation of the number in polar coordinates.
+ *
+ * @param Complex|mixed $complex Complex number or a numeric value.
+ * @return float The theta value of the complex argument.
+ * @throws Exception If argument isn't a valid real or complex number.
+ */
+ public static function theta($complex): float
+ {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($complex->getReal() == 0.0) {
+ if ($complex->isReal()) {
+ return 0.0;
+ } elseif ($complex->getImaginary() < 0.0) {
+ return M_PI / -2;
+ }
+ return M_PI / 2;
+ } elseif ($complex->getReal() > 0.0) {
+ return \atan($complex->getImaginary() / $complex->getReal());
+ } elseif ($complex->getImaginary() < 0.0) {
+ return -(M_PI - \atan(\abs($complex->getImaginary()) / \abs($complex->getReal())));
+ }
+
+ return M_PI - \atan($complex->getImaginary() / \abs($complex->getReal()));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/Operations.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/Operations.php
new file mode 100644
index 00000000000..b13a8734dc4
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/Operations.php
@@ -0,0 +1,210 @@
+isComplex() && $complex->isComplex() &&
+ $result->getSuffix() !== $complex->getSuffix()) {
+ throw new Exception('Suffix Mismatch');
+ }
+
+ $real = $result->getReal() + $complex->getReal();
+ $imaginary = $result->getImaginary() + $complex->getImaginary();
+
+ $result = new Complex(
+ $real,
+ $imaginary,
+ ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
+ );
+ }
+
+ return $result;
+ }
+
+ /**
+ * Divides two or more complex numbers
+ *
+ * @param array of string|integer|float|Complex $complexValues The numbers to divide
+ * @return Complex
+ */
+ public static function divideby(...$complexValues): Complex
+ {
+ if (count($complexValues) < 2) {
+ throw new \Exception('This function requires at least 2 arguments');
+ }
+
+ $base = array_shift($complexValues);
+ $result = clone Complex::validateComplexArgument($base);
+
+ foreach ($complexValues as $complex) {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($result->isComplex() && $complex->isComplex() &&
+ $result->getSuffix() !== $complex->getSuffix()) {
+ throw new Exception('Suffix Mismatch');
+ }
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ throw new InvalidArgumentException('Division by zero');
+ }
+
+ $delta1 = ($result->getReal() * $complex->getReal()) +
+ ($result->getImaginary() * $complex->getImaginary());
+ $delta2 = ($result->getImaginary() * $complex->getReal()) -
+ ($result->getReal() * $complex->getImaginary());
+ $delta3 = ($complex->getReal() * $complex->getReal()) +
+ ($complex->getImaginary() * $complex->getImaginary());
+
+ $real = $delta1 / $delta3;
+ $imaginary = $delta2 / $delta3;
+
+ $result = new Complex(
+ $real,
+ $imaginary,
+ ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
+ );
+ }
+
+ return $result;
+ }
+
+ /**
+ * Divides two or more complex numbers
+ *
+ * @param array of string|integer|float|Complex $complexValues The numbers to divide
+ * @return Complex
+ */
+ public static function divideinto(...$complexValues): Complex
+ {
+ if (count($complexValues) < 2) {
+ throw new \Exception('This function requires at least 2 arguments');
+ }
+
+ $base = array_shift($complexValues);
+ $result = clone Complex::validateComplexArgument($base);
+
+ foreach ($complexValues as $complex) {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($result->isComplex() && $complex->isComplex() &&
+ $result->getSuffix() !== $complex->getSuffix()) {
+ throw new Exception('Suffix Mismatch');
+ }
+ if ($result->getReal() == 0.0 && $result->getImaginary() == 0.0) {
+ throw new InvalidArgumentException('Division by zero');
+ }
+
+ $delta1 = ($complex->getReal() * $result->getReal()) +
+ ($complex->getImaginary() * $result->getImaginary());
+ $delta2 = ($complex->getImaginary() * $result->getReal()) -
+ ($complex->getReal() * $result->getImaginary());
+ $delta3 = ($result->getReal() * $result->getReal()) +
+ ($result->getImaginary() * $result->getImaginary());
+
+ $real = $delta1 / $delta3;
+ $imaginary = $delta2 / $delta3;
+
+ $result = new Complex(
+ $real,
+ $imaginary,
+ ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
+ );
+ }
+
+ return $result;
+ }
+
+ /**
+ * Multiplies two or more complex numbers
+ *
+ * @param array of string|integer|float|Complex $complexValues The numbers to multiply
+ * @return Complex
+ */
+ public static function multiply(...$complexValues): Complex
+ {
+ if (count($complexValues) < 2) {
+ throw new \Exception('This function requires at least 2 arguments');
+ }
+
+ $base = array_shift($complexValues);
+ $result = clone Complex::validateComplexArgument($base);
+
+ foreach ($complexValues as $complex) {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($result->isComplex() && $complex->isComplex() &&
+ $result->getSuffix() !== $complex->getSuffix()) {
+ throw new Exception('Suffix Mismatch');
+ }
+
+ $real = ($result->getReal() * $complex->getReal()) -
+ ($result->getImaginary() * $complex->getImaginary());
+ $imaginary = ($result->getReal() * $complex->getImaginary()) +
+ ($result->getImaginary() * $complex->getReal());
+
+ $result = new Complex(
+ $real,
+ $imaginary,
+ ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
+ );
+ }
+
+ return $result;
+ }
+
+ /**
+ * Subtracts two or more complex numbers
+ *
+ * @param array of string|integer|float|Complex $complexValues The numbers to subtract
+ * @return Complex
+ */
+ public static function subtract(...$complexValues): Complex
+ {
+ if (count($complexValues) < 2) {
+ throw new \Exception('This function requires at least 2 arguments');
+ }
+
+ $base = array_shift($complexValues);
+ $result = clone Complex::validateComplexArgument($base);
+
+ foreach ($complexValues as $complex) {
+ $complex = Complex::validateComplexArgument($complex);
+
+ if ($result->isComplex() && $complex->isComplex() &&
+ $result->getSuffix() !== $complex->getSuffix()) {
+ throw new Exception('Suffix Mismatch');
+ }
+
+ $real = $result->getReal() - $complex->getReal();
+ $imaginary = $result->getImaginary() - $complex->getImaginary();
+
+ $result = new Complex(
+ $real,
+ $imaginary,
+ ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
+ );
+ }
+
+ return $result;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/abs.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/abs.php
deleted file mode 100644
index 6e2729a891e..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/abs.php
+++ /dev/null
@@ -1,29 +0,0 @@
-getReal() - $invsqrt->getImaginary(),
- $complex->getImaginary() + $invsqrt->getReal()
- );
- $log = ln($adjust);
-
- return new Complex(
- $log->getImaginary(),
- -1 * $log->getReal()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/acosh.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/acosh.php
deleted file mode 100644
index 18a992e4308..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/acosh.php
+++ /dev/null
@@ -1,34 +0,0 @@
-isReal() && ($complex->getReal() > 1)) {
- return new Complex(\acosh($complex->getReal()));
- }
-
- $acosh = acos($complex)
- ->reverse();
- if ($acosh->getReal() < 0.0) {
- $acosh = $acosh->invertReal();
- }
-
- return $acosh;
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/acot.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/acot.php
deleted file mode 100644
index 4ddc2ddb37c..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/acot.php
+++ /dev/null
@@ -1,25 +0,0 @@
-getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- return new Complex(INF);
- }
-
- return asin(inverse($complex));
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/acsch.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/acsch.php
deleted file mode 100644
index 66d9bdf2c09..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/acsch.php
+++ /dev/null
@@ -1,29 +0,0 @@
-getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- return new Complex(INF);
- }
-
- return asinh(inverse($complex));
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/argument.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/argument.php
deleted file mode 100644
index 17217bb3073..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/argument.php
+++ /dev/null
@@ -1,28 +0,0 @@
-getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- return new Complex(INF);
- }
-
- return acos(inverse($complex));
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/asech.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/asech.php
deleted file mode 100644
index 929b0d19f1a..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/asech.php
+++ /dev/null
@@ -1,29 +0,0 @@
-getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- return new Complex(INF);
- }
-
- return acosh(inverse($complex));
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/asin.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/asin.php
deleted file mode 100644
index b675046a80e..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/asin.php
+++ /dev/null
@@ -1,37 +0,0 @@
-getReal() - $complex->getImaginary(),
- $invsqrt->getImaginary() + $complex->getReal()
- );
- $log = ln($adjust);
-
- return new Complex(
- $log->getImaginary(),
- -1 * $log->getReal()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/asinh.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/asinh.php
deleted file mode 100644
index 3e5c2944fee..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/asinh.php
+++ /dev/null
@@ -1,33 +0,0 @@
-isReal() && ($complex->getReal() > 1)) {
- return new Complex(\asinh($complex->getReal()));
- }
-
- $asinh = clone $complex;
- $asinh = $asinh->reverse()
- ->invertReal();
- $asinh = asin($asinh);
- return $asinh->reverse()
- ->invertImaginary();
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/atan.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/atan.php
deleted file mode 100644
index ecbea801c58..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/atan.php
+++ /dev/null
@@ -1,45 +0,0 @@
-isReal()) {
- return new Complex(\atan($complex->getReal()));
- }
-
- $t1Value = new Complex(-1 * $complex->getImaginary(), $complex->getReal());
- $uValue = new Complex(1, 0);
-
- $d1Value = clone $uValue;
- $d1Value = subtract($d1Value, $t1Value);
- $d2Value = add($t1Value, $uValue);
- $uResult = $d1Value->divideBy($d2Value);
- $uResult = ln($uResult);
-
- return new Complex(
- (($uResult->getImaginary() == M_PI) ? -M_PI : $uResult->getImaginary()) * -0.5,
- $uResult->getReal() * 0.5,
- $complex->getSuffix()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/atanh.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/atanh.php
deleted file mode 100644
index 189493b8831..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/atanh.php
+++ /dev/null
@@ -1,38 +0,0 @@
-isReal()) {
- $real = $complex->getReal();
- if ($real >= -1.0 && $real <= 1.0) {
- return new Complex(\atanh($real));
- } else {
- return new Complex(\atanh(1 / $real), (($real < 0.0) ? M_PI_2 : -1 * M_PI_2));
- }
- }
-
- $iComplex = clone $complex;
- $iComplex = $iComplex->invertImaginary()
- ->reverse();
- return atan($iComplex)
- ->invertReal()
- ->reverse();
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/conjugate.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/conjugate.php
deleted file mode 100644
index 52666176e11..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/conjugate.php
+++ /dev/null
@@ -1,28 +0,0 @@
-getReal(),
- -1 * $complex->getImaginary(),
- $complex->getSuffix()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/cos.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/cos.php
deleted file mode 100644
index 0c6ea1a8e49..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/cos.php
+++ /dev/null
@@ -1,34 +0,0 @@
-isReal()) {
- return new Complex(\cos($complex->getReal()));
- }
-
- return conjugate(
- new Complex(
- \cos($complex->getReal()) * \cosh($complex->getImaginary()),
- \sin($complex->getReal()) * \sinh($complex->getImaginary()),
- $complex->getSuffix()
- )
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/cosh.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/cosh.php
deleted file mode 100644
index ee674c27053..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/cosh.php
+++ /dev/null
@@ -1,32 +0,0 @@
-isReal()) {
- return new Complex(\cosh($complex->getReal()));
- }
-
- return new Complex(
- \cosh($complex->getReal()) * \cos($complex->getImaginary()),
- \sinh($complex->getReal()) * \sin($complex->getImaginary()),
- $complex->getSuffix()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/cot.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/cot.php
deleted file mode 100644
index 693d0f7c5c2..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/cot.php
+++ /dev/null
@@ -1,29 +0,0 @@
-getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- return new Complex(INF);
- }
-
- return inverse(tan($complex));
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/coth.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/coth.php
deleted file mode 100644
index 1ff1ad50627..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/coth.php
+++ /dev/null
@@ -1,24 +0,0 @@
-getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- return new Complex(INF);
- }
-
- return inverse(sin($complex));
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/csch.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/csch.php
deleted file mode 100644
index acaa6c0cd8b..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/csch.php
+++ /dev/null
@@ -1,29 +0,0 @@
-getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- return new Complex(INF);
- }
-
- return inverse(sinh($complex));
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/exp.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/exp.php
deleted file mode 100644
index 8ab3b3e5968..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/exp.php
+++ /dev/null
@@ -1,34 +0,0 @@
-getReal() == 0.0) && (\abs($complex->getImaginary()) == M_PI)) {
- return new Complex(-1.0, 0.0);
- }
-
- $rho = \exp($complex->getReal());
-
- return new Complex(
- $rho * \cos($complex->getImaginary()),
- $rho * \sin($complex->getImaginary()),
- $complex->getSuffix()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/inverse.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/inverse.php
deleted file mode 100644
index 563e3fd8dc6..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/inverse.php
+++ /dev/null
@@ -1,29 +0,0 @@
-getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- throw new \InvalidArgumentException('Division by zero');
- }
-
- return $complex->divideInto(1.0);
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/ln.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/ln.php
deleted file mode 100644
index d57bb7af586..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/ln.php
+++ /dev/null
@@ -1,33 +0,0 @@
-getReal() == 0.0) && ($complex->getImaginary() == 0.0)) {
- throw new \InvalidArgumentException();
- }
-
- return new Complex(
- \log(rho($complex)),
- theta($complex),
- $complex->getSuffix()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/log10.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/log10.php
deleted file mode 100644
index ce4d001fc2e..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/log10.php
+++ /dev/null
@@ -1,32 +0,0 @@
-getReal() == 0.0) && ($complex->getImaginary() == 0.0)) {
- throw new \InvalidArgumentException();
- } elseif (($complex->getReal() > 0.0) && ($complex->getImaginary() == 0.0)) {
- return new Complex(\log10($complex->getReal()), 0.0, $complex->getSuffix());
- }
-
- return ln($complex)
- ->multiply(\log10(Complex::EULER));
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/log2.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/log2.php
deleted file mode 100644
index 21b3e2aabb5..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/log2.php
+++ /dev/null
@@ -1,32 +0,0 @@
-getReal() == 0.0) && ($complex->getImaginary() == 0.0)) {
- throw new \InvalidArgumentException();
- } elseif (($complex->getReal() > 0.0) && ($complex->getImaginary() == 0.0)) {
- return new Complex(\log($complex->getReal(), 2), 0.0, $complex->getSuffix());
- }
-
- return ln($complex)
- ->multiply(\log(Complex::EULER, 2));
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/negative.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/negative.php
deleted file mode 100644
index 232e178a076..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/negative.php
+++ /dev/null
@@ -1,31 +0,0 @@
-getReal(),
- -1 * $complex->getImaginary(),
- $complex->getSuffix()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/pow.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/pow.php
deleted file mode 100644
index da3340fe1bb..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/pow.php
+++ /dev/null
@@ -1,40 +0,0 @@
-getImaginary() == 0.0 && $complex->getReal() >= 0.0) {
- return new Complex(\pow($complex->getReal(), $power));
- }
-
- $rValue = \sqrt(($complex->getReal() * $complex->getReal()) + ($complex->getImaginary() * $complex->getImaginary()));
- $rPower = \pow($rValue, $power);
- $theta = $complex->argument() * $power;
- if ($theta == 0) {
- return new Complex(1);
- }
-
- return new Complex($rPower * \cos($theta), $rPower * \sin($theta), $complex->getSuffix());
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/rho.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/rho.php
deleted file mode 100644
index d5264a769ff..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/rho.php
+++ /dev/null
@@ -1,28 +0,0 @@
-getReal() * $complex->getReal()) +
- ($complex->getImaginary() * $complex->getImaginary())
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/sec.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/sec.php
deleted file mode 100644
index 1c7768d4ff7..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/sec.php
+++ /dev/null
@@ -1,25 +0,0 @@
-isReal()) {
- return new Complex(\sin($complex->getReal()));
- }
-
- return new Complex(
- \sin($complex->getReal()) * \cosh($complex->getImaginary()),
- \cos($complex->getReal()) * \sinh($complex->getImaginary()),
- $complex->getSuffix()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/sinh.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/sinh.php
deleted file mode 100644
index f051a8e2a59..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/sinh.php
+++ /dev/null
@@ -1,32 +0,0 @@
-isReal()) {
- return new Complex(\sinh($complex->getReal()));
- }
-
- return new Complex(
- \sinh($complex->getReal()) * \cos($complex->getImaginary()),
- \cosh($complex->getReal()) * \sin($complex->getImaginary()),
- $complex->getSuffix()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/sqrt.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/sqrt.php
deleted file mode 100644
index 17c19c70bf9..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/sqrt.php
+++ /dev/null
@@ -1,29 +0,0 @@
-getSuffix());
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/tan.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/tan.php
deleted file mode 100644
index 6996a3a622a..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/tan.php
+++ /dev/null
@@ -1,40 +0,0 @@
-isReal()) {
- return new Complex(\tan($complex->getReal()));
- }
-
- $real = $complex->getReal();
- $imaginary = $complex->getImaginary();
- $divisor = 1 + \pow(\tan($real), 2) * \pow(\tanh($imaginary), 2);
- if ($divisor == 0.0) {
- throw new \InvalidArgumentException('Division by zero');
- }
-
- return new Complex(
- \pow(sech($imaginary)->getReal(), 2) * \tan($real) / $divisor,
- \pow(sec($real)->getReal(), 2) * \tanh($imaginary) / $divisor,
- $complex->getSuffix()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/tanh.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/tanh.php
deleted file mode 100644
index a401042ad5c..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/tanh.php
+++ /dev/null
@@ -1,35 +0,0 @@
-getReal();
- $imaginary = $complex->getImaginary();
- $divisor = \cos($imaginary) * \cos($imaginary) + \sinh($real) * \sinh($real);
- if ($divisor == 0.0) {
- throw new \InvalidArgumentException('Division by zero');
- }
-
- return new Complex(
- \sinh($real) * \cosh($real) / $divisor,
- 0.5 * \sin(2 * $imaginary) / $divisor,
- $complex->getSuffix()
- );
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/theta.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/theta.php
deleted file mode 100644
index f022abb4ec9..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/functions/theta.php
+++ /dev/null
@@ -1,38 +0,0 @@
-getReal() == 0.0) {
- if ($complex->isReal()) {
- return 0.0;
- } elseif ($complex->getImaginary() < 0.0) {
- return M_PI / -2;
- }
- return M_PI / 2;
- } elseif ($complex->getReal() > 0.0) {
- return \atan($complex->getImaginary() / $complex->getReal());
- } elseif ($complex->getImaginary() < 0.0) {
- return -(M_PI - \atan(\abs($complex->getImaginary()) / \abs($complex->getReal())));
- }
-
- return M_PI - \atan($complex->getImaginary() / \abs($complex->getReal()));
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/add.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/add.php
deleted file mode 100644
index 6963bb0450a..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/add.php
+++ /dev/null
@@ -1,46 +0,0 @@
-isComplex() && $complex->isComplex() &&
- $result->getSuffix() !== $complex->getSuffix()) {
- throw new Exception('Suffix Mismatch');
- }
-
- $real = $result->getReal() + $complex->getReal();
- $imaginary = $result->getImaginary() + $complex->getImaginary();
-
- $result = new Complex(
- $real,
- $imaginary,
- ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
- );
- }
-
- return $result;
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/divideby.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/divideby.php
deleted file mode 100644
index a680931cb20..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/divideby.php
+++ /dev/null
@@ -1,56 +0,0 @@
-isComplex() && $complex->isComplex() &&
- $result->getSuffix() !== $complex->getSuffix()) {
- throw new Exception('Suffix Mismatch');
- }
- if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- throw new \InvalidArgumentException('Division by zero');
- }
-
- $delta1 = ($result->getReal() * $complex->getReal()) +
- ($result->getImaginary() * $complex->getImaginary());
- $delta2 = ($result->getImaginary() * $complex->getReal()) -
- ($result->getReal() * $complex->getImaginary());
- $delta3 = ($complex->getReal() * $complex->getReal()) +
- ($complex->getImaginary() * $complex->getImaginary());
-
- $real = $delta1 / $delta3;
- $imaginary = $delta2 / $delta3;
-
- $result = new Complex(
- $real,
- $imaginary,
- ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
- );
- }
-
- return $result;
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/divideinto.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/divideinto.php
deleted file mode 100644
index 70869933efd..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/divideinto.php
+++ /dev/null
@@ -1,56 +0,0 @@
-isComplex() && $complex->isComplex() &&
- $result->getSuffix() !== $complex->getSuffix()) {
- throw new Exception('Suffix Mismatch');
- }
- if ($result->getReal() == 0.0 && $result->getImaginary() == 0.0) {
- throw new \InvalidArgumentException('Division by zero');
- }
-
- $delta1 = ($complex->getReal() * $result->getReal()) +
- ($complex->getImaginary() * $result->getImaginary());
- $delta2 = ($complex->getImaginary() * $result->getReal()) -
- ($complex->getReal() * $result->getImaginary());
- $delta3 = ($result->getReal() * $result->getReal()) +
- ($result->getImaginary() * $result->getImaginary());
-
- $real = $delta1 / $delta3;
- $imaginary = $delta2 / $delta3;
-
- $result = new Complex(
- $real,
- $imaginary,
- ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
- );
- }
-
- return $result;
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/multiply.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/multiply.php
deleted file mode 100644
index 06a52b2781f..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/multiply.php
+++ /dev/null
@@ -1,48 +0,0 @@
-isComplex() && $complex->isComplex() &&
- $result->getSuffix() !== $complex->getSuffix()) {
- throw new Exception('Suffix Mismatch');
- }
-
- $real = ($result->getReal() * $complex->getReal()) -
- ($result->getImaginary() * $complex->getImaginary());
- $imaginary = ($result->getReal() * $complex->getImaginary()) +
- ($result->getImaginary() * $complex->getReal());
-
- $result = new Complex(
- $real,
- $imaginary,
- ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
- );
- }
-
- return $result;
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/subtract.php b/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/subtract.php
deleted file mode 100644
index 0d9985cc534..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/complex/classes/src/operations/subtract.php
+++ /dev/null
@@ -1,46 +0,0 @@
-isComplex() && $complex->isComplex() &&
- $result->getSuffix() !== $complex->getSuffix()) {
- throw new Exception('Suffix Mismatch');
- }
-
- $real = $result->getReal() - $complex->getReal();
- $imaginary = $result->getImaginary() - $complex->getImaginary();
-
- $result = new Complex(
- $real,
- $imaginary,
- ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
- );
- }
-
- return $result;
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/composer.json b/lib/phpspreadsheet/vendor/markbaker/complex/composer.json
index a343d6e8708..ea1d06f5638 100644
--- a/lib/phpspreadsheet/vendor/markbaker/complex/composer.json
+++ b/lib/phpspreadsheet/vendor/markbaker/complex/composer.json
@@ -16,10 +16,6 @@
},
"require-dev": {
"phpunit/phpunit": "^7.0 || ^8.0 || ^9.3",
- "phpdocumentor/phpdocumentor": "2.*",
- "phpmd/phpmd": "2.*",
- "sebastian/phpcpd": "^4.0",
- "phploc/phploc": "^4.0",
"squizlabs/php_codesniffer": "^3.4",
"phpcompatibility/php-compatibility": "^9.0",
"dealerdirect/phpcodesniffer-composer-installer": "^0.7.0"
@@ -27,57 +23,10 @@
"autoload": {
"psr-4": {
"Complex\\": "classes/src/"
- },
- "files": [
- "classes/src/functions/abs.php",
- "classes/src/functions/acos.php",
- "classes/src/functions/acosh.php",
- "classes/src/functions/acot.php",
- "classes/src/functions/acoth.php",
- "classes/src/functions/acsc.php",
- "classes/src/functions/acsch.php",
- "classes/src/functions/argument.php",
- "classes/src/functions/asec.php",
- "classes/src/functions/asech.php",
- "classes/src/functions/asin.php",
- "classes/src/functions/asinh.php",
- "classes/src/functions/atan.php",
- "classes/src/functions/atanh.php",
- "classes/src/functions/conjugate.php",
- "classes/src/functions/cos.php",
- "classes/src/functions/cosh.php",
- "classes/src/functions/cot.php",
- "classes/src/functions/coth.php",
- "classes/src/functions/csc.php",
- "classes/src/functions/csch.php",
- "classes/src/functions/exp.php",
- "classes/src/functions/inverse.php",
- "classes/src/functions/ln.php",
- "classes/src/functions/log2.php",
- "classes/src/functions/log10.php",
- "classes/src/functions/negative.php",
- "classes/src/functions/pow.php",
- "classes/src/functions/rho.php",
- "classes/src/functions/sec.php",
- "classes/src/functions/sech.php",
- "classes/src/functions/sin.php",
- "classes/src/functions/sinh.php",
- "classes/src/functions/sqrt.php",
- "classes/src/functions/tan.php",
- "classes/src/functions/tanh.php",
- "classes/src/functions/theta.php",
- "classes/src/operations/add.php",
- "classes/src/operations/subtract.php",
- "classes/src/operations/multiply.php",
- "classes/src/operations/divideby.php",
- "classes/src/operations/divideinto.php"
- ]
+ }
},
"scripts": {
"style": "phpcs --report-width=200 --standard=PSR2 --report=summary,full classes/src/ unitTests/classes/src -n",
- "mess": "phpmd classes/src/ xml codesize,unusedcode,design,naming -n",
- "lines": "phploc classes/src/ -n",
- "cpd": "phpcpd classes/src/ -n",
"versions": "phpcs --report-width=200 --standard=PHPCompatibility --report=summary,full classes/src/ --runtime-set testVersion 7.2- -n"
},
"minimum-stability": "dev"
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/examples/complexTest.php b/lib/phpspreadsheet/vendor/markbaker/complex/examples/complexTest.php
index 7dafd8a6392..9a5e1238d11 100644
--- a/lib/phpspreadsheet/vendor/markbaker/complex/examples/complexTest.php
+++ b/lib/phpspreadsheet/vendor/markbaker/complex/examples/complexTest.php
@@ -2,7 +2,7 @@
use Complex\Complex as Complex;
-include('../classes/Bootstrap.php');
+include(__DIR__ . '/../vendor/autoload.php');
echo 'Create', PHP_EOL;
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/examples/testFunctions.php b/lib/phpspreadsheet/vendor/markbaker/complex/examples/testFunctions.php
index 4d5ed7358b4..bad1c03ded5 100644
--- a/lib/phpspreadsheet/vendor/markbaker/complex/examples/testFunctions.php
+++ b/lib/phpspreadsheet/vendor/markbaker/complex/examples/testFunctions.php
@@ -2,7 +2,7 @@
namespace Complex;
-include('../classes/Bootstrap.php');
+include(__DIR__ . '/../vendor/autoload.php');
echo 'Function Examples', PHP_EOL;
@@ -39,7 +39,7 @@ $functions = array(
for ($real = -3.5; $real <= 3.5; $real += 0.5) {
for ($imaginary = -3.5; $imaginary <= 3.5; $imaginary += 0.5) {
foreach ($functions as $function) {
- $complexFunction = __NAMESPACE__ . '\\' . $function;
+ $complexFunction = __NAMESPACE__ . '\\Functions::' . $function;
$complex = new Complex($real, $imaginary);
try {
echo $function, '(', $complex, ') = ', $complexFunction($complex), PHP_EOL;
diff --git a/lib/phpspreadsheet/vendor/markbaker/complex/examples/testOperations.php b/lib/phpspreadsheet/vendor/markbaker/complex/examples/testOperations.php
index f791263efd3..2b7e0ba4b66 100644
--- a/lib/phpspreadsheet/vendor/markbaker/complex/examples/testOperations.php
+++ b/lib/phpspreadsheet/vendor/markbaker/complex/examples/testOperations.php
@@ -1,8 +1,9 @@
', $result, PHP_EOL;
echo PHP_EOL;
echo 'Subtraction', PHP_EOL;
-$result = \Complex\subtract(...$values);
+$result = Operations::subtract(...$values);
echo '=> ', $result, PHP_EOL;
echo PHP_EOL;
echo 'Multiplication', PHP_EOL;
-$result = \Complex\multiply(...$values);
+$result = Operations::multiply(...$values);
echo '=> ', $result, PHP_EOL;
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/README.md b/lib/phpspreadsheet/vendor/markbaker/matrix/README.md
index 66a1de4d387..d0dc91452c7 100644
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/README.md
+++ b/lib/phpspreadsheet/vendor/markbaker/matrix/README.md
@@ -5,9 +5,11 @@ PHPMatrix
PHP Class for handling Matrices
-Master: [](http://travis-ci.org/MarkBaker/PHPMatrix)
+[](https://github.com/MarkBaker/PHPMatrix/actions)
+[](https://packagist.org/packages/markbaker/matrix)
+[](https://packagist.org/packages/markbaker/matrix)
+[](https://packagist.org/packages/markbaker/matrix)
-Develop: [](http://travis-ci.org/MarkBaker/PHPMatrix)
[](https://xkcd.com/184/)
@@ -37,22 +39,54 @@ together with functions for
- minors
- trace
- transpose
+ - solve
+ Given Matrices A and B, calculate X for A.X = B
+
+and classes for
+
+ - Decomposition
+ - LU Decomposition with partial row pivoting,
+
+ such that [P].[A] = [L].[U] and [A] = [P]|.[L].[U]
+ - QR Decomposition
+
+ such that [A] = [Q].[R]
## TO DO
- - power()
- - EigenValues
- - EigenVectors
+ - power() function
- Decomposition
+ - Cholesky Decomposition
+ - EigenValue Decomposition
+ - EigenValues
+ - EigenVectors
---
+# Installation
+
+```shell
+composer require markbaker/matrix:^3.0
+```
+
+# Important BC Note
+
+If you've previously been using procedural calls to functions and operations using this library, then from version 3.0 you should use [MarkBaker/PHPMatrixFunctions](https://github.com/MarkBaker/PHPMatrixFunctions) instead (available on packagist as [markbaker/matrix-functions](https://packagist.org/packages/markbaker/matrix-functions)).
+
+You'll need to replace `markbaker/matrix`in your `composer.json` file with the new library, but otherwise there should be no difference in the namespacing, or in the way that you have called the Matrix functions in the past, so no actual code changes are required.
+
+```shell
+composer require markbaker/matrix-functions:^1.0
+```
+
+You should not reference this library (`markbaker/matrix`) in your `composer.json`, composer wil take care of that for you.
+
# Usage
To create a new Matrix object, provide an array as the constructor argument
-```
+```php
$grid = [
[16, 3, 2, 13],
[ 5, 10, 11, 8],
@@ -63,12 +97,12 @@ $grid = [
$matrix = new Matrix\Matrix($grid);
```
The `Builder` class provides helper methods for creating specific matrices, specifically an identity matrix of a specified size; or a matrix of a specified dimensions, with every cell containing a set value.
-```
-$matrix = new Matrix\Builder::createFilledMatrix(1, 5, 3);
+```php
+$matrix = Matrix\Builder::createFilledMatrix(1, 5, 3);
```
Will create a matrix of 5 rows and 3 columns, filled with a `1` in every cell; while
-```
-$matrix = new Matrix\Builder::createIdentityMatrix(3);
+```php
+$matrix = Matrix\Builder::createIdentityMatrix(3);
```
will create a 3x3 identity matrix.
@@ -79,34 +113,34 @@ Matrix objects are immutable: whenever you call a method or pass a grid to a fun
To perform mathematical operations with Matrices, you can call the appropriate method against a matrix value, passing other values as arguments
-```
-$matrix1 = new Matrix([
+```php
+$matrix1 = new Matrix\Matrix([
[2, 7, 6],
[9, 5, 1],
[4, 3, 8],
]);
-$matrix2 = new Matrix([
+$matrix2 = new Matrix\Matrix([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]);
-echo $matrix1->multiply($matrix2);
+var_dump($matrix1->multiply($matrix2)->toArray());
```
-or pass all values to the appropriate function
-```
-$matrix1 = new Matrix([
+or pass all values to the appropriate static method
+```php
+$matrix1 = new Matrix\Matrix([
[2, 7, 6],
[9, 5, 1],
[4, 3, 8],
]);
-$matrix2 = new Matrix([
+$matrix2 = new Matrix\Matrix([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]);
-echo Matrix\multiply($matrix1, $matrix2);
+var_dump(Matrix\Operations::multiply($matrix1, $matrix2)->toArray());
```
You can pass in the arguments as Matrix objects, or as arrays.
@@ -115,7 +149,7 @@ If you want to perform the same operation against multiple values (e.g. to add t
## Using functions
When calling any of the available functions for a matrix value, you can either call the relevant method for the Matrix object
-```
+```php
$grid = [
[16, 3, 2, 13],
[ 5, 10, 11, 8],
@@ -127,31 +161,8 @@ $matrix = new Matrix\Matrix($grid);
echo $matrix->trace();
```
-or you can call the function as you would in procedural code, passing the Matrix object as an argument
-```
-$grid = [
- [16, 3, 2, 13],
- [ 5, 10, 11, 8],
- [ 9, 6, 7, 12],
- [ 4, 15, 14, 1],
-];
-
-$matrix = new Matrix\Matrix($grid);
-echo Matrix\trace($matrix);
-```
-When called procedurally using the function, you can pass in the argument as a Matrix object, or as an array.
-```
-$grid = [
- [16, 3, 2, 13],
- [ 5, 10, 11, 8],
- [ 9, 6, 7, 12],
- [ 4, 15, 14, 1],
-];
-
-echo Matrix\trace($grid);
-```
-As an alternative, it is also possible to call the method directly from the `Functions` class.
-```
+or you can call the static method, passing the Matrix object or array as an argument
+```php
$grid = [
[16, 3, 2, 13],
[ 5, 10, 11, 8],
@@ -162,4 +173,43 @@ $grid = [
$matrix = new Matrix\Matrix($grid);
echo Matrix\Functions::trace($matrix);
```
-Used this way, methods must be called statically, and the argument must be the Matrix object, and cannot be an array.
+```php
+$grid = [
+ [16, 3, 2, 13],
+ [ 5, 10, 11, 8],
+ [ 9, 6, 7, 12],
+ [ 4, 15, 14, 1],
+];
+
+echo Matrix\Functions::trace($grid);
+```
+
+## Decomposition
+
+The library also provides classes for matrix decomposition. You can access these using
+```php
+$grid = [
+ [1, 2],
+ [3, 4],
+];
+
+$matrix = new Matrix\Matrix($grid);
+
+$decomposition = new Matrix\Decomposition\QR($matrix);
+$Q = $decomposition->getQ();
+$R = $decomposition->getR();
+```
+
+or alternatively us the `Decomposition` factory, identifying which form of decomposition you want to use
+```php
+$grid = [
+ [1, 2],
+ [3, 4],
+];
+
+$matrix = new Matrix\Matrix($grid);
+
+$decomposition = Matrix\Decomposition\Decomposition::decomposition(Matrix\Decomposition\Decomposition::QR, $matrix);
+$Q = $decomposition->getQ();
+$R = $decomposition->getR();
+```
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/Autoloader.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/Autoloader.php
deleted file mode 100644
index 279d176eff7..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/Autoloader.php
+++ /dev/null
@@ -1,53 +0,0 @@
-regex = $regex;
- parent::__construct($it, $regex);
- }
-}
-
-class FilenameFilter extends FilesystemRegexFilter
-{
- // Filter files against the regex
- public function accept()
- {
- return (!$this->isFile() || preg_match($this->regex, $this->getFilename()));
- }
-}
-
-
-$srcFolder = __DIR__ . DIRECTORY_SEPARATOR . 'src';
-$srcDirectory = new RecursiveDirectoryIterator($srcFolder);
-
-$filteredFileList = new FilenameFilter($srcDirectory, '/(?:php)$/i');
-$filteredFileList = new FilenameFilter($filteredFileList, '/^(?!.*(Matrix|Exception)\.php).*$/i');
-
-foreach (new RecursiveIteratorIterator($filteredFileList) as $file) {
- if ($file->isFile()) {
- include_once $file;
- }
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Builder.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Builder.php
index 6bc334adcf9..161bb6889d9 100644
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Builder.php
+++ b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Builder.php
@@ -21,13 +21,13 @@ class Builder
* Create a new matrix of specified dimensions, and filled with a specified value
* If the column argument isn't provided, then a square matrix will be created
*
- * @param mixed $value
+ * @param mixed $fillValue
* @param int $rows
* @param int|null $columns
* @return Matrix
* @throws Exception
*/
- public static function createFilledMatrix($value, $rows, $columns = null)
+ public static function createFilledMatrix($fillValue, $rows, $columns = null)
{
if ($columns === null) {
$columns = $rows;
@@ -43,7 +43,7 @@ class Builder
array_fill(
0,
$columns,
- $value
+ $fillValue
)
)
);
@@ -57,9 +57,9 @@ class Builder
* @return Matrix
* @throws Exception
*/
- public static function createIdentityMatrix($dimensions)
+ public static function createIdentityMatrix($dimensions, $fillValue = null)
{
- $grid = static::createFilledMatrix(null, $dimensions)->toArray();
+ $grid = static::createFilledMatrix($fillValue, $dimensions)->toArray();
for ($x = 0; $x < $dimensions; ++$x) {
$grid[$x][$x] = 1;
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Decomposition/Decomposition.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Decomposition/Decomposition.php
new file mode 100644
index 00000000000..f0144487586
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Decomposition/Decomposition.php
@@ -0,0 +1,27 @@
+luMatrix = $matrix->toArray();
+ $this->rows = $matrix->rows;
+ $this->columns = $matrix->columns;
+
+ $this->buildPivot();
+ }
+
+ /**
+ * Get lower triangular factor.
+ *
+ * @return Matrix Lower triangular factor
+ */
+ public function getL(): Matrix
+ {
+ $lower = [];
+
+ $columns = min($this->rows, $this->columns);
+ for ($row = 0; $row < $this->rows; ++$row) {
+ for ($column = 0; $column < $columns; ++$column) {
+ if ($row > $column) {
+ $lower[$row][$column] = $this->luMatrix[$row][$column];
+ } elseif ($row === $column) {
+ $lower[$row][$column] = 1.0;
+ } else {
+ $lower[$row][$column] = 0.0;
+ }
+ }
+ }
+
+ return new Matrix($lower);
+ }
+
+ /**
+ * Get upper triangular factor.
+ *
+ * @return Matrix Upper triangular factor
+ */
+ public function getU(): Matrix
+ {
+ $upper = [];
+
+ $rows = min($this->rows, $this->columns);
+ for ($row = 0; $row < $rows; ++$row) {
+ for ($column = 0; $column < $this->columns; ++$column) {
+ if ($row <= $column) {
+ $upper[$row][$column] = $this->luMatrix[$row][$column];
+ } else {
+ $upper[$row][$column] = 0.0;
+ }
+ }
+ }
+
+ return new Matrix($upper);
+ }
+
+ /**
+ * Return pivot permutation vector.
+ *
+ * @return Matrix Pivot matrix
+ */
+ public function getP(): Matrix
+ {
+ $pMatrix = [];
+
+ $pivots = $this->pivot;
+ $pivotCount = count($pivots);
+ foreach ($pivots as $row => $pivot) {
+ $pMatrix[$row] = array_fill(0, $pivotCount, 0);
+ $pMatrix[$row][$pivot] = 1;
+ }
+
+ return new Matrix($pMatrix);
+ }
+
+ /**
+ * Return pivot permutation vector.
+ *
+ * @return array Pivot vector
+ */
+ public function getPivot(): array
+ {
+ return $this->pivot;
+ }
+
+ /**
+ * Is the matrix nonsingular?
+ *
+ * @return bool true if U, and hence A, is nonsingular
+ */
+ public function isNonsingular(): bool
+ {
+ for ($diagonal = 0; $diagonal < $this->columns; ++$diagonal) {
+ if ($this->luMatrix[$diagonal][$diagonal] === 0.0) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private function buildPivot(): void
+ {
+ for ($row = 0; $row < $this->rows; ++$row) {
+ $this->pivot[$row] = $row;
+ }
+
+ for ($column = 0; $column < $this->columns; ++$column) {
+ $luColumn = $this->localisedReferenceColumn($column);
+
+ $this->applyTransformations($column, $luColumn);
+
+ $pivot = $this->findPivot($column, $luColumn);
+ if ($pivot !== $column) {
+ $this->pivotExchange($pivot, $column);
+ }
+
+ $this->computeMultipliers($column);
+
+ unset($luColumn);
+ }
+ }
+
+ private function localisedReferenceColumn($column): array
+ {
+ $luColumn = [];
+
+ for ($row = 0; $row < $this->rows; ++$row) {
+ $luColumn[$row] = &$this->luMatrix[$row][$column];
+ }
+
+ return $luColumn;
+ }
+
+ private function applyTransformations($column, array $luColumn): void
+ {
+ for ($row = 0; $row < $this->rows; ++$row) {
+ $luRow = $this->luMatrix[$row];
+ // Most of the time is spent in the following dot product.
+ $kmax = min($row, $column);
+ $sValue = 0.0;
+ for ($kValue = 0; $kValue < $kmax; ++$kValue) {
+ $sValue += $luRow[$kValue] * $luColumn[$kValue];
+ }
+ $luRow[$column] = $luColumn[$row] -= $sValue;
+ }
+ }
+
+ private function findPivot($column, array $luColumn): int
+ {
+ $pivot = $column;
+ for ($row = $column + 1; $row < $this->rows; ++$row) {
+ if (abs($luColumn[$row]) > abs($luColumn[$pivot])) {
+ $pivot = $row;
+ }
+ }
+
+ return $pivot;
+ }
+
+ private function pivotExchange($pivot, $column): void
+ {
+ for ($kValue = 0; $kValue < $this->columns; ++$kValue) {
+ $tValue = $this->luMatrix[$pivot][$kValue];
+ $this->luMatrix[$pivot][$kValue] = $this->luMatrix[$column][$kValue];
+ $this->luMatrix[$column][$kValue] = $tValue;
+ }
+
+ $lValue = $this->pivot[$pivot];
+ $this->pivot[$pivot] = $this->pivot[$column];
+ $this->pivot[$column] = $lValue;
+ }
+
+ private function computeMultipliers($diagonal): void
+ {
+ if (($diagonal < $this->rows) && ($this->luMatrix[$diagonal][$diagonal] != 0.0)) {
+ for ($row = $diagonal + 1; $row < $this->rows; ++$row) {
+ $this->luMatrix[$row][$diagonal] /= $this->luMatrix[$diagonal][$diagonal];
+ }
+ }
+ }
+
+ private function pivotB(Matrix $B): array
+ {
+ $X = [];
+ foreach ($this->pivot as $rowId) {
+ $row = $B->getRows($rowId + 1)->toArray();
+ $X[] = array_pop($row);
+ }
+
+ return $X;
+ }
+
+ /**
+ * Solve A*X = B.
+ *
+ * @param Matrix $B a Matrix with as many rows as A and any number of columns
+ *
+ * @throws Exception
+ *
+ * @return Matrix X so that L*U*X = B(piv,:)
+ */
+ public function solve(Matrix $B): Matrix
+ {
+ if ($B->rows !== $this->rows) {
+ throw new Exception('Matrix row dimensions are not equal');
+ }
+
+ if ($this->rows !== $this->columns) {
+ throw new Exception('LU solve() only works on square matrices');
+ }
+
+ if (!$this->isNonsingular()) {
+ throw new Exception('Can only perform operation on singular matrix');
+ }
+
+ // Copy right hand side with pivoting
+ $nx = $B->columns;
+ $X = $this->pivotB($B);
+
+ // Solve L*Y = B(piv,:)
+ for ($k = 0; $k < $this->columns; ++$k) {
+ for ($i = $k + 1; $i < $this->columns; ++$i) {
+ for ($j = 0; $j < $nx; ++$j) {
+ $X[$i][$j] -= $X[$k][$j] * $this->luMatrix[$i][$k];
+ }
+ }
+ }
+
+ // Solve U*X = Y;
+ for ($k = $this->columns - 1; $k >= 0; --$k) {
+ for ($j = 0; $j < $nx; ++$j) {
+ $X[$k][$j] /= $this->luMatrix[$k][$k];
+ }
+ for ($i = 0; $i < $k; ++$i) {
+ for ($j = 0; $j < $nx; ++$j) {
+ $X[$i][$j] -= $X[$k][$j] * $this->luMatrix[$i][$k];
+ }
+ }
+ }
+
+ return new Matrix($X);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Decomposition/QR.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Decomposition/QR.php
new file mode 100644
index 00000000000..4b6106f6413
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Decomposition/QR.php
@@ -0,0 +1,191 @@
+qrMatrix = $matrix->toArray();
+ $this->rows = $matrix->rows;
+ $this->columns = $matrix->columns;
+
+ $this->decompose();
+ }
+
+ public function getHouseholdVectors(): Matrix
+ {
+ $householdVectors = [];
+ for ($row = 0; $row < $this->rows; ++$row) {
+ for ($column = 0; $column < $this->columns; ++$column) {
+ if ($row >= $column) {
+ $householdVectors[$row][$column] = $this->qrMatrix[$row][$column];
+ } else {
+ $householdVectors[$row][$column] = 0.0;
+ }
+ }
+ }
+
+ return new Matrix($householdVectors);
+ }
+
+ public function getQ(): Matrix
+ {
+ $qGrid = [];
+
+ $rowCount = $this->rows;
+ for ($k = $this->columns - 1; $k >= 0; --$k) {
+ for ($i = 0; $i < $this->rows; ++$i) {
+ $qGrid[$i][$k] = 0.0;
+ }
+ $qGrid[$k][$k] = 1.0;
+ if ($this->columns > $this->rows) {
+ $qGrid = array_slice($qGrid, 0, $this->rows);
+ }
+
+ for ($j = $k; $j < $this->columns; ++$j) {
+ if (isset($this->qrMatrix[$k], $this->qrMatrix[$k][$k]) && $this->qrMatrix[$k][$k] != 0.0) {
+ $s = 0.0;
+ for ($i = $k; $i < $this->rows; ++$i) {
+ $s += $this->qrMatrix[$i][$k] * $qGrid[$i][$j];
+ }
+ $s = -$s / $this->qrMatrix[$k][$k];
+ for ($i = $k; $i < $this->rows; ++$i) {
+ $qGrid[$i][$j] += $s * $this->qrMatrix[$i][$k];
+ }
+ }
+ }
+ }
+
+ array_walk(
+ $qGrid,
+ function (&$row) use ($rowCount) {
+ $row = array_reverse($row);
+ $row = array_slice($row, 0, $rowCount);
+ }
+ );
+
+ return new Matrix($qGrid);
+ }
+
+ public function getR(): Matrix
+ {
+ $rGrid = [];
+
+ for ($row = 0; $row < $this->columns; ++$row) {
+ for ($column = 0; $column < $this->columns; ++$column) {
+ if ($row < $column) {
+ $rGrid[$row][$column] = $this->qrMatrix[$row][$column] ?? 0.0;
+ } elseif ($row === $column) {
+ $rGrid[$row][$column] = $this->rDiagonal[$row] ?? 0.0;
+ } else {
+ $rGrid[$row][$column] = 0.0;
+ }
+ }
+ }
+
+ if ($this->columns > $this->rows) {
+ $rGrid = array_slice($rGrid, 0, $this->rows);
+ }
+
+ return new Matrix($rGrid);
+ }
+
+ private function hypo($a, $b): float
+ {
+ if (abs($a) > abs($b)) {
+ $r = $b / $a;
+ $r = abs($a) * sqrt(1 + $r * $r);
+ } elseif ($b != 0.0) {
+ $r = $a / $b;
+ $r = abs($b) * sqrt(1 + $r * $r);
+ } else {
+ $r = 0.0;
+ }
+
+ return $r;
+ }
+
+ /**
+ * QR Decomposition computed by Householder reflections.
+ */
+ private function decompose(): void
+ {
+ for ($k = 0; $k < $this->columns; ++$k) {
+ // Compute 2-norm of k-th column without under/overflow.
+ $norm = 0.0;
+ for ($i = $k; $i < $this->rows; ++$i) {
+ $norm = $this->hypo($norm, $this->qrMatrix[$i][$k]);
+ }
+ if ($norm != 0.0) {
+ // Form k-th Householder vector.
+ if ($this->qrMatrix[$k][$k] < 0.0) {
+ $norm = -$norm;
+ }
+ for ($i = $k; $i < $this->rows; ++$i) {
+ $this->qrMatrix[$i][$k] /= $norm;
+ }
+ $this->qrMatrix[$k][$k] += 1.0;
+ // Apply transformation to remaining columns.
+ for ($j = $k + 1; $j < $this->columns; ++$j) {
+ $s = 0.0;
+ for ($i = $k; $i < $this->rows; ++$i) {
+ $s += $this->qrMatrix[$i][$k] * $this->qrMatrix[$i][$j];
+ }
+ $s = -$s / $this->qrMatrix[$k][$k];
+ for ($i = $k; $i < $this->rows; ++$i) {
+ $this->qrMatrix[$i][$j] += $s * $this->qrMatrix[$i][$k];
+ }
+ }
+ }
+ $this->rDiagonal[$k] = -$norm;
+ }
+ }
+
+ public function isFullRank(): bool
+ {
+ for ($j = 0; $j < $this->columns; ++$j) {
+ if ($this->rDiagonal[$j] == 0.0) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Least squares solution of A*X = B.
+ *
+ * @param Matrix $B a Matrix with as many rows as A and any number of columns
+ *
+ * @throws Exception
+ *
+ * @return Matrix matrix that minimizes the two norm of Q*R*X-B
+ */
+ public function solve(Matrix $B): Matrix
+ {
+ if ($B->rows !== $this->rows) {
+ throw new Exception('Matrix row dimensions are not equal');
+ }
+
+ if (!$this->isFullRank()) {
+ throw new Exception('Can only perform this operation on a full-rank matrix');
+ }
+
+ // Compute Y = transpose(Q)*B
+ $Y = $this->getQ()->transpose()
+ ->multiply($B);
+ // Solve R*X = Y;
+ return $this->getR()->inverse()
+ ->multiply($Y);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Div0Exception.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Div0Exception.php
new file mode 100644
index 00000000000..eba28f8a457
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Div0Exception.php
@@ -0,0 +1,13 @@
+isSquare()) {
throw new Exception('Adjoint can only be calculated for a square matrix');
}
@@ -67,13 +88,15 @@ class Functions
/**
* Return the cofactors of this matrix
*
- * @param Matrix $matrix The matrix whose cofactors we wish to calculate
+ * @param Matrix|array $matrix The matrix whose cofactors we wish to calculate
* @return Matrix
*
* @throws Exception
*/
- public static function cofactors(Matrix $matrix)
+ public static function cofactors($matrix)
{
+ $matrix = self::validateMatrix($matrix);
+
if (!$matrix->isSquare()) {
throw new Exception('Cofactors can only be calculated for a square matrix');
}
@@ -141,12 +164,14 @@ class Functions
/**
* Return the determinant of this matrix
*
- * @param Matrix $matrix The matrix whose determinant we wish to calculate
+ * @param Matrix|array $matrix The matrix whose determinant we wish to calculate
* @return float
* @throws Exception
**/
- public static function determinant(Matrix $matrix)
+ public static function determinant($matrix)
{
+ $matrix = self::validateMatrix($matrix);
+
if (!$matrix->isSquare()) {
throw new Exception('Determinant can only be calculated for a square matrix');
}
@@ -157,12 +182,14 @@ class Functions
/**
* Return the diagonal of this matrix
*
- * @param Matrix $matrix The matrix whose diagonal we wish to calculate
+ * @param Matrix|array $matrix The matrix whose diagonal we wish to calculate
* @return Matrix
* @throws Exception
**/
- public static function diagonal(Matrix $matrix)
+ public static function diagonal($matrix)
{
+ $matrix = self::validateMatrix($matrix);
+
if (!$matrix->isSquare()) {
throw new Exception('Diagonal can only be extracted from a square matrix');
}
@@ -181,12 +208,14 @@ class Functions
/**
* Return the antidiagonal of this matrix
*
- * @param Matrix $matrix The matrix whose antidiagonal we wish to calculate
+ * @param Matrix|array $matrix The matrix whose antidiagonal we wish to calculate
* @return Matrix
* @throws Exception
**/
- public static function antidiagonal(Matrix $matrix)
+ public static function antidiagonal($matrix)
{
+ $matrix = self::validateMatrix($matrix);
+
if (!$matrix->isSquare()) {
throw new Exception('Anti-Diagonal can only be extracted from a square matrix');
}
@@ -207,12 +236,14 @@ class Functions
* The identity matrix, or sometimes ambiguously called a unit matrix, of size n is the n × n square matrix
* with ones on the main diagonal and zeros elsewhere
*
- * @param Matrix $matrix The matrix whose identity we wish to calculate
+ * @param Matrix|array $matrix The matrix whose identity we wish to calculate
* @return Matrix
* @throws Exception
**/
- public static function identity(Matrix $matrix)
+ public static function identity($matrix)
{
+ $matrix = self::validateMatrix($matrix);
+
if (!$matrix->isSquare()) {
throw new Exception('Identity can only be created for a square matrix');
}
@@ -225,19 +256,21 @@ class Functions
/**
* Return the inverse of this matrix
*
- * @param Matrix $matrix The matrix whose inverse we wish to calculate
+ * @param Matrix|array $matrix The matrix whose inverse we wish to calculate
* @return Matrix
* @throws Exception
**/
- public static function inverse(Matrix $matrix)
+ public static function inverse($matrix, string $type = 'inverse')
{
+ $matrix = self::validateMatrix($matrix);
+
if (!$matrix->isSquare()) {
- throw new Exception('Inverse can only be calculated for a square matrix');
+ throw new Exception(ucfirst($type) . ' can only be calculated for a square matrix');
}
$determinant = self::getDeterminant($matrix);
if ($determinant == 0.0) {
- throw new Exception('Inverse can only be calculated for a matrix with a non-zero determinant');
+ throw new Div0Exception(ucfirst($type) . ' can only be calculated for a matrix with a non-zero determinant');
}
if ($matrix->rows == 1) {
@@ -281,12 +314,14 @@ class Functions
* calculating matrix cofactors, which in turn are useful for computing both the determinant and inverse of
* square matrices.
*
- * @param Matrix $matrix The matrix whose minors we wish to calculate
+ * @param Matrix|array $matrix The matrix whose minors we wish to calculate
* @return Matrix
* @throws Exception
**/
- public static function minors(Matrix $matrix)
+ public static function minors($matrix)
{
+ $matrix = self::validateMatrix($matrix);
+
if (!$matrix->isSquare()) {
throw new Exception('Minors can only be calculated for a square matrix');
}
@@ -299,12 +334,14 @@ class Functions
* The trace is defined as the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right)
* of the matrix
*
- * @param Matrix $matrix The matrix whose trace we wish to calculate
+ * @param Matrix|array $matrix The matrix whose trace we wish to calculate
* @return float
* @throws Exception
**/
- public static function trace(Matrix $matrix)
+ public static function trace($matrix)
{
+ $matrix = self::validateMatrix($matrix);
+
if (!$matrix->isSquare()) {
throw new Exception('Trace can only be extracted from a square matrix');
}
@@ -321,11 +358,13 @@ class Functions
/**
* Return the transpose of this matrix
*
- * @param Matrix $matrix The matrix whose transpose we wish to calculate
+ * @param Matrix|\a $matrix The matrix whose transpose we wish to calculate
* @return Matrix
**/
- public static function transpose(Matrix $matrix)
+ public static function transpose($matrix)
{
+ $matrix = self::validateMatrix($matrix);
+
$array = array_values(array_merge([null], $matrix->toArray()));
$grid = call_user_func_array(
'array_map',
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Matrix.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Matrix.php
index e4e3140d12e..95f55e75a35 100644
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Matrix.php
+++ b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Matrix.php
@@ -10,6 +10,10 @@
namespace Matrix;
+use Generator;
+use Matrix\Decomposition\LU;
+use Matrix\Decomposition\QR;
+
/**
* Matrix object.
*
@@ -24,7 +28,6 @@ namespace Matrix;
* @method Matrix diagonal()
* @method Matrix identity()
* @method Matrix inverse()
- * @method Matrix pseudoInverse()
* @method Matrix minors()
* @method float trace()
* @method Matrix transpose()
@@ -33,6 +36,7 @@ namespace Matrix;
* @method Matrix multiply(...$matrices)
* @method Matrix divideby(...$matrices)
* @method Matrix divideinto(...$matrices)
+ * @method Matrix directsum(...$matrices)
*/
class Matrix
{
@@ -270,11 +274,11 @@ class Matrix
/**
* Returns a Generator that will yield each row of the matrix in turn as a vector matrix
- * or the value of each cell if the matrix is a vector
+ * or the value of each cell if the matrix is a column vector
*
- * @return \Generator|Matrix[]|mixed[]
+ * @return Generator|Matrix[]|mixed[]
*/
- public function rows(): \Generator
+ public function rows(): Generator
{
foreach ($this->grid as $i => $row) {
yield $i + 1 => ($this->columns == 1)
@@ -285,11 +289,11 @@ class Matrix
/**
* Returns a Generator that will yield each column of the matrix in turn as a vector matrix
- * or the value of each cell if the matrix is a vector
+ * or the value of each cell if the matrix is a row vector
*
- * @return \Generator|Matrix[]|mixed[]
+ * @return Generator|Matrix[]|mixed[]
*/
- public function columns(): \Generator
+ public function columns(): Generator
{
for ($i = 0; $i < $this->columns; ++$i) {
yield $i + 1 => ($this->rows == 1)
@@ -306,7 +310,7 @@ class Matrix
*/
public function isSquare(): bool
{
- return $this->rows == $this->columns;
+ return $this->rows === $this->columns;
}
/**
@@ -317,7 +321,7 @@ class Matrix
*/
public function isVector(): bool
{
- return $this->rows == 1 || $this->columns == 1;
+ return $this->rows === 1 || $this->columns === 1;
}
/**
@@ -330,6 +334,24 @@ class Matrix
return $this->grid;
}
+ /**
+ * Solve A*X = B.
+ *
+ * @param Matrix $B Right hand side
+ *
+ * @throws Exception
+ *
+ * @return Matrix ... Solution if A is square, least squares solution otherwise
+ */
+ public function solve(Matrix $B): Matrix
+ {
+ if ($this->columns === $this->rows) {
+ return (new LU($this))->solve($B);
+ }
+
+ return (new QR($this))->solve($B);
+ }
+
protected static $getters = [
'rows',
'columns',
@@ -355,8 +377,8 @@ class Matrix
}
protected static $functions = [
- 'antidiagonal',
'adjoint',
+ 'antidiagonal',
'cofactors',
'determinant',
'diagonal',
@@ -388,12 +410,13 @@ class Matrix
{
$functionName = strtolower(str_replace('_', '', $functionName));
- if (in_array($functionName, self::$functions, true) || in_array($functionName, self::$operations, true)) {
- $functionName = "\\" . __NAMESPACE__ . "\\{$functionName}";
- if (is_callable($functionName)) {
- $arguments = array_values(array_merge([$this], $arguments));
- return call_user_func_array($functionName, $arguments);
- }
+ // Test for function calls
+ if (in_array($functionName, self::$functions, true)) {
+ return Functions::$functionName($this, ...$arguments);
+ }
+ // Test for operation calls
+ if (in_array($functionName, self::$operations, true)) {
+ return Operations::$functionName($this, ...$arguments);
}
throw new Exception('Function or Operation does not exist');
}
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Operations.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Operations.php
new file mode 100644
index 00000000000..e3d88d64183
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Operations.php
@@ -0,0 +1,157 @@
+execute($matrix);
+ }
+
+ return $result->result();
+ }
+
+ public static function directsum(...$matrixValues): Matrix
+ {
+ if (count($matrixValues) < 2) {
+ throw new Exception('DirectSum operation requires at least 2 arguments');
+ }
+
+ $matrix = array_shift($matrixValues);
+
+ if (is_array($matrix)) {
+ $matrix = new Matrix($matrix);
+ }
+ if (!$matrix instanceof Matrix) {
+ throw new Exception('DirectSum arguments must be Matrix or array');
+ }
+
+ $result = new DirectSum($matrix);
+
+ foreach ($matrixValues as $matrix) {
+ $result->execute($matrix);
+ }
+
+ return $result->result();
+ }
+
+ public static function divideby(...$matrixValues): Matrix
+ {
+ if (count($matrixValues) < 2) {
+ throw new Exception('Division operation requires at least 2 arguments');
+ }
+
+ $matrix = array_shift($matrixValues);
+
+ if (is_array($matrix)) {
+ $matrix = new Matrix($matrix);
+ }
+ if (!$matrix instanceof Matrix) {
+ throw new Exception('Division arguments must be Matrix or array');
+ }
+
+ $result = new Division($matrix);
+
+ foreach ($matrixValues as $matrix) {
+ $result->execute($matrix);
+ }
+
+ return $result->result();
+ }
+
+ public static function divideinto(...$matrixValues): Matrix
+ {
+ if (count($matrixValues) < 2) {
+ throw new Exception('Division operation requires at least 2 arguments');
+ }
+
+ $matrix = array_pop($matrixValues);
+ $matrixValues = array_reverse($matrixValues);
+
+ if (is_array($matrix)) {
+ $matrix = new Matrix($matrix);
+ }
+ if (!$matrix instanceof Matrix) {
+ throw new Exception('Division arguments must be Matrix or array');
+ }
+
+ $result = new Division($matrix);
+
+ foreach ($matrixValues as $matrix) {
+ $result->execute($matrix);
+ }
+
+ return $result->result();
+ }
+
+ public static function multiply(...$matrixValues): Matrix
+ {
+ if (count($matrixValues) < 2) {
+ throw new Exception('Multiplication operation requires at least 2 arguments');
+ }
+
+ $matrix = array_shift($matrixValues);
+
+ if (is_array($matrix)) {
+ $matrix = new Matrix($matrix);
+ }
+ if (!$matrix instanceof Matrix) {
+ throw new Exception('Multiplication arguments must be Matrix or array');
+ }
+
+ $result = new Multiplication($matrix);
+
+ foreach ($matrixValues as $matrix) {
+ $result->execute($matrix);
+ }
+
+ return $result->result();
+ }
+
+ public static function subtract(...$matrixValues): Matrix
+ {
+ if (count($matrixValues) < 2) {
+ throw new Exception('Subtraction operation requires at least 2 arguments');
+ }
+
+ $matrix = array_shift($matrixValues);
+
+ if (is_array($matrix)) {
+ $matrix = new Matrix($matrix);
+ }
+ if (!$matrix instanceof Matrix) {
+ throw new Exception('Subtraction arguments must be Matrix or array');
+ }
+
+ $result = new Subtraction($matrix);
+
+ foreach ($matrixValues as $matrix) {
+ $result->execute($matrix);
+ }
+
+ return $result->result();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Operators/Division.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Operators/Division.php
index b262f596ae2..dbfec9d3f7d 100644
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Operators/Division.php
+++ b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Operators/Division.php
@@ -2,9 +2,10 @@
namespace Matrix\Operators;
+use Matrix\Div0Exception;
+use Matrix\Exception;
use \Matrix\Matrix;
use \Matrix\Functions;
-use Matrix\Exception;
class Division extends Multiplication
{
@@ -15,22 +16,18 @@ class Division extends Multiplication
* @throws Exception If the provided argument is not appropriate for the operation
* @return $this The operation object, allowing multiple divisions to be chained
**/
- public function execute($value): Operator
+ public function execute($value, string $type = 'division'): Operator
{
if (is_array($value)) {
$value = new Matrix($value);
}
if (is_object($value) && ($value instanceof Matrix)) {
- try {
- $value = Functions::inverse($value);
- } catch (Exception $e) {
- throw new Exception('Division can only be calculated using a matrix with a non-zero determinant');
- }
+ $value = Functions::inverse($value, $type);
- return $this->multiplyMatrix($value);
+ return $this->multiplyMatrix($value, $type);
} elseif (is_numeric($value)) {
- return $this->multiplyScalar(1 / $value);
+ return $this->multiplyScalar(1 / $value, $type);
}
throw new Exception('Invalid argument for division');
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Operators/Multiplication.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Operators/Multiplication.php
index e75d0ade17b..0761e466a40 100644
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Operators/Multiplication.php
+++ b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/Operators/Multiplication.php
@@ -5,6 +5,7 @@ namespace Matrix\Operators;
use Matrix\Matrix;
use \Matrix\Builder;
use Matrix\Exception;
+use Throwable;
class Multiplication extends Operator
{
@@ -15,19 +16,19 @@ class Multiplication extends Operator
* @throws Exception If the provided argument is not appropriate for the operation
* @return $this The operation object, allowing multiple multiplications to be chained
**/
- public function execute($value): Operator
+ public function execute($value, string $type = 'multiplication'): Operator
{
if (is_array($value)) {
$value = new Matrix($value);
}
if (is_object($value) && ($value instanceof Matrix)) {
- return $this->multiplyMatrix($value);
+ return $this->multiplyMatrix($value, $type);
} elseif (is_numeric($value)) {
- return $this->multiplyScalar($value);
+ return $this->multiplyScalar($value, $type);
}
- throw new Exception('Invalid argument for multiplication');
+ throw new Exception("Invalid argument for $type");
}
/**
@@ -36,12 +37,16 @@ class Multiplication extends Operator
* @param mixed $value The numeric value to multiply with the current base value
* @return $this The operation object, allowing multiple mutiplications to be chained
**/
- protected function multiplyScalar($value): Operator
+ protected function multiplyScalar($value, string $type = 'multiplication'): Operator
{
- for ($row = 0; $row < $this->rows; ++$row) {
- for ($column = 0; $column < $this->columns; ++$column) {
- $this->matrix[$row][$column] *= $value;
+ try {
+ for ($row = 0; $row < $this->rows; ++$row) {
+ for ($column = 0; $column < $this->columns; ++$column) {
+ $this->matrix[$row][$column] *= $value;
+ }
}
+ } catch (Throwable $e) {
+ throw new Exception("Invalid argument for $type");
}
return $this;
@@ -54,7 +59,7 @@ class Multiplication extends Operator
* @return $this The operation object, allowing multiple mutiplications to be chained
* @throws Exception If the provided argument is not appropriate for the operation
**/
- protected function multiplyMatrix(Matrix $value): Operator
+ protected function multiplyMatrix(Matrix $value, string $type = 'multiplication'): Operator
{
$this->validateReflectingDimensions($value);
@@ -62,13 +67,17 @@ class Multiplication extends Operator
$newColumns = $value->columns;
$matrix = Builder::createFilledMatrix(0, $newRows, $newColumns)
->toArray();
- for ($row = 0; $row < $newRows; ++$row) {
- for ($column = 0; $column < $newColumns; ++$column) {
- $columnData = $value->getColumns($column + 1)->toArray();
- foreach ($this->matrix[$row] as $key => $valueData) {
- $matrix[$row][$column] += $valueData * $columnData[$key][0];
+ try {
+ for ($row = 0; $row < $newRows; ++$row) {
+ for ($column = 0; $column < $newColumns; ++$column) {
+ $columnData = $value->getColumns($column + 1)->toArray();
+ foreach ($this->matrix[$row] as $key => $valueData) {
+ $matrix[$row][$column] += $valueData * $columnData[$key][0];
+ }
}
}
+ } catch (Throwable $e) {
+ throw new Exception("Invalid argument for $type");
}
$this->matrix = $matrix;
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/functions/adjoint.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/functions/adjoint.php
deleted file mode 100644
index ec1933f11ef..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/functions/adjoint.php
+++ /dev/null
@@ -1,30 +0,0 @@
- $matrixValues The matrices to add
- * @return Matrix
- * @throws Exception
- */
-function add(...$matrixValues): Matrix
-{
- if (count($matrixValues) < 2) {
- throw new Exception('Addition operation requires at least 2 arguments');
- }
-
- $matrix = array_shift($matrixValues);
-
- if (is_array($matrix)) {
- $matrix = new Matrix($matrix);
- }
- if (!$matrix instanceof Matrix) {
- throw new Exception('Addition arguments must be Matrix or array');
- }
-
- $result = new Addition($matrix);
-
- foreach ($matrixValues as $matrix) {
- $result->execute($matrix);
- }
-
- return $result->result();
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/directsum.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/directsum.php
deleted file mode 100644
index 0fb540d7ff0..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/directsum.php
+++ /dev/null
@@ -1,44 +0,0 @@
- $matrixValues The matrices to add
- * @return Matrix
- * @throws Exception
- */
-function directsum(...$matrixValues): Matrix
-{
- if (count($matrixValues) < 2) {
- throw new Exception('DirectSum operation requires at least 2 arguments');
- }
-
- $matrix = array_shift($matrixValues);
-
- if (is_array($matrix)) {
- $matrix = new Matrix($matrix);
- }
- if (!$matrix instanceof Matrix) {
- throw new Exception('DirectSum arguments must be Matrix or array');
- }
-
- $result = new DirectSum($matrix);
-
- foreach ($matrixValues as $matrix) {
- $result->execute($matrix);
- }
-
- return $result->result();
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/divideby.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/divideby.php
deleted file mode 100644
index 3c6074bb069..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/divideby.php
+++ /dev/null
@@ -1,44 +0,0 @@
- $matrixValues The matrices to divide
- * @return Matrix
- * @throws Exception
- */
-function divideby(...$matrixValues): Matrix
-{
- if (count($matrixValues) < 2) {
- throw new Exception('Division operation requires at least 2 arguments');
- }
-
- $matrix = array_shift($matrixValues);
-
- if (is_array($matrix)) {
- $matrix = new Matrix($matrix);
- }
- if (!$matrix instanceof Matrix) {
- throw new Exception('Division arguments must be Matrix or array');
- }
-
- $result = new Division($matrix);
-
- foreach ($matrixValues as $matrix) {
- $result->execute($matrix);
- }
-
- return $result->result();
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/divideinto.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/divideinto.php
deleted file mode 100644
index d0487c8e8a5..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/divideinto.php
+++ /dev/null
@@ -1,44 +0,0 @@
- $matrixValues The numbers to divide
- * @return Matrix
- * @throws Exception
- */
-function divideinto(...$matrixValues): Matrix
-{
- if (count($matrixValues) < 2) {
- throw new Exception('Division operation requires at least 2 arguments');
- }
-
- $matrix = array_shift($matrixValues);
-
- if (is_array($matrix)) {
- $matrix = new Matrix($matrix);
- }
- if (!$matrix instanceof Matrix) {
- throw new Exception('Division arguments must be Matrix or array');
- }
-
- $result = new Division($matrix);
-
- foreach ($matrixValues as $matrix) {
- $result->execute($matrix);
- }
-
- return $result->result();
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/multiply.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/multiply.php
deleted file mode 100644
index 10bca05f35e..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/multiply.php
+++ /dev/null
@@ -1,44 +0,0 @@
- $matrixValues The matrices to multiply
- * @return Matrix
- * @throws Exception
- */
-function multiply(...$matrixValues): Matrix
-{
- if (count($matrixValues) < 2) {
- throw new Exception('Multiplication operation requires at least 2 arguments');
- }
-
- $matrix = array_shift($matrixValues);
-
- if (is_array($matrix)) {
- $matrix = new Matrix($matrix);
- }
- if (!$matrix instanceof Matrix) {
- throw new Exception('Multiplication arguments must be Matrix or array');
- }
-
- $result = new Multiplication($matrix);
-
- foreach ($matrixValues as $matrix) {
- $result->execute($matrix);
- }
-
- return $result->result();
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/subtract.php b/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/subtract.php
deleted file mode 100644
index 55a827f6844..00000000000
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/classes/src/operations/subtract.php
+++ /dev/null
@@ -1,44 +0,0 @@
- $matrixValues The matrices to subtract
- * @return Matrix
- * @throws Exception
- */
-function subtract(...$matrixValues): Matrix
-{
- if (count($matrixValues) < 2) {
- throw new Exception('Subtraction operation requires at least 2 arguments');
- }
-
- $matrix = array_shift($matrixValues);
-
- if (is_array($matrix)) {
- $matrix = new Matrix($matrix);
- }
- if (!$matrix instanceof Matrix) {
- throw new Exception('Subtraction arguments must be Matrix or array');
- }
-
- $result = new Subtraction($matrix);
-
- foreach ($matrixValues as $matrix) {
- $result->execute($matrix);
- }
-
- return $result->result();
-}
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/composer.json b/lib/phpspreadsheet/vendor/markbaker/matrix/composer.json
index 1386afc2aa3..fa90f56390b 100644
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/composer.json
+++ b/lib/phpspreadsheet/vendor/markbaker/matrix/composer.json
@@ -12,7 +12,7 @@
}
],
"require": {
- "php": "^7.2 || ^8.0"
+ "php": "^7.1 || ^8.0"
},
"require-dev": {
"phpunit/phpunit": "^7.0 || ^8.0 || ^9.3",
@@ -27,48 +27,12 @@
"autoload": {
"psr-4": {
"Matrix\\": "classes/src/"
- },
- "files": [
- "classes/src/functions/adjoint.php",
- "classes/src/functions/antidiagonal.php",
- "classes/src/functions/cofactors.php",
- "classes/src/functions/determinant.php",
- "classes/src/functions/diagonal.php",
- "classes/src/functions/identity.php",
- "classes/src/functions/inverse.php",
- "classes/src/functions/minors.php",
- "classes/src/functions/trace.php",
- "classes/src/functions/transpose.php",
- "classes/src/operations/add.php",
- "classes/src/operations/directsum.php",
- "classes/src/operations/subtract.php",
- "classes/src/operations/multiply.php",
- "classes/src/operations/divideby.php",
- "classes/src/operations/divideinto.php"
- ]
+ }
},
"autoload-dev": {
"psr-4": {
- "Matrix\\Test\\": "unitTests/classes/src/"
- },
- "files": [
- "unitTests/classes/src/functions/adjointTest.php",
- "unitTests/classes/src/functions/antidiagonalTest.php",
- "unitTests/classes/src/functions/cofactorsTest.php",
- "unitTests/classes/src/functions/determinantTest.php",
- "unitTests/classes/src/functions/diagonalTest.php",
- "unitTests/classes/src/functions/identityTest.php",
- "unitTests/classes/src/functions/inverseTest.php",
- "unitTests/classes/src/functions/minorsTest.php",
- "unitTests/classes/src/functions/traceTest.php",
- "unitTests/classes/src/functions/transposeTest.php",
- "unitTests/classes/src/operations/addTest.php",
- "unitTests/classes/src/operations/directsumTest.php",
- "unitTests/classes/src/operations/subtractTest.php",
- "unitTests/classes/src/operations/multiplyTest.php",
- "unitTests/classes/src/operations/dividebyTest.php",
- "unitTests/classes/src/operations/divideintoTest.php"
- ]
+ "MatrixTest\\": "unitTests/classes/src/"
+ }
},
"scripts": {
"style": "phpcs --report-width=200 --standard=PSR2 --report=summary,full classes/src/ unitTests/classes/src -n",
@@ -80,4 +44,4 @@
"coverage": "phpunit -c phpunit.xml.dist --coverage-text --coverage-html ./build/coverage"
},
"minimum-stability": "dev"
-}
+}
\ No newline at end of file
diff --git a/lib/phpspreadsheet/vendor/markbaker/matrix/examples/test.php b/lib/phpspreadsheet/vendor/markbaker/matrix/examples/test.php
index d8b56dcd9a7..071dae910c0 100644
--- a/lib/phpspreadsheet/vendor/markbaker/matrix/examples/test.php
+++ b/lib/phpspreadsheet/vendor/markbaker/matrix/examples/test.php
@@ -1,19 +1,33 @@
directsum(new Matrix\Matrix($grid2));
+$matrix = new Matrix($grid);
+$target = new Matrix($targetGrid);
-var_dump($new);
+$decomposition = new QR($matrix);
+
+$X = $decomposition->solve($target);
+
+echo 'X', PHP_EOL;
+var_export($X->toArray());
+echo PHP_EOL;
+
+$resolve = $matrix->multiply($X);
+
+echo 'Resolve', PHP_EOL;
+var_export($resolve->toArray());
+echo PHP_EOL;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/CHANGELOG.md b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/CHANGELOG.md
index a4741afe0aa..3bfc215a0b7 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/CHANGELOG.md
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/CHANGELOG.md
@@ -5,11 +5,96 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com)
and this project adheres to [Semantic Versioning](https://semver.org).
-## Unreleased - TBD
+## 1.21.0 - 2022-01-06
### Added
-- Nothing.
+- Ability to add a picture to the background of the comment. Supports four image formats: png, jpeg, gif, bmp. New `Comment::setSizeAsBackgroundImage()` to change the size of a comment to the size of a background image. [Issue #1547](https://github.com/PHPOffice/PhpSpreadsheet/issues/1547) [PR #2422](https://github.com/PHPOffice/PhpSpreadsheet/pull/2422)
+- Ability to set default paper size and orientation [PR #2410](https://github.com/PHPOffice/PhpSpreadsheet/pull/2410)
+- Ability to extend AutoFilter to Maximum Row [PR #2414](https://github.com/PHPOffice/PhpSpreadsheet/pull/2414)
+
+### Changed
+
+- Xlsx Writer will evaluate AutoFilter only if it is as yet unevaluated, or has changed since it was last evaluated [PR #2414](https://github.com/PHPOffice/PhpSpreadsheet/pull/2414)
+
+### Deprecated
+
+- Nothing
+
+### Removed
+
+- Nothing
+
+### Fixed
+
+- Rounding in `NumberFormatter` [Issue #2385](https://github.com/PHPOffice/PhpSpreadsheet/issues/2385) [PR #2399](https://github.com/PHPOffice/PhpSpreadsheet/pull/2399)
+- Support for themes [Issue #2075](https://github.com/PHPOffice/PhpSpreadsheet/issues/2075) [Issue #2387](https://github.com/PHPOffice/PhpSpreadsheet/issues/2387) [PR #2403](https://github.com/PHPOffice/PhpSpreadsheet/pull/2403)
+- Read spreadsheet with `#` in name [Issue #2405](https://github.com/PHPOffice/PhpSpreadsheet/issues/2405) [PR #2409](https://github.com/PHPOffice/PhpSpreadsheet/pull/2409)
+- Improve PDF support for page size and orientation [Issue #1691](https://github.com/PHPOffice/PhpSpreadsheet/issues/1691) [PR #2410](https://github.com/PHPOffice/PhpSpreadsheet/pull/2410)
+- Wildcard handling issues in text match [Issue #2430](https://github.com/PHPOffice/PhpSpreadsheet/issues/2430) [PR #2431](https://github.com/PHPOffice/PhpSpreadsheet/pull/2431)
+- Respect DataType in `insertNewBefore` [PR #2433](https://github.com/PHPOffice/PhpSpreadsheet/pull/2433)
+- Handle rows explicitly hidden after AutoFilter [Issue #1641](https://github.com/PHPOffice/PhpSpreadsheet/issues/1641) [PR #2414](https://github.com/PHPOffice/PhpSpreadsheet/pull/2414)
+- Special characters in image file name [Issue #1470](https://github.com/PHPOffice/PhpSpreadsheet/issues/1470) [Issue #2415](https://github.com/PHPOffice/PhpSpreadsheet/issues/2415) [PR #2416](https://github.com/PHPOffice/PhpSpreadsheet/pull/2416)
+- Mpdf with very many styles [Issue #2432](https://github.com/PHPOffice/PhpSpreadsheet/issues/2432) [PR #2434](https://github.com/PHPOffice/PhpSpreadsheet/pull/2434)
+- Name clashes between parsed and unparsed drawings [Issue #1767](https://github.com/PHPOffice/PhpSpreadsheet/issues/1767) [Issue #2396](https://github.com/PHPOffice/PhpSpreadsheet/issues/2396) [PR #2423](https://github.com/PHPOffice/PhpSpreadsheet/pull/2423)
+- Fill pattern start and end colors [Issue #2441](https://github.com/PHPOffice/PhpSpreadsheet/issues/2441) [PR #2444](https://github.com/PHPOffice/PhpSpreadsheet/pull/2444)
+- General style specified in wrong case [Issue #2450](https://github.com/PHPOffice/PhpSpreadsheet/issues/2450) [PR #2451](https://github.com/PHPOffice/PhpSpreadsheet/pull/2451)
+- Null passed to `AutoFilter::setRange()` [Issue #2281](https://github.com/PHPOffice/PhpSpreadsheet/issues/2281) [PR #2454](https://github.com/PHPOffice/PhpSpreadsheet/pull/2454)
+- Another undefined index in Xls reader (#2470) [Issue #2463](https://github.com/PHPOffice/PhpSpreadsheet/issues/2463) [PR #2470](https://github.com/PHPOffice/PhpSpreadsheet/pull/2470)
+- Allow single-cell checks on conditional styles, even when the style is configured for a range of cells (#) [PR #2483](https://github.com/PHPOffice/PhpSpreadsheet/pull/2483)
+
+## 1.20.0 - 2021-11-23
+
+### Added
+
+- Xlsx Writer Support for WMF Files [#2339](https://github.com/PHPOffice/PhpSpreadsheet/issues/2339)
+- Use standard temporary file for internal use of HTMLPurifier [#2383](https://github.com/PHPOffice/PhpSpreadsheet/issues/2383)
+
+### Changed
+
+- Drop support for PHP 7.2, according to https://phpspreadsheet.readthedocs.io/en/latest/#php-version-support
+- Use native typing for objects that were already documented as such
+
+### Deprecated
+
+- Nothing
+
+### Removed
+
+- Nothing
+
+### Fixed
+
+- Fixed null conversation for strToUpper [#2292](https://github.com/PHPOffice/PhpSpreadsheet/issues/2292)
+- Fixed Trying to access array offset on value of type null (Xls Reader) [#2315](https://github.com/PHPOffice/PhpSpreadsheet/issues/2315)
+- Don't corrupt XLSX files containing data validation [#2377](https://github.com/PHPOffice/PhpSpreadsheet/issues/2377)
+- Non-fixed cells were not updated if shared formula has a fixed cell [#2354](https://github.com/PHPOffice/PhpSpreadsheet/issues/2354)
+- Declare key of generic ArrayObject
+- CSV reader better support for boolean values [#2374](https://github.com/PHPOffice/PhpSpreadsheet/pull/2374)
+- Some ZIP file could not be read [#2376](https://github.com/PHPOffice/PhpSpreadsheet/pull/2376)
+- Fix regression were hyperlinks could not be read [#2391](https://github.com/PHPOffice/PhpSpreadsheet/pull/2391)
+- AutoFilter Improvements [#2393](https://github.com/PHPOffice/PhpSpreadsheet/pull/2393)
+- Don't corrupt file when using chart with fill color [#589](https://github.com/PHPOffice/PhpSpreadsheet/pull/589)
+- Restore imperfect array formula values in xlsx writer [#2343](https://github.com/PHPOffice/PhpSpreadsheet/pull/2343)
+- Restore explicit list of changes to PHPExcel migration document [#1546](https://github.com/PHPOffice/PhpSpreadsheet/issues/1546)
+
+## 1.19.0 - 2021-10-31
+
+### Added
+
+- Ability to set style on named range, and validate input to setSelectedCells [Issue #2279](https://github.com/PHPOffice/PhpSpreadsheet/issues/2279) [PR #2280](https://github.com/PHPOffice/PhpSpreadsheet/pull/2280)
+- Process comments in Sylk file [Issue #2276](https://github.com/PHPOffice/PhpSpreadsheet/issues/2276) [PR #2277](https://github.com/PHPOffice/PhpSpreadsheet/pull/2277)
+- Addition of Custom Properties to Ods Writer, and 32-bit-safe timestamps for Document Properties [PR #2113](https://github.com/PHPOffice/PhpSpreadsheet/pull/2113)
+- Added callback to CSV reader to set user-specified defaults for various properties (especially for escape which has a poor PHP-inherited default of backslash which does not correspond with Excel) [PR #2103](https://github.com/PHPOffice/PhpSpreadsheet/pull/2103)
+- Phase 1 of better namespace handling for Xlsx, resolving many open issues [PR #2173](https://github.com/PHPOffice/PhpSpreadsheet/pull/2173) [PR #2204](https://github.com/PHPOffice/PhpSpreadsheet/pull/2204) [PR #2303](https://github.com/PHPOffice/PhpSpreadsheet/pull/2303)
+- Add ability to extract images if source is a URL [Issue #1997](https://github.com/PHPOffice/PhpSpreadsheet/issues/1997) [PR #2072](https://github.com/PHPOffice/PhpSpreadsheet/pull/2072)
+- Support for passing flags in the Reader `load()` and Writer `save()`methods, and through the IOFactory, to set behaviours [PR #2136](https://github.com/PHPOffice/PhpSpreadsheet/pull/2136)
+ - See [documentation](https://phpspreadsheet.readthedocs.io/en/latest/topics/reading-and-writing-to-file/#readerwriter-flags) for details
+- More flexibility in the StringValueBinder to determine what datatypes should be treated as strings [PR #2138](https://github.com/PHPOffice/PhpSpreadsheet/pull/2138)
+- Helper class for conversion between css size Units of measure (`px`, `pt`, `pc`, `in`, `cm`, `mm`) [PR #2152](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145)
+- Allow Row height and Column Width to be set using different units of measure (`px`, `pt`, `pc`, `in`, `cm`, `mm`), rather than only in points or MS Excel column width units [PR #2152](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145)
+- Ability to stream to an Amazon S3 bucket [Issue #2249](https://github.com/PHPOffice/PhpSpreadsheet/issues/2249)
+- Provided a Size Helper class to validate size values (pt, px, em) [PR #1694](https://github.com/PHPOffice/PhpSpreadsheet/pull/1694)
### Changed
@@ -17,7 +102,7 @@ and this project adheres to [Semantic Versioning](https://semver.org).
### Deprecated
-- Nothing.
+- PHP 8.1 will deprecate auto_detect_line_endings. As a result of this change, Csv Reader using some release after PHP8.1 will no longer be able to handle a Csv with Mac line endings.
### Removed
@@ -25,8 +110,145 @@ and this project adheres to [Semantic Versioning](https://semver.org).
### Fixed
+- Unexpected format in Xlsx Timestamp [Issue #2331](https://github.com/PHPOffice/PhpSpreadsheet/issues/2331) [PR #2332](https://github.com/PHPOffice/PhpSpreadsheet/pull/2332)
+- Corrections for HLOOKUP [Issue #2123](https://github.com/PHPOffice/PhpSpreadsheet/issues/2123) [PR #2330](https://github.com/PHPOffice/PhpSpreadsheet/pull/2330)
+- Corrections for Xlsx Read Comments [Issue #2316](https://github.com/PHPOffice/PhpSpreadsheet/issues/2316) [PR #2329](https://github.com/PHPOffice/PhpSpreadsheet/pull/2329)
+- Lowercase Calibri font names [Issue #2273](https://github.com/PHPOffice/PhpSpreadsheet/issues/2273) [PR #2325](https://github.com/PHPOffice/PhpSpreadsheet/pull/2325)
+- isFormula Referencing Sheet with Space in Title [Issue #2304](https://github.com/PHPOffice/PhpSpreadsheet/issues/2304) [PR #2306](https://github.com/PHPOffice/PhpSpreadsheet/pull/2306)
+- Xls Reader Fatal Error due to Undefined Offset [Issue #1114](https://github.com/PHPOffice/PhpSpreadsheet/issues/1114) [PR #2308](https://github.com/PHPOffice/PhpSpreadsheet/pull/2308)
+- Permit Csv Reader delimiter to be set to null [Issue #2287](https://github.com/PHPOffice/PhpSpreadsheet/issues/2287) [PR #2288](https://github.com/PHPOffice/PhpSpreadsheet/pull/2288)
+- Csv Reader did not handle booleans correctly [PR #2232](https://github.com/PHPOffice/PhpSpreadsheet/pull/2232)
+- Problems when deleting sheet with local defined name [Issue #2266](https://github.com/PHPOffice/PhpSpreadsheet/issues/2266) [PR #2284](https://github.com/PHPOffice/PhpSpreadsheet/pull/2284)
+- Worksheet passwords were not always handled correctly [Issue #1897](https://github.com/PHPOffice/PhpSpreadsheet/issues/1897) [PR #2197](https://github.com/PHPOffice/PhpSpreadsheet/pull/2197)
+- Gnumeric Reader will now distinguish between Created and Modified timestamp [PR #2133](https://github.com/PHPOffice/PhpSpreadsheet/pull/2133)
+- Xls Reader will now handle MACCENTRALEUROPE with or without hyphen [Issue #549](https://github.com/PHPOffice/PhpSpreadsheet/issues/549) [PR #2213](https://github.com/PHPOffice/PhpSpreadsheet/pull/2213)
+- Tweaks to input file validation [Issue #1718](https://github.com/PHPOffice/PhpSpreadsheet/issues/1718) [PR #2217](https://github.com/PHPOffice/PhpSpreadsheet/pull/2217)
+- Html Reader did not handle comments correctly [Issue #2234](https://github.com/PHPOffice/PhpSpreadsheet/issues/2234) [PR #2235](https://github.com/PHPOffice/PhpSpreadsheet/pull/2235)
+- Apache OpenOffice Uses Unexpected Case for General format [Issue #2239](https://github.com/PHPOffice/PhpSpreadsheet/issues/2239) [PR #2242](https://github.com/PHPOffice/PhpSpreadsheet/pull/2242)
+- Problems with fraction formatting [Issue #2253](https://github.com/PHPOffice/PhpSpreadsheet/issues/2253) [PR #2254](https://github.com/PHPOffice/PhpSpreadsheet/pull/2254)
+- Xlsx Reader had problems reading file with no styles.xml or empty styles.xml [Issue #2246](https://github.com/PHPOffice/PhpSpreadsheet/issues/2246) [PR #2247](https://github.com/PHPOffice/PhpSpreadsheet/pull/2247)
+- Xlsx Reader did not read Data Validation flags correctly [Issue #2224](https://github.com/PHPOffice/PhpSpreadsheet/issues/2224) [PR #2225](https://github.com/PHPOffice/PhpSpreadsheet/pull/2225)
+- Better handling of empty arguments in Calculation engine [PR #2143](https://github.com/PHPOffice/PhpSpreadsheet/pull/2143)
+- Many fixes for Autofilter [Issue #2216](https://github.com/PHPOffice/PhpSpreadsheet/issues/2216) [PR #2141](https://github.com/PHPOffice/PhpSpreadsheet/pull/2141) [PR #2162](https://github.com/PHPOffice/PhpSpreadsheet/pull/2162) [PR #2218](https://github.com/PHPOffice/PhpSpreadsheet/pull/2218)
+- Locale generator will now use Unix line endings even on Windows [Issue #2172](https://github.com/PHPOffice/PhpSpreadsheet/issues/2172) [PR #2174](https://github.com/PHPOffice/PhpSpreadsheet/pull/2174)
+- Support differences in implementation of Text functions between Excel/Ods/Gnumeric [PR #2151](https://github.com/PHPOffice/PhpSpreadsheet/pull/2151)
+- Fixes to places where PHP8.1 enforces new or previously unenforced restrictions [PR #2137](https://github.com/PHPOffice/PhpSpreadsheet/pull/2137) [PR #2191](https://github.com/PHPOffice/PhpSpreadsheet/pull/2191) [PR #2231](https://github.com/PHPOffice/PhpSpreadsheet/pull/2231)
+- Clone for HashTable was incorrect [PR #2130](https://github.com/PHPOffice/PhpSpreadsheet/pull/2130)
+- Xlsx Reader was not evaluating Document Security Lock correctly [PR #2128](https://github.com/PHPOffice/PhpSpreadsheet/pull/2128)
+- Error in COUPNCD handling end of month [Issue #2116](https://github.com/PHPOffice/PhpSpreadsheet/issues/2116) [PR #2119](https://github.com/PHPOffice/PhpSpreadsheet/pull/2119)
+- Xls Writer Parser did not handle concatenation operator correctly [PR #2080](https://github.com/PHPOffice/PhpSpreadsheet/pull/2080)
+- Xlsx Writer did not handle boolean false correctly [Issue #2082](https://github.com/PHPOffice/PhpSpreadsheet/issues/2082) [PR #2087](https://github.com/PHPOffice/PhpSpreadsheet/pull/2087)
+- SUM needs to treat invalid strings differently depending on whether they come from a cell or are used as literals [Issue #2042](https://github.com/PHPOffice/PhpSpreadsheet/issues/2042) [PR #2045](https://github.com/PHPOffice/PhpSpreadsheet/pull/2045)
+- Html reader could have set illegal coordinates when dealing with embedded tables [Issue #2029](https://github.com/PHPOffice/PhpSpreadsheet/issues/2029) [PR #2032](https://github.com/PHPOffice/PhpSpreadsheet/pull/2032)
+- Documentation for printing gridlines was wrong [PR #2188](https://github.com/PHPOffice/PhpSpreadsheet/pull/2188)
+- Return Value Error - DatabaseAbstruct::buildQuery() return null but must be string [Issue #2158](https://github.com/PHPOffice/PhpSpreadsheet/issues/2158) [PR #2160](https://github.com/PHPOffice/PhpSpreadsheet/pull/2160)
+- Xlsx reader not recognize data validations that references another sheet [Issue #1432](https://github.com/PHPOffice/PhpSpreadsheet/issues/1432) [Issue #2149](https://github.com/PHPOffice/PhpSpreadsheet/issues/2149) [PR #2150](https://github.com/PHPOffice/PhpSpreadsheet/pull/2150) [PR #2265](https://github.com/PHPOffice/PhpSpreadsheet/pull/2265)
+- Don't calculate cell width for autosize columns if a cell contains a null or empty string value [Issue #2165](https://github.com/PHPOffice/PhpSpreadsheet/issues/2165) [PR #2167](https://github.com/PHPOffice/PhpSpreadsheet/pull/2167)
+- Allow negative interest rate values in a number of the Financial functions (`PPMT()`, `PMT()`, `FV()`, `PV()`, `NPER()`, etc) [Issue #2163](https://github.com/PHPOffice/PhpSpreadsheet/issues/2163) [PR #2164](https://github.com/PHPOffice/PhpSpreadsheet/pull/2164)
+- Xls Reader changing grey background to black in Excel template [Issue #2147](https://github.com/PHPOffice/PhpSpreadsheet/issues/2147) [PR #2156](https://github.com/PHPOffice/PhpSpreadsheet/pull/2156)
+- Column width and Row height styles in the Html Reader when the value includes a unit of measure [Issue #2145](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145).
+- Data Validation flags not set correctly when reading XLSX files [Issue #2224](https://github.com/PHPOffice/PhpSpreadsheet/issues/2224) [PR #2225](https://github.com/PHPOffice/PhpSpreadsheet/pull/2225)
+- Reading XLSX files without styles.xml throws an exception [Issue #2246](https://github.com/PHPOffice/PhpSpreadsheet/issues/2246)
+- Improved performance of `Style::applyFromArray()` when applied to several cells [PR #1785](https://github.com/PHPOffice/PhpSpreadsheet/issues/1785).
+- Improve XLSX parsing speed if no readFilter is applied (again) - [#772](https://github.com/PHPOffice/PhpSpreadsheet/issues/772)
+
+## 1.18.0 - 2021-05-31
+
+### Added
+
+- Enhancements to CSV Reader, allowing options to be set when using `IOFactory::load()` with a callback to set delimiter, enclosure, charset etc [PR #2103](https://github.com/PHPOffice/PhpSpreadsheet/pull/2103) - See [documentation](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/docs/topics/reading-and-writing-to-file.md#csv-comma-separated-values) for details.
+- Implemented basic AutoFiltering for Ods Reader and Writer [PR #2053](https://github.com/PHPOffice/PhpSpreadsheet/pull/2053)
+- Implemented basic AutoFiltering for Gnumeric Reader [PR #2055](https://github.com/PHPOffice/PhpSpreadsheet/pull/2055)
+- Improved support for Row and Column ranges in formulae [Issue #1755](https://github.com/PHPOffice/PhpSpreadsheet/issues/1755) [PR #2028](https://github.com/PHPOffice/PhpSpreadsheet/pull/2028)
+- Implemented URLENCODE() Web Function
+- Implemented the CHITEST(), CHISQ.DIST() and CHISQ.INV() and equivalent Statistical functions, for both left- and right-tailed distributions.
+- Support for ActiveSheet and SelectedCells in the ODS Reader and Writer [PR #1908](https://github.com/PHPOffice/PhpSpreadsheet/pull/1908)
+- Support for notContainsText Conditional Style in xlsx [Issue #984](https://github.com/PHPOffice/PhpSpreadsheet/issues/984)
+
+### Changed
+
+- Use of `nb` rather than `no` as the locale code for Norsk Bokmål.
+
+### Deprecated
+
+- All Excel Function implementations in `Calculation\Database`, `Calculation\DateTime`, `Calculation\Engineering`, `Calculation\Financial`, `Calculation\Logical`, `Calculation\LookupRef`, `Calculation\MathTrig`, `Calculation\Statistical`, `Calculation\TextData` and `Calculation\Web` have been moved to dedicated classes for individual functions or groups of related functions. See the docblocks against all the deprecated methods for details of the new methods to call instead. At some point, these old classes will be deleted.
+
+### Removed
+
+- Use of `nb` rather than `no` as the locale language code for Norsk Bokmål.
+
+### Fixed
+
+- Fixed error in COUPNCD() calculation for end of month [Issue #2116](https://github.com/PHPOffice/PhpSpreadsheet/issues/2116) - [PR #2119](https://github.com/PHPOffice/PhpSpreadsheet/pull/2119)
+- Resolve default values when a null argument is passed for HLOOKUP(), VLOOKUP() and ADDRESS() functions [Issue #2120](https://github.com/PHPOffice/PhpSpreadsheet/issues/2120) - [PR #2121](https://github.com/PHPOffice/PhpSpreadsheet/pull/2121)
+- Fixed incorrect R1C1 to A1 subtraction formula conversion (`R[-2]C-R[2]C`) [Issue #2076](https://github.com/PHPOffice/PhpSpreadsheet/pull/2076) [PR #2086](https://github.com/PHPOffice/PhpSpreadsheet/pull/2086)
+- Correctly handle absolute A1 references when converting to R1C1 format [PR #2060](https://github.com/PHPOffice/PhpSpreadsheet/pull/2060)
+- Correct default fill style for conditional without a pattern defined [Issue #2035](https://github.com/PHPOffice/PhpSpreadsheet/issues/2035) [PR #2050](https://github.com/PHPOffice/PhpSpreadsheet/pull/2050)
+- Fixed issue where array key check for existince before accessing arrays in Xlsx.php [PR #1970](https://github.com/PHPOffice/PhpSpreadsheet/pull/1970)
+- Fixed issue with quoted strings in number format mask rendered with toFormattedString() [Issue 1972#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1972) [PR #1978](https://github.com/PHPOffice/PhpSpreadsheet/pull/1978)
+- Fixed issue with percentage formats in number format mask rendered with toFormattedString() [Issue 1929#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1929) [PR #1928](https://github.com/PHPOffice/PhpSpreadsheet/pull/1928)
+- Fixed issue with _ spacing character in number format mask corrupting output from toFormattedString() [Issue 1924#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1924) [PR #1927](https://github.com/PHPOffice/PhpSpreadsheet/pull/1927)
+- Fix for [Issue #1887](https://github.com/PHPOffice/PhpSpreadsheet/issues/1887) - Lose Track of Selected Cells After Save
+- Fixed issue with Xlsx@listWorksheetInfo not returning any data
+- Fixed invalid arguments triggering mb_substr() error in LEFT(), MID() and RIGHT() text functions [Issue #640](https://github.com/PHPOffice/PhpSpreadsheet/issues/640)
+- Fix for [Issue #1916](https://github.com/PHPOffice/PhpSpreadsheet/issues/1916) - Invalid signature check for XML files
+- Fix change in `Font::setSize()` behavior for PHP8 [PR #2100](https://github.com/PHPOffice/PhpSpreadsheet/pull/2100)
+
+## 1.17.1 - 2021-03-01
+
+### Added
+
+- Implementation of the Excel `AVERAGEIFS()` functions as part of a restructuring of Database functions and Conditional Statistical functions.
+- Support for date values and percentages in query parameters for Database functions, and the IF expressions in functions like COUNTIF() and AVERAGEIF(). [#1875](https://github.com/PHPOffice/PhpSpreadsheet/pull/1875)
+- Support for booleans, and for wildcard text search in query parameters for Database functions, and the IF expressions in functions like COUNTIF() and AVERAGEIF(). [#1876](https://github.com/PHPOffice/PhpSpreadsheet/pull/1876)
+- Implemented DataBar for conditional formatting in Xlsx, providing read/write and creation of (type, value, direction, fills, border, axis position, color settings) as DataBar options in Excel. [#1754](https://github.com/PHPOffice/PhpSpreadsheet/pull/1754)
+- Alignment for ODS Writer [#1796](https://github.com/PHPOffice/PhpSpreadsheet/issues/1796)
+- Basic implementation of the PERMUTATIONA() Statistical Function
+
+### Changed
+
+- Formula functions that previously called PHP functions directly are now processed through the Excel Functions classes; resolving issues with PHP8 stricter typing. [#1789](https://github.com/PHPOffice/PhpSpreadsheet/issues/1789)
+
+ The following MathTrig functions are affected:
+ `ABS()`, `ACOS()`, `ACOSH()`, `ASIN()`, `ASINH()`, `ATAN()`, `ATANH()`,
+ `COS()`, `COSH()`, `DEGREES()` (rad2deg), `EXP()`, `LN()` (log), `LOG10()`,
+ `RADIANS()` (deg2rad), `SIN()`, `SINH()`, `SQRT()`, `TAN()`, `TANH()`.
+
+ One TextData function is also affected: `REPT()` (str_repeat).
+- `formatAsDate` correctly matches language metadata, reverting c55272e
+- Formulae that previously crashed on sub function call returning excel error value now return said value.
+ The following functions are affected `CUMPRINC()`, `CUMIPMT()`, `AMORLINC()`,
+ `AMORDEGRC()`.
+- Adapt some function error return value to match excel's error.
+ The following functions are affected `PPMT()`, `IPMT()`.
+
+### Deprecated
+
+- Calling many of the Excel formula functions directly rather than through the Calculation Engine.
+
+ The logic for these Functions is now being moved out of the categorised `Database`, `DateTime`, `Engineering`, `Financial`, `Logical`, `LookupRef`, `MathTrig`, `Statistical`, `TextData` and `Web` classes into small, dedicated classes for individual functions or related groups of functions.
+
+ This makes the logic in these classes easier to maintain; and will reduce the memory footprint required to execute formulae when calling these functions.
+
+### Removed
+
- Nothing.
+### Fixed
+
+- Avoid Duplicate Titles When Reading Multiple HTML Files.[Issue #1823](https://github.com/PHPOffice/PhpSpreadsheet/issues/1823) [PR #1829](https://github.com/PHPOffice/PhpSpreadsheet/pull/1829)
+- Fixed issue with Worksheet's `getCell()` method when trying to get a cell by defined name. [#1858](https://github.com/PHPOffice/PhpSpreadsheet/issues/1858)
+- Fix possible endless loop in NumberFormat Masks [#1792](https://github.com/PHPOffice/PhpSpreadsheet/issues/1792)
+- Fix problem resulting from literal dot inside quotes in number format masks [PR #1830](https://github.com/PHPOffice/PhpSpreadsheet/pull/1830)
+- Resolve Google Sheets Xlsx charts issue. Google Sheets uses oneCellAnchor positioning and does not include *Cache values in the exported Xlsx [PR #1761](https://github.com/PHPOffice/PhpSpreadsheet/pull/1761)
+- Fix for Xlsx Chart axis titles mapping to correct X or Y axis label when only one is present [PR #1760](https://github.com/PHPOffice/PhpSpreadsheet/pull/1760)
+- Fix For Null Exception on ODS Read of Page Settings. [#1772](https://github.com/PHPOffice/PhpSpreadsheet/issues/1772)
+- Fix Xlsx reader overriding manually set number format with builtin number format [PR #1805](https://github.com/PHPOffice/PhpSpreadsheet/pull/1805)
+- Fix Xlsx reader cell alignment [PR #1710](https://github.com/PHPOffice/PhpSpreadsheet/pull/1710)
+- Fix for not yet implemented data-types in Open Document writer [Issue #1674](https://github.com/PHPOffice/PhpSpreadsheet/issues/1674)
+- Fix XLSX reader when having a corrupt numeric cell data type [PR #1664](https://github.com/phpoffice/phpspreadsheet/pull/1664)
+- Fix on `CUMPRINC()`, `CUMIPMT()`, `AMORLINC()`, `AMORDEGRC()` usage. When those functions called one of `YEARFRAC()`, `PPMT()`, `IPMT()` and they would get back an error value (represented as a string), trying to use numeral operands (`+`, `/`, `-`, `*`) on said return value and a number (`float or `int`) would fail.
+
## 1.16.0 - 2020-12-31
### Added
@@ -39,7 +261,7 @@ and this project adheres to [Semantic Versioning](https://semver.org).
### Deprecated
-- Nothing.
+- All Excel Function implementations in `Calculation\Database`, `Calculation\DateTime`, `Calculation\Engineering`, `Calculation\Financial`, `Calculation\Logical`, `Calculation\LookupRef`, `Calculation\MathTrig`, `Calculation\Statistical`, `Calculation\TextData` and `Calculation\Web` have been moved to dedicated classes for individual functions or groups of related functions. See the docblocks against all the deprecated methods for details of the new methods to call instead. At some point, these old classes will be deleted.
### Removed
@@ -47,6 +269,7 @@ and this project adheres to [Semantic Versioning](https://semver.org).
### Fixed
+- Fixed issue with absolute path in worksheets' Target [PR #1769](https://github.com/PHPOffice/PhpSpreadsheet/pull/1769)
- Fix for Xls Reader when SST has a bad length [#1592](https://github.com/PHPOffice/PhpSpreadsheet/issues/1592)
- Resolve Xlsx loader issue whe hyperlinks don't have a destination
- Resolve issues when printer settings resources IDs clash with drawing IDs
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/CONTRIBUTING.md b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/CONTRIBUTING.md
index aed13fe2db2..f59535331c1 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/CONTRIBUTING.md
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/CONTRIBUTING.md
@@ -9,3 +9,12 @@ If you would like to contribute, here are some notes and guidelines:
- All code changes must be validated by `composer check`
- [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")
+
+## 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 tag with `git push --tags`, GitHub Actions will create a GitHub release automatically
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/composer.json b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/composer.json
index c6f8e30e890..d80fc62ffab 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/composer.json
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/composer.json
@@ -1,7 +1,19 @@
{
"name": "phpoffice/phpspreadsheet",
"description": "PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine",
- "keywords": ["PHP", "OpenXML", "Excel", "xlsx", "xls", "ods", "gnumeric", "spreadsheet"],
+ "keywords": [
+ "PHP",
+ "OpenXML",
+ "Excel",
+ "xlsx",
+ "xls",
+ "ods",
+ "gnumeric",
+ "spreadsheet"
+ ],
+ "config": {
+ "sort-packages": true
+ },
"homepage": "https://github.com/PHPOffice/PhpSpreadsheet",
"type": "library",
"license": "MIT",
@@ -29,47 +41,51 @@
"check": [
"php-cs-fixer fix --ansi --dry-run --diff",
"phpcs",
- "phpunit --color=always"
+ "phpunit --color=always",
+ "phpstan analyse --ansi"
],
"fix": [
"php-cs-fixer fix --ansi"
],
"versions": [
- "phpcs --report-width=200 samples/ src/ tests/ --ignore=samples/Header.php --standard=PHPCompatibility --runtime-set testVersion 7.2- -n"
+ "phpcs --report-width=200 samples/ src/ tests/ --ignore=samples/Header.php --standard=PHPCompatibility --runtime-set testVersion 7.3- -n"
]
},
"require": {
- "php": "^7.2||^8.0",
+ "php": "^7.3 || ^8.0",
"ext-ctype": "*",
"ext-dom": "*",
+ "ext-fileinfo": "*",
"ext-gd": "*",
"ext-iconv": "*",
- "ext-fileinfo": "*",
"ext-libxml": "*",
"ext-mbstring": "*",
- "ext-SimpleXML": "*",
+ "ext-simplexml": "*",
"ext-xml": "*",
"ext-xmlreader": "*",
"ext-xmlwriter": "*",
"ext-zip": "*",
"ext-zlib": "*",
+ "ezyang/htmlpurifier": "^4.13",
"maennchen/zipstream-php": "^2.1",
- "markbaker/complex": "^1.5||^2.0",
- "markbaker/matrix": "^1.2||^2.0",
- "psr/simple-cache": "^1.0",
+ "markbaker/complex": "^3.0",
+ "markbaker/matrix": "^3.0",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0",
- "ezyang/htmlpurifier": "^4.13"
+ "psr/simple-cache": "^1.0"
},
"require-dev": {
- "dompdf/dompdf": "^0.8.5",
- "friendsofphp/php-cs-fixer": "^2.16",
+ "dealerdirect/phpcodesniffer-composer-installer": "dev-master",
+ "dompdf/dompdf": "^1.0",
+ "friendsofphp/php-cs-fixer": "^3.2",
"jpgraph/jpgraph": "^4.0",
"mpdf/mpdf": "^8.0",
"phpcompatibility/php-compatibility": "^9.3",
- "phpunit/phpunit": "^8.5||^9.3",
- "squizlabs/php_codesniffer": "^3.5",
- "tecnickcom/tcpdf": "^6.3"
+ "phpstan/phpstan": "^1.1",
+ "phpstan/phpstan-phpunit": "^1.0",
+ "phpunit/phpunit": "^8.5 || ^9.0",
+ "squizlabs/php_codesniffer": "^3.6",
+ "tecnickcom/tcpdf": "^6.4"
},
"suggest": {
"mpdf/mpdf": "Option for rendering PDF with PDF Writer",
@@ -84,7 +100,8 @@
},
"autoload-dev": {
"psr-4": {
- "PhpOffice\\PhpSpreadsheetTests\\": "tests/PhpSpreadsheetTests"
+ "PhpOffice\\PhpSpreadsheetTests\\": "tests/PhpSpreadsheetTests",
+ "PhpOffice\\PhpSpreadsheetInfra\\": "infra"
}
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php
index 99260e3bf15..25f7695904c 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php
@@ -12,7 +12,9 @@ use PhpOffice\PhpSpreadsheet\ReferenceHelper;
use PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
+use ReflectionClassConstant;
use ReflectionMethod;
+use ReflectionParameter;
class Calculation
{
@@ -30,6 +32,9 @@ class Calculation
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})';
@@ -130,7 +135,7 @@ class Calculation
/**
* Error message for any error that was raised/thrown by the calculation engine.
*
- * @var string
+ * @var null|string
*/
public $formulaError;
@@ -204,7 +209,7 @@ class Calculation
/**
* Locale-specific translations for Excel constants (True, False and Null).
*
- * @var string[]
+ * @var array
*/
public static $localeBoolean = [
'TRUE' => 'TRUE',
@@ -216,7 +221,7 @@ class Calculation
* Excel constant string translations to their PHP equivalents
* Constant conversion from text name/value to actual (datatyped) value.
*
- * @var string[]
+ * @var array
*/
private static $excelConstants = [
'TRUE' => true,
@@ -228,42 +233,42 @@ class Calculation
private static $phpSpreadsheetFunctions = [
'ABS' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'abs',
+ 'functionCall' => [MathTrig\Absolute::class, 'evaluate'],
'argumentCount' => '1',
],
'ACCRINT' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'ACCRINT'],
- 'argumentCount' => '4-7',
+ 'functionCall' => [Financial\Securities\AccruedInterest::class, 'periodic'],
+ 'argumentCount' => '4-8',
],
'ACCRINTM' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'ACCRINTM'],
+ 'functionCall' => [Financial\Securities\AccruedInterest::class, 'atMaturity'],
'argumentCount' => '3-5',
],
'ACOS' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'acos',
+ 'functionCall' => [MathTrig\Trig\Cosine::class, 'acos'],
'argumentCount' => '1',
],
'ACOSH' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'acosh',
+ 'functionCall' => [MathTrig\Trig\Cosine::class, 'acosh'],
'argumentCount' => '1',
],
'ACOT' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'ACOT'],
+ 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acot'],
'argumentCount' => '1',
],
'ACOTH' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'ACOTH'],
+ 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acoth'],
'argumentCount' => '1',
],
'ADDRESS' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'cellAddress'],
+ 'functionCall' => [LookupRef\Address::class, 'cell'],
'argumentCount' => '2-5',
],
'AGGREGATE' => [
@@ -273,22 +278,22 @@ class Calculation
],
'AMORDEGRC' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'AMORDEGRC'],
+ 'functionCall' => [Financial\Amortization::class, 'AMORDEGRC'],
'argumentCount' => '6,7',
],
'AMORLINC' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'AMORLINC'],
+ 'functionCall' => [Financial\Amortization::class, 'AMORLINC'],
'argumentCount' => '6,7',
],
'AND' => [
'category' => Category::CATEGORY_LOGICAL,
- 'functionCall' => [Logical::class, 'logicalAnd'],
+ 'functionCall' => [Logical\Operations::class, 'logicalAnd'],
'argumentCount' => '1+',
],
'ARABIC' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'ARABIC'],
+ 'functionCall' => [MathTrig\Arabic::class, 'evaluate'],
'argumentCount' => '1',
],
'AREAS' => [
@@ -296,6 +301,11 @@ class Calculation
'functionCall' => [Functions::class, 'DUMMY'],
'argumentCount' => '1',
],
+ 'ARRAYTOTEXT' => [
+ 'category' => Category::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => [Functions::class, 'DUMMY'],
+ 'argumentCount' => '?',
+ ],
'ASC' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
'functionCall' => [Functions::class, 'DUMMY'],
@@ -303,52 +313,52 @@ class Calculation
],
'ASIN' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'asin',
+ 'functionCall' => [MathTrig\Trig\Sine::class, 'asin'],
'argumentCount' => '1',
],
'ASINH' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'asinh',
+ 'functionCall' => [MathTrig\Trig\Sine::class, 'asinh'],
'argumentCount' => '1',
],
'ATAN' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'atan',
+ 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan'],
'argumentCount' => '1',
],
'ATAN2' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'ATAN2'],
+ 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan2'],
'argumentCount' => '2',
],
'ATANH' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'atanh',
+ 'functionCall' => [MathTrig\Trig\Tangent::class, 'atanh'],
'argumentCount' => '1',
],
'AVEDEV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'AVEDEV'],
+ 'functionCall' => [Statistical\Averages::class, 'averageDeviations'],
'argumentCount' => '1+',
],
'AVERAGE' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'AVERAGE'],
+ 'functionCall' => [Statistical\Averages::class, 'average'],
'argumentCount' => '1+',
],
'AVERAGEA' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'AVERAGEA'],
+ 'functionCall' => [Statistical\Averages::class, 'averageA'],
'argumentCount' => '1+',
],
'AVERAGEIF' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'AVERAGEIF'],
+ 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIF'],
'argumentCount' => '2,3',
],
'AVERAGEIFS' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIFS'],
'argumentCount' => '3+',
],
'BAHTTEXT' => [
@@ -358,32 +368,32 @@ class Calculation
],
'BASE' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'BASE'],
+ 'functionCall' => [MathTrig\Base::class, 'evaluate'],
'argumentCount' => '2,3',
],
'BESSELI' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BESSELI'],
+ 'functionCall' => [Engineering\BesselI::class, 'BESSELI'],
'argumentCount' => '2',
],
'BESSELJ' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BESSELJ'],
+ 'functionCall' => [Engineering\BesselJ::class, 'BESSELJ'],
'argumentCount' => '2',
],
'BESSELK' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BESSELK'],
+ 'functionCall' => [Engineering\BesselK::class, 'BESSELK'],
'argumentCount' => '2',
],
'BESSELY' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BESSELY'],
+ 'functionCall' => [Engineering\BesselY::class, 'BESSELY'],
'argumentCount' => '2',
],
'BETADIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'BETADIST'],
+ 'functionCall' => [Statistical\Distributions\Beta::class, 'distribution'],
'argumentCount' => '3-5',
],
'BETA.DIST' => [
@@ -393,88 +403,88 @@ class Calculation
],
'BETAINV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'BETAINV'],
+ 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'],
'argumentCount' => '3-5',
],
'BETA.INV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'BETAINV'],
+ 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'],
'argumentCount' => '3-5',
],
'BIN2DEC' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BINTODEC'],
+ 'functionCall' => [Engineering\ConvertBinary::class, 'toDecimal'],
'argumentCount' => '1',
],
'BIN2HEX' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BINTOHEX'],
+ 'functionCall' => [Engineering\ConvertBinary::class, 'toHex'],
'argumentCount' => '1,2',
],
'BIN2OCT' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BINTOOCT'],
+ 'functionCall' => [Engineering\ConvertBinary::class, 'toOctal'],
'argumentCount' => '1,2',
],
'BINOMDIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'BINOMDIST'],
+ 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'],
'argumentCount' => '4',
],
'BINOM.DIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'BINOMDIST'],
+ 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'],
'argumentCount' => '4',
],
'BINOM.DIST.RANGE' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [Statistical\Distributions\Binomial::class, 'range'],
'argumentCount' => '3,4',
],
'BINOM.INV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'],
'argumentCount' => '3',
],
'BITAND' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BITAND'],
+ 'functionCall' => [Engineering\BitWise::class, 'BITAND'],
'argumentCount' => '2',
],
'BITOR' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BITOR'],
+ 'functionCall' => [Engineering\BitWise::class, 'BITOR'],
'argumentCount' => '2',
],
'BITXOR' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BITOR'],
+ 'functionCall' => [Engineering\BitWise::class, 'BITXOR'],
'argumentCount' => '2',
],
'BITLSHIFT' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BITLSHIFT'],
+ 'functionCall' => [Engineering\BitWise::class, 'BITLSHIFT'],
'argumentCount' => '2',
],
'BITRSHIFT' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'BITRSHIFT'],
+ 'functionCall' => [Engineering\BitWise::class, 'BITRSHIFT'],
'argumentCount' => '2',
],
'CEILING' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'CEILING'],
- 'argumentCount' => '2',
+ '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' => [Functions::class, 'DUMMY'],
- 'argumentCount' => '3',
+ 'functionCall' => [MathTrig\Ceiling::class, 'math'],
+ 'argumentCount' => '1-3',
],
'CEILING.PRECISE' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [Functions::class, 'DUMMY'],
- 'argumentCount' => '2',
+ 'functionCall' => [MathTrig\Ceiling::class, 'precise'],
+ 'argumentCount' => '1,2',
],
'CELL' => [
'category' => Category::CATEGORY_INFORMATION,
@@ -483,108 +493,109 @@ class Calculation
],
'CHAR' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'CHARACTER'],
+ 'functionCall' => [TextData\CharacterConvert::class, 'character'],
'argumentCount' => '1',
],
'CHIDIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'CHIDIST'],
+ 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'],
'argumentCount' => '2',
],
'CHISQ.DIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionLeftTail'],
'argumentCount' => '3',
],
'CHISQ.DIST.RT' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'CHIDIST'],
+ 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'],
'argumentCount' => '2',
],
'CHIINV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'CHIINV'],
+ 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'],
'argumentCount' => '2',
],
'CHISQ.INV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseLeftTail'],
'argumentCount' => '2',
],
'CHISQ.INV.RT' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'CHIINV'],
+ 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'],
'argumentCount' => '2',
],
'CHITEST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'],
'argumentCount' => '2',
],
'CHISQ.TEST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'],
'argumentCount' => '2',
],
'CHOOSE' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'CHOOSE'],
+ 'functionCall' => [LookupRef\Selection::class, 'CHOOSE'],
'argumentCount' => '2+',
],
'CLEAN' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'TRIMNONPRINTABLE'],
+ 'functionCall' => [TextData\Trim::class, 'nonPrintable'],
'argumentCount' => '1',
],
'CODE' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'ASCIICODE'],
+ 'functionCall' => [TextData\CharacterConvert::class, 'code'],
'argumentCount' => '1',
],
'COLUMN' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'COLUMN'],
+ 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMN'],
'argumentCount' => '-1',
+ 'passCellReference' => true,
'passByReference' => [true],
],
'COLUMNS' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'COLUMNS'],
+ 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMNS'],
'argumentCount' => '1',
],
'COMBIN' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'COMBIN'],
+ 'functionCall' => [MathTrig\Combinations::class, 'withoutRepetition'],
'argumentCount' => '2',
],
'COMBINA' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [MathTrig\Combinations::class, 'withRepetition'],
'argumentCount' => '2',
],
'COMPLEX' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'COMPLEX'],
+ 'functionCall' => [Engineering\Complex::class, 'COMPLEX'],
'argumentCount' => '2,3',
],
'CONCAT' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'CONCATENATE'],
+ 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'],
'argumentCount' => '1+',
],
'CONCATENATE' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'CONCATENATE'],
+ 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'],
'argumentCount' => '1+',
],
'CONFIDENCE' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'CONFIDENCE'],
+ 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'],
'argumentCount' => '3',
],
'CONFIDENCE.NORM' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'CONFIDENCE'],
+ 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'],
'argumentCount' => '3',
],
'CONFIDENCE.T' => [
@@ -594,97 +605,97 @@ class Calculation
],
'CONVERT' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'CONVERTUOM'],
+ 'functionCall' => [Engineering\ConvertUOM::class, 'CONVERT'],
'argumentCount' => '3',
],
'CORREL' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'CORREL'],
+ 'functionCall' => [Statistical\Trends::class, 'CORREL'],
'argumentCount' => '2',
],
'COS' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'cos',
+ 'functionCall' => [MathTrig\Trig\Cosine::class, 'cos'],
'argumentCount' => '1',
],
'COSH' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'cosh',
+ 'functionCall' => [MathTrig\Trig\Cosine::class, 'cosh'],
'argumentCount' => '1',
],
'COT' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'COT'],
+ 'functionCall' => [MathTrig\Trig\Cotangent::class, 'cot'],
'argumentCount' => '1',
],
'COTH' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'COTH'],
+ 'functionCall' => [MathTrig\Trig\Cotangent::class, 'coth'],
'argumentCount' => '1',
],
'COUNT' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'COUNT'],
+ 'functionCall' => [Statistical\Counts::class, 'COUNT'],
'argumentCount' => '1+',
],
'COUNTA' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'COUNTA'],
+ 'functionCall' => [Statistical\Counts::class, 'COUNTA'],
'argumentCount' => '1+',
],
'COUNTBLANK' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'COUNTBLANK'],
+ 'functionCall' => [Statistical\Counts::class, 'COUNTBLANK'],
'argumentCount' => '1',
],
'COUNTIF' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'COUNTIF'],
+ 'functionCall' => [Statistical\Conditional::class, 'COUNTIF'],
'argumentCount' => '2',
],
'COUNTIFS' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'COUNTIFS'],
+ 'functionCall' => [Statistical\Conditional::class, 'COUNTIFS'],
'argumentCount' => '2+',
],
'COUPDAYBS' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'COUPDAYBS'],
+ 'functionCall' => [Financial\Coupons::class, 'COUPDAYBS'],
'argumentCount' => '3,4',
],
'COUPDAYS' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'COUPDAYS'],
+ 'functionCall' => [Financial\Coupons::class, 'COUPDAYS'],
'argumentCount' => '3,4',
],
'COUPDAYSNC' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'COUPDAYSNC'],
+ 'functionCall' => [Financial\Coupons::class, 'COUPDAYSNC'],
'argumentCount' => '3,4',
],
'COUPNCD' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'COUPNCD'],
+ 'functionCall' => [Financial\Coupons::class, 'COUPNCD'],
'argumentCount' => '3,4',
],
'COUPNUM' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'COUPNUM'],
+ 'functionCall' => [Financial\Coupons::class, 'COUPNUM'],
'argumentCount' => '3,4',
],
'COUPPCD' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'COUPPCD'],
+ 'functionCall' => [Financial\Coupons::class, 'COUPPCD'],
'argumentCount' => '3,4',
],
'COVAR' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'COVAR'],
+ 'functionCall' => [Statistical\Trends::class, 'COVAR'],
'argumentCount' => '2',
],
'COVARIANCE.P' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'COVAR'],
+ 'functionCall' => [Statistical\Trends::class, 'COVAR'],
'argumentCount' => '2',
],
'COVARIANCE.S' => [
@@ -694,17 +705,17 @@ class Calculation
],
'CRITBINOM' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'CRITBINOM'],
+ 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'],
'argumentCount' => '3',
],
'CSC' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'CSC'],
+ 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csc'],
'argumentCount' => '1',
],
'CSCH' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'CSCH'],
+ 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csch'],
'argumentCount' => '1',
],
'CUBEKPIMEMBER' => [
@@ -744,52 +755,57 @@ class Calculation
],
'CUMIPMT' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'CUMIPMT'],
+ 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'interest'],
'argumentCount' => '6',
],
'CUMPRINC' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'CUMPRINC'],
+ 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'principal'],
'argumentCount' => '6',
],
'DATE' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'DATE'],
+ 'functionCall' => [DateTimeExcel\Date::class, 'fromYMD'],
'argumentCount' => '3',
],
'DATEDIF' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'DATEDIF'],
+ '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' => [DateTime::class, 'DATEVALUE'],
+ 'functionCall' => [DateTimeExcel\DateValue::class, 'fromString'],
'argumentCount' => '1',
],
'DAVERAGE' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DAVERAGE'],
+ 'functionCall' => [Database\DAverage::class, 'evaluate'],
'argumentCount' => '3',
],
'DAY' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'DAYOFMONTH'],
+ 'functionCall' => [DateTimeExcel\DateParts::class, 'day'],
'argumentCount' => '1',
],
'DAYS' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'DAYS'],
+ 'functionCall' => [DateTimeExcel\Days::class, 'between'],
'argumentCount' => '2',
],
'DAYS360' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'DAYS360'],
+ 'functionCall' => [DateTimeExcel\Days360::class, 'between'],
'argumentCount' => '2,3',
],
'DB' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'DB'],
+ 'functionCall' => [Financial\Depreciation::class, 'DB'],
'argumentCount' => '4,5',
],
'DBCS' => [
@@ -799,32 +815,32 @@ class Calculation
],
'DCOUNT' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DCOUNT'],
+ 'functionCall' => [Database\DCount::class, 'evaluate'],
'argumentCount' => '3',
],
'DCOUNTA' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DCOUNTA'],
+ 'functionCall' => [Database\DCountA::class, 'evaluate'],
'argumentCount' => '3',
],
'DDB' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'DDB'],
+ 'functionCall' => [Financial\Depreciation::class, 'DDB'],
'argumentCount' => '4,5',
],
'DEC2BIN' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'DECTOBIN'],
+ 'functionCall' => [Engineering\ConvertDecimal::class, 'toBinary'],
'argumentCount' => '1,2',
],
'DEC2HEX' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'DECTOHEX'],
+ 'functionCall' => [Engineering\ConvertDecimal::class, 'toHex'],
'argumentCount' => '1,2',
],
'DEC2OCT' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'DECTOOCT'],
+ 'functionCall' => [Engineering\ConvertDecimal::class, 'toOctal'],
'argumentCount' => '1,2',
],
'DECIMAL' => [
@@ -834,72 +850,72 @@ class Calculation
],
'DEGREES' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'rad2deg',
+ 'functionCall' => [MathTrig\Angle::class, 'toDegrees'],
'argumentCount' => '1',
],
'DELTA' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'DELTA'],
+ 'functionCall' => [Engineering\Compare::class, 'DELTA'],
'argumentCount' => '1,2',
],
'DEVSQ' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'DEVSQ'],
+ 'functionCall' => [Statistical\Deviations::class, 'sumSquares'],
'argumentCount' => '1+',
],
'DGET' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DGET'],
+ 'functionCall' => [Database\DGet::class, 'evaluate'],
'argumentCount' => '3',
],
'DISC' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'DISC'],
+ 'functionCall' => [Financial\Securities\Rates::class, 'discount'],
'argumentCount' => '4,5',
],
'DMAX' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DMAX'],
+ 'functionCall' => [Database\DMax::class, 'evaluate'],
'argumentCount' => '3',
],
'DMIN' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DMIN'],
+ 'functionCall' => [Database\DMin::class, 'evaluate'],
'argumentCount' => '3',
],
'DOLLAR' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'DOLLAR'],
+ 'functionCall' => [TextData\Format::class, 'DOLLAR'],
'argumentCount' => '1,2',
],
'DOLLARDE' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'DOLLARDE'],
+ 'functionCall' => [Financial\Dollar::class, 'decimal'],
'argumentCount' => '2',
],
'DOLLARFR' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'DOLLARFR'],
+ 'functionCall' => [Financial\Dollar::class, 'fractional'],
'argumentCount' => '2',
],
'DPRODUCT' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DPRODUCT'],
+ 'functionCall' => [Database\DProduct::class, 'evaluate'],
'argumentCount' => '3',
],
'DSTDEV' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DSTDEV'],
+ 'functionCall' => [Database\DStDev::class, 'evaluate'],
'argumentCount' => '3',
],
'DSTDEVP' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DSTDEVP'],
+ 'functionCall' => [Database\DStDevP::class, 'evaluate'],
'argumentCount' => '3',
],
'DSUM' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DSUM'],
+ 'functionCall' => [Database\DSum::class, 'evaluate'],
'argumentCount' => '3',
],
'DURATION' => [
@@ -909,52 +925,57 @@ class Calculation
],
'DVAR' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DVAR'],
+ 'functionCall' => [Database\DVar::class, 'evaluate'],
'argumentCount' => '3',
],
'DVARP' => [
'category' => Category::CATEGORY_DATABASE,
- 'functionCall' => [Database::class, 'DVARP'],
+ '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' => [DateTime::class, 'EDATE'],
+ 'functionCall' => [DateTimeExcel\Month::class, 'adjust'],
'argumentCount' => '2',
],
'EFFECT' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'EFFECT'],
+ 'functionCall' => [Financial\InterestRate::class, 'effective'],
'argumentCount' => '2',
],
'ENCODEURL' => [
'category' => Category::CATEGORY_WEB,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [Web\Service::class, 'urlEncode'],
'argumentCount' => '1',
],
'EOMONTH' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'EOMONTH'],
+ 'functionCall' => [DateTimeExcel\Month::class, 'lastDay'],
'argumentCount' => '2',
],
'ERF' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'ERF'],
+ 'functionCall' => [Engineering\Erf::class, 'ERF'],
'argumentCount' => '1,2',
],
'ERF.PRECISE' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'ERFPRECISE'],
+ 'functionCall' => [Engineering\Erf::class, 'ERFPRECISE'],
'argumentCount' => '1',
],
'ERFC' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'ERFC'],
+ 'functionCall' => [Engineering\ErfC::class, 'ERFC'],
'argumentCount' => '1',
],
'ERFC.PRECISE' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'ERFC'],
+ 'functionCall' => [Engineering\ErfC::class, 'ERFC'],
'argumentCount' => '1',
],
'ERROR.TYPE' => [
@@ -964,42 +985,42 @@ class Calculation
],
'EVEN' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'EVEN'],
+ 'functionCall' => [MathTrig\Round::class, 'even'],
'argumentCount' => '1',
],
'EXACT' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'EXACT'],
+ 'functionCall' => [TextData\Text::class, 'exact'],
'argumentCount' => '2',
],
'EXP' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'exp',
+ 'functionCall' => [MathTrig\Exp::class, 'evaluate'],
'argumentCount' => '1',
],
'EXPONDIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'EXPONDIST'],
+ 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'],
'argumentCount' => '3',
],
'EXPON.DIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'EXPONDIST'],
+ 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'],
'argumentCount' => '3',
],
'FACT' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'FACT'],
+ 'functionCall' => [MathTrig\Factorial::class, 'fact'],
'argumentCount' => '1',
],
'FACTDOUBLE' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'FACTDOUBLE'],
+ 'functionCall' => [MathTrig\Factorial::class, 'factDouble'],
'argumentCount' => '1',
],
'FALSE' => [
'category' => Category::CATEGORY_LOGICAL,
- 'functionCall' => [Logical::class, 'FALSE'],
+ 'functionCall' => [Logical\Boolean::class, 'FALSE'],
'argumentCount' => '0',
],
'FDIST' => [
@@ -1009,7 +1030,7 @@ class Calculation
],
'F.DIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'FDIST2'],
+ 'functionCall' => [Statistical\Distributions\F::class, 'distribution'],
'argumentCount' => '4',
],
'F.DIST.RT' => [
@@ -1029,12 +1050,12 @@ class Calculation
],
'FIND' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'SEARCHSENSITIVE'],
+ 'functionCall' => [TextData\Search::class, 'sensitive'],
'argumentCount' => '2,3',
],
'FINDB' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'SEARCHSENSITIVE'],
+ 'functionCall' => [TextData\Search::class, 'sensitive'],
'argumentCount' => '2,3',
],
'FINV' => [
@@ -1054,37 +1075,37 @@ class Calculation
],
'FISHER' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'FISHER'],
+ 'functionCall' => [Statistical\Distributions\Fisher::class, 'distribution'],
'argumentCount' => '1',
],
'FISHERINV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'FISHERINV'],
+ 'functionCall' => [Statistical\Distributions\Fisher::class, 'inverse'],
'argumentCount' => '1',
],
'FIXED' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'FIXEDFORMAT'],
+ 'functionCall' => [TextData\Format::class, 'FIXEDFORMAT'],
'argumentCount' => '1-3',
],
'FLOOR' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'FLOOR'],
- 'argumentCount' => '2',
+ '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::class, 'FLOORMATH'],
- 'argumentCount' => '3',
+ 'functionCall' => [MathTrig\Floor::class, 'math'],
+ 'argumentCount' => '1-3',
],
'FLOOR.PRECISE' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'FLOORPRECISE'],
- 'argumentCount' => '2',
+ 'functionCall' => [MathTrig\Floor::class, 'precise'],
+ 'argumentCount' => '1-2',
],
'FORECAST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'FORECAST'],
+ 'functionCall' => [Statistical\Trends::class, 'FORECAST'],
'argumentCount' => '3',
],
'FORECAST.ETS' => [
@@ -1109,12 +1130,12 @@ class Calculation
],
'FORECAST.LINEAR' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'FORECAST'],
+ 'functionCall' => [Statistical\Trends::class, 'FORECAST'],
'argumentCount' => '3',
],
'FORMULATEXT' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'FORMULATEXT'],
+ 'functionCall' => [LookupRef\Formula::class, 'text'],
'argumentCount' => '1',
'passCellReference' => true,
'passByReference' => [true],
@@ -1136,67 +1157,67 @@ class Calculation
],
'FV' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'FV'],
+ 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'futureValue'],
'argumentCount' => '3-5',
],
'FVSCHEDULE' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'FVSCHEDULE'],
+ 'functionCall' => [Financial\CashFlow\Single::class, 'futureValue'],
'argumentCount' => '2',
],
'GAMMA' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'GAMMAFunction'],
+ 'functionCall' => [Statistical\Distributions\Gamma::class, 'gamma'],
'argumentCount' => '1',
],
'GAMMADIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'GAMMADIST'],
+ 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'],
'argumentCount' => '4',
],
'GAMMA.DIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'GAMMADIST'],
+ 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'],
'argumentCount' => '4',
],
'GAMMAINV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'GAMMAINV'],
+ 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'],
'argumentCount' => '3',
],
'GAMMA.INV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'GAMMAINV'],
+ 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'],
'argumentCount' => '3',
],
'GAMMALN' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'GAMMALN'],
+ 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'],
'argumentCount' => '1',
],
'GAMMALN.PRECISE' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'GAMMALN'],
+ 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'],
'argumentCount' => '1',
],
'GAUSS' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'GAUSS'],
+ 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'gauss'],
'argumentCount' => '1',
],
'GCD' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'GCD'],
+ 'functionCall' => [MathTrig\Gcd::class, 'evaluate'],
'argumentCount' => '1+',
],
'GEOMEAN' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'GEOMEAN'],
+ 'functionCall' => [Statistical\Averages\Mean::class, 'geometric'],
'argumentCount' => '1+',
],
'GESTEP' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'GESTEP'],
+ 'functionCall' => [Engineering\Compare::class, 'GESTEP'],
'argumentCount' => '1,2',
],
'GETPIVOTDATA' => [
@@ -1206,48 +1227,48 @@ class Calculation
],
'GROWTH' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'GROWTH'],
+ 'functionCall' => [Statistical\Trends::class, 'GROWTH'],
'argumentCount' => '1-4',
],
'HARMEAN' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'HARMEAN'],
+ 'functionCall' => [Statistical\Averages\Mean::class, 'harmonic'],
'argumentCount' => '1+',
],
'HEX2BIN' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'HEXTOBIN'],
+ 'functionCall' => [Engineering\ConvertHex::class, 'toBinary'],
'argumentCount' => '1,2',
],
'HEX2DEC' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'HEXTODEC'],
+ 'functionCall' => [Engineering\ConvertHex::class, 'toDecimal'],
'argumentCount' => '1',
],
'HEX2OCT' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'HEXTOOCT'],
+ 'functionCall' => [Engineering\ConvertHex::class, 'toOctal'],
'argumentCount' => '1,2',
],
'HLOOKUP' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'HLOOKUP'],
+ 'functionCall' => [LookupRef\HLookup::class, 'lookup'],
'argumentCount' => '3,4',
],
'HOUR' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'HOUROFDAY'],
+ 'functionCall' => [DateTimeExcel\TimeParts::class, 'hour'],
'argumentCount' => '1',
],
'HYPERLINK' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'HYPERLINK'],
+ 'functionCall' => [LookupRef\Hyperlink::class, 'set'],
'argumentCount' => '1,2',
'passCellReference' => true,
],
'HYPGEOMDIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'HYPGEOMDIST'],
+ 'functionCall' => [Statistical\Distributions\HyperGeometric::class, 'distribution'],
'argumentCount' => '4',
],
'HYPGEOM.DIST' => [
@@ -1257,157 +1278,157 @@ class Calculation
],
'IF' => [
'category' => Category::CATEGORY_LOGICAL,
- 'functionCall' => [Logical::class, 'statementIf'],
+ 'functionCall' => [Logical\Conditional::class, 'statementIf'],
'argumentCount' => '1-3',
],
'IFERROR' => [
'category' => Category::CATEGORY_LOGICAL,
- 'functionCall' => [Logical::class, 'IFERROR'],
+ 'functionCall' => [Logical\Conditional::class, 'IFERROR'],
'argumentCount' => '2',
],
'IFNA' => [
'category' => Category::CATEGORY_LOGICAL,
- 'functionCall' => [Logical::class, 'IFNA'],
+ 'functionCall' => [Logical\Conditional::class, 'IFNA'],
'argumentCount' => '2',
],
'IFS' => [
'category' => Category::CATEGORY_LOGICAL,
- 'functionCall' => [Logical::class, 'IFS'],
+ 'functionCall' => [Logical\Conditional::class, 'IFS'],
'argumentCount' => '2+',
],
'IMABS' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMABS'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMABS'],
'argumentCount' => '1',
],
'IMAGINARY' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMAGINARY'],
+ 'functionCall' => [Engineering\Complex::class, 'IMAGINARY'],
'argumentCount' => '1',
],
'IMARGUMENT' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMARGUMENT'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMARGUMENT'],
'argumentCount' => '1',
],
'IMCONJUGATE' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMCONJUGATE'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCONJUGATE'],
'argumentCount' => '1',
],
'IMCOS' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMCOS'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOS'],
'argumentCount' => '1',
],
'IMCOSH' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMCOSH'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOSH'],
'argumentCount' => '1',
],
'IMCOT' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMCOT'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOT'],
'argumentCount' => '1',
],
'IMCSC' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMCSC'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSC'],
'argumentCount' => '1',
],
'IMCSCH' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMCSCH'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSCH'],
'argumentCount' => '1',
],
'IMDIV' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMDIV'],
+ 'functionCall' => [Engineering\ComplexOperations::class, 'IMDIV'],
'argumentCount' => '2',
],
'IMEXP' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMEXP'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMEXP'],
'argumentCount' => '1',
],
'IMLN' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMLN'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLN'],
'argumentCount' => '1',
],
'IMLOG10' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMLOG10'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG10'],
'argumentCount' => '1',
],
'IMLOG2' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMLOG2'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG2'],
'argumentCount' => '1',
],
'IMPOWER' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMPOWER'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMPOWER'],
'argumentCount' => '2',
],
'IMPRODUCT' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMPRODUCT'],
+ 'functionCall' => [Engineering\ComplexOperations::class, 'IMPRODUCT'],
'argumentCount' => '1+',
],
'IMREAL' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMREAL'],
+ 'functionCall' => [Engineering\Complex::class, 'IMREAL'],
'argumentCount' => '1',
],
'IMSEC' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMSEC'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSEC'],
'argumentCount' => '1',
],
'IMSECH' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMSECH'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSECH'],
'argumentCount' => '1',
],
'IMSIN' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMSIN'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSIN'],
'argumentCount' => '1',
],
'IMSINH' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMSINH'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSINH'],
'argumentCount' => '1',
],
'IMSQRT' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMSQRT'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSQRT'],
'argumentCount' => '1',
],
'IMSUB' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMSUB'],
+ 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUB'],
'argumentCount' => '2',
],
'IMSUM' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMSUM'],
+ 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUM'],
'argumentCount' => '1+',
],
'IMTAN' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'IMTAN'],
+ 'functionCall' => [Engineering\ComplexFunctions::class, 'IMTAN'],
'argumentCount' => '1',
],
'INDEX' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'INDEX'],
+ 'functionCall' => [LookupRef\Matrix::class, 'index'],
'argumentCount' => '1-4',
],
'INDIRECT' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'INDIRECT'],
+ 'functionCall' => [LookupRef\Indirect::class, 'INDIRECT'],
'argumentCount' => '1,2',
'passCellReference' => true,
],
@@ -1418,27 +1439,27 @@ class Calculation
],
'INT' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'INT'],
+ 'functionCall' => [MathTrig\IntClass::class, 'evaluate'],
'argumentCount' => '1',
],
'INTERCEPT' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'INTERCEPT'],
+ 'functionCall' => [Statistical\Trends::class, 'INTERCEPT'],
'argumentCount' => '2',
],
'INTRATE' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'INTRATE'],
+ 'functionCall' => [Financial\Securities\Rates::class, 'interest'],
'argumentCount' => '4,5',
],
'IPMT' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'IPMT'],
+ 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'payment'],
'argumentCount' => '4-6',
],
'IRR' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'IRR'],
+ 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'rate'],
'argumentCount' => '1,2',
],
'ISBLANK' => [
@@ -1500,12 +1521,12 @@ class Calculation
],
'ISOWEEKNUM' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'ISOWEEKNUM'],
+ 'functionCall' => [DateTimeExcel\Week::class, 'isoWeekNumber'],
'argumentCount' => '1',
],
'ISPMT' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'ISPMT'],
+ 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'schedulePayment'],
'argumentCount' => '4',
],
'ISREF' => [
@@ -1518,6 +1539,11 @@ class Calculation
'functionCall' => [Functions::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'],
@@ -1525,117 +1551,117 @@ class Calculation
],
'KURT' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'KURT'],
+ 'functionCall' => [Statistical\Deviations::class, 'kurtosis'],
'argumentCount' => '1+',
],
'LARGE' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'LARGE'],
+ 'functionCall' => [Statistical\Size::class, 'large'],
'argumentCount' => '2',
],
'LCM' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'LCM'],
+ 'functionCall' => [MathTrig\Lcm::class, 'evaluate'],
'argumentCount' => '1+',
],
'LEFT' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'LEFT'],
+ 'functionCall' => [TextData\Extract::class, 'left'],
'argumentCount' => '1,2',
],
'LEFTB' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'LEFT'],
+ 'functionCall' => [TextData\Extract::class, 'left'],
'argumentCount' => '1,2',
],
'LEN' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'STRINGLENGTH'],
+ 'functionCall' => [TextData\Text::class, 'length'],
'argumentCount' => '1',
],
'LENB' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'STRINGLENGTH'],
+ 'functionCall' => [TextData\Text::class, 'length'],
'argumentCount' => '1',
],
'LINEST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'LINEST'],
+ 'functionCall' => [Statistical\Trends::class, 'LINEST'],
'argumentCount' => '1-4',
],
'LN' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'log',
+ 'functionCall' => [MathTrig\Logarithms::class, 'natural'],
'argumentCount' => '1',
],
'LOG' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'logBase'],
+ 'functionCall' => [MathTrig\Logarithms::class, 'withBase'],
'argumentCount' => '1,2',
],
'LOG10' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'log10',
+ 'functionCall' => [MathTrig\Logarithms::class, 'base10'],
'argumentCount' => '1',
],
'LOGEST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'LOGEST'],
+ 'functionCall' => [Statistical\Trends::class, 'LOGEST'],
'argumentCount' => '1-4',
],
'LOGINV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'LOGINV'],
+ 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'],
'argumentCount' => '3',
],
'LOGNORMDIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'LOGNORMDIST'],
+ 'functionCall' => [Statistical\Distributions\LogNormal::class, 'cumulative'],
'argumentCount' => '3',
],
'LOGNORM.DIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'LOGNORMDIST2'],
+ 'functionCall' => [Statistical\Distributions\LogNormal::class, 'distribution'],
'argumentCount' => '4',
],
'LOGNORM.INV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'LOGINV'],
+ 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'],
'argumentCount' => '3',
],
'LOOKUP' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'LOOKUP'],
+ 'functionCall' => [LookupRef\Lookup::class, 'lookup'],
'argumentCount' => '2,3',
],
'LOWER' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'LOWERCASE'],
+ 'functionCall' => [TextData\CaseConvert::class, 'lower'],
'argumentCount' => '1',
],
'MATCH' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'MATCH'],
+ 'functionCall' => [LookupRef\ExcelMatch::class, 'MATCH'],
'argumentCount' => '2,3',
],
'MAX' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'MAX'],
+ 'functionCall' => [Statistical\Maximum::class, 'max'],
'argumentCount' => '1+',
],
'MAXA' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'MAXA'],
+ 'functionCall' => [Statistical\Maximum::class, 'maxA'],
'argumentCount' => '1+',
],
'MAXIFS' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'MAXIFS'],
+ 'functionCall' => [Statistical\Conditional::class, 'MAXIFS'],
'argumentCount' => '3+',
],
'MDETERM' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'MDETERM'],
+ 'functionCall' => [MathTrig\MatrixFunctions::class, 'determinant'],
'argumentCount' => '1',
],
'MDURATION' => [
@@ -1645,7 +1671,7 @@ class Calculation
],
'MEDIAN' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'MEDIAN'],
+ 'functionCall' => [Statistical\Averages::class, 'median'],
'argumentCount' => '1+',
],
'MEDIANIF' => [
@@ -1655,57 +1681,57 @@ class Calculation
],
'MID' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'MID'],
+ 'functionCall' => [TextData\Extract::class, 'mid'],
'argumentCount' => '3',
],
'MIDB' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'MID'],
+ 'functionCall' => [TextData\Extract::class, 'mid'],
'argumentCount' => '3',
],
'MIN' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'MIN'],
+ 'functionCall' => [Statistical\Minimum::class, 'min'],
'argumentCount' => '1+',
],
'MINA' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'MINA'],
+ 'functionCall' => [Statistical\Minimum::class, 'minA'],
'argumentCount' => '1+',
],
'MINIFS' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'MINIFS'],
+ 'functionCall' => [Statistical\Conditional::class, 'MINIFS'],
'argumentCount' => '3+',
],
'MINUTE' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'MINUTE'],
+ 'functionCall' => [DateTimeExcel\TimeParts::class, 'minute'],
'argumentCount' => '1',
],
'MINVERSE' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'MINVERSE'],
+ 'functionCall' => [MathTrig\MatrixFunctions::class, 'inverse'],
'argumentCount' => '1',
],
'MIRR' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'MIRR'],
+ 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'modifiedRate'],
'argumentCount' => '3',
],
'MMULT' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'MMULT'],
+ 'functionCall' => [MathTrig\MatrixFunctions::class, 'multiply'],
'argumentCount' => '2',
],
'MOD' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'MOD'],
+ 'functionCall' => [MathTrig\Operations::class, 'mod'],
'argumentCount' => '2',
],
'MODE' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'MODE'],
+ 'functionCall' => [Statistical\Averages::class, 'mode'],
'argumentCount' => '1+',
],
'MODE.MULT' => [
@@ -1715,27 +1741,27 @@ class Calculation
],
'MODE.SNGL' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'MODE'],
+ 'functionCall' => [Statistical\Averages::class, 'mode'],
'argumentCount' => '1+',
],
'MONTH' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'MONTHOFYEAR'],
+ 'functionCall' => [DateTimeExcel\DateParts::class, 'month'],
'argumentCount' => '1',
],
'MROUND' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'MROUND'],
+ 'functionCall' => [MathTrig\Round::class, 'multiple'],
'argumentCount' => '2',
],
'MULTINOMIAL' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'MULTINOMIAL'],
+ 'functionCall' => [MathTrig\Factorial::class, 'multinomial'],
'argumentCount' => '1+',
],
'MUNIT' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [MathTrig\MatrixFunctions::class, 'identity'],
'argumentCount' => '1',
],
'N' => [
@@ -1750,7 +1776,7 @@ class Calculation
],
'NEGBINOMDIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'NEGBINOMDIST'],
+ 'functionCall' => [Statistical\Distributions\Binomial::class, 'negative'],
'argumentCount' => '3',
],
'NEGBINOM.DIST' => [
@@ -1760,7 +1786,7 @@ class Calculation
],
'NETWORKDAYS' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'NETWORKDAYS'],
+ 'functionCall' => [DateTimeExcel\NetworkDays::class, 'count'],
'argumentCount' => '2-3',
],
'NETWORKDAYS.INTL' => [
@@ -1770,92 +1796,97 @@ class Calculation
],
'NOMINAL' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'NOMINAL'],
+ 'functionCall' => [Financial\InterestRate::class, 'nominal'],
'argumentCount' => '2',
],
'NORMDIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'NORMDIST'],
+ 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'],
'argumentCount' => '4',
],
'NORM.DIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'NORMDIST'],
+ 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'],
'argumentCount' => '4',
],
'NORMINV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'NORMINV'],
+ 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'],
'argumentCount' => '3',
],
'NORM.INV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'NORMINV'],
+ 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'],
'argumentCount' => '3',
],
'NORMSDIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'NORMSDIST'],
+ 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'cumulative'],
'argumentCount' => '1',
],
'NORM.S.DIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'NORMSDIST2'],
+ 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'distribution'],
'argumentCount' => '1,2',
],
'NORMSINV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'NORMSINV'],
+ 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'],
'argumentCount' => '1',
],
'NORM.S.INV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'NORMSINV'],
+ 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'],
'argumentCount' => '1',
],
'NOT' => [
'category' => Category::CATEGORY_LOGICAL,
- 'functionCall' => [Logical::class, 'NOT'],
+ 'functionCall' => [Logical\Operations::class, 'NOT'],
'argumentCount' => '1',
],
'NOW' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'DATETIMENOW'],
+ 'functionCall' => [DateTimeExcel\Current::class, 'now'],
'argumentCount' => '0',
],
'NPER' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'NPER'],
+ 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'periods'],
'argumentCount' => '3-5',
],
'NPV' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'NPV'],
+ '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::class, 'NUMBERVALUE'],
+ 'functionCall' => [TextData\Format::class, 'NUMBERVALUE'],
'argumentCount' => '1+',
],
'OCT2BIN' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'OCTTOBIN'],
+ 'functionCall' => [Engineering\ConvertOctal::class, 'toBinary'],
'argumentCount' => '1,2',
],
'OCT2DEC' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'OCTTODEC'],
+ 'functionCall' => [Engineering\ConvertOctal::class, 'toDecimal'],
'argumentCount' => '1',
],
'OCT2HEX' => [
'category' => Category::CATEGORY_ENGINEERING,
- 'functionCall' => [Engineering::class, 'OCTTOHEX'],
+ 'functionCall' => [Engineering\ConvertOctal::class, 'toHex'],
'argumentCount' => '1,2',
],
'ODD' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'ODD'],
+ 'functionCall' => [MathTrig\Round::class, 'odd'],
'argumentCount' => '1',
],
'ODDFPRICE' => [
@@ -1880,29 +1911,29 @@ class Calculation
],
'OFFSET' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'OFFSET'],
+ 'functionCall' => [LookupRef\Offset::class, 'OFFSET'],
'argumentCount' => '3-5',
'passCellReference' => true,
'passByReference' => [true],
],
'OR' => [
'category' => Category::CATEGORY_LOGICAL,
- 'functionCall' => [Logical::class, 'logicalOr'],
+ 'functionCall' => [Logical\Operations::class, 'logicalOr'],
'argumentCount' => '1+',
],
'PDURATION' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'PDURATION'],
+ 'functionCall' => [Financial\CashFlow\Single::class, 'periods'],
'argumentCount' => '3',
],
'PEARSON' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'CORREL'],
+ 'functionCall' => [Statistical\Trends::class, 'CORREL'],
'argumentCount' => '2',
],
'PERCENTILE' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'PERCENTILE'],
+ 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'],
'argumentCount' => '2',
],
'PERCENTILE.EXC' => [
@@ -1912,12 +1943,12 @@ class Calculation
],
'PERCENTILE.INC' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'PERCENTILE'],
+ 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'],
'argumentCount' => '2',
],
'PERCENTRANK' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'PERCENTRANK'],
+ 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'],
'argumentCount' => '2,3',
],
'PERCENTRANK.EXC' => [
@@ -1927,17 +1958,17 @@ class Calculation
],
'PERCENTRANK.INC' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'PERCENTRANK'],
+ 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'],
'argumentCount' => '2,3',
],
'PERMUT' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'PERMUT'],
+ 'functionCall' => [Statistical\Permutations::class, 'PERMUT'],
'argumentCount' => '2',
],
'PERMUTATIONA' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [Statistical\Permutations::class, 'PERMUTATIONA'],
'argumentCount' => '2',
],
'PHONETIC' => [
@@ -1957,42 +1988,42 @@ class Calculation
],
'PMT' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'PMT'],
+ 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'annuity'],
'argumentCount' => '3-5',
],
'POISSON' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'POISSON'],
+ 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'],
'argumentCount' => '3',
],
'POISSON.DIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'POISSON'],
+ 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'],
'argumentCount' => '3',
],
'POWER' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'POWER'],
+ 'functionCall' => [MathTrig\Operations::class, 'power'],
'argumentCount' => '2',
],
'PPMT' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'PPMT'],
+ 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'interestPayment'],
'argumentCount' => '4-6',
],
'PRICE' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'PRICE'],
+ 'functionCall' => [Financial\Securities\Price::class, 'price'],
'argumentCount' => '6,7',
],
'PRICEDISC' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'PRICEDISC'],
+ 'functionCall' => [Financial\Securities\Price::class, 'priceDiscounted'],
'argumentCount' => '4,5',
],
'PRICEMAT' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'PRICEMAT'],
+ 'functionCall' => [Financial\Securities\Price::class, 'priceAtMaturity'],
'argumentCount' => '5,6',
],
'PROB' => [
@@ -2002,22 +2033,22 @@ class Calculation
],
'PRODUCT' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'PRODUCT'],
+ 'functionCall' => [MathTrig\Operations::class, 'product'],
'argumentCount' => '1+',
],
'PROPER' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'PROPERCASE'],
+ 'functionCall' => [TextData\CaseConvert::class, 'proper'],
'argumentCount' => '1',
],
'PV' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'PV'],
+ 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'presentValue'],
'argumentCount' => '3-5',
],
'QUARTILE' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'QUARTILE'],
+ 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'],
'argumentCount' => '2',
],
'QUARTILE.EXC' => [
@@ -2027,22 +2058,22 @@ class Calculation
],
'QUARTILE.INC' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'QUARTILE'],
+ 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'],
'argumentCount' => '2',
],
'QUOTIENT' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'QUOTIENT'],
+ 'functionCall' => [MathTrig\Operations::class, 'quotient'],
'argumentCount' => '2',
],
'RADIANS' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'deg2rad',
+ 'functionCall' => [MathTrig\Angle::class, 'toRadians'],
'argumentCount' => '1',
],
'RAND' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'RAND'],
+ 'functionCall' => [MathTrig\Random::class, 'rand'],
'argumentCount' => '0',
],
'RANDARRAY' => [
@@ -2052,12 +2083,12 @@ class Calculation
],
'RANDBETWEEN' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'RAND'],
+ 'functionCall' => [MathTrig\Random::class, 'randBetween'],
'argumentCount' => '2',
],
'RANK' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'RANK'],
+ 'functionCall' => [Statistical\Percentiles::class, 'RANK'],
'argumentCount' => '2,3',
],
'RANK.AVG' => [
@@ -2067,83 +2098,94 @@ class Calculation
],
'RANK.EQ' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'RANK'],
+ 'functionCall' => [Statistical\Percentiles::class, 'RANK'],
'argumentCount' => '2,3',
],
'RATE' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'RATE'],
+ 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'rate'],
'argumentCount' => '3-6',
],
'RECEIVED' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'RECEIVED'],
+ 'functionCall' => [Financial\Securities\Price::class, 'received'],
'argumentCount' => '4-5',
],
'REPLACE' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'REPLACE'],
+ 'functionCall' => [TextData\Replace::class, 'replace'],
'argumentCount' => '4',
],
'REPLACEB' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'REPLACE'],
+ 'functionCall' => [TextData\Replace::class, 'replace'],
'argumentCount' => '4',
],
'REPT' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => 'str_repeat',
+ 'functionCall' => [TextData\Concatenate::class, 'builtinREPT'],
'argumentCount' => '2',
],
'RIGHT' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'RIGHT'],
+ 'functionCall' => [TextData\Extract::class, 'right'],
'argumentCount' => '1,2',
],
'RIGHTB' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'RIGHT'],
+ 'functionCall' => [TextData\Extract::class, 'right'],
'argumentCount' => '1,2',
],
'ROMAN' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'ROMAN'],
+ 'functionCall' => [MathTrig\Roman::class, 'evaluate'],
'argumentCount' => '1,2',
],
'ROUND' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'round',
+ '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::class, 'ROUNDDOWN'],
+ 'functionCall' => [MathTrig\Round::class, 'down'],
'argumentCount' => '2',
],
'ROUNDUP' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'ROUNDUP'],
+ 'functionCall' => [MathTrig\Round::class, 'up'],
'argumentCount' => '2',
],
'ROW' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'ROW'],
+ 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROW'],
'argumentCount' => '-1',
+ 'passCellReference' => true,
'passByReference' => [true],
],
'ROWS' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'ROWS'],
+ 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROWS'],
'argumentCount' => '1',
],
'RRI' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'RRI'],
+ 'functionCall' => [Financial\CashFlow\Single::class, 'interestRate'],
'argumentCount' => '3',
],
'RSQ' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'RSQ'],
+ 'functionCall' => [Statistical\Trends::class, 'RSQ'],
'argumentCount' => '2',
],
'RTD' => [
@@ -2153,27 +2195,27 @@ class Calculation
],
'SEARCH' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'SEARCHINSENSITIVE'],
+ 'functionCall' => [TextData\Search::class, 'insensitive'],
'argumentCount' => '2,3',
],
'SEARCHB' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'SEARCHINSENSITIVE'],
+ 'functionCall' => [TextData\Search::class, 'insensitive'],
'argumentCount' => '2,3',
],
'SEC' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SEC'],
+ 'functionCall' => [MathTrig\Trig\Secant::class, 'sec'],
'argumentCount' => '1',
],
'SECH' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SECH'],
+ 'functionCall' => [MathTrig\Trig\Secant::class, 'sech'],
'argumentCount' => '1',
],
'SECOND' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'SECOND'],
+ 'functionCall' => [DateTimeExcel\TimeParts::class, 'second'],
'argumentCount' => '1',
],
'SEQUENCE' => [
@@ -2183,7 +2225,7 @@ class Calculation
],
'SERIESSUM' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SERIESSUM'],
+ 'functionCall' => [MathTrig\SeriesSum::class, 'evaluate'],
'argumentCount' => '4',
],
'SHEET' => [
@@ -2198,22 +2240,22 @@ class Calculation
],
'SIGN' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SIGN'],
+ 'functionCall' => [MathTrig\Sign::class, 'evaluate'],
'argumentCount' => '1',
],
'SIN' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'sin',
+ 'functionCall' => [MathTrig\Trig\Sine::class, 'sin'],
'argumentCount' => '1',
],
'SINH' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'sinh',
+ 'functionCall' => [MathTrig\Trig\Sine::class, 'sinh'],
'argumentCount' => '1',
],
'SKEW' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'SKEW'],
+ 'functionCall' => [Statistical\Deviations::class, 'skew'],
'argumentCount' => '1+',
],
'SKEW.P' => [
@@ -2223,17 +2265,17 @@ class Calculation
],
'SLN' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'SLN'],
+ 'functionCall' => [Financial\Depreciation::class, 'SLN'],
'argumentCount' => '3',
],
'SLOPE' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'SLOPE'],
+ 'functionCall' => [Statistical\Trends::class, 'SLOPE'],
'argumentCount' => '2',
],
'SMALL' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'SMALL'],
+ 'functionCall' => [Statistical\Size::class, 'small'],
'argumentCount' => '2',
],
'SORT' => [
@@ -2248,148 +2290,148 @@ class Calculation
],
'SQRT' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'sqrt',
+ 'functionCall' => [MathTrig\Sqrt::class, 'sqrt'],
'argumentCount' => '1',
],
'SQRTPI' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SQRTPI'],
+ 'functionCall' => [MathTrig\Sqrt::class, 'pi'],
'argumentCount' => '1',
],
'STANDARDIZE' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'STANDARDIZE'],
+ 'functionCall' => [Statistical\Standardize::class, 'execute'],
'argumentCount' => '3',
],
'STDEV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'STDEV'],
+ 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'],
'argumentCount' => '1+',
],
'STDEV.S' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'STDEV'],
+ 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'],
'argumentCount' => '1+',
],
'STDEV.P' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'STDEVP'],
+ 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'],
'argumentCount' => '1+',
],
'STDEVA' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'STDEVA'],
+ 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVA'],
'argumentCount' => '1+',
],
'STDEVP' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'STDEVP'],
+ 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'],
'argumentCount' => '1+',
],
'STDEVPA' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'STDEVPA'],
+ 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVPA'],
'argumentCount' => '1+',
],
'STEYX' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'STEYX'],
+ 'functionCall' => [Statistical\Trends::class, 'STEYX'],
'argumentCount' => '2',
],
'SUBSTITUTE' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'SUBSTITUTE'],
+ 'functionCall' => [TextData\Replace::class, 'substitute'],
'argumentCount' => '3,4',
],
'SUBTOTAL' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SUBTOTAL'],
+ 'functionCall' => [MathTrig\Subtotal::class, 'evaluate'],
'argumentCount' => '2+',
'passCellReference' => true,
],
'SUM' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SUM'],
+ 'functionCall' => [MathTrig\Sum::class, 'sumErroringStrings'],
'argumentCount' => '1+',
],
'SUMIF' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SUMIF'],
+ 'functionCall' => [Statistical\Conditional::class, 'SUMIF'],
'argumentCount' => '2,3',
],
'SUMIFS' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SUMIFS'],
+ 'functionCall' => [Statistical\Conditional::class, 'SUMIFS'],
'argumentCount' => '3+',
],
'SUMPRODUCT' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SUMPRODUCT'],
+ 'functionCall' => [MathTrig\Sum::class, 'product'],
'argumentCount' => '1+',
],
'SUMSQ' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SUMSQ'],
+ 'functionCall' => [MathTrig\SumSquares::class, 'sumSquare'],
'argumentCount' => '1+',
],
'SUMX2MY2' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SUMX2MY2'],
+ 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredMinusYSquared'],
'argumentCount' => '2',
],
'SUMX2PY2' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SUMX2PY2'],
+ 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredPlusYSquared'],
'argumentCount' => '2',
],
'SUMXMY2' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'SUMXMY2'],
+ 'functionCall' => [MathTrig\SumSquares::class, 'sumXMinusYSquared'],
'argumentCount' => '2',
],
'SWITCH' => [
'category' => Category::CATEGORY_LOGICAL,
- 'functionCall' => [Logical::class, 'statementSwitch'],
+ 'functionCall' => [Logical\Conditional::class, 'statementSwitch'],
'argumentCount' => '3+',
],
'SYD' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'SYD'],
+ 'functionCall' => [Financial\Depreciation::class, 'SYD'],
'argumentCount' => '4',
],
'T' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'RETURNSTRING'],
+ 'functionCall' => [TextData\Text::class, 'test'],
'argumentCount' => '1',
],
'TAN' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'tan',
+ 'functionCall' => [MathTrig\Trig\Tangent::class, 'tan'],
'argumentCount' => '1',
],
'TANH' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => 'tanh',
+ 'functionCall' => [MathTrig\Trig\Tangent::class, 'tanh'],
'argumentCount' => '1',
],
'TBILLEQ' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'TBILLEQ'],
+ 'functionCall' => [Financial\TreasuryBill::class, 'bondEquivalentYield'],
'argumentCount' => '3',
],
'TBILLPRICE' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'TBILLPRICE'],
+ 'functionCall' => [Financial\TreasuryBill::class, 'price'],
'argumentCount' => '3',
],
'TBILLYIELD' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'TBILLYIELD'],
+ 'functionCall' => [Financial\TreasuryBill::class, 'yield'],
'argumentCount' => '3',
],
'TDIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'TDIST'],
+ 'functionCall' => [Statistical\Distributions\StudentT::class, 'distribution'],
'argumentCount' => '3',
],
'T.DIST' => [
@@ -2409,32 +2451,67 @@ class Calculation
],
'TEXT' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'TEXTFORMAT'],
+ 'functionCall' => [TextData\Format::class, 'TEXTFORMAT'],
'argumentCount' => '2',
],
'TEXTJOIN' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'TEXTJOIN'],
+ 'functionCall' => [TextData\Concatenate::class, 'TEXTJOIN'],
'argumentCount' => '3+',
],
+ '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' => [DateTime::class, 'TIME'],
+ 'functionCall' => [DateTimeExcel\Time::class, 'fromHMS'],
'argumentCount' => '3',
],
'TIMEVALUE' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'TIMEVALUE'],
+ 'functionCall' => [DateTimeExcel\TimeValue::class, 'fromString'],
'argumentCount' => '1',
],
'TINV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'TINV'],
+ 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'],
'argumentCount' => '2',
],
'T.INV' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'TINV'],
+ 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'],
'argumentCount' => '2',
],
'T.INV.2T' => [
@@ -2444,37 +2521,37 @@ class Calculation
],
'TODAY' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'DATENOW'],
+ 'functionCall' => [DateTimeExcel\Current::class, 'today'],
'argumentCount' => '0',
],
'TRANSPOSE' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'TRANSPOSE'],
+ 'functionCall' => [LookupRef\Matrix::class, 'transpose'],
'argumentCount' => '1',
],
'TREND' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'TREND'],
+ 'functionCall' => [Statistical\Trends::class, 'TREND'],
'argumentCount' => '1-4',
],
'TRIM' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'TRIMSPACES'],
+ 'functionCall' => [TextData\Trim::class, 'spaces'],
'argumentCount' => '1',
],
'TRIMMEAN' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'TRIMMEAN'],
+ 'functionCall' => [Statistical\Averages\Mean::class, 'trim'],
'argumentCount' => '2',
],
'TRUE' => [
'category' => Category::CATEGORY_LOGICAL,
- 'functionCall' => [Logical::class, 'TRUE'],
+ 'functionCall' => [Logical\Boolean::class, 'TRUE'],
'argumentCount' => '0',
],
'TRUNC' => [
'category' => Category::CATEGORY_MATH_AND_TRIG,
- 'functionCall' => [MathTrig::class, 'TRUNC'],
+ 'functionCall' => [MathTrig\Trunc::class, 'evaluate'],
'argumentCount' => '1,2',
],
'TTEST' => [
@@ -2494,12 +2571,12 @@ class Calculation
],
'UNICHAR' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'CHARACTER'],
+ 'functionCall' => [TextData\CharacterConvert::class, 'character'],
'argumentCount' => '1',
],
'UNICODE' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'ASCIICODE'],
+ 'functionCall' => [TextData\CharacterConvert::class, 'code'],
'argumentCount' => '1',
],
'UNIQUE' => [
@@ -2509,47 +2586,52 @@ class Calculation
],
'UPPER' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'UPPERCASE'],
+ 'functionCall' => [TextData\CaseConvert::class, 'upper'],
'argumentCount' => '1',
],
'USDOLLAR' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Functions::class, 'DUMMY'],
+ 'functionCall' => [Financial\Dollar::class, 'format'],
'argumentCount' => '2',
],
'VALUE' => [
'category' => Category::CATEGORY_TEXT_AND_DATA,
- 'functionCall' => [TextData::class, 'VALUE'],
+ 'functionCall' => [TextData\Format::class, 'VALUE'],
'argumentCount' => '1',
],
+ 'VALUETOTEXT' => [
+ 'category' => Category::CATEGORY_TEXT_AND_DATA,
+ 'functionCall' => [Functions::class, 'DUMMY'],
+ 'argumentCount' => '?',
+ ],
'VAR' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'VARFunc'],
+ 'functionCall' => [Statistical\Variances::class, 'VAR'],
'argumentCount' => '1+',
],
'VAR.P' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'VARP'],
+ 'functionCall' => [Statistical\Variances::class, 'VARP'],
'argumentCount' => '1+',
],
'VAR.S' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'VARFunc'],
+ 'functionCall' => [Statistical\Variances::class, 'VAR'],
'argumentCount' => '1+',
],
'VARA' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'VARA'],
+ 'functionCall' => [Statistical\Variances::class, 'VARA'],
'argumentCount' => '1+',
],
'VARP' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'VARP'],
+ 'functionCall' => [Statistical\Variances::class, 'VARP'],
'argumentCount' => '1+',
],
'VARPA' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'VARPA'],
+ 'functionCall' => [Statistical\Variances::class, 'VARPA'],
'argumentCount' => '1+',
],
'VDB' => [
@@ -2559,37 +2641,37 @@ class Calculation
],
'VLOOKUP' => [
'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
- 'functionCall' => [LookupRef::class, 'VLOOKUP'],
+ 'functionCall' => [LookupRef\VLookup::class, 'lookup'],
'argumentCount' => '3,4',
],
'WEBSERVICE' => [
'category' => Category::CATEGORY_WEB,
- 'functionCall' => [Web::class, 'WEBSERVICE'],
+ 'functionCall' => [Web\Service::class, 'webService'],
'argumentCount' => '1',
],
'WEEKDAY' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'WEEKDAY'],
+ 'functionCall' => [DateTimeExcel\Week::class, 'day'],
'argumentCount' => '1,2',
],
'WEEKNUM' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'WEEKNUM'],
+ 'functionCall' => [DateTimeExcel\Week::class, 'number'],
'argumentCount' => '1,2',
],
'WEIBULL' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'WEIBULL'],
+ 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'],
'argumentCount' => '4',
],
'WEIBULL.DIST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'WEIBULL'],
+ 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'],
'argumentCount' => '4',
],
'WORKDAY' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'WORKDAY'],
+ 'functionCall' => [DateTimeExcel\WorkDay::class, 'date'],
'argumentCount' => '2-3',
],
'WORKDAY.INTL' => [
@@ -2599,7 +2681,7 @@ class Calculation
],
'XIRR' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'XIRR'],
+ 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'rate'],
'argumentCount' => '2,3',
],
'XLOOKUP' => [
@@ -2609,7 +2691,7 @@ class Calculation
],
'XNPV' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'XNPV'],
+ 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'presentValue'],
'argumentCount' => '3',
],
'XMATCH' => [
@@ -2619,17 +2701,17 @@ class Calculation
],
'XOR' => [
'category' => Category::CATEGORY_LOGICAL,
- 'functionCall' => [Logical::class, 'logicalXor'],
+ 'functionCall' => [Logical\Operations::class, 'logicalXor'],
'argumentCount' => '1+',
],
'YEAR' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'YEAR'],
+ 'functionCall' => [DateTimeExcel\DateParts::class, 'year'],
'argumentCount' => '1',
],
'YEARFRAC' => [
'category' => Category::CATEGORY_DATE_AND_TIME,
- 'functionCall' => [DateTime::class, 'YEARFRAC'],
+ 'functionCall' => [DateTimeExcel\YearFrac::class, 'fraction'],
'argumentCount' => '2,3',
],
'YIELD' => [
@@ -2639,22 +2721,22 @@ class Calculation
],
'YIELDDISC' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'YIELDDISC'],
+ 'functionCall' => [Financial\Securities\Yields::class, 'yieldDiscounted'],
'argumentCount' => '4,5',
],
'YIELDMAT' => [
'category' => Category::CATEGORY_FINANCIAL,
- 'functionCall' => [Financial::class, 'YIELDMAT'],
+ 'functionCall' => [Financial\Securities\Yields::class, 'yieldAtMaturity'],
'argumentCount' => '5,6',
],
'ZTEST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'ZTEST'],
+ 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'],
'argumentCount' => '2-3',
],
'Z.TEST' => [
'category' => Category::CATEGORY_STATISTICAL,
- 'functionCall' => [Statistical::class, 'ZTEST'],
+ 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'],
'argumentCount' => '2-3',
],
];
@@ -2663,12 +2745,16 @@ class Calculation
private static $controlFunctions = [
'MKMATRIX' => [
'argumentCount' => '*',
- 'functionCall' => [__CLASS__, 'mkMatrix'],
+ '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)
@@ -2695,12 +2781,10 @@ class Calculation
/**
* Get an instance of this class.
*
- * @param Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object,
- * or NULL to create a standalone claculation engine
- *
- * @return Calculation
+ * @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)
+ public static function getInstance(?Spreadsheet $spreadsheet = null): self
{
if ($spreadsheet !== null) {
$instance = $spreadsheet->getCalculationEngine();
@@ -2749,7 +2833,7 @@ class Calculation
*
* @return string locale-specific translation of TRUE
*/
- public static function getTRUE()
+ public static function getTRUE(): string
{
return self::$localeBoolean['TRUE'];
}
@@ -2759,7 +2843,7 @@ class Calculation
*
* @return string locale-specific translation of FALSE
*/
- public static function getFALSE()
+ public static function getFALSE(): string
{
return self::$localeBoolean['FALSE'];
}
@@ -2809,11 +2893,11 @@ class Calculation
/**
* Enable/disable calculation cache.
*
- * @param bool $pValue
+ * @param bool $calculationCacheEnabled
*/
- public function setCalculationCacheEnabled($pValue): void
+ public function setCalculationCacheEnabled($calculationCacheEnabled): void
{
- $this->calculationCacheEnabled = $pValue;
+ $this->calculationCacheEnabled = $calculationCacheEnabled;
$this->clearCalculationCache();
}
@@ -2902,6 +2986,21 @@ class Calculation
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.
*
@@ -2909,7 +3008,7 @@ class Calculation
*
* @return bool
*/
- public function setLocale($locale)
+ public function setLocale(string $locale)
{
// Identify our locale and language
$language = $locale = strtolower($locale);
@@ -2919,31 +3018,30 @@ class Calculation
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)) {
// initialise language/locale settings
self::$localeFunctions = [];
self::$localeArgumentSeparator = ',';
self::$localeBoolean = ['TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL'];
- // Default is English, if user isn't requesting english, then read the necessary data from the locale files
- if ($locale != 'en_us') {
+
+ // 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
- $functionNamesFile = __DIR__ . '/locale/' . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . 'functions';
- if (!file_exists($functionNamesFile)) {
- // If there isn't a locale specific function file, look for a language specific function file
- $functionNamesFile = __DIR__ . '/locale/' . $language . DIRECTORY_SEPARATOR . 'functions';
- if (!file_exists($functionNamesFile)) {
- return false;
- }
+ 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] = explode('=', $localeFunction);
- $fName = trim($fName);
- $lfName = trim($lfName);
+ [$fName, $lfName] = array_map('trim', explode('=', $localeFunction));
if ((isset(self::$phpSpreadsheetFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) {
self::$localeFunctions[$fName] = $lfName;
}
@@ -2957,20 +3055,22 @@ class Calculation
self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE'];
}
- $configFile = __DIR__ . '/locale/' . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . 'config';
- if (!file_exists($configFile)) {
- $configFile = __DIR__ . '/locale/' . $language . DIRECTORY_SEPARATOR . 'config';
+ try {
+ $configFile = $this->getLocaleFile($localeDir, $locale, $language, 'config');
+ } catch (Exception $e) {
+ return false;
}
- if (file_exists($configFile)) {
- $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] = explode('=', $localeSetting);
- $settingName = strtoupper(trim($settingName));
+
+ $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 = trim($settingValue);
+ self::$localeArgumentSeparator = $settingValue;
break;
}
@@ -3061,9 +3161,9 @@ class Calculation
return $formula;
}
- private static $functionReplaceFromExcel = null;
+ private static $functionReplaceFromExcel;
- private static $functionReplaceToLocale = null;
+ private static $functionReplaceToLocale;
public function _translateFormulaToLocale($formula)
{
@@ -3090,9 +3190,9 @@ class Calculation
return self::translateFormula(self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$localeArgumentSeparator);
}
- private static $functionReplaceFromLocale = null;
+ private static $functionReplaceFromLocale;
- private static $functionReplaceToExcel = null;
+ private static $functionReplaceToExcel;
public function _translateFormulaToEnglish($formula)
{
@@ -3150,6 +3250,7 @@ class Calculation
// 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)))) {
@@ -3185,14 +3286,14 @@ class Calculation
* Calculate cell value (using formula from a cell ID)
* Retained for backward compatibility.
*
- * @param Cell $pCell Cell to calculate
+ * @param Cell $cell Cell to calculate
*
* @return mixed
*/
- public function calculate(?Cell $pCell = null)
+ public function calculate(?Cell $cell = null)
{
try {
- return $this->calculateCellValue($pCell);
+ return $this->calculateCellValue($cell);
} catch (\Exception $e) {
throw new Exception($e->getMessage());
}
@@ -3201,14 +3302,14 @@ class Calculation
/**
* Calculate the value of a cell formula.
*
- * @param Cell $pCell Cell to calculate
+ * @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 $pCell = null, $resetLog = true)
+ public function calculateCellValue(?Cell $cell = null, $resetLog = true)
{
- if ($pCell === null) {
+ if ($cell === null) {
return null;
}
@@ -3225,12 +3326,12 @@ class Calculation
// Execute the calculation for the cell formula
$this->cellStack[] = [
- 'sheet' => $pCell->getWorksheet()->getTitle(),
- 'cell' => $pCell->getCoordinate(),
+ 'sheet' => $cell->getWorksheet()->getTitle(),
+ 'cell' => $cell->getCoordinate(),
];
try {
- $result = self::unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell));
+ $result = self::unwrapResult($this->_calculateFormulaValue($cell->getValue(), $cell->getCoordinate(), $cell));
$cellAddress = array_pop($this->cellStack);
$this->spreadsheet->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']);
} catch (\Exception $e) {
@@ -3266,7 +3367,7 @@ class Calculation
}
self::$returnArrayAsType = $returnArrayAsType;
- if ($result === null && $pCell->getWorksheet()->getSheetView()->getShowZeros()) {
+ if ($result === null && $cell->getWorksheet()->getSheetView()->getShowZeros()) {
return 0;
} elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) {
return Functions::NAN();
@@ -3304,11 +3405,11 @@ class Calculation
*
* @param string $formula Formula to parse
* @param string $cellID Address of the cell to calculate
- * @param Cell $pCell Cell to calculate
+ * @param Cell $cell Cell to calculate
*
* @return mixed
*/
- public function calculateFormula($formula, $cellID = null, ?Cell $pCell = null)
+ public function calculateFormula($formula, $cellID = null, ?Cell $cell = null)
{
// Initialise the logging settings
$this->formulaError = null;
@@ -3316,9 +3417,9 @@ class Calculation
$this->cyclicReferenceStack->clear();
$resetCache = $this->getCalculationCacheEnabled();
- if ($this->spreadsheet !== null && $cellID === null && $pCell === null) {
+ if ($this->spreadsheet !== null && $cellID === null && $cell === null) {
$cellID = 'A1';
- $pCell = $this->spreadsheet->getActiveSheet()->getCell($cellID);
+ $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
@@ -3327,7 +3428,7 @@ class Calculation
// Execute the calculation
try {
- $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $pCell));
+ $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell));
} catch (\Exception $e) {
throw new Exception($e->getMessage());
}
@@ -3341,18 +3442,15 @@ class Calculation
}
/**
- * @param string $cellReference
* @param mixed $cellValue
- *
- * @return bool
*/
- public function getValueFromCache($cellReference, &$cellValue)
+ public function getValueFromCache(string $cellReference, &$cellValue): bool
{
+ $this->debugLog->writeDebugLog("Testing cache value for cell {$cellReference}");
// Is calculation cacheing enabled?
- // Is the value present in calculation cache?
- $this->debugLog->writeDebugLog('Testing cache value for cell ', $cellReference);
+ // If so, is the required value present in calculation cache?
if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) {
- $this->debugLog->writeDebugLog('Retrieving value for cell ', $cellReference, ' from cache');
+ $this->debugLog->writeDebugLog("Retrieving value for cell {$cellReference} from cache");
// Return the cached result
$cellValue = $this->calculationCache[$cellReference];
@@ -3379,16 +3477,16 @@ class Calculation
*
* @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 $pCell Cell to calculate
+ * @param Cell $cell Cell to calculate
*
* @return mixed
*/
- public function _calculateFormulaValue($formula, $cellID = null, ?Cell $pCell = null)
+ public function _calculateFormulaValue($formula, $cellID = null, ?Cell $cell = null)
{
$cellValue = null;
// Quote-Prefixed cell values cannot be formulae, but are treated as strings
- if ($pCell !== null && $pCell->getStyle()->getQuotePrefix() === true) {
+ if ($cell !== null && $cell->getStyle()->getQuotePrefix() === true) {
return self::wrapResult((string) $formula);
}
@@ -3407,14 +3505,14 @@ class Calculation
return self::wrapResult($formula);
}
- $pCellParent = ($pCell !== null) ? $pCell->getWorksheet() : null;
+ $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 ', $wsCellReference);
+ $this->debugLog->writeDebugLog("Evaluating formula for cell {$wsCellReference}");
if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) {
if ($this->cyclicFormulaCount <= 0) {
@@ -3436,10 +3534,11 @@ class Calculation
}
}
- $this->debugLog->writeDebugLog('Formula for cell ', $wsCellReference, ' is ', $formula);
+ $this->debugLog->writeDebugLog("Formula for cell {$wsCellReference} is {$formula}");
// Parse the formula onto the token stack and calculate the value
$this->cyclicReferenceStack->push($wsCellReference);
- $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $pCell), $cellID, $pCell);
+
+ $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $cell), $cellID, $cell);
$this->cyclicReferenceStack->pop();
// Save to calculation cache
@@ -3454,8 +3553,8 @@ class Calculation
/**
* 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 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.
@@ -3499,7 +3598,7 @@ class Calculation
/**
* 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
+ * @param array $matrix matrix operand
*
* @return int[] An array comprising the number of rows, and number of columns
*/
@@ -3524,8 +3623,8 @@ class Calculation
/**
* 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 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
@@ -3567,8 +3666,8 @@ class Calculation
/**
* 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 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
@@ -3685,6 +3784,8 @@ class Calculation
return $typeString . ' with a value of ' . $this->showValue($value);
}
+
+ return null;
}
/**
@@ -3743,11 +3844,6 @@ class Calculation
return $formula;
}
- private static function mkMatrix(...$args)
- {
- return $args;
- }
-
// 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
@@ -3784,9 +3880,9 @@ class Calculation
/**
* @param string $formula
*
- * @return bool
+ * @return array|false
*/
- private function internalParseFormula($formula, ?Cell $pCell = null)
+ private function internalParseFormula($formula, ?Cell $cell = null)
{
if (($formula = $this->convertMatrixReferences(trim($formula))) === false) {
return false;
@@ -3794,10 +3890,12 @@ class Calculation
// 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 = ($pCell !== null) ? $pCell->getWorksheet() : null;
+ $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null;
$regexpMatchString = '/^(' . self::CALCULATION_REGEXP_FUNCTION .
'|' . self::CALCULATION_REGEXP_CELLREF .
+ '|' . self::CALCULATION_REGEXP_COLUMN_RANGE .
+ '|' . self::CALCULATION_REGEXP_ROW_RANGE .
'|' . self::CALCULATION_REGEXP_NUMBER .
'|' . self::CALCULATION_REGEXP_STRING .
'|' . self::CALCULATION_REGEXP_OPENBRACE .
@@ -3866,7 +3964,8 @@ class Calculation
$opCharacter .= $formula[++$index];
}
// Find out if we're currently at the beginning of a number, variable, cell reference, function, parenthesis or operand
- $isOperandOrFunction = preg_match($regexpMatchString, substr($formula, $index), $match);
+ $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match);
+
if ($opCharacter == '-' && !$expectingOperator) { // Is it a negation instead of a minus?
// Put a negation on the stack
$stack->push('Unary Operator', '~', null, $currentCondition, $currentOnlyIf, $currentOnlyIfNot);
@@ -3942,6 +4041,7 @@ class Calculation
}
// Check the argument count
$argumentCountError = false;
+ $expectedArgumentCountString = null;
if (is_numeric($expectedArgumentCount)) {
if ($expectedArgumentCount < 0) {
if ($argumentCount > abs($expectedArgumentCount)) {
@@ -4010,7 +4110,7 @@ class Calculation
// 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' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null];
+ $output[] = ['type' => 'Empty Argument', 'value' => self::$excelConstants['NULL'], 'reference' => null];
}
// make sure there was a function
$d = $stack->last(2);
@@ -4037,6 +4137,7 @@ class Calculation
$expectingOperand = false;
$val = $match[1];
$length = strlen($val);
+
if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) {
$val = preg_replace('/\s/u', '', $val);
if (isset(self::$phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) { // it's a function
@@ -4073,7 +4174,7 @@ class Calculation
// 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 ($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
@@ -4090,62 +4191,59 @@ class Calculation
return $this->raiseFormulaError('3D Range references are not yet supported');
}
}
+ } elseif (strpos($val, '!') === false && $pCellParent !== null) {
+ $worksheet = $pCellParent->getTitle();
+ $val = "'{$worksheet}'!{$val}";
}
$outputItem = $stack->getStackItem('Cell Reference', $val, $val, $currentCondition, $currentOnlyIf, $currentOnlyIfNot);
$output[] = $outputItem;
} 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';
$startRowColRef = $output[count($output) - 1]['value'];
[$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true);
$rangeSheetRef = $rangeWS1;
- if ($rangeWS1 != '') {
+ if ($rangeWS1 !== '') {
$rangeWS1 .= '!';
}
+ $rangeSheetRef = trim($rangeSheetRef, "'");
[$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true);
- if ($rangeWS2 != '') {
+ if ($rangeWS2 !== '') {
$rangeWS2 .= '!';
} else {
$rangeWS2 = $rangeWS1;
}
+
$refSheet = $pCellParent;
- if ($pCellParent !== null && $rangeSheetRef !== $pCellParent->getTitle()) {
+ if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) {
$refSheet = $pCellParent->getParent()->getSheetByName($rangeSheetRef);
}
- if (
- (is_int($startRowColRef)) && (ctype_digit($val)) &&
- ($startRowColRef <= 1048576) && ($val <= 1048576)
- ) {
- // Row range
- $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007
- $output[count($output) - 1]['value'] = $rangeWS1 . 'A' . $startRowColRef;
- $val = $rangeWS2 . $endRowColRef . $val;
- } elseif (
- (ctype_alpha($startRowColRef)) && (ctype_alpha($val)) &&
- (strlen($startRowColRef) <= 3) && (strlen($val) <= 3)
- ) {
- // Column range
- $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007
- $output[count($output) - 1]['value'] = $rangeWS1 . strtoupper($startRowColRef) . '1';
- $val = $rangeWS2 . $val . $endRowColRef;
- }
- }
- $localeConstant = false;
- $stackItemType = 'Value';
- $stackItemReference = null;
- if ($opCharacter == self::FORMULA_STRING_QUOTE) {
+ if (ctype_digit($val) && $val <= 1048576) {
+ // Row range
+ $stackItemType = 'Row Reference';
+ /** @var int $valx */
+ $valx = $val;
+ $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($valx) : 'XFD'; // 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) : 1048576; // 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 (is_numeric($val)) {
- if ((strpos($val, '.') !== false) || (stripos($val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
- $val = (float) $val;
- } else {
- $val = (int) $val;
- }
} elseif (isset(self::$excelConstants[trim(strtoupper($val))])) {
$stackItemType = 'Constant';
$excelConstant = trim(strtoupper($val));
@@ -4153,10 +4251,41 @@ class Calculation
} elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) {
$stackItemType = 'Constant';
$val = self::$excelConstants[$localeConstant];
+ } elseif (
+ preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference)
+ ) {
+ $val = $rowRangeReference[1];
+ $length = strlen($rowRangeReference[1]);
+ $stackItemType = 'Row Reference';
+ $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';
+ $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($val, '.') !== false) || (stripos($val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
+ $val = (float) $val;
+ } else {
+ $val = (int) $val;
+ }
}
+
$details = $stack->getStackItem($stackItemType, $val, $stackItemReference, $currentCondition, $currentOnlyIf, $currentOnlyIfNot);
if ($localeConstant) {
$details['localeValue'] = $localeConstant;
@@ -4168,7 +4297,7 @@ class Calculation
++$index;
} elseif ($opCharacter == ')') { // miscellaneous error checking
if ($expectingOperand) {
- $output[] = ['type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null];
+ $output[] = ['type' => 'Empty Argument', 'value' => self::$excelConstants['NULL'], 'reference' => null];
$expectingOperand = false;
$expectingOperator = true;
} else {
@@ -4203,7 +4332,8 @@ class Calculation
// Cell References) then we have an INTERSECTION operator
if (
($expectingOperator) &&
- ((preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/Ui', substr($formula, $index), $match)) &&
+ (
+ (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/Ui', substr($formula, $index), $match)) &&
($output[count($output) - 1]['type'] == 'Cell Reference') ||
(preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match)) &&
($output[count($output) - 1]['type'] == 'Defined Name' || $output[count($output) - 1]['type'] == 'Value')
@@ -4241,7 +4371,7 @@ class Calculation
$rowKey = array_shift($rKeys);
$cKeys = array_keys(array_keys($operand[$rowKey]));
$colKey = array_shift($cKeys);
- if (ctype_upper($colKey)) {
+ if (ctype_upper("$colKey")) {
$operandData['reference'] = $colKey . $rowKey;
}
}
@@ -4255,9 +4385,9 @@ class Calculation
* @param mixed $tokens
* @param null|string $cellID
*
- * @return bool
+ * @return array|false
*/
- private function processTokenStack($tokens, $cellID = null, ?Cell $pCell = null)
+ private function processTokenStack($tokens, $cellID = null, ?Cell $cell = null)
{
if ($tokens == false) {
return false;
@@ -4265,8 +4395,8 @@ class Calculation
// 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 = ($pCell !== null) ? $pCell->getWorksheet() : null;
- $pCellParent = ($pCell !== null) ? $pCell->getParent() : null;
+ $pCellWorksheet = ($cell !== null) ? $cell->getWorksheet() : null;
+ $pCellParent = ($cell !== null) ? $cell->getParent() : null;
$stack = new Stack();
// Stores branches that have been pruned
@@ -4329,7 +4459,8 @@ class Calculation
&& (
$storeValueAsBool
|| Functions::isError($storeValue)
- || ($storeValue === 'Pruned branch'))
+ || ($storeValue === 'Pruned branch')
+ )
) {
// If branching value is true, we don't need to compute
if (!isset($fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey])) {
@@ -4350,7 +4481,7 @@ class Calculation
}
// 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
- if (isset(self::$binaryOperators[$token])) {
+ if (!is_numeric($token) && isset(self::$binaryOperators[$token])) {
// 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');
@@ -4397,23 +4528,23 @@ class Calculation
$sheet2 = $sheet1;
}
- if ($sheet1 == $sheet2) {
+ if (trim($sheet1, "'") === trim($sheet2, "'")) {
if ($operand1Data['reference'] === null) {
if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
- $operand1Data['reference'] = $pCell->getColumn() . $operand1Data['value'];
+ $operand1Data['reference'] = $cell->getColumn() . $operand1Data['value'];
} elseif (trim($operand1Data['reference']) == '') {
- $operand1Data['reference'] = $pCell->getCoordinate();
+ $operand1Data['reference'] = $cell->getCoordinate();
} else {
- $operand1Data['reference'] = $operand1Data['value'] . $pCell->getRow();
+ $operand1Data['reference'] = $operand1Data['value'] . $cell->getRow();
}
}
if ($operand2Data['reference'] === null) {
if ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
- $operand2Data['reference'] = $pCell->getColumn() . $operand2Data['value'];
+ $operand2Data['reference'] = $cell->getColumn() . $operand2Data['value'];
} elseif (trim($operand2Data['reference']) == '') {
- $operand2Data['reference'] = $pCell->getCoordinate();
+ $operand2Data['reference'] = $cell->getCoordinate();
} else {
- $operand2Data['reference'] = $operand2Data['value'] . $pCell->getRow();
+ $operand2Data['reference'] = $operand2Data['value'] . $cell->getRow();
}
}
@@ -4430,6 +4561,7 @@ class Calculation
} else {
return $this->raiseFormulaError('Unable to access Cell Reference');
}
+
$stack->push('Cell Reference', $cellValue, $cellRef);
} else {
$stack->push('Error', Functions::REF(), null);
@@ -4561,10 +4693,11 @@ class Calculation
} else {
$this->executeNumericBinaryOperation($multiplier, $arg, '*', 'arrayTimesEquals', $stack);
}
- } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token, $matches)) {
+ } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token ?? '', $matches)) {
$cellRef = null;
+
if (isset($matches[8])) {
- if ($pCell === null) {
+ if ($cell === null) {
// We can't access the range, so return a REF error
$cellValue = Functions::REF();
} else {
@@ -4594,8 +4727,8 @@ class Calculation
}
}
} else {
- if ($pCell === null) {
- // We can't access the cell, so return a REF error
+ if ($cell === null) {
+ // We can't access the cell, so return a REF error
$cellValue = Functions::REF();
} else {
$cellRef = $matches[6] . $matches[7];
@@ -4610,8 +4743,9 @@ class Calculation
$cellSheet = $this->spreadsheet->getSheetByName($matches[2]);
if ($cellSheet && $cellSheet->cellExists($cellRef)) {
$cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
- $pCell->attach($pCellParent);
+ $cell->attach($pCellParent);
} else {
+ $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef;
$cellValue = null;
}
} else {
@@ -4622,7 +4756,7 @@ class Calculation
$this->debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in current worksheet');
if ($pCellParent->has($cellRef)) {
$cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
- $pCell->attach($pCellParent);
+ $cell->attach($pCellParent);
} else {
$cellValue = null;
}
@@ -4630,24 +4764,28 @@ class Calculation
}
}
}
- $stack->push('Value', $cellValue, $cellRef);
+
+ $stack->push('Cell Value', $cellValue, $cellRef);
if (isset($storeKey)) {
$branchStore[$storeKey] = $cellValue;
}
// if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
- } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $token, $matches)) {
+ } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $token ?? '', $matches)) {
if ($pCellParent) {
- $pCell->attach($pCellParent);
+ $cell->attach($pCellParent);
}
$functionName = $matches[1];
$argCount = $stack->pop();
$argCount = $argCount['value'];
- if ($functionName != 'MKMATRIX') {
+ if ($functionName !== 'MKMATRIX') {
$this->debugLog->writeDebugLog('Evaluating Function ', self::localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($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']);
@@ -4657,8 +4795,10 @@ class Calculation
$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;
@@ -4669,18 +4809,19 @@ class Calculation
) {
if ($arg['reference'] === null) {
$args[] = $cellID;
- if ($functionName != 'MKMATRIX') {
+ if ($functionName !== 'MKMATRIX') {
$argArrayVals[] = $this->showValue($cellID);
}
} else {
$args[] = $arg['reference'];
- if ($functionName != 'MKMATRIX') {
+ if ($functionName !== 'MKMATRIX') {
$argArrayVals[] = $this->showValue($arg['reference']);
}
}
} else {
+ $emptyArguments[] = ($arg['type'] === 'Empty Argument');
$args[] = self::unwrapResult($arg['value']);
- if ($functionName != 'MKMATRIX') {
+ if ($functionName !== 'MKMATRIX') {
$argArrayVals[] = $this->showValue($arg['value']);
}
}
@@ -4688,13 +4829,18 @@ class Calculation
// 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 ($functionName !== 'MKMATRIX') {
if ($this->debugLog->getWriteDebugLog()) {
krsort($argArrayVals);
$this->debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals)), ' )');
@@ -4702,7 +4848,7 @@ class Calculation
}
// Process the argument with the appropriate function call
- $args = $this->addCellReference($args, $passCellReference, $functionCall, $pCell);
+ $args = $this->addCellReference($args, $passCellReference, $functionCall, $cell);
if (!is_array($functionCall)) {
foreach ($args as &$arg) {
@@ -4713,7 +4859,7 @@ class Calculation
$result = call_user_func_array($functionCall, $args);
- if ($functionName != 'MKMATRIX') {
+ if ($functionName !== 'MKMATRIX') {
$this->debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($result));
}
$stack->push('Value', self::wrapResult($result));
@@ -4723,7 +4869,7 @@ class Calculation
}
} else {
// if the token is a number, boolean, string or an Excel error, push it onto the stack
- if (isset(self::$excelConstants[strtoupper($token)])) {
+ if (isset(self::$excelConstants[strtoupper($token ?? '')])) {
$excelConstant = strtoupper($token);
$stack->push('Constant Value', self::$excelConstants[$excelConstant]);
if (isset($storeKey)) {
@@ -4731,14 +4877,14 @@ class Calculation
}
$this->debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $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('Value', $token);
+ $stack->push($tokenData['type'], $token, $tokenData['reference']);
if (isset($storeKey)) {
$branchStore[$storeKey] = $token;
}
// if the token is a named range or formula, evaluate it and push the result onto the stack
} elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token, $matches)) {
$definedName = $matches[6];
- if ($pCell === null || $pCellWorksheet === null) {
+ if ($cell === null || $pCellWorksheet === null) {
return $this->raiseFormulaError("undefined name '$token'");
}
@@ -4748,7 +4894,7 @@ class Calculation
return $this->raiseFormulaError("undefined name '$definedName'");
}
- $result = $this->evaluateDefinedName($pCell, $namedRange, $pCellWorksheet, $stack);
+ $result = $this->evaluateDefinedName($cell, $namedRange, $pCellWorksheet, $stack);
if (isset($storeKey)) {
$branchStore[$storeKey] = $result;
}
@@ -4805,6 +4951,53 @@ class Calculation
return true;
}
+ /**
+ * @param null|string $cellID
+ * @param mixed $operand1
+ * @param mixed $operand2
+ * @param string $operation
+ *
+ * @return array
+ */
+ private function executeArrayComparison($cellID, $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 ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2));
+ $this->executeBinaryComparisonOperation($cellID, $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 ', $this->showValue($operand1), ' ', $operation, ' ', $this->showValue($operandData));
+ $this->executeBinaryComparisonOperation($cellID, $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 ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2[$x]));
+ $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2[$x], $operation, $stack, true);
+ $r = $stack->pop();
+ $result[$x] = $r['value'];
+ }
+ }
+ // Log the result details
+ $this->debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->showTypeDetails($result));
+ // And push the result onto the stack
+ $stack->push('Array', $result);
+
+ return $result;
+ }
+
/**
* @param null|string $cellID
* @param mixed $operand1
@@ -4818,38 +5011,7 @@ class Calculation
{
// If we're dealing with matrix operations, we want a matrix result
if ((is_array($operand1)) || (is_array($operand2))) {
- $result = [];
- if ((is_array($operand1)) && (!is_array($operand2))) {
- foreach ($operand1 as $x => $operandData) {
- $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2));
- $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2, $operation, $stack);
- $r = $stack->pop();
- $result[$x] = $r['value'];
- }
- } elseif ((!is_array($operand1)) && (is_array($operand2))) {
- foreach ($operand2 as $x => $operandData) {
- $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operand1), ' ', $operation, ' ', $this->showValue($operandData));
- $this->executeBinaryComparisonOperation($cellID, $operand1, $operandData, $operation, $stack);
- $r = $stack->pop();
- $result[$x] = $r['value'];
- }
- } else {
- if (!$recursingArrays) {
- self::checkMatrixOperands($operand1, $operand2, 2);
- }
- foreach ($operand1 as $x => $operandData) {
- $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2[$x]));
- $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2[$x], $operation, $stack, true);
- $r = $stack->pop();
- $result[$x] = $r['value'];
- }
- }
- // Log the result details
- $this->debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->showTypeDetails($result));
- // And push the result onto the stack
- $stack->push('Array', $result);
-
- return $result;
+ return $this->executeArrayComparison($cellID, $operand1, $operand2, $operation, $stack, $recursingArrays);
}
// Simple validate the two operands if they are string values
@@ -4863,10 +5025,10 @@ class Calculation
// Use case insensitive comparaison if not OpenOffice mode
if (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) {
if (is_string($operand1)) {
- $operand1 = strtoupper($operand1);
+ $operand1 = Shared\StringHelper::strToUpper($operand1);
}
if (is_string($operand2)) {
- $operand2 = strtoupper($operand2);
+ $operand2 = Shared\StringHelper::strToUpper($operand2);
}
}
@@ -4897,7 +5059,7 @@ class Calculation
if (is_numeric($operand1) && is_numeric($operand2)) {
$result = (abs($operand1 - $operand2) < $this->delta);
} else {
- $result = strcmp($operand1, $operand2) == 0;
+ $result = $this->strcmpAllowNull($operand1, $operand2) == 0;
}
break;
@@ -4908,7 +5070,7 @@ class Calculation
} elseif ($useLowercaseFirstComparison) {
$result = $this->strcmpLowercaseFirst($operand1, $operand2) >= 0;
} else {
- $result = strcmp($operand1, $operand2) >= 0;
+ $result = $this->strcmpAllowNull($operand1, $operand2) >= 0;
}
break;
@@ -4919,7 +5081,7 @@ class Calculation
} elseif ($useLowercaseFirstComparison) {
$result = $this->strcmpLowercaseFirst($operand1, $operand2) <= 0;
} else {
- $result = strcmp($operand1, $operand2) <= 0;
+ $result = $this->strcmpAllowNull($operand1, $operand2) <= 0;
}
break;
@@ -4928,10 +5090,13 @@ class Calculation
if (is_numeric($operand1) && is_numeric($operand2)) {
$result = (abs($operand1 - $operand2) > 1E-14);
} else {
- $result = strcmp($operand1, $operand2) != 0;
+ $result = $this->strcmpAllowNull($operand1, $operand2) != 0;
}
break;
+
+ default:
+ throw new Exception('Unsupported binary comparison operation');
}
// Log the result details
@@ -4945,8 +5110,8 @@ class Calculation
/**
* Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters.
*
- * @param string $str1 First string value for the comparison
- * @param string $str2 Second string value for the comparison
+ * @param null|string $str1 First string value for the comparison
+ * @param null|string $str2 Second string value for the comparison
*
* @return int
*/
@@ -4955,7 +5120,20 @@ class Calculation
$inversedStr1 = Shared\StringHelper::strCaseReverse($str1);
$inversedStr2 = Shared\StringHelper::strCaseReverse($str2);
- return strcmp($inversedStr1, $inversedStr2);
+ 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
+ *
+ * @return int
+ */
+ private function strcmpAllowNull($str1, $str2)
+ {
+ return strcmp($str1 ?? '', $str2 ?? '');
}
/**
@@ -5036,6 +5214,9 @@ class Calculation
$result = $operand1 ** $operand2;
break;
+
+ default:
+ throw new Exception('Unsupported numeric binary operation');
}
}
}
@@ -5048,15 +5229,22 @@ class Calculation
return $result;
}
- // trigger an error, but nicely, if need be
- protected function raiseFormulaError($errorMessage)
+ /**
+ * Trigger an error, but nicely, if need be.
+ *
+ * @return false
+ */
+ protected function raiseFormulaError(string $errorMessage)
{
$this->formulaError = $errorMessage;
$this->cyclicReferenceStack->clear();
if (!$this->suppressFormulaErrors) {
throw new Exception($errorMessage);
}
- trigger_error($errorMessage, E_USER_ERROR);
+
+ if (strlen($errorMessage) > 0) {
+ trigger_error($errorMessage, E_USER_ERROR);
+ }
return false;
}
@@ -5064,34 +5252,35 @@ class Calculation
/**
* Extract range values.
*
- * @param string &$pRange String based range representation
- * @param Worksheet $pSheet Worksheet
+ * @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(&$pRange = 'A1', ?Worksheet $pSheet = null, $resetLog = true)
+ public function extractCellRange(&$range = 'A1', ?Worksheet $worksheet = null, $resetLog = true)
{
// Return value
$returnValue = [];
- if ($pSheet !== null) {
- $pSheetName = $pSheet->getTitle();
- if (strpos($pRange, '!') !== false) {
- [$pSheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true);
- $pSheet = $this->spreadsheet->getSheetByName($pSheetName);
+ if ($worksheet !== null) {
+ $worksheetName = $worksheet->getTitle();
+
+ if (strpos($range, '!') !== false) {
+ [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true);
+ $worksheet = $this->spreadsheet->getSheetByName($worksheetName);
}
// Extract range
- $aReferences = Coordinate::extractAllCellReferencesInRange($pRange);
- $pRange = $pSheetName . '!' . $pRange;
+ $aReferences = Coordinate::extractAllCellReferencesInRange($range);
+ $range = "'" . $worksheetName . "'" . '!' . $range;
if (!isset($aReferences[1])) {
$currentCol = '';
$currentRow = 0;
// Single cell in range
sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow);
- if ($pSheet->cellExists($aReferences[0])) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
+ if ($worksheet->cellExists($aReferences[0])) {
+ $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
} else {
$returnValue[$currentRow][$currentCol] = null;
}
@@ -5102,8 +5291,8 @@ class Calculation
$currentRow = 0;
// Extract range
sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow);
- if ($pSheet->cellExists($reference)) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
+ if ($worksheet->cellExists($reference)) {
+ $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
} else {
$returnValue[$currentRow][$currentCol] = null;
}
@@ -5117,47 +5306,46 @@ class Calculation
/**
* Extract range values.
*
- * @param string &$pRange String based range representation
- * @param Worksheet $pSheet Worksheet
+ * @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(&$pRange = 'A1', ?Worksheet $pSheet = null, $resetLog = true)
+ public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, $resetLog = true)
{
// Return value
$returnValue = [];
- if ($pSheet !== null) {
- $pSheetName = $pSheet->getTitle();
- if (strpos($pRange, '!') !== false) {
- [$pSheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true);
- $pSheet = $this->spreadsheet->getSheetByName($pSheetName);
+ if ($worksheet !== null) {
+ if (strpos($range, '!') !== false) {
+ [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true);
+ $worksheet = $this->spreadsheet->getSheetByName($worksheetName);
}
// Named range?
- $namedRange = DefinedName::resolveName($pRange, $pSheet);
+ $namedRange = DefinedName::resolveName($range, $worksheet);
if ($namedRange === null) {
return Functions::REF();
}
- $pSheet = $namedRange->getWorksheet();
- $pRange = $namedRange->getValue();
- $splitRange = Coordinate::splitRange($pRange);
+ $worksheet = $namedRange->getWorksheet();
+ $range = $namedRange->getValue();
+ $splitRange = Coordinate::splitRange($range);
// Convert row and column references
if (ctype_alpha($splitRange[0][0])) {
- $pRange = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow();
+ $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow();
} elseif (ctype_digit($splitRange[0][0])) {
- $pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1];
+ $range = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1];
}
// Extract range
- $aReferences = Coordinate::extractAllCellReferencesInRange($pRange);
+ $aReferences = Coordinate::extractAllCellReferencesInRange($range);
if (!isset($aReferences[1])) {
// Single cell (or single column or row) in range
[$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]);
- if ($pSheet->cellExists($aReferences[0])) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
+ if ($worksheet->cellExists($aReferences[0])) {
+ $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
} else {
$returnValue[$currentRow][$currentCol] = null;
}
@@ -5166,8 +5354,8 @@ class Calculation
foreach ($aReferences as $reference) {
// Extract range
[$currentCol, $currentRow] = Coordinate::coordinateFromString($reference);
- if ($pSheet->cellExists($reference)) {
- $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
+ if ($worksheet->cellExists($reference)) {
+ $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
} else {
$returnValue[$currentRow][$currentCol] = null;
}
@@ -5181,24 +5369,22 @@ class Calculation
/**
* Is a specific function implemented?
*
- * @param string $pFunction Function Name
+ * @param string $function Function Name
*
* @return bool
*/
- public function isImplemented($pFunction)
+ public function isImplemented($function)
{
- $pFunction = strtoupper($pFunction);
- $notImplemented = !isset(self::$phpSpreadsheetFunctions[$pFunction]) || (is_array(self::$phpSpreadsheetFunctions[$pFunction]['functionCall']) && self::$phpSpreadsheetFunctions[$pFunction]['functionCall'][1] === 'DUMMY');
+ $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.
- *
- * @return array of Category
*/
- public function getFunctions()
+ public function getFunctions(): array
{
return self::$phpSpreadsheetFunctions;
}
@@ -5220,6 +5406,57 @@ class Calculation
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.
*
@@ -5228,7 +5465,7 @@ class Calculation
*
* @return array
*/
- private function addCellReference(array $args, $passCellReference, $functionCall, ?Cell $pCell = null)
+ private function addCellReference(array $args, $passCellReference, $functionCall, ?Cell $cell = null)
{
if ($passCellReference) {
if (is_array($functionCall)) {
@@ -5242,7 +5479,7 @@ class Calculation
}
}
- $args[] = $pCell;
+ $args[] = $cell;
}
return $args;
@@ -5273,10 +5510,10 @@ class Calculation
/**
* @return mixed|string
*/
- private function evaluateDefinedName(Cell $pCell, DefinedName $namedRange, Worksheet $pCellWorksheet, Stack $stack)
+ private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksheet $cellWorksheet, Stack $stack)
{
$definedNameScope = $namedRange->getScope();
- if ($definedNameScope !== null && $definedNameScope !== $pCellWorksheet) {
+ if ($definedNameScope !== null && $definedNameScope !== $cellWorksheet) {
// The defined name isn't in our current scope, so #REF
$result = Functions::REF();
$stack->push('Error', $result, $namedRange->getName());
@@ -5294,18 +5531,16 @@ class Calculation
$this->debugLog->writeDebugLog("Defined Name is a {$definedNameType} with a value of {$definedNameValue}");
- $recursiveCalculationCell = ($definedNameWorksheet !== null && $definedNameWorksheet !== $pCellWorksheet)
+ $recursiveCalculationCell = ($definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet)
? $definedNameWorksheet->getCell('A1')
- : $pCell;
- $recursiveCalculationCellAddress = $recursiveCalculationCell !== null
- ? $recursiveCalculationCell->getCoordinate()
- : null;
+ : $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($pCell->getColumn()) - 1,
- $pCell->getRow() - 1
+ Coordinate::columnIndexFromString($cell->getColumn()) - 1,
+ $cell->getRow() - 1
);
$this->debugLog->writeDebugLog("Value adjusted for relative references is {$definedNameValue}");
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database.php
index 2ba4af2dc4c..65031674756 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database.php
@@ -2,126 +2,11 @@
namespace PhpOffice\PhpSpreadsheet\Calculation;
+/**
+ * @deprecated 1.17.0
+ */
class Database
{
- /**
- * 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.
- *
- * @return null|string
- */
- private static function fieldExtract($database, $field)
- {
- $field = strtoupper(Functions::flattenSingleValue($field));
- $fieldNames = array_map('strtoupper', array_shift($database));
-
- if (is_numeric($field)) {
- $keys = array_keys($fieldNames);
-
- return $keys[$field - 1];
- }
- $key = array_search($field, $fieldNames);
-
- return ($key) ? $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 array of mixed
- */
- private static function filter($database, $criteria)
- {
- $fieldNames = array_shift($database);
- $criteriaNames = array_shift($criteria);
-
- // Convert the criteria into a set of AND/OR conditions with [:placeholders]
- $testConditions = $testValues = [];
- $testConditionsCount = 0;
- foreach ($criteriaNames as $key => $criteriaName) {
- $testCondition = [];
- $testConditionCount = 0;
- foreach ($criteria as $row => $criterion) {
- if ($criterion[$key] > '') {
- $testCondition[] = '[:' . $criteriaName . ']' . Functions::ifCondition($criterion[$key]);
- ++$testConditionCount;
- }
- }
- if ($testConditionCount > 1) {
- $testConditions[] = 'OR(' . implode(',', $testCondition) . ')';
- ++$testConditionsCount;
- } elseif ($testConditionCount == 1) {
- $testConditions[] = $testCondition[0];
- ++$testConditionsCount;
- }
- }
-
- if ($testConditionsCount > 1) {
- $testConditionSet = 'AND(' . implode(',', $testConditions) . ')';
- } elseif ($testConditionsCount == 1) {
- $testConditionSet = $testConditions[0];
- }
-
- // Loop through each row of the database
- foreach ($database as $dataRow => $dataValues) {
- // Substitute actual values from the database row for our [:placeholders]
- $testConditionList = $testConditionSet;
- foreach ($criteriaNames as $key => $criteriaName) {
- $k = array_search($criteriaName, $fieldNames);
- if (isset($dataValues[$k])) {
- $dataValue = $dataValues[$k];
- $dataValue = (is_string($dataValue)) ? Calculation::wrapResult(strtoupper($dataValue)) : $dataValue;
- $testConditionList = str_replace('[:' . $criteriaName . ']', $dataValue, $testConditionList);
- }
- }
- // evaluate the criteria against the row data
- $result = Calculation::getInstance()->_calculateFormulaValue('=' . $testConditionList);
- // If the row failed to meet the criteria, remove it from the database
- if (!$result) {
- unset($database[$dataRow]);
- }
- }
-
- return $database;
- }
-
- private static function getFilteredColumn($database, $field, $criteria)
- {
- // reduce the database to a set of rows that match all the criteria
- $database = self::filter($database, $criteria);
- // extract an array of values for the requested column
- $colData = [];
- foreach ($database as $row) {
- $colData[] = $row[$field];
- }
-
- return $colData;
- }
-
/**
* DAVERAGE.
*
@@ -130,6 +15,11 @@ class Database
* Excel Function:
* DAVERAGE(database,field,criteria)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DAverage::evaluate()
+ * Use the evaluate() method in the Database\DAverage class instead
+ *
* @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
@@ -145,19 +35,11 @@ class Database
* the column label in which you specify a condition for the
* column.
*
- * @return float|string
+ * @return null|float|string
*/
public static function DAVERAGE($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // Return
- return Statistical::AVERAGE(
- self::getFilteredColumn($database, $field, $criteria)
- );
+ return Database\DAverage::evaluate($database, $field, $criteria);
}
/**
@@ -169,14 +51,16 @@ class Database
* Excel Function:
* DCOUNT(database,[field],criteria)
*
- * Excel Function:
- * DAVERAGE(database,field,criteria)
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DCount::evaluate()
+ * Use the evaluate() method in the Database\DCount class instead
*
* @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
+ * @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
@@ -194,15 +78,7 @@ class Database
*/
public static function DCOUNT($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // Return
- return Statistical::COUNT(
- self::getFilteredColumn($database, $field, $criteria)
- );
+ return Database\DCount::evaluate($database, $field, $criteria);
}
/**
@@ -213,11 +89,16 @@ class Database
* Excel Function:
* DCOUNTA(database,[field],criteria)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DCountA::evaluate()
+ * Use the evaluate() method in the Database\DCountA class instead
+ *
* @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
+ * @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
@@ -229,29 +110,10 @@ class Database
* column.
*
* @return int
- *
- * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the
- * database that match the criteria.
*/
public static function DCOUNTA($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // reduce the database to a set of rows that match all the criteria
- $database = self::filter($database, $criteria);
- // extract an array of values for the requested column
- $colData = [];
- foreach ($database as $row) {
- $colData[] = $row[$field];
- }
-
- // Return
- return Statistical::COUNTA(
- self::getFilteredColumn($database, $field, $criteria)
- );
+ return Database\DCountA::evaluate($database, $field, $criteria);
}
/**
@@ -263,6 +125,11 @@ class Database
* Excel Function:
* DGET(database,field,criteria)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DGet::evaluate()
+ * Use the evaluate() method in the Database\DGet class instead
+ *
* @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
@@ -282,18 +149,7 @@ class Database
*/
public static function DGET($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // Return
- $colData = self::getFilteredColumn($database, $field, $criteria);
- if (count($colData) > 1) {
- return Functions::NAN();
- }
-
- return $colData[0];
+ return Database\DGet::evaluate($database, $field, $criteria);
}
/**
@@ -305,6 +161,11 @@ class Database
* Excel Function:
* DMAX(database,field,criteria)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DMax::evaluate()
+ * Use the evaluate() method in the Database\DMax class instead
+ *
* @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
@@ -324,15 +185,7 @@ class Database
*/
public static function DMAX($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // Return
- return Statistical::MAX(
- self::getFilteredColumn($database, $field, $criteria)
- );
+ return Database\DMax::evaluate($database, $field, $criteria);
}
/**
@@ -344,6 +197,11 @@ class Database
* Excel Function:
* DMIN(database,field,criteria)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DMin::evaluate()
+ * Use the evaluate() method in the Database\DMin class instead
+ *
* @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
@@ -363,15 +221,7 @@ class Database
*/
public static function DMIN($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // Return
- return Statistical::MIN(
- self::getFilteredColumn($database, $field, $criteria)
- );
+ return Database\DMin::evaluate($database, $field, $criteria);
}
/**
@@ -382,6 +232,11 @@ class Database
* Excel Function:
* DPRODUCT(database,field,criteria)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DProduct::evaluate()
+ * Use the evaluate() method in the Database\DProduct class instead
+ *
* @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
@@ -397,19 +252,11 @@ class Database
* the column label in which you specify a condition for the
* column.
*
- * @return float
+ * @return float|string
*/
public static function DPRODUCT($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // Return
- return MathTrig::PRODUCT(
- self::getFilteredColumn($database, $field, $criteria)
- );
+ return Database\DProduct::evaluate($database, $field, $criteria);
}
/**
@@ -421,6 +268,11 @@ class Database
* Excel Function:
* DSTDEV(database,field,criteria)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DStDev::evaluate()
+ * Use the evaluate() method in the Database\DStDev class instead
+ *
* @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
@@ -440,15 +292,7 @@ class Database
*/
public static function DSTDEV($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // Return
- return Statistical::STDEV(
- self::getFilteredColumn($database, $field, $criteria)
- );
+ return Database\DStDev::evaluate($database, $field, $criteria);
}
/**
@@ -460,6 +304,11 @@ class Database
* Excel Function:
* DSTDEVP(database,field,criteria)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DStDevP::evaluate()
+ * Use the evaluate() method in the Database\DStDevP class instead
+ *
* @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
@@ -479,15 +328,7 @@ class Database
*/
public static function DSTDEVP($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // Return
- return Statistical::STDEVP(
- self::getFilteredColumn($database, $field, $criteria)
- );
+ return Database\DStDevP::evaluate($database, $field, $criteria);
}
/**
@@ -498,6 +339,11 @@ class Database
* Excel Function:
* DSUM(database,field,criteria)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DSum::evaluate()
+ * Use the evaluate() method in the Database\DSum class instead
+ *
* @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
@@ -513,19 +359,11 @@ class Database
* the column label in which you specify a condition for the
* column.
*
- * @return float
+ * @return float|string
*/
public static function DSUM($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // Return
- return MathTrig::SUM(
- self::getFilteredColumn($database, $field, $criteria)
- );
+ return Database\DSum::evaluate($database, $field, $criteria);
}
/**
@@ -537,6 +375,11 @@ class Database
* Excel Function:
* DVAR(database,field,criteria)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DVar::evaluate()
+ * Use the evaluate() method in the Database\DVar class instead
+ *
* @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
@@ -556,15 +399,7 @@ class Database
*/
public static function DVAR($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // Return
- return Statistical::VARFunc(
- self::getFilteredColumn($database, $field, $criteria)
- );
+ return Database\DVar::evaluate($database, $field, $criteria);
}
/**
@@ -576,6 +411,11 @@ class Database
* Excel Function:
* DVARP(database,field,criteria)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Database\DVarP::evaluate()
+ * Use the evaluate() method in the Database\DVarP class instead
+ *
* @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
@@ -595,14 +435,6 @@ class Database
*/
public static function DVARP($database, $field, $criteria)
{
- $field = self::fieldExtract($database, $field);
- if ($field === null) {
- return null;
- }
-
- // Return
- return Statistical::VARP(
- self::getFilteredColumn($database, $field, $criteria)
- );
+ return Database\DVarP::evaluate($database, $field, $criteria);
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DAverage.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DAverage.php
new file mode 100644
index 00000000000..e30842dc5e9
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DAverage.php
@@ -0,0 +1,45 @@
+ 1) {
+ return Functions::NAN();
+ }
+
+ $row = array_pop($columnData);
+
+ return array_pop($row);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DMax.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DMax.php
new file mode 100644
index 00000000000..9c5c7301e9d
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DMax.php
@@ -0,0 +1,46 @@
+ $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] ?? '');
+ }
+
+ private static function buildCondition($criterion, string $criterionName): string
+ {
+ $ifCondition = Functions::ifCondition($criterion);
+
+ // Check for wildcard characters used in the condition
+ $result = preg_match('/(?[^"]*)(?".*[*?].*")/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;
+ }
+
+ 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);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTime.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTime.php
index 4c2b108ad9f..44a38c19e01 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTime.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTime.php
@@ -2,127 +2,49 @@
namespace PhpOffice\PhpSpreadsheet\Calculation;
-use DateTimeImmutable;
use DateTimeInterface;
-use PhpOffice\PhpSpreadsheet\Shared\Date;
-use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
+/**
+ * @deprecated 1.18.0
+ */
class DateTime
{
/**
* Identify if a year is a leap year or not.
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Helpers::isLeapYear()
+ * Use the isLeapYear method in the DateTimeExcel\Helpers class instead
+ *
* @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 (($year % 4) === 0) && (($year % 100) !== 0) || (($year % 400) === 0);
- }
-
- /**
- * Return the number of days between two dates based on a 360 day calendar.
- *
- * @param int $startDay Day of month of the start date
- * @param int $startMonth Month of the start date
- * @param int $startYear Year of the start date
- * @param int $endDay Day of month of the start date
- * @param int $endMonth Month of the start date
- * @param int $endYear Year of the start date
- * @param bool $methodUS Whether to use the US method or the European method of calculation
- *
- * @return int Number of days between the start date and the end date
- */
- private static function dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS)
- {
- if ($startDay == 31) {
- --$startDay;
- } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::isLeapYear($startYear))))) {
- $startDay = 30;
- }
- if ($endDay == 31) {
- if ($methodUS && $startDay != 30) {
- $endDay = 1;
- if ($endMonth == 12) {
- ++$endYear;
- $endMonth = 1;
- } else {
- ++$endMonth;
- }
- } else {
- $endDay = 30;
- }
- }
-
- return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360;
+ return DateTimeExcel\Helpers::isLeapYear($year);
}
/**
* getDateValue.
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Helpers::getDateValue()
+ * Use the getDateValue method in the DateTimeExcel\Helpers class instead
+ *
* @param mixed $dateValue
*
* @return mixed Excel date/time serial value, or string if error
*/
public static function getDateValue($dateValue)
{
- if (!is_numeric($dateValue)) {
- if ((is_object($dateValue)) && ($dateValue instanceof DateTimeInterface)) {
- $dateValue = Date::PHPToExcel($dateValue);
- } else {
- $saveReturnDateType = Functions::getReturnDateType();
- Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
- $dateValue = self::DATEVALUE($dateValue);
- Functions::setReturnDateType($saveReturnDateType);
- }
+ try {
+ return DateTimeExcel\Helpers::getDateValue($dateValue);
+ } catch (Exception $e) {
+ return $e->getMessage();
}
-
- return $dateValue;
- }
-
- /**
- * getTimeValue.
- *
- * @param string $timeValue
- *
- * @return mixed Excel date/time serial value, or string if error
- */
- private static function getTimeValue($timeValue)
- {
- $saveReturnDateType = Functions::getReturnDateType();
- Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
- $timeValue = self::TIMEVALUE($timeValue);
- Functions::setReturnDateType($saveReturnDateType);
-
- return $timeValue;
- }
-
- private static function adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0)
- {
- // Execute function
- $PHPDateObject = Date::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;
}
/**
@@ -139,31 +61,17 @@ class DateTime
* Excel Function:
* NOW()
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Current::now()
+ * Use the now method in the DateTimeExcel\Current class instead
+ *
* @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()
{
- $saveTimeZone = date_default_timezone_get();
- date_default_timezone_set('UTC');
- $retValue = false;
- switch (Functions::getReturnDateType()) {
- case Functions::RETURNDATE_EXCEL:
- $retValue = (float) Date::PHPToExcel(time());
-
- break;
- case Functions::RETURNDATE_UNIX_TIMESTAMP:
- $retValue = (int) time();
-
- break;
- case Functions::RETURNDATE_PHP_DATETIME_OBJECT:
- $retValue = new \DateTime();
-
- break;
- }
- date_default_timezone_set($saveTimeZone);
-
- return $retValue;
+ return DateTimeExcel\Current::now();
}
/**
@@ -180,32 +88,17 @@ class DateTime
* Excel Function:
* TODAY()
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Current::today()
+ * Use the today method in the DateTimeExcel\Current class instead
+ *
* @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()
{
- $saveTimeZone = date_default_timezone_get();
- date_default_timezone_set('UTC');
- $retValue = false;
- $excelDateTime = floor(Date::PHPToExcel(time()));
- switch (Functions::getReturnDateType()) {
- case Functions::RETURNDATE_EXCEL:
- $retValue = (float) $excelDateTime;
-
- break;
- case Functions::RETURNDATE_UNIX_TIMESTAMP:
- $retValue = (int) Date::excelToTimestamp($excelDateTime);
-
- break;
- case Functions::RETURNDATE_PHP_DATETIME_OBJECT:
- $retValue = Date::excelToDateTimeObject($excelDateTime);
-
- break;
- }
- date_default_timezone_set($saveTimeZone);
-
- return $retValue;
+ return DateTimeExcel\Current::today();
}
/**
@@ -216,9 +109,15 @@ class DateTime
* 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
+ *
+ * @See DateTimeExcel\Date::fromYMD()
+ * Use the fromYMD method in the DateTimeExcel\Date class instead
+ *
* 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.
@@ -259,71 +158,7 @@ class DateTime
*/
public static function DATE($year = 0, $month = 1, $day = 1)
{
- $year = Functions::flattenSingleValue($year);
- $month = Functions::flattenSingleValue($month);
- $day = Functions::flattenSingleValue($day);
-
- if (($month !== null) && (!is_numeric($month))) {
- $month = Date::monthStringToNumber($month);
- }
-
- if (($day !== null) && (!is_numeric($day))) {
- $day = Date::dayStringToNumber($day);
- }
-
- $year = ($year !== null) ? StringHelper::testStringAsNumeric($year) : 0;
- $month = ($month !== null) ? StringHelper::testStringAsNumeric($month) : 0;
- $day = ($day !== null) ? StringHelper::testStringAsNumeric($day) : 0;
- if (
- (!is_numeric($year)) ||
- (!is_numeric($month)) ||
- (!is_numeric($day))
- ) {
- return Functions::VALUE();
- }
- $year = (int) $year;
- $month = (int) $month;
- $day = (int) $day;
-
- $baseYear = Date::getExcelCalendar();
- // Validate parameters
- if ($year < ($baseYear - 1900)) {
- return Functions::NAN();
- }
- if ((($baseYear - 1900) != 0) && ($year < $baseYear) && ($year >= 1900)) {
- return Functions::NAN();
- }
-
- if (($year < $baseYear) && ($year >= ($baseYear - 1900))) {
- $year += 1900;
- }
-
- 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)) {
- return Functions::NAN();
- }
-
- // Execute function
- $excelDateValue = Date::formattedPHPToExcel($year, $month, $day);
- switch (Functions::getReturnDateType()) {
- case Functions::RETURNDATE_EXCEL:
- return (float) $excelDateValue;
- case Functions::RETURNDATE_UNIX_TIMESTAMP:
- return (int) Date::excelToTimestamp($excelDateValue);
- case Functions::RETURNDATE_PHP_DATETIME_OBJECT:
- return Date::excelToDateTimeObject($excelDateValue);
- }
+ return DateTimeExcel\Date::fromYMD($year, $month, $day);
}
/**
@@ -337,6 +172,11 @@ class DateTime
* Excel Function:
* TIME(hour,minute,second)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Time::fromHMS()
+ * Use the fromHMS method in the DateTimeExcel\Time class instead
+ *
* @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) =
@@ -354,85 +194,7 @@ class DateTime
*/
public static function TIME($hour = 0, $minute = 0, $second = 0)
{
- $hour = Functions::flattenSingleValue($hour);
- $minute = Functions::flattenSingleValue($minute);
- $second = Functions::flattenSingleValue($second);
-
- if ($hour == '') {
- $hour = 0;
- }
- if ($minute == '') {
- $minute = 0;
- }
- if ($second == '') {
- $second = 0;
- }
-
- if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) {
- return Functions::VALUE();
- }
- $hour = (int) $hour;
- $minute = (int) $minute;
- $second = (int) $second;
-
- 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;
- }
- 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;
- }
-
- if ($hour > 23) {
- $hour = $hour % 24;
- } elseif ($hour < 0) {
- return Functions::NAN();
- }
-
- // Execute function
- switch (Functions::getReturnDateType()) {
- case Functions::RETURNDATE_EXCEL:
- $date = 0;
- $calendar = Date::getExcelCalendar();
- if ($calendar != Date::CALENDAR_WINDOWS_1900) {
- $date = 1;
- }
-
- return (float) Date::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second);
- case Functions::RETURNDATE_UNIX_TIMESTAMP:
- return (int) Date::excelToTimestamp(Date::formattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600
- case Functions::RETURNDATE_PHP_DATETIME_OBJECT:
- $dayAdjust = 0;
- if ($hour < 0) {
- $dayAdjust = floor($hour / 24);
- $hour = 24 - abs($hour % 24);
- if ($hour == 24) {
- $hour = 0;
- }
- } elseif ($hour >= 24) {
- $dayAdjust = floor($hour / 24);
- $hour = $hour % 24;
- }
- $phpDateObject = new \DateTime('1900-01-01 ' . $hour . ':' . $minute . ':' . $second);
- if ($dayAdjust != 0) {
- $phpDateObject->modify($dayAdjust . ' days');
- }
-
- return $phpDateObject;
- }
+ return DateTimeExcel\Time::fromHMS($hour, $minute, $second);
}
/**
@@ -448,6 +210,11 @@ class DateTime
* Excel Function:
* DATEVALUE(dateValue)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\DateValue::fromString()
+ * Use the fromString method in the DateTimeExcel\DateValue class instead
+ *
* @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
@@ -460,112 +227,9 @@ class DateTime
* @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 = 1)
+ public static function DATEVALUE($dateValue)
{
- $dateValue = trim(Functions::flattenSingleValue($dateValue), '"');
- // Strip any ordinals because they're allowed in Excel (English only)
- $dateValue = 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);
- foreach ($t1 as &$t) {
- if ((is_numeric($t)) && ($t > 31)) {
- if ($yearFound) {
- return Functions::VALUE();
- }
- if ($t < 100) {
- $t += 1900;
- }
- $yearFound = true;
- }
- }
- if ((count($t1) == 1) && (strpos($t, ':') !== false)) {
- // We've been fed a time value without any date
- return 0.0;
- } elseif (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[] = date('Y');
- }
- }
- }
- unset($t);
- $dateValue = implode(' ', $t1);
-
- $PHPDateArray = date_parse($dateValue);
- if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
- $testVal1 = strtok($dateValue, '- ');
- if ($testVal1 !== false) {
- $testVal2 = strtok('- ');
- if ($testVal2 !== false) {
- $testVal3 = strtok('- ');
- if ($testVal3 === false) {
- $testVal3 = strftime('%Y');
- }
- } else {
- return Functions::VALUE();
- }
- } else {
- return Functions::VALUE();
- }
- if ($testVal1 < 31 && $testVal2 < 12 && $testVal3 < 12 && strlen($testVal3) == 2) {
- $testVal3 += 2000;
- }
- $PHPDateArray = date_parse($testVal1 . '-' . $testVal2 . '-' . $testVal3);
- if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
- $PHPDateArray = date_parse($testVal2 . '-' . $testVal1 . '-' . $testVal3);
- if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
- return Functions::VALUE();
- }
- }
- }
-
- if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) {
- // Execute function
- if ($PHPDateArray['year'] == '') {
- $PHPDateArray['year'] = strftime('%Y');
- }
- if ($PHPDateArray['year'] < 1900) {
- return Functions::VALUE();
- }
- if ($PHPDateArray['month'] == '') {
- $PHPDateArray['month'] = strftime('%m');
- }
- if ($PHPDateArray['day'] == '') {
- $PHPDateArray['day'] = strftime('%d');
- }
- if (!checkdate($PHPDateArray['month'], $PHPDateArray['day'], $PHPDateArray['year'])) {
- return Functions::VALUE();
- }
- $excelDateValue = floor(
- Date::formattedPHPToExcel(
- $PHPDateArray['year'],
- $PHPDateArray['month'],
- $PHPDateArray['day'],
- $PHPDateArray['hour'],
- $PHPDateArray['minute'],
- $PHPDateArray['second']
- )
- );
- switch (Functions::getReturnDateType()) {
- case Functions::RETURNDATE_EXCEL:
- return (float) $excelDateValue;
- case Functions::RETURNDATE_UNIX_TIMESTAMP:
- return (int) Date::excelToTimestamp($excelDateValue);
- case Functions::RETURNDATE_PHP_DATETIME_OBJECT:
- return new \DateTime($PHPDateArray['year'] . '-' . $PHPDateArray['month'] . '-' . $PHPDateArray['day'] . ' 00:00:00');
- }
- }
-
- return Functions::VALUE();
+ return DateTimeExcel\DateValue::fromString($dateValue);
}
/**
@@ -581,6 +245,11 @@ class DateTime
* Excel Function:
* TIMEVALUE(timeValue)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\TimeValue::fromString()
+ * Use the fromString method in the DateTimeExcel\TimeValue class instead
+ *
* @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.
@@ -591,46 +260,20 @@ class DateTime
*/
public static function TIMEVALUE($timeValue)
{
- $timeValue = trim(Functions::flattenSingleValue($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 = date_parse($timeValue);
- if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
- $excelDateValue = Date::formattedPHPToExcel(
- $PHPDateArray['year'],
- $PHPDateArray['month'],
- $PHPDateArray['day'],
- $PHPDateArray['hour'],
- $PHPDateArray['minute'],
- $PHPDateArray['second']
- );
- } else {
- $excelDateValue = Date::formattedPHPToExcel(1900, 1, 1, $PHPDateArray['hour'], $PHPDateArray['minute'], $PHPDateArray['second']) - 1;
- }
-
- switch (Functions::getReturnDateType()) {
- case Functions::RETURNDATE_EXCEL:
- return (float) $excelDateValue;
- case Functions::RETURNDATE_UNIX_TIMESTAMP:
- return (int) $phpDateValue = Date::excelToTimestamp($excelDateValue + 25569) - 3600;
- case Functions::RETURNDATE_PHP_DATETIME_OBJECT:
- return new \DateTime('1900-01-01 ' . $PHPDateArray['hour'] . ':' . $PHPDateArray['minute'] . ':' . $PHPDateArray['second']);
- }
- }
-
- return Functions::VALUE();
+ return DateTimeExcel\TimeValue::fromString($timeValue);
}
/**
* DATEDIF.
*
+ * Excel Function:
+ * DATEDIF(startdate, enddate, unit)
+ *
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Difference::interval()
+ * Use the interval method in the DateTimeExcel\Difference class instead
+ *
* @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
@@ -641,95 +284,7 @@ class DateTime
*/
public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D')
{
- $startDate = Functions::flattenSingleValue($startDate);
- $endDate = Functions::flattenSingleValue($endDate);
- $unit = strtoupper(Functions::flattenSingleValue($unit));
-
- if (is_string($startDate = self::getDateValue($startDate))) {
- return Functions::VALUE();
- }
- if (is_string($endDate = self::getDateValue($endDate))) {
- return Functions::VALUE();
- }
-
- // Validate parameters
- if ($startDate > $endDate) {
- return Functions::NAN();
- }
-
- // Execute function
- $difference = $endDate - $startDate;
-
- $PHPStartDateObject = Date::excelToDateTimeObject($startDate);
- $startDays = $PHPStartDateObject->format('j');
- $startMonths = $PHPStartDateObject->format('n');
- $startYears = $PHPStartDateObject->format('Y');
-
- $PHPEndDateObject = Date::excelToDateTimeObject($endDate);
- $endDays = $PHPEndDateObject->format('j');
- $endMonths = $PHPEndDateObject->format('n');
- $endYears = $PHPEndDateObject->format('Y');
-
- $PHPDiffDateObject = $PHPEndDateObject->diff($PHPStartDateObject);
-
- switch ($unit) {
- case 'D':
- $retVal = (int) $difference;
-
- break;
- case 'M':
- $retVal = (int) 12 * $PHPDiffDateObject->format('%y') + $PHPDiffDateObject->format('%m');
-
- break;
- case 'Y':
- $retVal = (int) $PHPDiffDateObject->format('%y');
-
- break;
- case 'MD':
- if ($endDays < $startDays) {
- $retVal = $endDays;
- $PHPEndDateObject->modify('-' . $endDays . ' days');
- $adjustDays = $PHPEndDateObject->format('j');
- $retVal += ($adjustDays - $startDays);
- } else {
- $retVal = (int) $PHPDiffDateObject->format('%d');
- }
-
- break;
- case 'YM':
- $retVal = (int) $PHPDiffDateObject->format('%m');
-
- break;
- case 'YD':
- $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 = $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;
- }
- }
-
- break;
- default:
- $retVal = Functions::VALUE();
- }
-
- return $retVal;
+ return DateTimeExcel\Difference::interval($startDate, $endDate, $unit);
}
/**
@@ -740,40 +295,21 @@ class DateTime
* Excel Function:
* DAYS(endDate, startDate)
*
- * @param DateTimeImmutable|float|int|string $endDate Excel date serial value (float),
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Days::between()
+ * Use the between method in the DateTimeExcel\Days class instead
+ *
+ * @param DateTimeInterface|float|int|string $endDate Excel date serial value (float),
* PHP date timestamp (integer), PHP DateTime object, or a standard date string
- * @param DateTimeImmutable|float|int|string $startDate Excel date serial value (float),
+ * @param DateTimeInterface|float|int|string $startDate Excel date serial value (float),
* PHP date timestamp (integer), PHP DateTime object, or a standard date string
*
* @return int|string Number of days between start date and end date or an error
*/
public static function DAYS($endDate = 0, $startDate = 0)
{
- $startDate = Functions::flattenSingleValue($startDate);
- $endDate = Functions::flattenSingleValue($endDate);
-
- $startDate = self::getDateValue($startDate);
- if (is_string($startDate)) {
- return Functions::VALUE();
- }
-
- $endDate = self::getDateValue($endDate);
- if (is_string($endDate)) {
- return Functions::VALUE();
- }
-
- // Execute function
- $PHPStartDateObject = Date::excelToDateTimeObject($startDate);
- $PHPEndDateObject = Date::excelToDateTimeObject($endDate);
-
- $diff = $PHPStartDateObject->diff($PHPEndDateObject);
- $days = $diff->days;
-
- if ($diff->invert) {
- $days = -$days;
- }
-
- return $days;
+ return DateTimeExcel\Days::between($endDate, $startDate);
}
/**
@@ -786,6 +322,11 @@ class DateTime
* Excel Function:
* DAYS360(startDate,endDate[,method])
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Days360::between()
+ * Use the between method in the DateTimeExcel\Days360 class instead
+ *
* @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),
@@ -806,32 +347,7 @@ class DateTime
*/
public static function DAYS360($startDate = 0, $endDate = 0, $method = false)
{
- $startDate = Functions::flattenSingleValue($startDate);
- $endDate = Functions::flattenSingleValue($endDate);
-
- if (is_string($startDate = self::getDateValue($startDate))) {
- return Functions::VALUE();
- }
- if (is_string($endDate = self::getDateValue($endDate))) {
- return Functions::VALUE();
- }
-
- if (!is_bool($method)) {
- return Functions::VALUE();
- }
-
- // Execute function
- $PHPStartDateObject = Date::excelToDateTimeObject($startDate);
- $startDay = $PHPStartDateObject->format('j');
- $startMonth = $PHPStartDateObject->format('n');
- $startYear = $PHPStartDateObject->format('Y');
-
- $PHPEndDateObject = Date::excelToDateTimeObject($endDate);
- $endDay = $PHPEndDateObject->format('j');
- $endMonth = $PHPEndDateObject->format('n');
- $endYear = $PHPEndDateObject->format('Y');
-
- return self::dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method);
+ return DateTimeExcel\Days360::between($startDate, $endDate, $method);
}
/**
@@ -844,6 +360,12 @@ class DateTime
*
* Excel Function:
* YEARFRAC(startDate,endDate[,method])
+ *
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\YearFrac::fraction()
+ * Use the fraction method in the DateTimeExcel\YearFrac class instead
+ *
* See https://lists.oasis-open.org/archives/office-formula/200806/msg00039.html
* for description of algorithm used in Excel
*
@@ -862,78 +384,7 @@ class DateTime
*/
public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0)
{
- $startDate = Functions::flattenSingleValue($startDate);
- $endDate = Functions::flattenSingleValue($endDate);
- $method = Functions::flattenSingleValue($method);
-
- if (is_string($startDate = self::getDateValue($startDate))) {
- return Functions::VALUE();
- }
- if (is_string($endDate = self::getDateValue($endDate))) {
- return Functions::VALUE();
- }
- if ($startDate > $endDate) {
- $temp = $startDate;
- $startDate = $endDate;
- $endDate = $temp;
- }
-
- if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) {
- switch ($method) {
- case 0:
- return self::DAYS360($startDate, $endDate) / 360;
- case 1:
- $days = self::DATEDIF($startDate, $endDate);
- $startYear = self::YEAR($startDate);
- $endYear = self::YEAR($endDate);
- $years = $endYear - $startYear + 1;
- $startMonth = self::MONTHOFYEAR($startDate);
- $startDay = self::DAYOFMONTH($startDate);
- $endMonth = self::MONTHOFYEAR($endDate);
- $endDay = self::DAYOFMONTH($endDate);
- $startMonthDay = 100 * $startMonth + $startDay;
- $endMonthDay = 100 * $endMonth + $endDay;
- if ($years == 1) {
- if (self::isLeapYear($endYear)) {
- $tmpCalcAnnualBasis = 366;
- } else {
- $tmpCalcAnnualBasis = 365;
- }
- } elseif ($years == 2 && $startMonthDay >= $endMonthDay) {
- if (self::isLeapYear($startYear)) {
- if ($startMonthDay <= 229) {
- $tmpCalcAnnualBasis = 366;
- } else {
- $tmpCalcAnnualBasis = 365;
- }
- } elseif (self::isLeapYear($endYear)) {
- if ($endMonthDay >= 229) {
- $tmpCalcAnnualBasis = 366;
- } else {
- $tmpCalcAnnualBasis = 365;
- }
- } else {
- $tmpCalcAnnualBasis = 365;
- }
- } else {
- $tmpCalcAnnualBasis = 0;
- for ($year = $startYear; $year <= $endYear; ++$year) {
- $tmpCalcAnnualBasis += self::isLeapYear($year) ? 366 : 365;
- }
- $tmpCalcAnnualBasis /= $years;
- }
-
- return $days / $tmpCalcAnnualBasis;
- case 2:
- return self::DATEDIF($startDate, $endDate) / 360;
- case 3:
- return self::DATEDIF($startDate, $endDate) / 365;
- case 4:
- return self::DAYS360($startDate, $endDate, true) / 360;
- }
- }
-
- return Functions::VALUE();
+ return DateTimeExcel\YearFrac::fraction($startDate, $endDate, $method);
}
/**
@@ -947,71 +398,22 @@ class DateTime
* Excel Function:
* NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]])
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\NetworkDays::count()
+ * Use the count method in the DateTimeExcel\NetworkDays class instead
+ *
* @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 int|string Interval between the dates
*/
public static function NETWORKDAYS($startDate, $endDate, ...$dateArgs)
{
- // Retrieve the mandatory start and end date that are referenced in the function definition
- $startDate = Functions::flattenSingleValue($startDate);
- $endDate = Functions::flattenSingleValue($endDate);
- // Get the optional days
- $dateArgs = Functions::flattenArray($dateArgs);
-
- // Validate the start and end dates
- if (is_string($startDate = $sDate = self::getDateValue($startDate))) {
- return Functions::VALUE();
- }
- $startDate = (float) floor($startDate);
- if (is_string($endDate = $eDate = self::getDateValue($endDate))) {
- return Functions::VALUE();
- }
- $endDate = (float) floor($endDate);
-
- if ($sDate > $eDate) {
- $startDate = $eDate;
- $endDate = $sDate;
- }
-
- // Execute function
- $startDoW = 6 - self::WEEKDAY($startDate, 2);
- if ($startDoW < 0) {
- $startDoW = 0;
- }
- $endDoW = self::WEEKDAY($endDate, 2);
- if ($endDoW >= 6) {
- $endDoW = 0;
- }
-
- $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5;
- $partWeekDays = $endDoW + $startDoW;
- if ($partWeekDays > 5) {
- $partWeekDays -= 5;
- }
-
- // Test any extra holiday parameters
- $holidayCountedArray = [];
- foreach ($dateArgs as $holidayDate) {
- if (is_string($holidayDate = self::getDateValue($holidayDate))) {
- return Functions::VALUE();
- }
- if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
- if ((self::WEEKDAY($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) {
- --$partWeekDays;
- $holidayCountedArray[] = $holidayDate;
- }
- }
- }
-
- if ($sDate > $eDate) {
- return 0 - ($wholeWeekDays + $partWeekDays);
- }
-
- return $wholeWeekDays + $partWeekDays;
+ return DateTimeExcel\NetworkDays::count($startDate, $endDate, ...$dateArgs);
}
/**
@@ -1025,102 +427,24 @@ class DateTime
* Excel Function:
* WORKDAY(startDate,endDays[,holidays[,holiday[,...]]])
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\WorkDay::date()
+ * Use the date method in the DateTimeExcel\WorkDay class instead
+ *
* @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)
{
- // Retrieve the mandatory start date and days that are referenced in the function definition
- $startDate = Functions::flattenSingleValue($startDate);
- $endDays = Functions::flattenSingleValue($endDays);
- // Get the optional days
- $dateArgs = Functions::flattenArray($dateArgs);
-
- if ((is_string($startDate = self::getDateValue($startDate))) || (!is_numeric($endDays))) {
- return Functions::VALUE();
- }
- $startDate = (float) floor($startDate);
- $endDays = (int) floor($endDays);
- // If endDays is 0, we always return startDate
- if ($endDays == 0) {
- return $startDate;
- }
-
- $decrementing = $endDays < 0;
-
- // Adjust the start date if it falls over a weekend
-
- $startDoW = self::WEEKDAY($startDate, 3);
- if (self::WEEKDAY($startDate, 3) >= 5) {
- $startDate += ($decrementing) ? -$startDoW + 4 : 7 - $startDoW;
- ($decrementing) ? $endDays++ : $endDays--;
- }
-
- // Add endDays
- $endDate = (float) $startDate + ((int) ($endDays / 5) * 7) + ($endDays % 5);
-
- // Adjust the calculated end date if it falls over a weekend
- $endDoW = self::WEEKDAY($endDate, 3);
- if ($endDoW >= 5) {
- $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW;
- }
-
- // Test any extra holiday parameters
- if (!empty($dateArgs)) {
- $holidayCountedArray = $holidayDates = [];
- foreach ($dateArgs as $holidayDate) {
- if (($holidayDate !== null) && (trim($holidayDate) > '')) {
- if (is_string($holidayDate = self::getDateValue($holidayDate))) {
- return Functions::VALUE();
- }
- if (self::WEEKDAY($holidayDate, 3) < 5) {
- $holidayDates[] = $holidayDate;
- }
- }
- }
- if ($decrementing) {
- rsort($holidayDates, SORT_NUMERIC);
- } else {
- sort($holidayDates, SORT_NUMERIC);
- }
- foreach ($holidayDates as $holidayDate) {
- if ($decrementing) {
- if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) {
- if (!in_array($holidayDate, $holidayCountedArray)) {
- --$endDate;
- $holidayCountedArray[] = $holidayDate;
- }
- }
- } else {
- 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::WEEKDAY($endDate, 3);
- if ($endDoW >= 5) {
- $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW;
- }
- }
- }
-
- switch (Functions::getReturnDateType()) {
- case Functions::RETURNDATE_EXCEL:
- return (float) $endDate;
- case Functions::RETURNDATE_UNIX_TIMESTAMP:
- return (int) Date::excelToTimestamp($endDate);
- case Functions::RETURNDATE_PHP_DATETIME_OBJECT:
- return Date::excelToDateTimeObject($endDate);
- }
+ return DateTimeExcel\WorkDay::date($startDate, $endDays, ...$dateArgs);
}
/**
@@ -1132,6 +456,11 @@ class DateTime
* Excel Function:
* DAY(dateValue)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\DateParts::day()
+ * Use the day method in the DateTimeExcel\DateParts class instead
+ *
* @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard date string
*
@@ -1139,26 +468,7 @@ class DateTime
*/
public static function DAYOFMONTH($dateValue = 1)
{
- $dateValue = Functions::flattenSingleValue($dateValue);
-
- if ($dateValue === null) {
- $dateValue = 1;
- } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
- return Functions::VALUE();
- }
-
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) {
- if ($dateValue < 0.0) {
- return Functions::NAN();
- } elseif ($dateValue < 1.0) {
- return 0;
- }
- }
-
- // Execute function
- $PHPDateObject = Date::excelToDateTimeObject($dateValue);
-
- return (int) $PHPDateObject->format('j');
+ return DateTimeExcel\DateParts::day($dateValue);
}
/**
@@ -1170,7 +480,12 @@ class DateTime
* Excel Function:
* WEEKDAY(dateValue[,style])
*
- * @param int $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Week::day()
+ * Use the day method in the DateTimeExcel\Week class instead
+ *
+ * @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).
@@ -1181,79 +496,169 @@ class DateTime
*/
public static function WEEKDAY($dateValue = 1, $style = 1)
{
- $dateValue = Functions::flattenSingleValue($dateValue);
- $style = Functions::flattenSingleValue($style);
-
- if (!is_numeric($style)) {
- return Functions::VALUE();
- } elseif (($style < 1) || ($style > 3)) {
- return Functions::NAN();
- }
- $style = floor($style);
-
- if ($dateValue === null) {
- $dateValue = 1;
- } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
- return Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return Functions::NAN();
- }
-
- // Execute function
- $PHPDateObject = Date::excelToDateTimeObject($dateValue);
- $DoW = (int) $PHPDateObject->format('w');
-
- $firstDay = 1;
- switch ($style) {
- case 1:
- ++$DoW;
-
- break;
- case 2:
- if ($DoW === 0) {
- $DoW = 7;
- }
-
- break;
- case 3:
- if ($DoW === 0) {
- $DoW = 7;
- }
- $firstDay = 0;
- --$DoW;
-
- break;
- }
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) {
- // Test for Excel's 1900 leap year, and introduce the error as required
- if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) {
- --$DoW;
- if ($DoW < $firstDay) {
- $DoW += 7;
- }
- }
- }
-
- return $DoW;
+ return DateTimeExcel\Week::day($dateValue, $style);
}
+ /**
+ * STARTWEEK_SUNDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\STARTWEEK_SUNDAY instead
+ */
const STARTWEEK_SUNDAY = 1;
+
+ /**
+ * STARTWEEK_MONDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\STARTWEEK_MONDAY instead
+ */
const STARTWEEK_MONDAY = 2;
+
+ /**
+ * STARTWEEK_MONDAY_ALT.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\STARTWEEK_MONDAY_ALT instead
+ */
const STARTWEEK_MONDAY_ALT = 11;
+
+ /**
+ * STARTWEEK_TUESDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\STARTWEEK_TUESDAY instead
+ */
const STARTWEEK_TUESDAY = 12;
+
+ /**
+ * STARTWEEK_WEDNESDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\STARTWEEK_WEDNESDAY instead
+ */
const STARTWEEK_WEDNESDAY = 13;
+
+ /**
+ * STARTWEEK_THURSDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\STARTWEEK_THURSDAY instead
+ */
const STARTWEEK_THURSDAY = 14;
+
+ /**
+ * STARTWEEK_FRIDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\STARTWEEK_FRIDAY instead
+ */
const STARTWEEK_FRIDAY = 15;
+
+ /**
+ * STARTWEEK_SATURDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\STARTWEEK_SATURDAY instead
+ */
const STARTWEEK_SATURDAY = 16;
+
+ /**
+ * STARTWEEK_SUNDAY_ALT.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\STARTWEEK_SUNDAY_ALT instead
+ */
const STARTWEEK_SUNDAY_ALT = 17;
+
+ /**
+ * DOW_SUNDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\DOW_SUNDAY instead
+ */
const DOW_SUNDAY = 1;
+
+ /**
+ * DOW_MONDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\DOW_MONDAY instead
+ */
const DOW_MONDAY = 2;
+
+ /**
+ * DOW_TUESDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\DOW_TUESDAY instead
+ */
const DOW_TUESDAY = 3;
+
+ /**
+ * DOW_WEDNESDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\DOW_WEDNESDAY instead
+ */
const DOW_WEDNESDAY = 4;
+
+ /**
+ * DOW_THURSDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\DOW_THURSDAY instead
+ */
const DOW_THURSDAY = 5;
+
+ /**
+ * DOW_FRIDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\DOW_FRIDAY instead
+ */
const DOW_FRIDAY = 6;
+
+ /**
+ * DOW_SATURDAY.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\DOW_SATURDAY instead
+ */
const DOW_SATURDAY = 7;
+
+ /**
+ * STARTWEEK_MONDAY_ISO.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\STARTWEEK_MONDAY_ISO instead
+ */
const STARTWEEK_MONDAY_ISO = 21;
+
+ /**
+ * METHODARR.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use DateTimeExcel\Constants\METHODARR instead
+ */
const METHODARR = [
self::STARTWEEK_SUNDAY => self::DOW_SUNDAY,
self::DOW_MONDAY,
@@ -1280,6 +685,11 @@ class DateTime
* Excel Function:
* WEEKNUM(dateValue[,style])
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Week::number(()
+ * Use the number method in the DateTimeExcel\Week class instead
+ *
* @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
@@ -1298,40 +708,7 @@ class DateTime
*/
public static function WEEKNUM($dateValue = 1, $method = self::STARTWEEK_SUNDAY)
{
- $dateValue = Functions::flattenSingleValue($dateValue);
- $method = Functions::flattenSingleValue($method);
-
- if (!is_numeric($method)) {
- return Functions::VALUE();
- }
- $method = (int) $method;
- if (!array_key_exists($method, self::METHODARR)) {
- return Functions::NaN();
- }
- $method = self::METHODARR[$method];
-
- $dateValue = self::getDateValue($dateValue);
- if (is_string($dateValue)) {
- return Functions::VALUE();
- }
- if ($dateValue < 0.0) {
- return Functions::NAN();
- }
-
- // Execute function
- $PHPDateObject = Date::excelToDateTimeObject($dateValue);
- if ($method == self::STARTWEEK_MONDAY_ISO) {
- return (int) $PHPDateObject->format('W');
- }
- $dayOfYear = $PHPDateObject->format('z');
- $PHPDateObject->modify('-' . $dayOfYear . ' days');
- $firstDayOfFirstWeek = $PHPDateObject->format('w');
- $daysInFirstWeek = (6 - $firstDayOfFirstWeek + $method) % 7;
- $daysInFirstWeek += 7 * !$daysInFirstWeek;
- $endFirstWeek = $daysInFirstWeek - 1;
- $weekOfYear = floor(($dayOfYear - $endFirstWeek + 13) / 7);
-
- return (int) $weekOfYear;
+ return DateTimeExcel\Week::number($dateValue, $method);
}
/**
@@ -1342,6 +719,11 @@ class DateTime
* Excel Function:
* ISOWEEKNUM(dateValue)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Week::isoWeekNumber()
+ * Use the isoWeekNumber method in the DateTimeExcel\Week class instead
+ *
* @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard date string
*
@@ -1349,20 +731,7 @@ class DateTime
*/
public static function ISOWEEKNUM($dateValue = 1)
{
- $dateValue = Functions::flattenSingleValue($dateValue);
-
- if ($dateValue === null) {
- $dateValue = 1;
- } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
- return Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return Functions::NAN();
- }
-
- // Execute function
- $PHPDateObject = Date::excelToDateTimeObject($dateValue);
-
- return (int) $PHPDateObject->format('W');
+ return DateTimeExcel\Week::isoWeekNumber($dateValue);
}
/**
@@ -1374,6 +743,11 @@ class DateTime
* Excel Function:
* MONTH(dateValue)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\DateParts::month()
+ * Use the month method in the DateTimeExcel\DateParts class instead
+ *
* @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard date string
*
@@ -1381,21 +755,7 @@ class DateTime
*/
public static function MONTHOFYEAR($dateValue = 1)
{
- $dateValue = Functions::flattenSingleValue($dateValue);
-
- if (empty($dateValue)) {
- $dateValue = 1;
- }
- if (is_string($dateValue = self::getDateValue($dateValue))) {
- return Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return Functions::NAN();
- }
-
- // Execute function
- $PHPDateObject = Date::excelToDateTimeObject($dateValue);
-
- return (int) $PHPDateObject->format('n');
+ return DateTimeExcel\DateParts::month($dateValue);
}
/**
@@ -1407,6 +767,11 @@ class DateTime
* Excel Function:
* YEAR(dateValue)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\DateParts::year()
+ * Use the ear method in the DateTimeExcel\DateParts class instead
+ *
* @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard date string
*
@@ -1414,20 +779,7 @@ class DateTime
*/
public static function YEAR($dateValue = 1)
{
- $dateValue = Functions::flattenSingleValue($dateValue);
-
- if ($dateValue === null) {
- $dateValue = 1;
- } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
- return Functions::VALUE();
- } elseif ($dateValue < 0.0) {
- return Functions::NAN();
- }
-
- // Execute function
- $PHPDateObject = Date::excelToDateTimeObject($dateValue);
-
- return (int) $PHPDateObject->format('Y');
+ return DateTimeExcel\DateParts::year($dateValue);
}
/**
@@ -1439,6 +791,11 @@ class DateTime
* Excel Function:
* HOUR(timeValue)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\TimeParts::hour()
+ * Use the hour method in the DateTimeExcel\TimeParts class instead
+ *
* @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard time string
*
@@ -1446,29 +803,7 @@ class DateTime
*/
public static function HOUROFDAY($timeValue = 0)
{
- $timeValue = Functions::flattenSingleValue($timeValue);
-
- if (!is_numeric($timeValue)) {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
- $testVal = strtok($timeValue, '/-: ');
- if (strlen($testVal) < strlen($timeValue)) {
- return Functions::VALUE();
- }
- }
- $timeValue = self::getTimeValue($timeValue);
- if (is_string($timeValue)) {
- return Functions::VALUE();
- }
- }
- // Execute function
- if ($timeValue >= 1) {
- $timeValue = fmod($timeValue, 1);
- } elseif ($timeValue < 0.0) {
- return Functions::NAN();
- }
- $timeValue = Date::excelToTimestamp($timeValue);
-
- return (int) gmdate('G', $timeValue);
+ return DateTimeExcel\TimeParts::hour($timeValue);
}
/**
@@ -1480,6 +815,11 @@ class DateTime
* Excel Function:
* MINUTE(timeValue)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\TimeParts::minute()
+ * Use the minute method in the DateTimeExcel\TimeParts class instead
+ *
* @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard time string
*
@@ -1487,29 +827,7 @@ class DateTime
*/
public static function MINUTE($timeValue = 0)
{
- $timeValue = $timeTester = Functions::flattenSingleValue($timeValue);
-
- if (!is_numeric($timeValue)) {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
- $testVal = strtok($timeValue, '/-: ');
- if (strlen($testVal) < strlen($timeValue)) {
- return Functions::VALUE();
- }
- }
- $timeValue = self::getTimeValue($timeValue);
- if (is_string($timeValue)) {
- return Functions::VALUE();
- }
- }
- // Execute function
- if ($timeValue >= 1) {
- $timeValue = fmod($timeValue, 1);
- } elseif ($timeValue < 0.0) {
- return Functions::NAN();
- }
- $timeValue = Date::excelToTimestamp($timeValue);
-
- return (int) gmdate('i', $timeValue);
+ return DateTimeExcel\TimeParts::minute($timeValue);
}
/**
@@ -1521,6 +839,11 @@ class DateTime
* Excel Function:
* SECOND(timeValue)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\TimeParts::second()
+ * Use the second method in the DateTimeExcel\TimeParts class instead
+ *
* @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
* PHP DateTime object, or a standard time string
*
@@ -1528,29 +851,7 @@ class DateTime
*/
public static function SECOND($timeValue = 0)
{
- $timeValue = Functions::flattenSingleValue($timeValue);
-
- if (!is_numeric($timeValue)) {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
- $testVal = strtok($timeValue, '/-: ');
- if (strlen($testVal) < strlen($timeValue)) {
- return Functions::VALUE();
- }
- }
- $timeValue = self::getTimeValue($timeValue);
- if (is_string($timeValue)) {
- return Functions::VALUE();
- }
- }
- // Execute function
- if ($timeValue >= 1) {
- $timeValue = fmod($timeValue, 1);
- } elseif ($timeValue < 0.0) {
- return Functions::NAN();
- }
- $timeValue = Date::excelToTimestamp($timeValue);
-
- return (int) gmdate('s', $timeValue);
+ return DateTimeExcel\TimeParts::second($timeValue);
}
/**
@@ -1564,6 +865,11 @@ class DateTime
* Excel Function:
* EDATE(dateValue,adjustmentMonths)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Month::adjust()
+ * Use the adjust method in the DateTimeExcel\Edate class instead
+ *
* @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.
@@ -1575,29 +881,7 @@ class DateTime
*/
public static function EDATE($dateValue = 1, $adjustmentMonths = 0)
{
- $dateValue = Functions::flattenSingleValue($dateValue);
- $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths);
-
- if (!is_numeric($adjustmentMonths)) {
- return Functions::VALUE();
- }
- $adjustmentMonths = floor($adjustmentMonths);
-
- if (is_string($dateValue = self::getDateValue($dateValue))) {
- return Functions::VALUE();
- }
-
- // Execute function
- $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths);
-
- switch (Functions::getReturnDateType()) {
- case Functions::RETURNDATE_EXCEL:
- return (float) Date::PHPToExcel($PHPDateObject);
- case Functions::RETURNDATE_UNIX_TIMESTAMP:
- return (int) Date::excelToTimestamp(Date::PHPToExcel($PHPDateObject));
- case Functions::RETURNDATE_PHP_DATETIME_OBJECT:
- return $PHPDateObject;
- }
+ return DateTimeExcel\Month::adjust($dateValue, $adjustmentMonths);
}
/**
@@ -1610,6 +894,11 @@ class DateTime
* Excel Function:
* EOMONTH(dateValue,adjustmentMonths)
*
+ * @Deprecated 1.18.0
+ *
+ * @See DateTimeExcel\Month::lastDay()
+ * Use the lastDay method in the DateTimeExcel\EoMonth class instead
+ *
* @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.
@@ -1621,31 +910,6 @@ class DateTime
*/
public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0)
{
- $dateValue = Functions::flattenSingleValue($dateValue);
- $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths);
-
- if (!is_numeric($adjustmentMonths)) {
- return Functions::VALUE();
- }
- $adjustmentMonths = floor($adjustmentMonths);
-
- if (is_string($dateValue = self::getDateValue($dateValue))) {
- return Functions::VALUE();
- }
-
- // Execute function
- $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths + 1);
- $adjustDays = (int) $PHPDateObject->format('d');
- $adjustDaysString = '-' . $adjustDays . ' days';
- $PHPDateObject->modify($adjustDaysString);
-
- switch (Functions::getReturnDateType()) {
- case Functions::RETURNDATE_EXCEL:
- return (float) Date::PHPToExcel($PHPDateObject);
- case Functions::RETURNDATE_UNIX_TIMESTAMP:
- return (int) Date::excelToTimestamp(Date::PHPToExcel($PHPDateObject));
- case Functions::RETURNDATE_PHP_DATETIME_OBJECT:
- return $PHPDateObject;
- }
+ return DateTimeExcel\Month::lastDay($dateValue, $adjustmentMonths);
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php
new file mode 100644
index 00000000000..1165eb1fee3
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php
@@ -0,0 +1,38 @@
+ 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,
+ ];
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php
new file mode 100644
index 00000000000..d23ce37b739
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php
@@ -0,0 +1,59 @@
+format('c'));
+
+ return Helpers::dateParseSucceeded($dateArray) ? Helpers::returnIn3FormatsArray($dateArray, true) : Functions::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) : Functions::VALUE();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php
new file mode 100644
index 00000000000..d18e2371c3f
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php
@@ -0,0 +1,168 @@
+getMessage();
+ }
+
+ // Execute function
+ $excelDateValue = SharedDateHelper::formattedPHPToExcel($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 = Functions::flattenSingleValue($year);
+ $year = ($year !== null) ? StringHelper::testStringAsNumeric((string) $year) : 0;
+ if (!is_numeric($year)) {
+ throw new Exception(Functions::VALUE());
+ }
+ $year = (int) $year;
+
+ if ($year < ($baseYear - 1900)) {
+ throw new Exception(Functions::NAN());
+ }
+ if ((($baseYear - 1900) !== 0) && ($year < $baseYear) && ($year >= 1900)) {
+ throw new Exception(Functions::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
+ {
+ $month = Functions::flattenSingleValue($month);
+
+ 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(Functions::VALUE());
+ }
+
+ return (int) $month;
+ }
+
+ /**
+ * Convert day from multiple formats to int.
+ *
+ * @param mixed $day
+ */
+ private static function getDay($day): int
+ {
+ $day = Functions::flattenSingleValue($day);
+
+ 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(Functions::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(Functions::NAN());
+ }
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php
new file mode 100644
index 00000000000..37ea0315154
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php
@@ -0,0 +1,127 @@
+= 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
+ *
+ * @return int|string Month of the year
+ */
+ public static function month($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
+ *
+ * @return int|string Year
+ */
+ public static function year($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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php
new file mode 100644
index 00000000000..3b21550626a
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php
@@ -0,0 +1,147 @@
+ 31)) {
+ if ($yearFound) {
+ return Functions::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)) ? Functions::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 = Functions::Value();
+ if (Helpers::dateParseSucceeded($PHPDateArray)) {
+ // Execute function
+ Helpers::replaceIfEmpty($PHPDateArray['year'], $dti->format('Y'));
+ if ($PHPDateArray['year'] < $baseYear) {
+ return Functions::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) : Functions::VALUE();
+ }
+ $retValue = Helpers::returnIn3FormatsArray($PHPDateArray, true);
+ }
+
+ return $retValue;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php
new file mode 100644
index 00000000000..5a97d8df8ab
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php
@@ -0,0 +1,51 @@
+getMessage();
+ }
+
+ // Execute function
+ $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate);
+ $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate);
+
+ $days = Functions::VALUE();
+ $diff = $PHPStartDateObject->diff($PHPEndDateObject);
+ if ($diff !== false && !is_bool($diff->days)) {
+ $days = $diff->days;
+ if ($diff->invert) {
+ $days = -$days;
+ }
+ }
+
+ return $days;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php
new file mode 100644
index 00000000000..bbc5d16aaa3
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php
@@ -0,0 +1,106 @@
+getMessage();
+ }
+
+ if (!is_bool($method)) {
+ return Functions::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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php
new file mode 100644
index 00000000000..6adeca179a0
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php
@@ -0,0 +1,146 @@
+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) ? Functions::VALUE() : $retVal;
+ }
+
+ private static function initialDiff(float $startDate, float $endDate): float
+ {
+ // Validate parameters
+ if ($startDate > $endDate) {
+ throw new Exception(Functions::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 = $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');
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php
new file mode 100644
index 00000000000..55ce13f1d2f
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php
@@ -0,0 +1,306 @@
+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(Functions::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(Functions::VALUE());
+ }
+ if ($number >= 0) {
+ return (float) $number;
+ }
+
+ throw new Exception(Functions::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];
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php
new file mode 100644
index 00000000000..560b7a80714
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php
@@ -0,0 +1,82 @@
+getMessage();
+ }
+ $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
+ * @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 lastDay($dateValue, $adjustmentMonths)
+ {
+ try {
+ $dateValue = Helpers::getDateValue($dateValue, false);
+ $adjustmentMonths = Helpers::validateNumericNull($adjustmentMonths);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+ $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);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php
new file mode 100644
index 00000000000..d0f53cf392c
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php
@@ -0,0 +1,102 @@
+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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php
new file mode 100644
index 00000000000..fb5e49652f8
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php
@@ -0,0 +1,119 @@
+getMessage();
+ }
+
+ self::adjustSecond($second, $minute);
+ self::adjustMinute($minute, $hour);
+
+ if ($hour > 23) {
+ $hour = $hour % 24;
+ } elseif ($hour < 0) {
+ return Functions::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 = Functions::flattenSingleValue($value);
+ $value = $value ?? 0;
+ if (is_bool($value)) {
+ $value = (int) $value;
+ }
+ if (!is_numeric($value)) {
+ throw new Exception(Functions::VALUE());
+ }
+
+ return (int) $value;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php
new file mode 100644
index 00000000000..49cd983d874
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php
@@ -0,0 +1,112 @@
+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
+ *
+ * @return int|string Minute
+ */
+ public static function minute($timeValue)
+ {
+ try {
+ $timeValue = Functions::flattenSingleValue($timeValue);
+ 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
+ *
+ * @return int|string Second
+ */
+ public static function second($timeValue)
+ {
+ try {
+ $timeValue = Functions::flattenSingleValue($timeValue);
+ 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');
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php
new file mode 100644
index 00000000000..c9645e66573
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php
@@ -0,0 +1,67 @@
+ 24) {
+ $arraySplit[0] = ($arraySplit[0] % 24);
+ $timeValue = implode(':', $arraySplit);
+ }
+
+ $PHPDateArray = Helpers::dateParse($timeValue);
+ $retValue = Functions::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) $phpDateValue = SharedDateHelper::excelToTimestamp($excelDateValue + 25569) - 3600;
+ } else {
+ $retValue = new DateTime('1900-01-01 ' . $PHPDateArray['hour'] . ':' . $PHPDateArray['minute'] . ':' . $PHPDateArray['second']);
+ }
+ }
+
+ return $retValue;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php
new file mode 100644
index 00000000000..66362221049
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php
@@ -0,0 +1,254 @@
+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
+ *
+ * @return int|string Week Number
+ */
+ public static function isoWeekNumber($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|float|int|string $dateValue Excel date serial value (float), PHP date timestamp (integer),
+ * PHP DateTime object, or a standard date string
+ * @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).
+ *
+ * @return int|string Day of the week value
+ */
+ public static function day($dateValue, $style = 1)
+ {
+ 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
+ {
+ $style = Functions::flattenSingleValue($style);
+
+ if (!is_numeric($style)) {
+ throw new Exception(Functions::VALUE());
+ }
+ $style = (int) $style;
+ if (($style < 1) || ($style > 3)) {
+ throw new Exception(Functions::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(Functions::VALUE());
+ }
+
+ return Helpers::getDateValue($dateValue);
+ }
+
+ /**
+ * Validate method parameter.
+ *
+ * @param mixed $method
+ */
+ private static function validateMethod($method): int
+ {
+ if ($method === null) {
+ $method = Constants::STARTWEEK_SUNDAY;
+ }
+ $method = Functions::flattenSingleValue($method);
+ if (!is_numeric($method)) {
+ throw new Exception(Functions::VALUE());
+ }
+
+ $method = (int) $method;
+ if (!array_key_exists($method, Constants::METHODARR)) {
+ throw new Exception(Functions::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';
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php
new file mode 100644
index 00000000000..89e47b9690b
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php
@@ -0,0 +1,189 @@
+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 (self::getWeekDay($startDate, 3) >= 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 (self::getWeekDay($startDate, 3) >= 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);
+ if ($endDoW >= 5) {
+ $endDate += -$endDoW + 4;
+ }
+ }
+
+ return $endDate;
+ }
+
+ private static function getWeekDay(float $date, int $wd): int
+ {
+ $result = Week::day($date, $wd);
+
+ return is_string($result) ? -1 : $result;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php
new file mode 100644
index 00000000000..da2ac12fc5a
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php
@@ -0,0 +1,120 @@
+getMessage();
+ }
+
+ switch ($method) {
+ case 0:
+ return Days360::between($startDate, $endDate) / 360;
+ case 1:
+ return self::method1($startDate, $endDate);
+ case 2:
+ return Difference::interval($startDate, $endDate) / 360;
+ case 3:
+ return Difference::interval($startDate, $endDate) / 365;
+ case 4:
+ return Days360::between($startDate, $endDate, true) / 360;
+ }
+
+ return Functions::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 = 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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Logger.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Logger.php
index 3c0f2377e4f..7f4657c43fc 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Logger.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Logger.php
@@ -48,11 +48,11 @@ class Logger
/**
* Enable/Disable Calculation engine logging.
*
- * @param bool $pValue
+ * @param bool $writeDebugLog
*/
- public function setWriteDebugLog($pValue): void
+ public function setWriteDebugLog($writeDebugLog): void
{
- $this->writeDebugLog = $pValue;
+ $this->writeDebugLog = $writeDebugLog;
}
/**
@@ -68,11 +68,11 @@ class Logger
/**
* Enable/Disable echoing of debug log information.
*
- * @param bool $pValue
+ * @param bool $echoDebugLog
*/
- public function setEchoDebugLog($pValue): void
+ public function setEchoDebugLog($echoDebugLog): void
{
- $this->echoDebugLog = $pValue;
+ $this->echoDebugLog = $echoDebugLog;
}
/**
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering.php
index 57116f28f53..a70ddac5cfb 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering.php
@@ -3,22 +3,28 @@
namespace PhpOffice\PhpSpreadsheet\Calculation;
use Complex\Complex;
-use Complex\Exception as ComplexException;
-use PhpOffice\PhpSpreadsheet\Calculation\Engineering\ConvertUOM;
+use PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions;
+use PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations;
+/**
+ * @deprecated 1.18.0
+ */
class Engineering
{
/**
* EULER.
+ *
+ * @deprecated 1.18.0
+ * @see Use Engineering\Constants\EULER instead
*/
- const EULER = 2.71828182845904523536;
+ public const EULER = 2.71828182845904523536;
/**
* parseComplex.
*
* Parses a complex number into its real and imaginary parts, and an I or J suffix
*
- * @deprecated 2.0.0 No longer used by internal code. Please use the Complex\Complex class instead
+ * @deprecated 1.12.0 No longer used by internal code. Please use the \Complex\Complex class instead
*
* @param string $complexNumber The complex number
*
@@ -35,35 +41,6 @@ class Engineering
];
}
- /**
- * Formats a number base string value with leading zeroes.
- *
- * @param string $xVal The "number" to pad
- * @param int $places The length that we want to pad this value
- *
- * @return string The padded "number"
- */
- private static function nbrConversionFormat($xVal, $places)
- {
- if ($places !== null) {
- if (is_numeric($places)) {
- $places = (int) $places;
- } else {
- return Functions::VALUE();
- }
- if ($places < 0) {
- return Functions::NAN();
- }
- if (strlen($xVal) <= $places) {
- return substr(str_pad($xVal, $places, '0', STR_PAD_LEFT), -10);
- }
-
- return Functions::NAN();
- }
-
- return substr($xVal, -10);
- }
-
/**
* BESSELI.
*
@@ -73,6 +50,10 @@ class Engineering
* Excel Function:
* BESSELI(x,ord)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the BESSELI() method in the Engineering\BesselI class instead
+ *
* @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.
@@ -84,38 +65,7 @@ class Engineering
*/
public static function BESSELI($x, $ord)
{
- $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x);
- $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- $ord = floor($ord);
- if ($ord < 0) {
- return Functions::NAN();
- }
-
- if (abs($x) <= 30) {
- $fResult = $fTerm = ($x / 2) ** $ord / MathTrig::FACT($ord);
- $ordK = 1;
- $fSqrX = ($x * $x) / 4;
- do {
- $fTerm *= $fSqrX;
- $fTerm /= ($ordK * ($ordK + $ord));
- $fResult += $fTerm;
- } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
- } else {
- $f_2_PI = 2 * M_PI;
-
- $fXAbs = abs($x);
- $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs);
- if (($ord & 1) && ($x < 0)) {
- $fResult = -$fResult;
- }
- }
-
- return (is_nan($fResult)) ? Functions::NAN() : $fResult;
- }
-
- return Functions::VALUE();
+ return Engineering\BesselI::BESSELI($x, $ord);
}
/**
@@ -126,6 +76,10 @@ class Engineering
* Excel Function:
* BESSELJ(x,ord)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the BESSELJ() method in the Engineering\BesselJ class instead
+ *
* @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.
@@ -136,76 +90,7 @@ class Engineering
*/
public static function BESSELJ($x, $ord)
{
- $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x);
- $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- $ord = floor($ord);
- if ($ord < 0) {
- return Functions::NAN();
- }
-
- $fResult = 0;
- if (abs($x) <= 30) {
- $fResult = $fTerm = ($x / 2) ** $ord / MathTrig::FACT($ord);
- $ordK = 1;
- $fSqrX = ($x * $x) / -4;
- do {
- $fTerm *= $fSqrX;
- $fTerm /= ($ordK * ($ordK + $ord));
- $fResult += $fTerm;
- } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
- } else {
- $f_PI_DIV_2 = M_PI / 2;
- $f_PI_DIV_4 = M_PI / 4;
-
- $fXAbs = abs($x);
- $fResult = sqrt(Functions::M_2DIVPI / $fXAbs) * cos($fXAbs - $ord * $f_PI_DIV_2 - $f_PI_DIV_4);
- if (($ord & 1) && ($x < 0)) {
- $fResult = -$fResult;
- }
- }
-
- return (is_nan($fResult)) ? Functions::NAN() : $fResult;
- }
-
- return Functions::VALUE();
- }
-
- private static function besselK0($fNum)
- {
- if ($fNum <= 2) {
- $fNum2 = $fNum * 0.5;
- $y = ($fNum2 * $fNum2);
- $fRet = -log($fNum2) * self::BESSELI($fNum, 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))))));
- } else {
- $y = 2 / $fNum;
- $fRet = exp(-$fNum) / sqrt($fNum) *
- (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))))));
- }
-
- return $fRet;
- }
-
- private static function besselK1($fNum)
- {
- if ($fNum <= 2) {
- $fNum2 = $fNum * 0.5;
- $y = ($fNum2 * $fNum2);
- $fRet = log($fNum2) * self::BESSELI($fNum, 1) +
- (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y *
- (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum;
- } else {
- $y = 2 / $fNum;
- $fRet = exp(-$fNum) / sqrt($fNum) *
- (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)))))));
- }
-
- return $fRet;
+ return Engineering\BesselJ::BESSELJ($x, $ord);
}
/**
@@ -217,6 +102,10 @@ class Engineering
* Excel Function:
* BESSELK(x,ord)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the BESSELK() method in the Engineering\BesselK class instead
+ *
* @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.
@@ -227,73 +116,7 @@ class Engineering
*/
public static function BESSELK($x, $ord)
{
- $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x);
- $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- if (($ord < 0) || ($x == 0.0)) {
- return Functions::NAN();
- }
-
- switch (floor($ord)) {
- case 0:
- $fBk = self::besselK0($x);
-
- break;
- case 1:
- $fBk = self::besselK1($x);
-
- break;
- default:
- $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 (is_nan($fBk)) ? Functions::NAN() : $fBk;
- }
-
- return Functions::VALUE();
- }
-
- private static function besselY0($fNum)
- {
- if ($fNum < 8.0) {
- $y = ($fNum * $fNum);
- $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733))));
- $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y))));
- $fRet = $f1 / $f2 + 0.636619772 * self::BESSELJ($fNum, 0) * log($fNum);
- } else {
- $z = 8.0 / $fNum;
- $y = ($z * $z);
- $xx = $fNum - 0.785398164;
- $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6)));
- $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7))));
- $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2);
- }
-
- return $fRet;
- }
-
- private static function besselY1($fNum)
- {
- if ($fNum < 8.0) {
- $y = ($fNum * $fNum);
- $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y *
- (-0.4237922726e7 + $y * 0.8511937935e4)))));
- $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y *
- (0.1020426050e6 + $y * (0.3549632885e3 + $y)))));
- $fRet = $f1 / $f2 + 0.636619772 * (self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum);
- } else {
- $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491);
- }
-
- return $fRet;
+ return Engineering\BesselK::BESSELK($x, $ord);
}
/**
@@ -304,48 +127,21 @@ class Engineering
* Excel Function:
* BESSELY(x,ord)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the BESSELY() method in the Engineering\BesselY class instead
+ *
* @param float $x The value at which to evaluate the function.
- * If x is nonnumeric, BESSELK returns the #VALUE! error value.
+ * 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, BESSELK returns the #VALUE! error value.
- * If $ord < 0, BESSELK returns the #NUM! error value.
+ * If $ord is nonnumeric, BESSELY returns the #VALUE! error value.
+ * If $ord < 0, BESSELY returns the #NUM! error value.
*
* @return float|string Result, or a string containing an error
*/
public static function BESSELY($x, $ord)
{
- $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x);
- $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord);
-
- if ((is_numeric($x)) && (is_numeric($ord))) {
- if (($ord < 0) || ($x == 0.0)) {
- return Functions::NAN();
- }
-
- switch (floor($ord)) {
- case 0:
- $fBy = self::besselY0($x);
-
- break;
- case 1:
- $fBy = self::besselY1($x);
-
- break;
- default:
- $fTox = 2 / $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 (is_nan($fBy)) ? Functions::NAN() : $fBy;
- }
-
- return Functions::VALUE();
+ return Engineering\BesselY::BESSELY($x, $ord);
}
/**
@@ -356,7 +152,11 @@ class Engineering
* Excel Function:
* BIN2DEC(x)
*
- * @param string $x The binary number (as a string) that you want to convert. The number
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toDecimal() method in the Engineering\ConvertBinary class instead
+ *
+ * @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.
@@ -367,32 +167,7 @@ class Engineering
*/
public static function BINTODEC($x)
{
- $x = Functions::flattenSingleValue($x);
-
- if (is_bool($x)) {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Functions::VALUE();
- }
- }
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
- $x = floor($x);
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[01]/', $x, $out)) {
- return Functions::NAN();
- }
- if (strlen($x) > 10) {
- return Functions::NAN();
- } elseif (strlen($x) == 10) {
- // Two's Complement
- $x = substr($x, -9);
-
- return '-' . (512 - bindec($x));
- }
-
- return bindec($x);
+ return Engineering\ConvertBinary::toDecimal($x);
}
/**
@@ -403,13 +178,17 @@ class Engineering
* Excel Function:
* BIN2HEX(x[,places])
*
- * @param string $x The binary number (as a string) that you want to convert. The number
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toHex() method in the Engineering\ConvertBinary class instead
+ *
+ * @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 int $places The number of characters to use. If places is omitted, BIN2HEX uses the
+ * @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.
@@ -420,33 +199,7 @@ class Engineering
*/
public static function BINTOHEX($x, $places = null)
{
- $x = Functions::flattenSingleValue($x);
- $places = Functions::flattenSingleValue($places);
-
- // Argument X
- if (is_bool($x)) {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Functions::VALUE();
- }
- }
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
- $x = floor($x);
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[01]/', $x, $out)) {
- return Functions::NAN();
- }
- if (strlen($x) > 10) {
- return Functions::NAN();
- } elseif (strlen($x) == 10) {
- // Two's Complement
- return str_repeat('F', 8) . substr(strtoupper(dechex(bindec(substr($x, -9)))), -2);
- }
- $hexVal = (string) strtoupper(dechex(bindec($x)));
-
- return self::nbrConversionFormat($hexVal, $places);
+ return Engineering\ConvertBinary::toHex($x, $places);
}
/**
@@ -457,13 +210,17 @@ class Engineering
* Excel Function:
* BIN2OCT(x[,places])
*
- * @param string $x The binary number (as a string) that you want to convert. The number
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toOctal() method in the Engineering\ConvertBinary class instead
+ *
+ * @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 int $places The number of characters to use. If places is omitted, BIN2OCT uses the
+ * @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.
@@ -474,32 +231,7 @@ class Engineering
*/
public static function BINTOOCT($x, $places = null)
{
- $x = Functions::flattenSingleValue($x);
- $places = Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Functions::VALUE();
- }
- }
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
- $x = floor($x);
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[01]/', $x, $out)) {
- return Functions::NAN();
- }
- if (strlen($x) > 10) {
- return Functions::NAN();
- } elseif (strlen($x) == 10) {
- // Two's Complement
- return str_repeat('7', 7) . substr(strtoupper(decoct(bindec(substr($x, -9)))), -3);
- }
- $octVal = (string) decoct(bindec($x));
-
- return self::nbrConversionFormat($octVal, $places);
+ return Engineering\ConvertBinary::toOctal($x, $places);
}
/**
@@ -510,7 +242,11 @@ class Engineering
* Excel Function:
* DEC2BIN(x[,places])
*
- * @param string $x The decimal integer you want to convert. If number is negative,
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toBinary() method in the Engineering\ConvertDecimal class instead
+ *
+ * @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
@@ -520,7 +256,7 @@ class Engineering
* If number is nonnumeric, DEC2BIN returns the #VALUE! error value.
* If DEC2BIN requires more than places characters, it returns the #NUM!
* error value.
- * @param int $places The number of characters to use. If places is omitted, DEC2BIN uses
+ * @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.
@@ -531,34 +267,7 @@ class Engineering
*/
public static function DECTOBIN($x, $places = null)
{
- $x = Functions::flattenSingleValue($x);
- $places = Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Functions::VALUE();
- }
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) {
- return Functions::VALUE();
- }
-
- $x = (string) floor($x);
- if ($x < -512 || $x > 511) {
- return Functions::NAN();
- }
-
- $r = decbin($x);
- // Two's Complement
- $r = substr($r, -10);
- if (strlen($r) >= 11) {
- return Functions::NAN();
- }
-
- return self::nbrConversionFormat($r, $places);
+ return Engineering\ConvertDecimal::toBinary($x, $places);
}
/**
@@ -569,7 +278,11 @@ class Engineering
* Excel Function:
* DEC2HEX(x[,places])
*
- * @param string $x The decimal integer you want to convert. If number is negative,
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toHex() method in the Engineering\ConvertDecimal class instead
+ *
+ * @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
@@ -579,7 +292,7 @@ class Engineering
* If number is nonnumeric, DEC2HEX returns the #VALUE! error value.
* If DEC2HEX requires more than places characters, it returns the
* #NUM! error value.
- * @param int $places The number of characters to use. If places is omitted, DEC2HEX uses
+ * @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.
@@ -590,28 +303,7 @@ class Engineering
*/
public static function DECTOHEX($x, $places = null)
{
- $x = Functions::flattenSingleValue($x);
- $places = Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Functions::VALUE();
- }
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) {
- return Functions::VALUE();
- }
- $x = (string) floor($x);
- $r = strtoupper(dechex($x));
- if (strlen($r) == 8) {
- // Two's Complement
- $r = 'FF' . $r;
- }
-
- return self::nbrConversionFormat($r, $places);
+ return Engineering\ConvertDecimal::toHex($x, $places);
}
/**
@@ -622,7 +314,11 @@ class Engineering
* Excel Function:
* DEC2OCT(x[,places])
*
- * @param string $x The decimal integer you want to convert. If number is negative,
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toOctal() method in the Engineering\ConvertDecimal class instead
+ *
+ * @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
@@ -632,7 +328,7 @@ class Engineering
* If number is nonnumeric, DEC2OCT returns the #VALUE! error value.
* If DEC2OCT requires more than places characters, it returns the
* #NUM! error value.
- * @param int $places The number of characters to use. If places is omitted, DEC2OCT uses
+ * @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.
@@ -643,29 +339,7 @@ class Engineering
*/
public static function DECTOOCT($x, $places = null)
{
- $xorig = $x;
- $x = Functions::flattenSingleValue($x);
- $places = Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
- $x = (int) $x;
- } else {
- return Functions::VALUE();
- }
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) {
- return Functions::VALUE();
- }
- $x = (string) floor($x);
- $r = decoct($x);
- if (strlen($r) == 11) {
- // Two's Complement
- $r = substr($r, -10);
- }
-
- return self::nbrConversionFormat($r, $places);
+ return Engineering\ConvertDecimal::toOctal($x, $places);
}
/**
@@ -676,7 +350,11 @@ class Engineering
* Excel Function:
* HEX2BIN(x[,places])
*
- * @param string $x the hexadecimal number you want to convert.
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toBinary() method in the Engineering\ConvertHex class instead
+ *
+ * @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.
@@ -686,7 +364,7 @@ class Engineering
* 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 int $places The number of characters to use. If places is omitted,
+ * @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.
@@ -697,18 +375,7 @@ class Engineering
*/
public static function HEXTOBIN($x, $places = null)
{
- $x = Functions::flattenSingleValue($x);
- $places = Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return Functions::VALUE();
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) {
- return Functions::NAN();
- }
-
- return self::DECTOBIN(self::HEXTODEC($x), $places);
+ return Engineering\ConvertHex::toBinary($x, $places);
}
/**
@@ -719,7 +386,11 @@ class Engineering
* Excel Function:
* HEX2DEC(x)
*
- * @param string $x The hexadecimal number you want to convert. This number cannot
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toDecimal() method in the Engineering\ConvertHex class instead
+ *
+ * @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
@@ -731,33 +402,7 @@ class Engineering
*/
public static function HEXTODEC($x)
{
- $x = Functions::flattenSingleValue($x);
-
- if (is_bool($x)) {
- return Functions::VALUE();
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) {
- return Functions::NAN();
- }
-
- if (strlen($x) > 10) {
- return Functions::NAN();
- }
-
- $binX = '';
- foreach (str_split($x) 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 (bindec($binX) + 1) * -1;
- }
-
- return bindec($binX);
+ return Engineering\ConvertHex::toDecimal($x);
}
/**
@@ -768,7 +413,11 @@ class Engineering
* Excel Function:
* HEX2OCT(x[,places])
*
- * @param string $x The hexadecimal number you want to convert. Number cannot
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toOctal() method in the Engineering\ConvertHex class instead
+ *
+ * @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
@@ -781,7 +430,7 @@ class Engineering
* the #NUM! error value.
* If HEX2OCT requires more than places characters, it returns
* the #NUM! error value.
- * @param int $places The number of characters to use. If places is omitted, HEX2OCT
+ * @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.
@@ -793,23 +442,7 @@ class Engineering
*/
public static function HEXTOOCT($x, $places = null)
{
- $x = Functions::flattenSingleValue($x);
- $places = Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return Functions::VALUE();
- }
- $x = (string) $x;
- if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) {
- return Functions::NAN();
- }
-
- $decimal = self::HEXTODEC($x);
- if ($decimal < -536870912 || $decimal > 536870911) {
- return Functions::NAN();
- }
-
- return self::DECTOOCT($decimal, $places);
+ return Engineering\ConvertHex::toOctal($x, $places);
}
/**
@@ -820,7 +453,11 @@ class Engineering
* Excel Function:
* OCT2BIN(x[,places])
*
- * @param string $x The octal number you want to convert. Number may not
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toBinary() method in the Engineering\ConvertOctal class instead
+ *
+ * @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
@@ -833,7 +470,7 @@ class Engineering
* the #NUM! error value.
* If OCT2BIN requires more than places characters, it
* returns the #NUM! error value.
- * @param int $places The number of characters to use. If places is omitted,
+ * @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).
@@ -847,18 +484,7 @@ class Engineering
*/
public static function OCTTOBIN($x, $places = null)
{
- $x = Functions::flattenSingleValue($x);
- $places = Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return Functions::VALUE();
- }
- $x = (string) $x;
- if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) {
- return Functions::NAN();
- }
-
- return self::DECTOBIN(self::OCTTODEC($x), $places);
+ return Engineering\ConvertOctal::toBinary($x, $places);
}
/**
@@ -869,7 +495,11 @@ class Engineering
* Excel Function:
* OCT2DEC(x)
*
- * @param string $x The octal number you want to convert. Number may not contain
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toDecimal() method in the Engineering\ConvertOctal class instead
+ *
+ * @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
@@ -881,28 +511,7 @@ class Engineering
*/
public static function OCTTODEC($x)
{
- $x = Functions::flattenSingleValue($x);
-
- if (is_bool($x)) {
- return Functions::VALUE();
- }
- $x = (string) $x;
- if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) {
- return Functions::NAN();
- }
- $binX = '';
- foreach (str_split($x) 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 (bindec($binX) + 1) * -1;
- }
-
- return bindec($binX);
+ return Engineering\ConvertOctal::toDecimal($x);
}
/**
@@ -913,7 +522,11 @@ class Engineering
* Excel Function:
* OCT2HEX(x[,places])
*
- * @param string $x The octal number you want to convert. Number may not contain
+ * @Deprecated 1.17.0
+ *
+ * @see Use the toHex() method in the Engineering\ConvertOctal class instead
+ *
+ * @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
@@ -924,7 +537,7 @@ class Engineering
* #NUM! error value.
* If OCT2HEX requires more than places characters, it returns
* the #NUM! error value.
- * @param int $places The number of characters to use. If places is omitted, OCT2HEX
+ * @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.
@@ -935,19 +548,7 @@ class Engineering
*/
public static function OCTTOHEX($x, $places = null)
{
- $x = Functions::flattenSingleValue($x);
- $places = Functions::flattenSingleValue($places);
-
- if (is_bool($x)) {
- return Functions::VALUE();
- }
- $x = (string) $x;
- if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) {
- return Functions::NAN();
- }
- $hexVal = strtoupper(dechex(self::OCTTODEC($x)));
-
- return self::nbrConversionFormat($hexVal, $places);
+ return Engineering\ConvertOctal::toHex($x, $places);
}
/**
@@ -958,6 +559,10 @@ class Engineering
* Excel Function:
* COMPLEX(realNumber,imaginary[,suffix])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the COMPLEX() method in the Engineering\Complex class instead
+ *
* @param float $realNumber the real coefficient of the complex number
* @param float $imaginary the imaginary coefficient of the complex number
* @param string $suffix The suffix for the imaginary component of the complex number.
@@ -967,20 +572,7 @@ class Engineering
*/
public static function COMPLEX($realNumber = 0.0, $imaginary = 0.0, $suffix = 'i')
{
- $realNumber = ($realNumber === null) ? 0.0 : Functions::flattenSingleValue($realNumber);
- $imaginary = ($imaginary === null) ? 0.0 : Functions::flattenSingleValue($imaginary);
- $suffix = ($suffix === null) ? 'i' : Functions::flattenSingleValue($suffix);
-
- if (
- ((is_numeric($realNumber)) && (is_numeric($imaginary))) &&
- (($suffix == 'i') || ($suffix == 'j') || ($suffix == ''))
- ) {
- $complex = new Complex($realNumber, $imaginary, $suffix);
-
- return (string) $complex;
- }
-
- return Functions::VALUE();
+ return Engineering\Complex::COMPLEX($realNumber, $imaginary, $suffix);
}
/**
@@ -991,16 +583,18 @@ class Engineering
* Excel Function:
* IMAGINARY(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMAGINARY() method in the Engineering\Complex class instead
+ *
* @param string $complexNumber the complex number for which you want the imaginary
* coefficient
*
- * @return float
+ * @return float|string
*/
public static function IMAGINARY($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (new Complex($complexNumber))->getImaginary();
+ return Engineering\Complex::IMAGINARY($complexNumber);
}
/**
@@ -1011,15 +605,17 @@ class Engineering
* Excel Function:
* IMREAL(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMREAL() method in the Engineering\Complex class instead
+ *
* @param string $complexNumber the complex number for which you want the real coefficient
*
- * @return float
+ * @return float|string
*/
public static function IMREAL($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (new Complex($complexNumber))->getReal();
+ return Engineering\Complex::IMREAL($complexNumber);
}
/**
@@ -1030,15 +626,17 @@ class Engineering
* Excel Function:
* IMABS(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMABS() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the absolute value
*
- * @return float
+ * @return float|string
*/
public static function IMABS($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (new Complex($complexNumber))->abs();
+ return ComplexFunctions::IMABS($complexNumber);
}
/**
@@ -1050,20 +648,17 @@ class Engineering
* Excel Function:
* IMARGUMENT(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMARGUMENT() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the argument theta
*
* @return float|string
*/
public static function IMARGUMENT($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- $complex = new Complex($complexNumber);
- if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- return Functions::DIV0();
- }
-
- return $complex->argument();
+ return ComplexFunctions::IMARGUMENT($complexNumber);
}
/**
@@ -1074,15 +669,17 @@ class Engineering
* Excel Function:
* IMCONJUGATE(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMARGUMENT() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the conjugate
*
* @return string
*/
public static function IMCONJUGATE($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->conjugate();
+ return ComplexFunctions::IMCONJUGATE($complexNumber);
}
/**
@@ -1093,15 +690,17 @@ class Engineering
* Excel Function:
* IMCOS(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMCOS() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the cosine
*
* @return float|string
*/
public static function IMCOS($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->cos();
+ return ComplexFunctions::IMCOS($complexNumber);
}
/**
@@ -1112,15 +711,17 @@ class Engineering
* Excel Function:
* IMCOSH(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMCOSH() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the hyperbolic cosine
*
* @return float|string
*/
public static function IMCOSH($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->cosh();
+ return ComplexFunctions::IMCOSH($complexNumber);
}
/**
@@ -1131,15 +732,17 @@ class Engineering
* Excel Function:
* IMCOT(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMCOT() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the cotangent
*
* @return float|string
*/
public static function IMCOT($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->cot();
+ return ComplexFunctions::IMCOT($complexNumber);
}
/**
@@ -1150,15 +753,17 @@ class Engineering
* Excel Function:
* IMCSC(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMCSC() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the cosecant
*
* @return float|string
*/
public static function IMCSC($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->csc();
+ return ComplexFunctions::IMCSC($complexNumber);
}
/**
@@ -1169,15 +774,17 @@ class Engineering
* Excel Function:
* IMCSCH(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMCSCH() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the hyperbolic cosecant
*
* @return float|string
*/
public static function IMCSCH($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->csch();
+ return ComplexFunctions::IMCSCH($complexNumber);
}
/**
@@ -1188,15 +795,17 @@ class Engineering
* Excel Function:
* IMSIN(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMSIN() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the sine
*
* @return float|string
*/
public static function IMSIN($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->sin();
+ return ComplexFunctions::IMSIN($complexNumber);
}
/**
@@ -1207,15 +816,17 @@ class Engineering
* Excel Function:
* IMSINH(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMSINH() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the hyperbolic sine
*
* @return float|string
*/
public static function IMSINH($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->sinh();
+ return ComplexFunctions::IMSINH($complexNumber);
}
/**
@@ -1226,15 +837,17 @@ class Engineering
* Excel Function:
* IMSEC(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMSEC() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the secant
*
* @return float|string
*/
public static function IMSEC($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->sec();
+ return ComplexFunctions::IMSEC($complexNumber);
}
/**
@@ -1245,15 +858,17 @@ class Engineering
* Excel Function:
* IMSECH(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMSECH() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the hyperbolic secant
*
* @return float|string
*/
public static function IMSECH($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->sech();
+ return ComplexFunctions::IMSECH($complexNumber);
}
/**
@@ -1264,15 +879,17 @@ class Engineering
* Excel Function:
* IMTAN(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMTAN() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the tangent
*
* @return float|string
*/
public static function IMTAN($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->tan();
+ return ComplexFunctions::IMTAN($complexNumber);
}
/**
@@ -1283,20 +900,17 @@ class Engineering
* Excel Function:
* IMSQRT(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMSQRT() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the square root
*
* @return string
*/
public static function IMSQRT($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- $theta = self::IMARGUMENT($complexNumber);
- if ($theta === Functions::DIV0()) {
- return '0';
- }
-
- return (string) (new Complex($complexNumber))->sqrt();
+ return ComplexFunctions::IMSQRT($complexNumber);
}
/**
@@ -1307,20 +921,17 @@ class Engineering
* Excel Function:
* IMLN(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMLN() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the natural logarithm
*
* @return string
*/
public static function IMLN($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- $complex = new Complex($complexNumber);
- if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- return Functions::NAN();
- }
-
- return (string) (new Complex($complexNumber))->ln();
+ return ComplexFunctions::IMLN($complexNumber);
}
/**
@@ -1331,20 +942,17 @@ class Engineering
* Excel Function:
* IMLOG10(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMLOG10() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the common logarithm
*
* @return string
*/
public static function IMLOG10($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- $complex = new Complex($complexNumber);
- if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- return Functions::NAN();
- }
-
- return (string) (new Complex($complexNumber))->log10();
+ return ComplexFunctions::IMLOG10($complexNumber);
}
/**
@@ -1355,20 +963,17 @@ class Engineering
* Excel Function:
* IMLOG2(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMLOG2() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the base-2 logarithm
*
* @return string
*/
public static function IMLOG2($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- $complex = new Complex($complexNumber);
- if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
- return Functions::NAN();
- }
-
- return (string) (new Complex($complexNumber))->log2();
+ return ComplexFunctions::IMLOG2($complexNumber);
}
/**
@@ -1379,15 +984,17 @@ class Engineering
* Excel Function:
* IMEXP(complexNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMEXP() method in the Engineering\ComplexFunctions class instead
+ *
* @param string $complexNumber the complex number for which you want the exponential
*
* @return string
*/
public static function IMEXP($complexNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
-
- return (string) (new Complex($complexNumber))->exp();
+ return ComplexFunctions::IMEXP($complexNumber);
}
/**
@@ -1398,6 +1005,10 @@ class Engineering
* Excel Function:
* IMPOWER(complexNumber,realNumber)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMPOWER() method in the Engineering\ComplexFunctions class instead
+ *
* @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
*
@@ -1405,14 +1016,7 @@ class Engineering
*/
public static function IMPOWER($complexNumber, $realNumber)
{
- $complexNumber = Functions::flattenSingleValue($complexNumber);
- $realNumber = Functions::flattenSingleValue($realNumber);
-
- if (!is_numeric($realNumber)) {
- return Functions::VALUE();
- }
-
- return (string) (new Complex($complexNumber))->pow($realNumber);
+ return ComplexFunctions::IMPOWER($complexNumber, $realNumber);
}
/**
@@ -1423,6 +1027,10 @@ class Engineering
* Excel Function:
* IMDIV(complexDividend,complexDivisor)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMDIV() method in the Engineering\ComplexOperations class instead
+ *
* @param string $complexDividend the complex numerator or dividend
* @param string $complexDivisor the complex denominator or divisor
*
@@ -1430,14 +1038,7 @@ class Engineering
*/
public static function IMDIV($complexDividend, $complexDivisor)
{
- $complexDividend = Functions::flattenSingleValue($complexDividend);
- $complexDivisor = Functions::flattenSingleValue($complexDivisor);
-
- try {
- return (string) (new Complex($complexDividend))->divideby(new Complex($complexDivisor));
- } catch (ComplexException $e) {
- return Functions::NAN();
- }
+ return ComplexOperations::IMDIV($complexDividend, $complexDivisor);
}
/**
@@ -1448,6 +1049,10 @@ class Engineering
* Excel Function:
* IMSUB(complexNumber1,complexNumber2)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMSUB() method in the Engineering\ComplexOperations class instead
+ *
* @param string $complexNumber1 the complex number from which to subtract complexNumber2
* @param string $complexNumber2 the complex number to subtract from complexNumber1
*
@@ -1455,14 +1060,7 @@ class Engineering
*/
public static function IMSUB($complexNumber1, $complexNumber2)
{
- $complexNumber1 = Functions::flattenSingleValue($complexNumber1);
- $complexNumber2 = Functions::flattenSingleValue($complexNumber2);
-
- try {
- return (string) (new Complex($complexNumber1))->subtract(new Complex($complexNumber2));
- } catch (ComplexException $e) {
- return Functions::NAN();
- }
+ return ComplexOperations::IMSUB($complexNumber1, $complexNumber2);
}
/**
@@ -1473,26 +1071,17 @@ class Engineering
* Excel Function:
* IMSUM(complexNumber[,complexNumber[,...]])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMSUM() method in the Engineering\ComplexOperations class instead
+ *
* @param string ...$complexNumbers Series of complex numbers to add
*
* @return string
*/
public static function IMSUM(...$complexNumbers)
{
- // Return value
- $returnValue = new Complex(0.0);
- $aArgs = Functions::flattenArray($complexNumbers);
-
- try {
- // Loop through the arguments
- foreach ($aArgs as $complex) {
- $returnValue = $returnValue->add(new Complex($complex));
- }
- } catch (ComplexException $e) {
- return Functions::NAN();
- }
-
- return (string) $returnValue;
+ return ComplexOperations::IMSUM(...$complexNumbers);
}
/**
@@ -1503,50 +1092,42 @@ class Engineering
* Excel Function:
* IMPRODUCT(complexNumber[,complexNumber[,...]])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the IMPRODUCT() method in the Engineering\ComplexOperations class instead
+ *
* @param string ...$complexNumbers Series of complex numbers to multiply
*
* @return string
*/
public static function IMPRODUCT(...$complexNumbers)
{
- // Return value
- $returnValue = new Complex(1.0);
- $aArgs = Functions::flattenArray($complexNumbers);
-
- try {
- // Loop through the arguments
- foreach ($aArgs as $complex) {
- $returnValue = $returnValue->multiply(new Complex($complex));
- }
- } catch (ComplexException $e) {
- return Functions::NAN();
- }
-
- return (string) $returnValue;
+ 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.
+ * 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
+ *
+ * @see Use the DELTA() method in the Engineering\Compare class instead
+ *
* @param float $a the first number
* @param float $b The second number. If omitted, b is assumed to be zero.
*
- * @return int
+ * @return int|string (string in the event of an error)
*/
public static function DELTA($a, $b = 0)
{
- $a = Functions::flattenSingleValue($a);
- $b = Functions::flattenSingleValue($b);
-
- return (int) ($a == $b);
+ return Engineering\Compare::DELTA($a, $b);
}
/**
@@ -1557,77 +1138,20 @@ class Engineering
*
* 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.
+ * functions you calculate the count of values that exceed a threshold.
+ *
+ * @Deprecated 1.17.0
+ *
+ * @see Use the GESTEP() method in the Engineering\Compare class instead
*
* @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.
+ * @param float $step The threshold value. If you omit a value for step, GESTEP uses zero.
*
- * @return int
+ * @return int|string (string in the event of an error)
*/
public static function GESTEP($number, $step = 0)
{
- $number = Functions::flattenSingleValue($number);
- $step = Functions::flattenSingleValue($step);
-
- return (int) ($number >= $step);
- }
-
- //
- // Private method to calculate the erf value
- //
- private static $twoSqrtPi = 1.128379167095512574;
-
- public static function erfVal($x)
- {
- if (abs($x) > 2.2) {
- return 1 - self::erfcVal($x);
- }
- $sum = $term = $x;
- $xsqr = ($x * $x);
- $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::$twoSqrtPi * $sum;
- }
-
- /**
- * Validate arguments passed to the bitwise functions.
- *
- * @param mixed $value
- *
- * @return int
- */
- private static function validateBitwiseArgument($value)
- {
- $value = Functions::flattenSingleValue($value);
-
- if (is_int($value)) {
- return $value;
- } elseif (is_numeric($value)) {
- if ($value == (int) ($value)) {
- $value = (int) ($value);
- if (($value > 2 ** 48 - 1) || ($value < 0)) {
- throw new Exception(Functions::NAN());
- }
-
- return $value;
- }
-
- throw new Exception(Functions::NAN());
- }
-
- throw new Exception(Functions::VALUE());
+ return Engineering\Compare::GESTEP($number, $step);
}
/**
@@ -1638,6 +1162,10 @@ class Engineering
* Excel Function:
* BITAND(number1, number2)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the BITAND() method in the Engineering\BitWise class instead
+ *
* @param int $number1
* @param int $number2
*
@@ -1645,14 +1173,7 @@ class Engineering
*/
public static function BITAND($number1, $number2)
{
- try {
- $number1 = self::validateBitwiseArgument($number1);
- $number2 = self::validateBitwiseArgument($number2);
- } catch (Exception $e) {
- return $e->getMessage();
- }
-
- return $number1 & $number2;
+ return Engineering\BitWise::BITAND($number1, $number2);
}
/**
@@ -1663,6 +1184,10 @@ class Engineering
* Excel Function:
* BITOR(number1, number2)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the BITOR() method in the Engineering\BitWise class instead
+ *
* @param int $number1
* @param int $number2
*
@@ -1670,14 +1195,7 @@ class Engineering
*/
public static function BITOR($number1, $number2)
{
- try {
- $number1 = self::validateBitwiseArgument($number1);
- $number2 = self::validateBitwiseArgument($number2);
- } catch (Exception $e) {
- return $e->getMessage();
- }
-
- return $number1 | $number2;
+ return Engineering\BitWise::BITOR($number1, $number2);
}
/**
@@ -1688,6 +1206,10 @@ class Engineering
* Excel Function:
* BITXOR(number1, number2)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the BITXOR() method in the Engineering\BitWise class instead
+ *
* @param int $number1
* @param int $number2
*
@@ -1695,14 +1217,7 @@ class Engineering
*/
public static function BITXOR($number1, $number2)
{
- try {
- $number1 = self::validateBitwiseArgument($number1);
- $number2 = self::validateBitwiseArgument($number2);
- } catch (Exception $e) {
- return $e->getMessage();
- }
-
- return $number1 ^ $number2;
+ return Engineering\BitWise::BITXOR($number1, $number2);
}
/**
@@ -1713,6 +1228,10 @@ class Engineering
* Excel Function:
* BITLSHIFT(number, shift_amount)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the BITLSHIFT() method in the Engineering\BitWise class instead
+ *
* @param int $number
* @param int $shiftAmount
*
@@ -1720,20 +1239,7 @@ class Engineering
*/
public static function BITLSHIFT($number, $shiftAmount)
{
- try {
- $number = self::validateBitwiseArgument($number);
- } catch (Exception $e) {
- return $e->getMessage();
- }
-
- $shiftAmount = Functions::flattenSingleValue($shiftAmount);
-
- $result = $number << $shiftAmount;
- if ($result > 2 ** 48 - 1) {
- return Functions::NAN();
- }
-
- return $result;
+ return Engineering\BitWise::BITLSHIFT($number, $shiftAmount);
}
/**
@@ -1744,6 +1250,10 @@ class Engineering
* Excel Function:
* BITRSHIFT(number, shift_amount)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the BITRSHIFT() method in the Engineering\BitWise class instead
+ *
* @param int $number
* @param int $shiftAmount
*
@@ -1751,15 +1261,7 @@ class Engineering
*/
public static function BITRSHIFT($number, $shiftAmount)
{
- try {
- $number = self::validateBitwiseArgument($number);
- } catch (Exception $e) {
- return $e->getMessage();
- }
-
- $shiftAmount = Functions::flattenSingleValue($shiftAmount);
-
- return $number >> $shiftAmount;
+ return Engineering\BitWise::BITRSHIFT($number, $shiftAmount);
}
/**
@@ -1775,6 +1277,10 @@ class Engineering
* Excel Function:
* ERF(lower[,upper])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the ERF() method in the Engineering\Erf class instead
+ *
* @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
@@ -1783,19 +1289,7 @@ class Engineering
*/
public static function ERF($lower, $upper = null)
{
- $lower = Functions::flattenSingleValue($lower);
- $upper = Functions::flattenSingleValue($upper);
-
- if (is_numeric($lower)) {
- if ($upper === null) {
- return self::erfVal($lower);
- }
- if (is_numeric($upper)) {
- return self::erfVal($upper) - self::erfVal($lower);
- }
- }
-
- return Functions::VALUE();
+ return Engineering\Erf::ERF($lower, $upper);
}
/**
@@ -1806,48 +1300,17 @@ class Engineering
* Excel Function:
* ERF.PRECISE(limit)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the ERFPRECISE() method in the Engineering\Erf class instead
+ *
* @param float $limit bound for integrating ERF
*
* @return float|string
*/
public static function ERFPRECISE($limit)
{
- $limit = Functions::flattenSingleValue($limit);
-
- return self::ERF($limit);
- }
-
- //
- // Private method to calculate the erfc value
- //
- private static $oneSqrtPi = 0.564189583547756287;
-
- private static function erfcVal($x)
- {
- if (abs($x) < 2.2) {
- return 1 - self::erfVal($x);
- }
- if ($x < 0) {
- return 2 - self::ERFC(-$x);
- }
- $a = $n = 1;
- $b = $c = $x;
- $d = ($x * $x) + 0.5;
- $q1 = $q2 = $b / $d;
- $t = 0;
- do {
- $t = $a * $n + $b * $x;
- $a = $b;
- $b = $t;
- $t = $c * $n + $d * $x;
- $c = $d;
- $d = $t;
- $n += 0.5;
- $q1 = $q2;
- $q2 = $b / $d;
- } while ((abs($q1 - $q2) / $q2) > Functions::PRECISION);
-
- return self::$oneSqrtPi * exp(-$x * $x) * $q2;
+ return Engineering\Erf::ERFPRECISE($limit);
}
/**
@@ -1863,26 +1326,26 @@ class Engineering
* Excel Function:
* ERFC(x)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Use the ERFC() method in the Engineering\ErfC class instead
+ *
* @param float $x The lower bound for integrating ERFC
*
* @return float|string
*/
public static function ERFC($x)
{
- $x = Functions::flattenSingleValue($x);
-
- if (is_numeric($x)) {
- return self::erfcVal($x);
- }
-
- return Functions::VALUE();
+ return Engineering\ErfC::ERFC($x);
}
/**
* getConversionGroups
* Returns a list of the different conversion groups for UOM conversions.
*
- * @Deprecated Use the getConversionCategories() method in the ConvertUOM class instead
+ * @Deprecated 1.16.0
+ *
+ * @see Use the getConversionCategories() method in the Engineering\ConvertUOM class instead
*
* @return array
*/
@@ -1895,7 +1358,9 @@ class Engineering
* getConversionGroupUnits
* Returns an array of units of measure, for a specified conversion group, or for all groups.
*
- * @Deprecated Use the getConversionCategoryUnits() method in the ConvertUOM class instead
+ * @Deprecated 1.16.0
+ *
+ * @see Use the getConversionCategoryUnits() method in the ConvertUOM class instead
*
* @param null|mixed $category
*
@@ -1909,7 +1374,9 @@ class Engineering
/**
* getConversionGroupUnitDetails.
*
- * @Deprecated Use the getConversionCategoryUnitDetails() method in the ConvertUOM class instead
+ * @Deprecated 1.16.0
+ *
+ * @see Use the getConversionCategoryUnitDetails() method in the ConvertUOM class instead
*
* @param null|mixed $category
*
@@ -1924,9 +1391,11 @@ class Engineering
* getConversionMultipliers
* Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM().
*
- * @Deprecated Use the getConversionMultipliers() method in the ConvertUOM class instead
+ * @Deprecated 1.16.0
*
- * @return array of mixed
+ * @see Use the getConversionMultipliers() method in the ConvertUOM class instead
+ *
+ * @return mixed[]
*/
public static function getConversionMultipliers()
{
@@ -1934,12 +1403,16 @@ class Engineering
}
/**
- * getBinaryConversionMultipliers
- * Returns an array of the additional Multiplier prefixes that can be used with Information Units of Measure in CONVERTUOM().
+ * getBinaryConversionMultipliers.
*
- * @Deprecated Use the getBinaryConversionMultipliers() method in the ConvertUOM class instead
+ * Returns an array of the additional Multiplier prefixes that can be used with Information Units of Measure
+ * in CONVERTUOM().
*
- * @return array of mixed
+ * @Deprecated 1.16.0
+ *
+ * @see Use the getBinaryConversionMultipliers() method in the ConvertUOM class instead
+ *
+ * @return mixed[]
*/
public static function getBinaryConversionMultipliers()
{
@@ -1956,7 +1429,9 @@ class Engineering
* Excel Function:
* CONVERT(value,fromUOM,toUOM)
*
- * @Deprecated Use the CONVERT() method in the ConvertUOM class instead
+ * @Deprecated 1.16.0
+ *
+ * @see Use the CONVERT() method in the ConvertUOM class instead
*
* @param float|int $value the value in fromUOM to convert
* @param string $fromUOM the units for value
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselI.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselI.php
new file mode 100644
index 00000000000..ea2577cdf85
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselI.php
@@ -0,0 +1,137 @@
+getMessage();
+ }
+
+ if ($ord < 0) {
+ return Functions::NAN();
+ }
+
+ $fResult = self::calculate($x, $ord);
+
+ return (is_nan($fResult)) ? Functions::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;
+ }
+
+ private static function besselI2(float $x, int $ord): float
+ {
+ if ($x === 0.0) {
+ 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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php
new file mode 100644
index 00000000000..7ea45a74fff
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php
@@ -0,0 +1,172 @@
+ 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.
+ * @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.
+ *
+ * @return float|string Result, or a string containing an error
+ */
+ public static function BESSELJ($x, $ord)
+ {
+ $x = Functions::flattenSingleValue($x);
+ $ord = Functions::flattenSingleValue($ord);
+
+ try {
+ $x = EngineeringValidations::validateFloat($x);
+ $ord = EngineeringValidations::validateInt($ord);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if ($ord < 0) {
+ return Functions::NAN();
+ }
+
+ $fResult = self::calculate($x, $ord);
+
+ return (is_nan($fResult)) ? Functions::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)
+ {
+ $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)
+ {
+ $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;
+ if ($j === $ord) {
+ $ans = $bjp;
+ }
+ }
+ $sum = 2.0 * $sum - $bj;
+ $ans /= $sum;
+
+ return ($x < 0.0 && ($ord % 2) === 1) ? -$ans : $ans;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselK.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselK.php
new file mode 100644
index 00000000000..8facdffc79f
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselK.php
@@ -0,0 +1,111 @@
+getMessage();
+ }
+
+ if (($ord < 0) || ($x <= 0.0)) {
+ return Functions::NAN();
+ }
+
+ $fBk = self::calculate($x, $ord);
+
+ return (is_nan($fBk)) ? Functions::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);
+ }
+
+ private static function besselK0(float $x): float
+ {
+ if ($x <= 2) {
+ $fNum2 = $x * 0.5;
+ $y = ($fNum2 * $fNum2);
+
+ return -log($fNum2) * BesselI::BESSELI($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) * BesselI::BESSELI($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)
+ {
+ $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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselY.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselY.php
new file mode 100644
index 00000000000..7f387497169
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselY.php
@@ -0,0 +1,118 @@
+getMessage();
+ }
+
+ if (($ord < 0) || ($x <= 0.0)) {
+ return Functions::NAN();
+ }
+
+ $fBy = self::calculate($x, $ord);
+
+ return (is_nan($fBy)) ? Functions::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);
+ }
+
+ 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 * BesselJ::BESSELJ($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 * (BesselJ::BESSELJ($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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BitWise.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BitWise.php
new file mode 100644
index 00000000000..9958f054f2d
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BitWise.php
@@ -0,0 +1,227 @@
+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 int $number1
+ * @param int $number2
+ *
+ * @return int|string
+ */
+ public static function BITOR($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 int $number1
+ * @param int $number2
+ *
+ * @return int|string
+ */
+ public static function BITXOR($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 int $number
+ * @param int $shiftAmount
+ *
+ * @return float|int|string
+ */
+ public static function BITLSHIFT($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 Functions::NAN();
+ }
+
+ return $result;
+ }
+
+ /**
+ * BITRSHIFT.
+ *
+ * Returns the number value shifted right by shift_amount bits.
+ *
+ * Excel Function:
+ * BITRSHIFT(number, shift_amount)
+ *
+ * @param int $number
+ * @param int $shiftAmount
+ *
+ * @return float|int|string
+ */
+ public static function BITRSHIFT($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 Functions::NAN();
+ }
+
+ return $result;
+ }
+
+ /**
+ * Validate arguments passed to the bitwise functions.
+ *
+ * @param mixed $value
+ *
+ * @return float|int
+ */
+ private static function validateBitwiseArgument($value)
+ {
+ self::nullFalseTrueToNumber($value);
+
+ if (is_numeric($value)) {
+ if ($value == floor($value)) {
+ if (($value > 2 ** 48 - 1) || ($value < 0)) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return floor($value);
+ }
+
+ throw new Exception(Functions::NAN());
+ }
+
+ throw new Exception(Functions::VALUE());
+ }
+
+ /**
+ * Validate arguments passed to the bitwise functions.
+ *
+ * @param mixed $value
+ *
+ * @return int
+ */
+ private static function validateShiftAmount($value)
+ {
+ self::nullFalseTrueToNumber($value);
+
+ if (is_numeric($value)) {
+ if (abs($value) > 53) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return (int) $value;
+ }
+
+ throw new Exception(Functions::VALUE());
+ }
+
+ /**
+ * Many functions accept null/false/true argument treated as 0/0/1.
+ *
+ * @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;
+ }
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Compare.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Compare.php
new file mode 100644
index 00000000000..0a6342069c9
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Compare.php
@@ -0,0 +1,70 @@
+getMessage();
+ }
+
+ return (int) ($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.
+ *
+ * @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 int|string (string in the event of an error)
+ */
+ public static function GESTEP($number, $step = 0)
+ {
+ $number = Functions::flattenSingleValue($number);
+ $step = Functions::flattenSingleValue($step);
+
+ try {
+ $number = EngineeringValidations::validateFloat($number);
+ $step = EngineeringValidations::validateFloat($step);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return (int) ($number >= $step);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Complex.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Complex.php
new file mode 100644
index 00000000000..1c2f5f773ac
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Complex.php
@@ -0,0 +1,99 @@
+getMessage();
+ }
+
+ if (($suffix == 'i') || ($suffix == 'j') || ($suffix == '')) {
+ $complex = new ComplexObject($realNumber, $imaginary, $suffix);
+
+ return (string) $complex;
+ }
+
+ return Functions::VALUE();
+ }
+
+ /**
+ * IMAGINARY.
+ *
+ * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMAGINARY(complexNumber)
+ *
+ * @param string $complexNumber the complex number for which you want the imaginary
+ * coefficient
+ *
+ * @return float|string
+ */
+ public static function IMAGINARY($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the real coefficient
+ *
+ * @return float|string
+ */
+ public static function IMREAL($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::NAN();
+ }
+
+ return $complex->getReal();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php
new file mode 100644
index 00000000000..3f37f373ff7
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php
@@ -0,0 +1,513 @@
+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 string $complexNumber the complex number for which you want the argument theta
+ *
+ * @return float|string
+ */
+ public static function IMARGUMENT($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::NAN();
+ }
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ return Functions::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 string $complexNumber the complex number for which you want the conjugate
+ *
+ * @return string
+ */
+ public static function IMCONJUGATE($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the cosine
+ *
+ * @return float|string
+ */
+ public static function IMCOS($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the hyperbolic cosine
+ *
+ * @return float|string
+ */
+ public static function IMCOSH($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the cotangent
+ *
+ * @return float|string
+ */
+ public static function IMCOT($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the cosecant
+ *
+ * @return float|string
+ */
+ public static function IMCSC($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the hyperbolic cosecant
+ *
+ * @return float|string
+ */
+ public static function IMCSCH($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the sine
+ *
+ * @return float|string
+ */
+ public static function IMSIN($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the hyperbolic sine
+ *
+ * @return float|string
+ */
+ public static function IMSINH($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the secant
+ *
+ * @return float|string
+ */
+ public static function IMSEC($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the hyperbolic secant
+ *
+ * @return float|string
+ */
+ public static function IMSECH($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the tangent
+ *
+ * @return float|string
+ */
+ public static function IMTAN($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 string $complexNumber the complex number for which you want the square root
+ *
+ * @return string
+ */
+ public static function IMSQRT($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::NAN();
+ }
+
+ $theta = self::IMARGUMENT($complexNumber);
+ if ($theta === Functions::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 string $complexNumber the complex number for which you want the natural logarithm
+ *
+ * @return string
+ */
+ public static function IMLN($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::NAN();
+ }
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ return Functions::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 string $complexNumber the complex number for which you want the common logarithm
+ *
+ * @return string
+ */
+ public static function IMLOG10($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::NAN();
+ }
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ return Functions::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 string $complexNumber the complex number for which you want the base-2 logarithm
+ *
+ * @return string
+ */
+ public static function IMLOG2($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::NAN();
+ }
+
+ if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
+ return Functions::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 string $complexNumber the complex number for which you want the exponential
+ *
+ * @return string
+ */
+ public static function IMEXP($complexNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::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 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 string
+ */
+ public static function IMPOWER($complexNumber, $realNumber)
+ {
+ $complexNumber = Functions::flattenSingleValue($complexNumber);
+ $realNumber = Functions::flattenSingleValue($realNumber);
+
+ try {
+ $complex = new ComplexObject($complexNumber);
+ } catch (ComplexException $e) {
+ return Functions::NAN();
+ }
+
+ if (!is_numeric($realNumber)) {
+ return Functions::VALUE();
+ }
+
+ return (string) $complex->pow($realNumber);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php
new file mode 100644
index 00000000000..681aad8cafe
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php
@@ -0,0 +1,120 @@
+divideby(new ComplexObject($complexDivisor));
+ } catch (ComplexException $e) {
+ return Functions::NAN();
+ }
+ }
+
+ /**
+ * IMSUB.
+ *
+ * Returns the difference of two complex numbers in x + yi or x + yj text format.
+ *
+ * Excel Function:
+ * IMSUB(complexNumber1,complexNumber2)
+ *
+ * @param string $complexNumber1 the complex number from which to subtract complexNumber2
+ * @param string $complexNumber2 the complex number to subtract from complexNumber1
+ *
+ * @return string
+ */
+ public static function IMSUB($complexNumber1, $complexNumber2)
+ {
+ $complexNumber1 = Functions::flattenSingleValue($complexNumber1);
+ $complexNumber2 = Functions::flattenSingleValue($complexNumber2);
+
+ try {
+ return (string) (new ComplexObject($complexNumber1))->subtract(new ComplexObject($complexNumber2));
+ } catch (ComplexException $e) {
+ return Functions::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 Functions::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 Functions::NAN();
+ }
+
+ return (string) $returnValue;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Constants.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Constants.php
new file mode 100644
index 00000000000..a926db6e1cd
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Constants.php
@@ -0,0 +1,11 @@
+ 10) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return (int) $places;
+ }
+
+ throw new Exception(Functions::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 Functions::NAN();
+ }
+
+ return substr($value, -10);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php
new file mode 100644
index 00000000000..a662b78de30
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php
@@ -0,0 +1,134 @@
+getMessage();
+ }
+
+ if (strlen($value) == 10) {
+ // 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 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.
+ * @param 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.
+ */
+ public static function toHex($value, $places = null): string
+ {
+ try {
+ $value = self::validateValue(Functions::flattenSingleValue($value));
+ $value = self::validateBinary($value);
+ $places = self::validatePlaces(Functions::flattenSingleValue($places));
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if (strlen($value) == 10) {
+ $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 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.
+ * @param 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.
+ */
+ public static function toOctal($value, $places = null): string
+ {
+ try {
+ $value = self::validateValue(Functions::flattenSingleValue($value));
+ $value = self::validateBinary($value);
+ $places = self::validatePlaces(Functions::flattenSingleValue($places));
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if (strlen($value) == 10 && substr($value, 0, 1) === '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(Functions::NAN());
+ }
+
+ return $value;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php
new file mode 100644
index 00000000000..a34332fb353
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php
@@ -0,0 +1,183 @@
+ 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 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.
+ */
+ public static function toBinary($value, $places = null): string
+ {
+ try {
+ $value = self::validateValue(Functions::flattenSingleValue($value));
+ $value = self::validateDecimal($value);
+ $places = self::validatePlaces(Functions::flattenSingleValue($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 Functions::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 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.
+ * @param 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.
+ */
+ public static function toHex($value, $places = null): string
+ {
+ try {
+ $value = self::validateValue(Functions::flattenSingleValue($value));
+ $value = self::validateDecimal($value);
+ $places = self::validatePlaces(Functions::flattenSingleValue($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 Functions::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 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.
+ * @param 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.
+ */
+ public static function toOctal($value, $places = null): string
+ {
+ try {
+ $value = self::validateValue(Functions::flattenSingleValue($value));
+ $value = self::validateDecimal($value);
+ $places = self::validatePlaces(Functions::flattenSingleValue($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 Functions::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(Functions::VALUE());
+ }
+
+ return $value;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php
new file mode 100644
index 00000000000..de1b0704f78
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php
@@ -0,0 +1,146 @@
+getMessage();
+ }
+
+ $dec = self::toDecimal($value);
+
+ return ConvertDecimal::toBinary($dec, $places);
+ }
+
+ /**
+ * toDecimal.
+ *
+ * Return a hex value as decimal.
+ *
+ * Excel Function:
+ * HEX2DEC(x)
+ *
+ * @param 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.
+ */
+ public static function toDecimal($value): string
+ {
+ try {
+ $value = self::validateValue(Functions::flattenSingleValue($value));
+ $value = self::validateHex($value);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if (strlen($value) > 10) {
+ return Functions::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 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.
+ * @param 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.
+ */
+ public static function toOctal($value, $places = null): string
+ {
+ try {
+ $value = self::validateValue(Functions::flattenSingleValue($value));
+ $value = self::validateHex($value);
+ $places = self::validatePlaces(Functions::flattenSingleValue($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(Functions::NAN());
+ }
+
+ return $value;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php
new file mode 100644
index 00000000000..1181e2ee191
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php
@@ -0,0 +1,145 @@
+getMessage();
+ }
+
+ return ConvertDecimal::toBinary(self::toDecimal($value), $places);
+ }
+
+ /**
+ * toDecimal.
+ *
+ * Return an octal value as decimal.
+ *
+ * Excel Function:
+ * OCT2DEC(x)
+ *
+ * @param 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.
+ */
+ public static function toDecimal($value): string
+ {
+ try {
+ $value = self::validateValue(Functions::flattenSingleValue($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 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.
+ * @param 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.
+ */
+ public static function toHex($value, $places = null): string
+ {
+ try {
+ $value = self::validateValue(Functions::flattenSingleValue($value));
+ $value = self::validateOctal($value);
+ $places = self::validatePlaces(Functions::flattenSingleValue($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(Functions::NAN());
+ }
+
+ return $value;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php
index 0aafe05ec3a..d169ae54bb0 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php
@@ -490,7 +490,7 @@ class ConvertUOM
* getConversionMultipliers
* Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM().
*
- * @return array of mixed
+ * @return mixed[]
*/
public static function getConversionMultipliers()
{
@@ -501,7 +501,7 @@ class ConvertUOM
* getBinaryConversionMultipliers
* Returns an array of the additional Multiplier prefixes that can be used with Information Units of Measure in CONVERTUOM().
*
- * @return array of mixed
+ * @return mixed[]
*/
public static function getBinaryConversionMultipliers()
{
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php
new file mode 100644
index 00000000000..01630af3412
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php
@@ -0,0 +1,33 @@
+ 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::$twoSqrtPi * $sum;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ErfC.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ErfC.php
new file mode 100644
index 00000000000..c57a28f490c
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ErfC.php
@@ -0,0 +1,68 @@
+ Functions::PRECISION);
+
+ return self::$oneSqrtPi * exp(-$value * $value) * $q2;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial.php
index 5a908aa5136..9d933b4a921 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial.php
@@ -2,167 +2,81 @@
namespace PhpOffice\PhpSpreadsheet\Calculation;
-use PhpOffice\PhpSpreadsheet\Shared\Date;
+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;
- /**
- * isLastDayOfMonth.
- *
- * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month
- *
- * @param \DateTime $testDate The date for testing
- *
- * @return bool
- */
- private static function isLastDayOfMonth(\DateTime $testDate)
- {
- return $testDate->format('d') == $testDate->format('t');
- }
-
- private static function couponFirstPeriodDate($settlement, $maturity, $frequency, $next)
- {
- $months = 12 / $frequency;
-
- $result = Date::excelToDateTimeObject($maturity);
- $eom = self::isLastDayOfMonth($result);
-
- while ($settlement < Date::PHPToExcel($result)) {
- $result->modify('-' . $months . ' months');
- }
- if ($next) {
- $result->modify('+' . $months . ' months');
- }
-
- if ($eom) {
- $result->modify('-1 day');
- }
-
- return Date::PHPToExcel($result);
- }
-
- private static function isValidFrequency($frequency)
- {
- if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) {
- return true;
- }
-
- return false;
- }
-
- /**
- * 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
- */
- private static function daysPerYear($year, $basis = 0)
- {
- switch ($basis) {
- case 0:
- case 2:
- case 4:
- $daysPerYear = 360;
-
- break;
- case 3:
- $daysPerYear = 365;
-
- break;
- case 1:
- $daysPerYear = (DateTime::isLeapYear($year)) ? 366 : 365;
-
- break;
- default:
- return Functions::NAN();
- }
-
- return $daysPerYear;
- }
-
- private static function interestAndPrincipal($rate = 0, $per = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0)
- {
- $pmt = self::PMT($rate, $nper, $pv, $fv, $type);
- $capital = $pv;
- for ($i = 1; $i <= $per; ++$i) {
- $interest = ($type && $i == 1) ? 0 : -$capital * $rate;
- $principal = $pmt - $interest;
- $capital += $principal;
- }
-
- return [$interest, $principal];
- }
-
/**
* ACCRINT.
*
* Returns the accrued interest for a security that pays periodic interest.
*
* Excel Function:
- * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis])
+ * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis][,calc_method])
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Securities\AccruedInterest::periodic()
+ * Use the periodic() method in the Financial\Securities\AccruedInterest class instead
*
* @param mixed $issue the security's issue date
- * @param mixed $firstinterest the security's first interest 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 float $rate the security's annual coupon rate
- * @param float $par The security's par value.
- * If you omit par, ACCRINT uses $1,000.
- * @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
+ * 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, $par = 1000, $frequency = 1, $basis = 0)
- {
- $issue = Functions::flattenSingleValue($issue);
- $firstinterest = Functions::flattenSingleValue($firstinterest);
- $settlement = Functions::flattenSingleValue($settlement);
- $rate = Functions::flattenSingleValue($rate);
- $par = ($par === null) ? 1000 : Functions::flattenSingleValue($par);
- $frequency = ($frequency === null) ? 1 : Functions::flattenSingleValue($frequency);
- $basis = ($basis === null) ? 0 : Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($rate)) && (is_numeric($par))) {
- $rate = (float) $rate;
- $par = (float) $par;
- if (($rate <= 0) || ($par <= 0)) {
- return Functions::NAN();
- }
- $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
-
- return $par * $rate * $daysBetweenIssueAndSettlement;
- }
-
- return Functions::VALUE();
+ 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
+ );
}
/**
@@ -173,45 +87,28 @@ class Financial
* Excel Function:
* ACCRINTM(issue,settlement,rate[,par[,basis]])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Securities\AccruedInterest::atMaturity()
+ * Use the atMaturity() method in the Financial\Securities\AccruedInterest class instead
+ *
* @param mixed $issue The security's issue date
* @param mixed $settlement The security's settlement (or maturity) date
- * @param float $rate The security's annual coupon rate
- * @param float $par The security's par value.
- * If you omit par, ACCRINT uses $1,000.
- * @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
+ * @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, $par = 1000, $basis = 0)
+ public static function ACCRINTM($issue, $settlement, $rate, $parValue = 1000, $basis = 0)
{
- $issue = Functions::flattenSingleValue($issue);
- $settlement = Functions::flattenSingleValue($settlement);
- $rate = Functions::flattenSingleValue($rate);
- $par = ($par === null) ? 1000 : Functions::flattenSingleValue($par);
- $basis = ($basis === null) ? 0 : Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($rate)) && (is_numeric($par))) {
- $rate = (float) $rate;
- $par = (float) $par;
- if (($rate <= 0) || ($par <= 0)) {
- return Functions::NAN();
- }
- $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
-
- return $par * $rate * $daysBetweenIssueAndSettlement;
- }
-
- return Functions::VALUE();
+ return Securities\AccruedInterest::atMaturity($issue, $settlement, $rate, $parValue, $basis);
}
/**
@@ -229,6 +126,11 @@ class Financial
* Excel Function:
* AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Amortization::AMORDEGRC()
+ * Use the AMORDEGRC() method in the Financial\Amortization class instead
+ *
* @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
@@ -236,63 +138,17 @@ class Financial
* @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
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
*
- * @return float
+ * @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)
{
- $cost = Functions::flattenSingleValue($cost);
- $purchased = Functions::flattenSingleValue($purchased);
- $firstPeriod = Functions::flattenSingleValue($firstPeriod);
- $salvage = Functions::flattenSingleValue($salvage);
- $period = floor(Functions::flattenSingleValue($period));
- $rate = Functions::flattenSingleValue($rate);
- $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis);
-
- // 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) {
- $amortiseCoeff = 1.0;
- } elseif ($fUsePer < 5.0) {
- $amortiseCoeff = 1.5;
- } elseif ($fUsePer <= 6.0) {
- $amortiseCoeff = 2.0;
- } else {
- $amortiseCoeff = 2.5;
- }
-
- $rate *= $amortiseCoeff;
- $fNRate = round(DateTime::YEARFRAC($purchased, $firstPeriod, $basis) * $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;
+ return Amortization::AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis);
}
/**
@@ -305,6 +161,11 @@ class Financial
* Excel Function:
* AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Amortization::AMORLINC()
+ * Use the AMORLINC() method in the Financial\Amortization class instead
+ *
* @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
@@ -312,46 +173,17 @@ class Financial
* @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
+ * 0 or omitted US (NASD) 30/360
+ * 1 Actual/actual
+ * 2 Actual/360
+ * 3 Actual/365
+ * 4 European 30/360
*
- * @return float
+ * @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)
{
- $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) ? 0 : (int) Functions::flattenSingleValue($basis);
-
- $fOneRate = $cost * $rate;
- $fCostDelta = $cost - $salvage;
- // Note, quirky variation for leap years on the YEARFRAC for this function
- $purchasedYear = DateTime::YEAR($purchased);
- $yearFrac = DateTime::YEARFRAC($purchased, $firstPeriod, $basis);
-
- if (($basis == 1) && ($yearFrac < 1) && (DateTime::isLeapYear($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;
+ return Amortization::AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis);
}
/**
@@ -362,6 +194,11 @@ class Financial
* Excel Function:
* COUPDAYBS(settlement,maturity,frequency[,basis])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Coupons::COUPDAYBS()
+ * Use the COUPDAYBS() method in the Financial\Coupons class instead
+ *
* @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.
@@ -383,34 +220,7 @@ class Financial
*/
public static function COUPDAYBS($settlement, $maturity, $frequency, $basis = 0)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $frequency = (int) Functions::flattenSingleValue($frequency);
- $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = DateTime::getDateValue($settlement))) {
- return Functions::VALUE();
- }
- if (is_string($maturity = DateTime::getDateValue($maturity))) {
- return Functions::VALUE();
- }
-
- if (
- ($settlement >= $maturity) ||
- (!self::isValidFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))
- ) {
- return Functions::NAN();
- }
-
- $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis);
- $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false);
-
- if ($basis == 1) {
- return abs(DateTime::DAYS($prev, $settlement));
- }
-
- return DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear;
+ return Coupons::COUPDAYBS($settlement, $maturity, $frequency, $basis);
}
/**
@@ -421,6 +231,11 @@ class Financial
* Excel Function:
* COUPDAYS(settlement,maturity,frequency[,basis])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Coupons::COUPDAYS()
+ * Use the COUPDAYS() method in the Financial\Coupons class instead
+ *
* @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.
@@ -442,45 +257,7 @@ class Financial
*/
public static function COUPDAYS($settlement, $maturity, $frequency, $basis = 0)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $frequency = (int) Functions::flattenSingleValue($frequency);
- $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = DateTime::getDateValue($settlement))) {
- return Functions::VALUE();
- }
- if (is_string($maturity = DateTime::getDateValue($maturity))) {
- return Functions::VALUE();
- }
-
- if (
- ($settlement >= $maturity) ||
- (!self::isValidFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))
- ) {
- return Functions::NAN();
- }
-
- switch ($basis) {
- case 3:
- // Actual/365
- return 365 / $frequency;
- case 1:
- // Actual/actual
- if ($frequency == 1) {
- $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis);
-
- return $daysPerYear / $frequency;
- }
- $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false);
- $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true);
-
- return $next - $prev;
- default:
- // US (NASD) 30/360, Actual/360 or European 30/360
- return 360 / $frequency;
- }
+ return Coupons::COUPDAYS($settlement, $maturity, $frequency, $basis);
}
/**
@@ -491,6 +268,11 @@ class Financial
* Excel Function:
* COUPDAYSNC(settlement,maturity,frequency[,basis])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Coupons::COUPDAYSNC()
+ * Use the COUPDAYSNC() method in the Financial\Coupons class instead
+ *
* @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.
@@ -512,30 +294,7 @@ class Financial
*/
public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis = 0)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $frequency = (int) Functions::flattenSingleValue($frequency);
- $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = DateTime::getDateValue($settlement))) {
- return Functions::VALUE();
- }
- if (is_string($maturity = DateTime::getDateValue($maturity))) {
- return Functions::VALUE();
- }
-
- if (
- ($settlement >= $maturity) ||
- (!self::isValidFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))
- ) {
- return Functions::NAN();
- }
-
- $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis);
- $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true);
-
- return DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear;
+ return Coupons::COUPDAYSNC($settlement, $maturity, $frequency, $basis);
}
/**
@@ -546,6 +305,11 @@ class Financial
* Excel Function:
* COUPNCD(settlement,maturity,frequency[,basis])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Coupons::COUPNCD()
+ * Use the COUPNCD() method in the Financial\Coupons class instead
+ *
* @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.
@@ -568,27 +332,7 @@ class Financial
*/
public static function COUPNCD($settlement, $maturity, $frequency, $basis = 0)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $frequency = (int) Functions::flattenSingleValue($frequency);
- $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = DateTime::getDateValue($settlement))) {
- return Functions::VALUE();
- }
- if (is_string($maturity = DateTime::getDateValue($maturity))) {
- return Functions::VALUE();
- }
-
- if (
- ($settlement >= $maturity) ||
- (!self::isValidFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))
- ) {
- return Functions::NAN();
- }
-
- return self::couponFirstPeriodDate($settlement, $maturity, $frequency, true);
+ return Coupons::COUPNCD($settlement, $maturity, $frequency, $basis);
}
/**
@@ -600,6 +344,11 @@ class Financial
* Excel Function:
* COUPNUM(settlement,maturity,frequency[,basis])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Coupons::COUPNUM()
+ * Use the COUPNUM() method in the Financial\Coupons class instead
+ *
* @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.
@@ -621,29 +370,7 @@ class Financial
*/
public static function COUPNUM($settlement, $maturity, $frequency, $basis = 0)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $frequency = (int) Functions::flattenSingleValue($frequency);
- $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = DateTime::getDateValue($settlement))) {
- return Functions::VALUE();
- }
- if (is_string($maturity = DateTime::getDateValue($maturity))) {
- return Functions::VALUE();
- }
-
- if (
- ($settlement >= $maturity) ||
- (!self::isValidFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))
- ) {
- return Functions::NAN();
- }
-
- $yearsBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, 0);
-
- return ceil($yearsBetweenSettlementAndMaturity * $frequency);
+ return Coupons::COUPNUM($settlement, $maturity, $frequency, $basis);
}
/**
@@ -654,6 +381,11 @@ class Financial
* Excel Function:
* COUPPCD(settlement,maturity,frequency[,basis])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Coupons::COUPPCD()
+ * Use the COUPPCD() method in the Financial\Coupons class instead
+ *
* @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.
@@ -676,27 +408,7 @@ class Financial
*/
public static function COUPPCD($settlement, $maturity, $frequency, $basis = 0)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $frequency = (int) Functions::flattenSingleValue($frequency);
- $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis);
-
- if (is_string($settlement = DateTime::getDateValue($settlement))) {
- return Functions::VALUE();
- }
- if (is_string($maturity = DateTime::getDateValue($maturity))) {
- return Functions::VALUE();
- }
-
- if (
- ($settlement >= $maturity) ||
- (!self::isValidFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))
- ) {
- return Functions::NAN();
- }
-
- return self::couponFirstPeriodDate($settlement, $maturity, $frequency, false);
+ return Coupons::COUPPCD($settlement, $maturity, $frequency, $basis);
}
/**
@@ -707,42 +419,26 @@ class Financial
* Excel Function:
* CUMIPMT(rate,nper,pv,start,end[,type])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Constant\Periodic\Cumulative::interest()
+ * Use the interest() method in the Financial\CashFlow\Constant\Periodic\Cumulative class instead
+ *
* @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.
+ * 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.
+ * 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)
{
- $rate = Functions::flattenSingleValue($rate);
- $nper = (int) Functions::flattenSingleValue($nper);
- $pv = Functions::flattenSingleValue($pv);
- $start = (int) Functions::flattenSingleValue($start);
- $end = (int) Functions::flattenSingleValue($end);
- $type = (int) Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Functions::NAN();
- }
- if ($start < 1 || $start > $end) {
- return Functions::VALUE();
- }
-
- // Calculate
- $interest = 0;
- for ($per = $start; $per <= $end; ++$per) {
- $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type);
- }
-
- return $interest;
+ return Financial\CashFlow\Constant\Periodic\Cumulative::interest($rate, $nper, $pv, $start, $end, $type);
}
/**
@@ -753,42 +449,26 @@ class Financial
* Excel Function:
* CUMPRINC(rate,nper,pv,start,end[,type])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Constant\Periodic\Cumulative::principal()
+ * Use the principal() method in the Financial\CashFlow\Constant\Periodic\Cumulative class instead
+ *
* @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.
+ * 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.
+ * 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)
{
- $rate = Functions::flattenSingleValue($rate);
- $nper = (int) Functions::flattenSingleValue($nper);
- $pv = Functions::flattenSingleValue($pv);
- $start = (int) Functions::flattenSingleValue($start);
- $end = (int) Functions::flattenSingleValue($end);
- $type = (int) Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Functions::NAN();
- }
- if ($start < 1 || $start > $end) {
- return Functions::VALUE();
- }
-
- // Calculate
- $principal = 0;
- for ($per = $start; $per <= $end; ++$per) {
- $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type);
- }
-
- return $principal;
+ return Financial\CashFlow\Constant\Periodic\Cumulative::principal($rate, $nper, $pv, $start, $end, $type);
}
/**
@@ -804,6 +484,11 @@ class Financial
* Excel Function:
* DB(cost,salvage,life,period[,month])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Depreciation::DB()
+ * Use the DB() method in the Financial\Depreciation class instead
+ *
* @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)
@@ -818,46 +503,7 @@ class Financial
*/
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);
-
- // Validate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) {
- $cost = (float) $cost;
- $salvage = (float) $salvage;
- $life = (int) $life;
- $period = (int) $period;
- $month = (int) $month;
- if ($cost == 0) {
- return 0.0;
- } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) {
- return Functions::NAN();
- }
- // Set Fixed Depreciation Rate
- $fixedDepreciationRate = 1 - ($salvage / $cost) ** (1 / $life);
- $fixedDepreciationRate = round($fixedDepreciationRate, 3);
-
- // Loop through each period calculating the depreciation
- $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;
- }
-
- return Functions::VALUE();
+ return Depreciation::DB($cost, $salvage, $life, $period, $month);
}
/**
@@ -869,6 +515,11 @@ class Financial
* Excel Function:
* DDB(cost,salvage,life,period[,factor])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Depreciation::DDB()
+ * Use the DDB() method in the Financial\Depreciation class instead
+ *
* @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)
@@ -884,38 +535,7 @@ class Financial
*/
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);
-
- // Validate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) {
- $cost = (float) $cost;
- $salvage = (float) $salvage;
- $life = (int) $life;
- $period = (int) $period;
- $factor = (float) $factor;
- if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) {
- return Functions::NAN();
- }
- // Set Fixed Depreciation Rate
- $fixedDepreciationRate = 1 - ($salvage / $cost) ** (1 / $life);
- $fixedDepreciationRate = round($fixedDepreciationRate, 3);
-
- // Loop through each period calculating the depreciation
- $previousDepreciation = 0;
- $depreciation = 0;
- for ($per = 1; $per <= $period; ++$per) {
- $depreciation = min(($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation));
- $previousDepreciation += $depreciation;
- }
-
- return $depreciation;
- }
-
- return Functions::VALUE();
+ return Depreciation::DDB($cost, $salvage, $life, $period, $factor);
}
/**
@@ -926,6 +546,11 @@ class Financial
* Excel Function:
* DISC(settlement,maturity,price,redemption[,basis])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Securities\Rates::discount()
+ * Use the discount() method in the Financial\Securities\Rates class instead
+ *
* @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.
@@ -944,30 +569,7 @@ class Financial
*/
public static function DISC($settlement, $maturity, $price, $redemption, $basis = 0)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $price = Functions::flattenSingleValue($price);
- $redemption = Functions::flattenSingleValue($redemption);
- $basis = Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) {
- $price = (float) $price;
- $redemption = (float) $redemption;
- $basis = (int) $basis;
- if (($price <= 0) || ($redemption <= 0)) {
- return Functions::NAN();
- }
- $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return (1 - $price / $redemption) / $daysBetweenSettlementAndMaturity;
- }
-
- return Functions::VALUE();
+ return Financial\Securities\Rates::discount($settlement, $maturity, $price, $redemption, $basis);
}
/**
@@ -980,6 +582,11 @@ class Financial
* Excel Function:
* DOLLARDE(fractional_dollar,fraction)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Dollar::decimal()
+ * Use the decimal() method in the Financial\Dollar class instead
+ *
* @param float $fractional_dollar Fractional Dollar
* @param int $fraction Fraction
*
@@ -987,23 +594,7 @@ class Financial
*/
public static function DOLLARDE($fractional_dollar = null, $fraction = 0)
{
- $fractional_dollar = Functions::flattenSingleValue($fractional_dollar);
- $fraction = (int) Functions::flattenSingleValue($fraction);
-
- // Validate parameters
- if ($fractional_dollar === null || $fraction < 0) {
- return Functions::NAN();
- }
- if ($fraction == 0) {
- return Functions::DIV0();
- }
-
- $dollars = floor($fractional_dollar);
- $cents = fmod($fractional_dollar, 1);
- $cents /= $fraction;
- $cents *= 10 ** ceil(log10($fraction));
-
- return $dollars + $cents;
+ return Dollar::decimal($fractional_dollar, $fraction);
}
/**
@@ -1016,6 +607,11 @@ class Financial
* Excel Function:
* DOLLARFR(decimal_dollar,fraction)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Dollar::fractional()
+ * Use the fractional() method in the Financial\Dollar class instead
+ *
* @param float $decimal_dollar Decimal Dollar
* @param int $fraction Fraction
*
@@ -1023,23 +619,7 @@ class Financial
*/
public static function DOLLARFR($decimal_dollar = null, $fraction = 0)
{
- $decimal_dollar = Functions::flattenSingleValue($decimal_dollar);
- $fraction = (int) Functions::flattenSingleValue($fraction);
-
- // Validate parameters
- if ($decimal_dollar === null || $fraction < 0) {
- return Functions::NAN();
- }
- if ($fraction == 0) {
- return Functions::DIV0();
- }
-
- $dollars = floor($decimal_dollar);
- $cents = fmod($decimal_dollar, 1);
- $cents *= $fraction;
- $cents *= 10 ** (-ceil(log10($fraction)));
-
- return $dollars + $cents;
+ return Dollar::fractional($decimal_dollar, $fraction);
}
/**
@@ -1051,22 +631,19 @@ class Financial
* Excel Function:
* EFFECT(nominal_rate,npery)
*
- * @param float $nominal_rate Nominal interest rate
- * @param int $npery Number of compounding payments per year
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\InterestRate::effective()
+ * Use the effective() method in the Financial\InterestRate class instead
+ *
+ * @param float $nominalRate Nominal interest rate
+ * @param int $periodsPerYear Number of compounding payments per year
*
* @return float|string
*/
- public static function EFFECT($nominal_rate = 0, $npery = 0)
+ public static function EFFECT($nominalRate = 0, $periodsPerYear = 0)
{
- $nominal_rate = Functions::flattenSingleValue($nominal_rate);
- $npery = (int) Functions::flattenSingleValue($npery);
-
- // Validate parameters
- if ($nominal_rate <= 0 || $npery < 1) {
- return Functions::NAN();
- }
-
- return (1 + $nominal_rate / $npery) ** $npery - 1;
+ return Financial\InterestRate::effective($nominalRate, $periodsPerYear);
}
/**
@@ -1077,6 +654,11 @@ class Financial
* Excel Function:
* FV(rate,nper,pmt[,pv[,type]])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Constant\Periodic::futureValue()
+ * Use the futureValue() method in the Financial\CashFlow\Constant\Periodic class instead
+ *
* @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
@@ -1092,23 +674,7 @@ class Financial
*/
public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0)
{
- $rate = Functions::flattenSingleValue($rate);
- $nper = Functions::flattenSingleValue($nper);
- $pmt = Functions::flattenSingleValue($pmt);
- $pv = Functions::flattenSingleValue($pv);
- $type = Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Functions::NAN();
- }
-
- // Calculate
- if ($rate !== null && $rate != 0) {
- return -$pv * (1 + $rate) ** $nper - $pmt * (1 + $rate * $type) * ((1 + $rate) ** $nper - 1) / $rate;
- }
-
- return -$pv - $pmt * $nper;
+ return Financial\CashFlow\Constant\Periodic::futureValue($rate, $nper, $pmt, $pv, $type);
}
/**
@@ -1120,21 +686,19 @@ class Financial
* Excel Function:
* FVSCHEDULE(principal,schedule)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Single::futureValue()
+ * Use the futureValue() method in the Financial\CashFlow\Single class instead
+ *
* @param float $principal the present value
* @param float[] $schedule an array of interest rates to apply
*
- * @return float
+ * @return float|string
*/
public static function FVSCHEDULE($principal, $schedule)
{
- $principal = Functions::flattenSingleValue($principal);
- $schedule = Functions::flattenArray($schedule);
-
- foreach ($schedule as $rate) {
- $principal *= 1 + $rate;
- }
-
- return $principal;
+ return Financial\CashFlow\Single::futureValue($principal, $schedule);
}
/**
@@ -1145,57 +709,46 @@ class Financial
* Excel Function:
* INTRATE(settlement,maturity,investment,redemption[,basis])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Securities\Rates::interest()
+ * Use the interest() method in the Financial\Securities\Rates class instead
+ *
* @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.
+ * 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.
+ * 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
+ * 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)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $investment = Functions::flattenSingleValue($investment);
- $redemption = Functions::flattenSingleValue($redemption);
- $basis = Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) {
- $investment = (float) $investment;
- $redemption = (float) $redemption;
- $basis = (int) $basis;
- if (($investment <= 0) || ($redemption <= 0)) {
- return Functions::NAN();
- }
- $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity);
- }
-
- return Functions::VALUE();
+ 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.
+ * 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
+ *
+ * @see Financial\CashFlow\Constant\Periodic\Interest::payment()
+ * Use the payment() method in the Financial\CashFlow\Constant\Periodic class instead
+ *
* @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
@@ -1207,25 +760,7 @@ class Financial
*/
public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0)
{
- $rate = Functions::flattenSingleValue($rate);
- $per = (int) Functions::flattenSingleValue($per);
- $nper = (int) Functions::flattenSingleValue($nper);
- $pv = Functions::flattenSingleValue($pv);
- $fv = Functions::flattenSingleValue($fv);
- $type = (int) Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Functions::NAN();
- }
- if ($per <= 0 || $per > $nper) {
- return Functions::VALUE();
- }
-
- // Calculate
- $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
-
- return $interestAndPrincipal[0];
+ return Financial\CashFlow\Constant\Periodic\Interest::payment($rate, $per, $nper, $pv, $fv, $type);
}
/**
@@ -1240,63 +775,22 @@ class Financial
* Excel Function:
* IRR(values[,guess])
*
- * @param float[] $values An array or a reference to cells that contain numbers for which you want
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Variable\Periodic::rate()
+ * Use the rate() method in the Financial\CashFlow\Variable\Periodic class instead
+ *
+ * @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 float $guess A number that you guess is close to the result of IRR
+ * @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)
{
- if (!is_array($values)) {
- return Functions::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::NPV($x1, $values);
- $f2 = self::NPV($x2, $values);
- for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) {
- if (($f1 * $f2) < 0.0) {
- break;
- }
- if (abs($f1) < abs($f2)) {
- $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values);
- } else {
- $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values);
- }
- }
- if (($f1 * $f2) > 0.0) {
- return Functions::VALUE();
- }
-
- $f = self::NPV($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::NPV($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 Functions::VALUE();
+ return Financial\CashFlow\Variable\Periodic::rate($values, $guess);
}
/**
@@ -1305,7 +799,12 @@ class Financial
* 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)
+ * =ISPMT(interest_rate, period, number_payments, pv)
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Constant\Periodic\Interest::schedulePayment()
+ * Use the schedulePayment() method in the Financial\CashFlow\Constant\Periodic class instead
*
* interest_rate is the interest rate for the investment
*
@@ -1313,32 +812,11 @@ class Financial
*
* number_payments is the number of payments for the annuity
*
- * PV is the loan amount or present value of the payments
+ * pv is the loan amount or present value of the payments
*/
public static function ISPMT(...$args)
{
- // Return value
- $returnValue = 0;
-
- // Get the parameters
- $aArgs = Functions::flattenArray($args);
- $interestRate = array_shift($aArgs);
- $period = array_shift($aArgs);
- $numberPeriods = array_shift($aArgs);
- $principleRemaining = array_shift($aArgs);
-
- // Calculate
- $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 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 == $numberPeriods) {
- $returnValue = 0;
- }
- }
-
- return $returnValue;
+ return Financial\CashFlow\Constant\Periodic\Interest::schedulePayment(...$args);
}
/**
@@ -1350,44 +828,22 @@ class Financial
* Excel Function:
* MIRR(values,finance_rate, reinvestment_rate)
*
- * @param float[] $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 float $finance_rate The interest rate you pay on the money used in the cash flows
- * @param float $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Variable\Periodic::modifiedRate()
+ * Use the modifiedRate() method in the Financial\CashFlow\Variable\Periodic class instead
+ *
+ * @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)
{
- if (!is_array($values)) {
- return Functions::VALUE();
- }
- $values = Functions::flattenArray($values);
- $finance_rate = Functions::flattenSingleValue($finance_rate);
- $reinvestment_rate = Functions::flattenSingleValue($reinvestment_rate);
- $n = count($values);
-
- $rr = 1.0 + $reinvestment_rate;
- $fr = 1.0 + $finance_rate;
-
- $npv_pos = $npv_neg = 0.0;
- foreach ($values as $i => $v) {
- if ($v >= 0) {
- $npv_pos += $v / $rr ** $i;
- } else {
- $npv_neg += $v / $fr ** $i;
- }
- }
-
- if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) {
- return Functions::VALUE();
- }
-
- $mirr = ((-$npv_pos * $rr ** $n)
- / ($npv_neg * ($rr))) ** (1.0 / ($n - 1)) - 1.0;
-
- return is_finite($mirr) ? $mirr : Functions::VALUE();
+ return Financial\CashFlow\Variable\Periodic::modifiedRate($values, $finance_rate, $reinvestment_rate);
}
/**
@@ -1395,23 +851,22 @@ class Financial
*
* Returns the nominal interest rate given the effective rate and the number of compounding payments per year.
*
- * @param float $effect_rate Effective interest rate
- * @param int $npery Number of compounding payments per year
+ * Excel Function:
+ * NOMINAL(effect_rate, npery)
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\InterestRate::nominal()
+ * Use the nominal() method in the Financial\InterestRate class instead
+ *
+ * @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($effect_rate = 0, $npery = 0)
+ public static function NOMINAL($effectiveRate = 0, $periodsPerYear = 0)
{
- $effect_rate = Functions::flattenSingleValue($effect_rate);
- $npery = (int) Functions::flattenSingleValue($npery);
-
- // Validate parameters
- if ($effect_rate <= 0 || $npery < 1) {
- return Functions::NAN();
- }
-
- // Calculate
- return $npery * (($effect_rate + 1) ** (1 / $npery) - 1);
+ return InterestRate::nominal($effectiveRate, $periodsPerYear);
}
/**
@@ -1419,6 +874,8 @@ class Financial
*
* Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate.
*
+ * @Deprecated 1.18.0
+ *
* @param float $rate Interest rate per period
* @param int $pmt Periodic payment (annuity)
* @param float $pv Present Value
@@ -1426,33 +883,13 @@ class Financial
* @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
+ *
+ *@see Financial\CashFlow\Constant\Periodic::periods()
+ * Use the periods() method in the Financial\CashFlow\Constant\Periodic class instead
*/
public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0)
{
- $rate = Functions::flattenSingleValue($rate);
- $pmt = Functions::flattenSingleValue($pmt);
- $pv = Functions::flattenSingleValue($pv);
- $fv = Functions::flattenSingleValue($fv);
- $type = Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Functions::NAN();
- }
-
- // Calculate
- if ($rate !== null && $rate != 0) {
- if ($pmt == 0 && $pv == 0) {
- return Functions::NAN();
- }
-
- return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate);
- }
- if ($pmt == 0) {
- return Functions::NAN();
- }
-
- return (-$pv - $fv) / $pmt;
+ return Financial\CashFlow\Constant\Periodic::periods($rate, $pmt, $pv, $fv, $type);
}
/**
@@ -1460,28 +897,16 @@ class Financial
*
* Returns the Net Present Value of a cash flow series given a discount rate.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Variable\Periodic::presentValue()
+ * Use the presentValue() method in the Financial\CashFlow\Variable\Periodic class instead
+ *
* @return float
*/
public static function NPV(...$args)
{
- // Return value
- $returnValue = 0;
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
-
- // Calculate
- $rate = array_shift($aArgs);
- $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
- return $returnValue;
+ return Financial\CashFlow\Variable\Periodic::presentValue(...$args);
}
/**
@@ -1489,6 +914,11 @@ class Financial
*
* Calculates the number of periods required for an investment to reach a specified value.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Single::periods()
+ * Use the periods() method in the Financial\CashFlow\Single class instead
+ *
* @param float $rate Interest rate per period
* @param float $pv Present Value
* @param float $fv Future Value
@@ -1497,18 +927,7 @@ class Financial
*/
public static function PDURATION($rate = 0, $pv = 0, $fv = 0)
{
- $rate = Functions::flattenSingleValue($rate);
- $pv = Functions::flattenSingleValue($pv);
- $fv = Functions::flattenSingleValue($fv);
-
- // Validate parameters
- if (!is_numeric($rate) || !is_numeric($pv) || !is_numeric($fv)) {
- return Functions::VALUE();
- } elseif ($rate <= 0.0 || $pv <= 0.0 || $fv <= 0.0) {
- return Functions::NAN();
- }
-
- return (log($fv) - log($pv)) / log(1 + $rate);
+ return Financial\CashFlow\Single::periods($rate, $pv, $fv);
}
/**
@@ -1516,6 +935,11 @@ class Financial
*
* Returns the constant payment (annuity) for a cash flow with a constant interest rate.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Constant\Periodic\Payments::annuity()
+ * Use the annuity() method in the Financial\CashFlow\Constant\Periodic\Payments class instead
+ *
* @param float $rate Interest rate per period
* @param int $nper Number of periods
* @param float $pv Present Value
@@ -1526,29 +950,19 @@ class Financial
*/
public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0)
{
- $rate = Functions::flattenSingleValue($rate);
- $nper = Functions::flattenSingleValue($nper);
- $pv = Functions::flattenSingleValue($pv);
- $fv = Functions::flattenSingleValue($fv);
- $type = Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Functions::NAN();
- }
-
- // Calculate
- if ($rate !== null && $rate != 0) {
- return (-$fv - $pv * (1 + $rate) ** $nper) / (1 + $rate * $type) / (((1 + $rate) ** $nper - 1) / $rate);
- }
-
- return (-$pv - $fv) / $nper;
+ 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.
+ * 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
+ *
+ * @see Financial\CashFlow\Constant\Periodic\Payments::interestPayment()
+ * Use the interestPayment() method in the Financial\CashFlow\Constant\Periodic\Payments class instead
*
* @param float $rate Interest rate per period
* @param int $per Period for which we want to find the interest
@@ -1561,100 +975,43 @@ class Financial
*/
public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0)
{
- $rate = Functions::flattenSingleValue($rate);
- $per = (int) Functions::flattenSingleValue($per);
- $nper = (int) Functions::flattenSingleValue($nper);
- $pv = Functions::flattenSingleValue($pv);
- $fv = Functions::flattenSingleValue($fv);
- $type = (int) Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Functions::NAN();
- }
- if ($per <= 0 || $per > $nper) {
- return Functions::VALUE();
- }
-
- // Calculate
- $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
-
- return $interestAndPrincipal[1];
- }
-
- private static function validatePrice($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis)
- {
- if (is_string($settlement)) {
- return Functions::VALUE();
- }
- if (is_string($maturity)) {
- return Functions::VALUE();
- }
- if (!is_numeric($rate)) {
- return Functions::VALUE();
- }
- if (!is_numeric($yield)) {
- return Functions::VALUE();
- }
- if (!is_numeric($redemption)) {
- return Functions::VALUE();
- }
- if (!is_numeric($frequency)) {
- return Functions::VALUE();
- }
- if (!is_numeric($basis)) {
- return Functions::VALUE();
- }
-
- return '';
+ 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
+ *
+ * @see Financial\Securities\Price::price()
+ * Use the price() method in the Financial\Securities\Price class instead
+ *
+ * @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)
{
- $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 = Functions::flattenSingleValue($basis);
-
- $settlement = DateTime::getDateValue($settlement);
- $maturity = DateTime::getDateValue($maturity);
- $rslt = self::validatePrice($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis);
- if ($rslt) {
- return $rslt;
- }
- $rate = (float) $rate;
- $yield = (float) $yield;
- $redemption = (float) $redemption;
- $frequency = (int) $frequency;
- $basis = (int) $basis;
-
- if (
- ($settlement > $maturity) ||
- (!self::isValidFrequency($frequency)) ||
- (($basis < 0) || ($basis > 4))
- ) {
- return Functions::NAN();
- }
-
- $dsc = self::COUPDAYSNC($settlement, $maturity, $frequency, $basis);
- $e = self::COUPDAYS($settlement, $maturity, $frequency, $basis);
- $n = self::COUPNUM($settlement, $maturity, $frequency, $basis);
- $a = self::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;
+ return Securities\Price::price($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis);
}
/**
@@ -1662,10 +1019,16 @@ class Financial
*
* Returns the price per $100 face value of a discounted security.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Securities\Price::priceDiscounted()
+ * Use the priceDiscounted() method in the Financial\Securities\Price class instead
+ *
* @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.
+ * 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.
+ * The maturity date is the date when the security expires.
* @param int $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.
@@ -1679,27 +1042,7 @@ class Financial
*/
public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis = 0)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $discount = (float) Functions::flattenSingleValue($discount);
- $redemption = (float) Functions::flattenSingleValue($redemption);
- $basis = (int) Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) {
- if (($discount <= 0) || ($redemption <= 0)) {
- return Functions::NAN();
- }
- $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity);
- }
-
- return Functions::VALUE();
+ return Securities\Price::priceDiscounted($settlement, $maturity, $discount, $redemption, $basis);
}
/**
@@ -1707,10 +1050,16 @@ class Financial
*
* Returns the price per $100 face value of a security that pays interest at maturity.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Securities\Price::priceAtMaturity()
+ * Use the priceAtMaturity() method in the Financial\Securities\Price class instead
+ *
* @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.
+ * 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.
+ * The maturity date is the date when the security expires.
* @param mixed $issue The security's issue date
* @param int $rate The security's interest rate at date of issue
* @param int $yield The security's annual yield
@@ -1725,47 +1074,7 @@ class Financial
*/
public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis = 0)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $issue = Functions::flattenSingleValue($issue);
- $rate = Functions::flattenSingleValue($rate);
- $yield = Functions::flattenSingleValue($yield);
- $basis = (int) Functions::flattenSingleValue($basis);
-
- // Validate
- if (is_numeric($rate) && is_numeric($yield)) {
- if (($rate <= 0) || ($yield <= 0)) {
- return Functions::NAN();
- }
- $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis);
- if (!is_numeric($daysPerYear)) {
- return $daysPerYear;
- }
- $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
- $daysBetweenIssueAndSettlement *= $daysPerYear;
- $daysBetweenIssueAndMaturity = DateTime::YEARFRAC($issue, $maturity, $basis);
- if (!is_numeric($daysBetweenIssueAndMaturity)) {
- // return date error
- return $daysBetweenIssueAndMaturity;
- }
- $daysBetweenIssueAndMaturity *= $daysPerYear;
- $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($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);
- }
-
- return Functions::VALUE();
+ return Securities\Price::priceAtMaturity($settlement, $maturity, $issue, $rate, $yield, $basis);
}
/**
@@ -1773,6 +1082,11 @@ class Financial
*
* Returns the Present Value of a cash flow with constant payments and interest rate (annuities).
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Constant\Periodic::presentValue()
+ * Use the presentValue() method in the Financial\CashFlow\Constant\Periodic class instead
+ *
* @param float $rate Interest rate per period
* @param int $nper Number of periods
* @param float $pmt Periodic payment (annuity)
@@ -1783,23 +1097,7 @@ class Financial
*/
public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0)
{
- $rate = Functions::flattenSingleValue($rate);
- $nper = Functions::flattenSingleValue($nper);
- $pmt = Functions::flattenSingleValue($pmt);
- $fv = Functions::flattenSingleValue($fv);
- $type = Functions::flattenSingleValue($type);
-
- // Validate parameters
- if ($type != 0 && $type != 1) {
- return Functions::NAN();
- }
-
- // Calculate
- if ($rate !== null && $rate != 0) {
- return (-$pmt * (1 + $rate * $type) * (((1 + $rate) ** $nper - 1) / $rate) - $fv) / (1 + $rate) ** $nper;
- }
-
- return -$fv - $pmt * $nper;
+ return Financial\CashFlow\Constant\Periodic::presentValue($rate, $nper, $pmt, $fv, $type);
}
/**
@@ -1813,112 +1111,63 @@ class Financial
* Excel Function:
* RATE(nper,pmt,pv[,fv[,type[,guess]]])
*
- * @param float $nper The total number of payment periods in an annuity
- * @param float $pmt The payment made each period and cannot change over the life
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Constant\Periodic\Interest::rate()
+ * Use the rate() method in the Financial\CashFlow\Constant\Periodic class instead
+ *
+ * @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 float $pv The present value - the total amount that a series of future
+ * @param mixed $pv The present value - the total amount that a series of future
* payments is worth now
- * @param float $fv The future value, or a cash balance you want to attain after
+ * @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 int $type A number 0 or 1 and indicates when payments are due:
+ * @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 float $guess Your guess for what the rate will be.
+ * @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)
{
- $nper = (int) Functions::flattenSingleValue($nper);
- $pmt = Functions::flattenSingleValue($pmt);
- $pv = Functions::flattenSingleValue($pv);
- $fv = ($fv === null) ? 0.0 : Functions::flattenSingleValue($fv);
- $type = ($type === null) ? 0 : (int) Functions::flattenSingleValue($type);
- $guess = ($guess === null) ? 0.1 : Functions::flattenSingleValue($guess);
-
- $rate = $guess;
- // rest of code adapted from python/numpy
- $close = false;
- $iter = 0;
- while (!$close && $iter < self::FINANCIAL_MAX_ITERATIONS) {
- $nextdiff = self::rateNextGuess($rate, $nper, $pmt, $pv, $fv, $type);
- if (!is_numeric($nextdiff)) {
- break;
- }
- $rate1 = $rate - $nextdiff;
- $close = abs($rate1 - $rate) < self::FINANCIAL_PRECISION;
- ++$iter;
- $rate = $rate1;
- }
-
- return $close ? $rate : Functions::NAN();
- }
-
- private static function rateNextGuess($rate, $nper, $pmt, $pv, $fv, $type)
- {
- if ($rate == 0) {
- return Functions::NAN();
- }
- $tt1 = ($rate + 1) ** $nper;
- $tt2 = ($rate + 1) ** ($nper - 1);
- $numerator = $fv + $tt1 * $pv + $pmt * ($tt1 - 1) * ($rate * $type + 1) / $rate;
- $denominator = $nper * $tt2 * $pv - $pmt * ($tt1 - 1) * ($rate * $type + 1) / ($rate * $rate)
- + $nper * $pmt * $tt2 * ($rate * $type + 1) / $rate
- + $pmt * ($tt1 - 1) * $type / $rate;
- if ($denominator == 0) {
- return Functions::NAN();
- }
-
- return $numerator / $denominator;
+ return Financial\CashFlow\Constant\Periodic\Interest::rate($nper, $pmt, $pv, $fv, $type, $guess);
}
/**
* RECEIVED.
*
- * Returns the price per $100 face value of a discounted security.
+ * Returns the amount received at maturity for a fully invested Security.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Securities\Price::received()
+ * Use the received() method in the Financial\Securities\Price class instead
*
* @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.
+ * 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 $discount The security's discount rate
- * @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
+ * 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)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $investment = (float) Functions::flattenSingleValue($investment);
- $discount = (float) Functions::flattenSingleValue($discount);
- $basis = (int) Functions::flattenSingleValue($basis);
-
- // Validate
- if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) {
- if (($investment <= 0) || ($discount <= 0)) {
- return Functions::NAN();
- }
- $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
-
- return $investment / (1 - ($discount * $daysBetweenSettlementAndMaturity));
- }
-
- return Functions::VALUE();
+ return Financial\Securities\Price::received($settlement, $maturity, $investment, $discount, $basis);
}
/**
@@ -1926,6 +1175,11 @@ class Financial
*
* Calculates the interest rate required for an investment to grow to a specified future value .
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Single::interestRate()
+ * Use the interestRate() method in the Financial\CashFlow\Single class instead
+ *
* @param float $nper The number of periods over which the investment is made
* @param float $pv Present Value
* @param float $fv Future Value
@@ -1934,18 +1188,7 @@ class Financial
*/
public static function RRI($nper = 0, $pv = 0, $fv = 0)
{
- $nper = Functions::flattenSingleValue($nper);
- $pv = Functions::flattenSingleValue($pv);
- $fv = Functions::flattenSingleValue($fv);
-
- // Validate parameters
- if (!is_numeric($nper) || !is_numeric($pv) || !is_numeric($fv)) {
- return Functions::VALUE();
- } elseif ($nper <= 0.0 || $pv <= 0.0 || $fv < 0.0) {
- return Functions::NAN();
- }
-
- return ($fv / $pv) ** (1 / $nper) - 1;
+ return Financial\CashFlow\Single::interestRate($nper, $pv, $fv);
}
/**
@@ -1953,6 +1196,11 @@ class Financial
*
* Returns the straight-line depreciation of an asset for one period
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Depreciation::SLN()
+ * Use the SLN() method in the Financial\Depreciation class instead
+ *
* @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
@@ -1961,20 +1209,7 @@ class Financial
*/
public static function SLN($cost, $salvage, $life)
{
- $cost = Functions::flattenSingleValue($cost);
- $salvage = Functions::flattenSingleValue($salvage);
- $life = Functions::flattenSingleValue($life);
-
- // Calculate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) {
- if ($life < 0) {
- return Functions::NAN();
- }
-
- return ($cost - $salvage) / $life;
- }
-
- return Functions::VALUE();
+ return Depreciation::SLN($cost, $salvage, $life);
}
/**
@@ -1982,6 +1217,11 @@ class Financial
*
* Returns the sum-of-years' digits depreciation of an asset for a specified period.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Depreciation::SYD()
+ * Use the SYD() method in the Financial\Depreciation class instead
+ *
* @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
@@ -1991,21 +1231,7 @@ class Financial
*/
public static function SYD($cost, $salvage, $life, $period)
{
- $cost = Functions::flattenSingleValue($cost);
- $salvage = Functions::flattenSingleValue($salvage);
- $life = Functions::flattenSingleValue($life);
- $period = Functions::flattenSingleValue($period);
-
- // Calculate
- if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) {
- if (($life < 1) || ($period > $life)) {
- return Functions::NAN();
- }
-
- return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1));
- }
-
- return Functions::VALUE();
+ return Depreciation::SYD($cost, $salvage, $life, $period);
}
/**
@@ -2013,8 +1239,14 @@ class Financial
*
* Returns the bond-equivalent yield for a Treasury bill.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\TreasuryBill::bondEquivalentYield()
+ * Use the bondEquivalentYield() method in the Financial\TreasuryBill class instead
+ *
* @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.
+ * 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 int $discount The Treasury bill's discount rate
@@ -2023,37 +1255,22 @@ class Financial
*/
public static function TBILLEQ($settlement, $maturity, $discount)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $discount = Functions::flattenSingleValue($discount);
-
- // Use TBILLPRICE for validation
- $testValue = self::TBILLPRICE($settlement, $maturity, $discount);
- if (is_string($testValue)) {
- return $testValue;
- }
-
- if (is_string($maturity = DateTime::getDateValue($maturity))) {
- return Functions::VALUE();
- }
-
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
- ++$maturity;
- $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity) * 360;
- } else {
- $daysBetweenSettlementAndMaturity = (DateTime::getDateValue($maturity) - DateTime::getDateValue($settlement));
- }
-
- return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity);
+ return TreasuryBill::bondEquivalentYield($settlement, $maturity, $discount);
}
/**
* TBILLPRICE.
*
- * Returns the yield for a Treasury bill.
+ * Returns the price per $100 face value for a Treasury bill.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\TreasuryBill::price()
+ * Use the price() method in the Financial\TreasuryBill class instead
*
* @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.
+ * 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 int $discount The Treasury bill's discount rate
@@ -2062,44 +1279,7 @@ class Financial
*/
public static function TBILLPRICE($settlement, $maturity, $discount)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $discount = Functions::flattenSingleValue($discount);
-
- if (is_string($maturity = DateTime::getDateValue($maturity))) {
- return Functions::VALUE();
- }
-
- // Validate
- if (is_numeric($discount)) {
- if ($discount <= 0) {
- return Functions::NAN();
- }
-
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
- ++$maturity;
- $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity) * 360;
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- } else {
- $daysBetweenSettlementAndMaturity = (DateTime::getDateValue($maturity) - DateTime::getDateValue($settlement));
- }
-
- if ($daysBetweenSettlementAndMaturity > 360) {
- return Functions::NAN();
- }
-
- $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360));
- if ($price <= 0) {
- return Functions::NAN();
- }
-
- return $price;
- }
-
- return Functions::VALUE();
+ return TreasuryBill::price($settlement, $maturity, $discount);
}
/**
@@ -2107,8 +1287,14 @@ class Financial
*
* Returns the yield for a Treasury bill.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\TreasuryBill::yield()
+ * Use the yield() method in the Financial\TreasuryBill class instead
+ *
* @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.
+ * 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 int $price The Treasury bill's price per $100 face value
@@ -2117,113 +1303,7 @@ class Financial
*/
public static function TBILLYIELD($settlement, $maturity, $price)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $price = Functions::flattenSingleValue($price);
-
- // Validate
- if (is_numeric($price)) {
- if ($price <= 0) {
- return Functions::NAN();
- }
-
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
- ++$maturity;
- $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity) * 360;
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- } else {
- $daysBetweenSettlementAndMaturity = (DateTime::getDateValue($maturity) - DateTime::getDateValue($settlement));
- }
-
- if ($daysBetweenSettlementAndMaturity > 360) {
- return Functions::NAN();
- }
-
- return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity);
- }
-
- return Functions::VALUE();
- }
-
- private static function bothNegAndPos($neg, $pos)
- {
- return $neg && $pos;
- }
-
- private static function xirrPart2(&$values)
- {
- $valCount = count($values);
- $foundpos = false;
- $foundneg = false;
- for ($i = 0; $i < $valCount; ++$i) {
- $fld = $values[$i];
- if (!is_numeric($fld)) {
- return Functions::VALUE();
- } elseif ($fld > 0) {
- $foundpos = true;
- } elseif ($fld < 0) {
- $foundneg = true;
- }
- }
- if (!self::bothNegAndPos($foundneg, $foundpos)) {
- return Functions::NAN();
- }
-
- return '';
- }
-
- private static function xirrPart1(&$values, &$dates)
- {
- if ((!is_array($values)) && (!is_array($dates))) {
- return Functions::NA();
- }
- $values = Functions::flattenArray($values);
- $dates = Functions::flattenArray($dates);
- if (count($values) != count($dates)) {
- return Functions::NAN();
- }
-
- $datesCount = count($dates);
- for ($i = 0; $i < $datesCount; ++$i) {
- $dates[$i] = DateTime::getDateValue($dates[$i]);
- if (!is_numeric($dates[$i])) {
- return Functions::VALUE();
- }
- }
-
- return self::xirrPart2($values);
- }
-
- private static function xirrPart3($values, $dates, $x1, $x2)
- {
- $f = self::xnpvOrdered($x1, $values, $dates, false);
- if ($f < 0.0) {
- $rtb = $x1;
- $dx = $x2 - $x1;
- } else {
- $rtb = $x2;
- $dx = $x1 - $x2;
- }
-
- $rslt = Functions::VALUE();
- for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) {
- $dx *= 0.5;
- $x_mid = $rtb + $dx;
- $f_mid = 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 TreasuryBill::yield($settlement, $maturity, $price);
}
/**
@@ -2234,6 +1314,11 @@ class Financial
* Excel Function:
* =XIRR(values,dates,guess)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Variable\NonPeriodic::rate()
+ * Use the rate() method in the Financial\CashFlow\Variable\NonPeriodic class instead
+ *
* @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
@@ -2245,37 +1330,7 @@ class Financial
*/
public static function XIRR($values, $dates, $guess = 0.1)
{
- $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);
- $x1 = 0.0;
- $x2 = $guess ? $guess : 0.1;
- $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) || !is_numeric($f2)) {
- break;
- }
- if (($f1 * $f2) < 0.0) {
- $found = true;
-
- break;
- } elseif (abs($f1) < abs($f2)) {
- $f1 = self::xnpvOrdered($x1 += 1.6 * ($x1 - $x2), $values, $dates, false);
- } else {
- $f2 = self::xnpvOrdered($x2 += 1.6 * ($x2 - $x1), $values, $dates, false);
- }
- }
- if (!$found) {
- return Functions::NAN();
- }
-
- return self::xirrPart3($values, $dates, $x1, $x2);
+ return Financial\CashFlow\Variable\NonPeriodic::rate($values, $dates, $guess);
}
/**
@@ -2287,74 +1342,27 @@ class Financial
* Excel Function:
* =XNPV(rate,values,dates)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\CashFlow\Variable\NonPeriodic::presentValue()
+ * Use the presentValue() method in the Financial\CashFlow\Variable\NonPeriodic class instead
+ *
* @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.
+ * @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 self::xnpvOrdered($rate, $values, $dates, true);
- }
-
- private static function validateXnpv($rate, $values, $dates)
- {
- if (!is_numeric($rate)) {
- return Functions::VALUE();
- }
- $valCount = count($values);
- if ($valCount != count($dates)) {
- return Functions::NAN();
- }
- if ($valCount > 1 && ((min($values) > 0) || (max($values) < 0))) {
- return Functions::NAN();
- }
- $date0 = DateTime::getDateValue($dates[0]);
- if (is_string($date0)) {
- return Functions::VALUE();
- }
-
- return '';
- }
-
- private static function xnpvOrdered($rate, $values, $dates, $ordered = true)
- {
- $rate = Functions::flattenSingleValue($rate);
- $values = Functions::flattenArray($values);
- $dates = Functions::flattenArray($dates);
- $valCount = count($values);
- $date0 = DateTime::getDateValue($dates[0]);
- $rslt = self::validateXnpv($rate, $values, $dates);
- if ($rslt) {
- return $rslt;
- }
- $xnpv = 0.0;
- for ($i = 0; $i < $valCount; ++$i) {
- if (!is_numeric($values[$i])) {
- return Functions::VALUE();
- }
- $datei = DateTime::getDateValue($dates[$i]);
- if (is_string($datei)) {
- return Functions::VALUE();
- }
- if ($date0 > $datei) {
- $dif = $ordered ? Functions::NAN() : -DateTime::DATEDIF($datei, $date0, 'd');
- } else {
- $dif = DateTime::DATEDIF($date0, $datei, 'd');
- }
- if (!is_numeric($dif)) {
- return $dif;
- }
- $xnpv += $values[$i] / (1 + $rate) ** ($dif / 365);
- }
-
- return is_finite($xnpv) ? $xnpv : Functions::VALUE();
+ return Financial\CashFlow\Variable\NonPeriodic::presentValue($rate, $values, $dates);
}
/**
@@ -2362,10 +1370,16 @@ class Financial
*
* Returns the annual yield of a security that pays interest at maturity.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Securities\Yields::yieldDiscounted()
+ * Use the yieldDiscounted() method in the Financial\Securities\Yields class instead
+ *
* @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.
+ * 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.
+ * The maturity date is the date when the security expires.
* @param int $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.
@@ -2379,32 +1393,7 @@ class Financial
*/
public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis = 0)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $price = Functions::flattenSingleValue($price);
- $redemption = Functions::flattenSingleValue($redemption);
- $basis = (int) Functions::flattenSingleValue($basis);
-
- // Validate
- if (is_numeric($price) && is_numeric($redemption)) {
- if (($price <= 0) || ($redemption <= 0)) {
- return Functions::NAN();
- }
- $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis);
- if (!is_numeric($daysPerYear)) {
- return $daysPerYear;
- }
- $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis);
- if (!is_numeric($daysBetweenSettlementAndMaturity)) {
- // return date error
- return $daysBetweenSettlementAndMaturity;
- }
- $daysBetweenSettlementAndMaturity *= $daysPerYear;
-
- return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity);
- }
-
- return Functions::VALUE();
+ return Securities\Yields::yieldDiscounted($settlement, $maturity, $price, $redemption, $basis);
}
/**
@@ -2412,64 +1401,30 @@ class Financial
*
* Returns the annual yield of a security that pays interest at maturity.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Financial\Securities\Yields::yieldAtMaturity()
+ * Use the yieldAtMaturity() method in the Financial\Securities\Yields class instead
+ *
* @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.
+ * 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.
+ * The maturity date is the date when the security expires.
* @param mixed $issue The security's issue date
* @param int $rate The security's interest rate at date of issue
* @param int $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
+ * 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)
{
- $settlement = Functions::flattenSingleValue($settlement);
- $maturity = Functions::flattenSingleValue($maturity);
- $issue = Functions::flattenSingleValue($issue);
- $rate = Functions::flattenSingleValue($rate);
- $price = Functions::flattenSingleValue($price);
- $basis = (int) Functions::flattenSingleValue($basis);
-
- // Validate
- if (is_numeric($rate) && is_numeric($price)) {
- if (($rate <= 0) || ($price <= 0)) {
- return Functions::NAN();
- }
- $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis);
- if (!is_numeric($daysPerYear)) {
- return $daysPerYear;
- }
- $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis);
- if (!is_numeric($daysBetweenIssueAndSettlement)) {
- // return date error
- return $daysBetweenIssueAndSettlement;
- }
- $daysBetweenIssueAndSettlement *= $daysPerYear;
- $daysBetweenIssueAndMaturity = DateTime::YEARFRAC($issue, $maturity, $basis);
- if (!is_numeric($daysBetweenIssueAndMaturity)) {
- // return date error
- return $daysBetweenIssueAndMaturity;
- }
- $daysBetweenIssueAndMaturity *= $daysPerYear;
- $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($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);
- }
-
- return Functions::VALUE();
+ return Securities\Yields::yieldAtMaturity($settlement, $maturity, $issue, $rate, $price, $basis);
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Amortization.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Amortization.php
new file mode 100644
index 00000000000..ba7fb5210d7
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Amortization.php
@@ -0,0 +1,210 @@
+getMessage();
+ }
+
+ $yearFrac = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis);
+ if (is_string($yearFrac)) {
+ return $yearFrac;
+ }
+
+ $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);
+ $yearFrac = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis);
+ if (is_string($yearFrac)) {
+ return $yearFrac;
+ }
+
+ if (
+ ($basis == FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL) &&
+ ($yearFrac < 1) && (DateTimeExcel\Helpers::isLeapYear($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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php
new file mode 100644
index 00000000000..e4c8a3a4ceb
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php
@@ -0,0 +1,53 @@
+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 Functions::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 Functions::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 Functions::NAN();
+ }
+
+ return log(($payment * (1 + $rate * $type) / $rate - $futureValue) /
+ ($presentValue + $payment * (1 + $rate * $type) / $rate)) / log(1 + $rate);
+ }
+
+ return (-$presentValue - $futureValue) / $payment;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Cumulative.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Cumulative.php
new file mode 100644
index 00000000000..b7f6011c315
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Cumulative.php
@@ -0,0 +1,141 @@
+getMessage();
+ }
+
+ // Validate parameters
+ if ($start < 1 || $start > $end) {
+ return Functions::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 Functions::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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php
new file mode 100644
index 00000000000..56d2e379298
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php
@@ -0,0 +1,216 @@
+getMessage();
+ }
+
+ // Validate parameters
+ if ($period <= 0 || $period > $numberOfPeriods) {
+ return Functions::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
+ */
+ 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 Functions::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 : Functions::NAN();
+ }
+
+ private static function rateNextGuess($rate, $numberOfPeriods, $payment, $presentValue, $futureValue, $type)
+ {
+ if ($rate == 0.0) {
+ return Functions::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 Functions::NAN();
+ }
+
+ return $numerator / $denominator;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php
new file mode 100644
index 00000000000..ca989e0058a
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php
@@ -0,0 +1,44 @@
+interest = $interest;
+ $this->principal = $principal;
+ }
+
+ public function interest(): float
+ {
+ return $this->interest;
+ }
+
+ public function principal(): float
+ {
+ return $this->principal;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php
new file mode 100644
index 00000000000..e103f923666
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php
@@ -0,0 +1,115 @@
+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 Functions::NAN();
+ }
+
+ // Calculate
+ $interestAndPrincipal = new InterestAndPrincipal(
+ $interestRate,
+ $period,
+ $numberOfPeriods,
+ $presentValue,
+ $futureValue,
+ $type
+ );
+
+ return $interestAndPrincipal->principal();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php
new file mode 100644
index 00000000000..a30634da3be
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php
@@ -0,0 +1,108 @@
+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 Functions::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 Functions::NAN();
+ }
+
+ return ($futureValue / $presentValue) ** (1 / $periods) - 1;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php
new file mode 100644
index 00000000000..8986146c11c
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php
@@ -0,0 +1,244 @@
+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 Functions::VALUE();
+ } elseif ($fld > 0) {
+ $foundpos = true;
+ } elseif ($fld < 0) {
+ $foundneg = true;
+ }
+ }
+ if (!self::bothNegAndPos($foundneg, $foundpos)) {
+ return Functions::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 = Functions::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;
+ }
+
+ /**
+ * @param mixed $rate
+ * @param mixed $values
+ * @param mixed $dates
+ *
+ * @return float|string
+ */
+ private static function xnpvOrdered($rate, $values, $dates, bool $ordered = true)
+ {
+ $rate = Functions::flattenSingleValue($rate);
+ $values = Functions::flattenArray($values);
+ $dates = Functions::flattenArray($dates);
+ $valCount = count($values);
+
+ try {
+ self::validateXnpv($rate, $values, $dates);
+ $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 Functions::VALUE();
+ }
+
+ try {
+ $datei = DateTimeExcel\Helpers::getDateValue($dates[$i]);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+ if ($date0 > $datei) {
+ $dif = $ordered ? Functions::NAN() : -((int) DateTimeExcel\Difference::interval($datei, $date0, 'd'));
+ } else {
+ $dif = DateTimeExcel\Difference::interval($date0, $datei, 'd');
+ }
+ if (!is_numeric($dif)) {
+ return $dif;
+ }
+ $xnpv += $values[$i] / (1 + $rate) ** ($dif / 365);
+ }
+
+ return is_finite($xnpv) ? $xnpv : Functions::VALUE();
+ }
+
+ /**
+ * @param mixed $rate
+ */
+ private static function validateXnpv($rate, array $values, array $dates): void
+ {
+ if (!is_numeric($rate)) {
+ throw new Exception(Functions::VALUE());
+ }
+ $valCount = count($values);
+ if ($valCount != count($dates)) {
+ throw new Exception(Functions::NAN());
+ }
+ if ($valCount > 1 && ((min($values) > 0) || (max($values) < 0))) {
+ throw new Exception(Functions::NAN());
+ }
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php
new file mode 100644
index 00000000000..c42df0c39eb
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php
@@ -0,0 +1,160 @@
+ 0.0) {
+ return Functions::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 Functions::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 Functions::VALUE();
+ }
+ $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 = 0.0;
+ foreach ($values as $i => $v) {
+ if ($v >= 0) {
+ $npvPos += $v / $rr ** $i;
+ } else {
+ $npvNeg += $v / $fr ** $i;
+ }
+ }
+
+ if (($npvNeg === 0.0) || ($npvPos === 0.0) || ($reinvestmentRate <= -1.0)) {
+ return Functions::VALUE();
+ }
+
+ $mirr = ((-$npvPos * $rr ** $n)
+ / ($npvNeg * ($rr))) ** (1.0 / ($n - 1)) - 1.0;
+
+ return is_finite($mirr) ? $mirr : Functions::VALUE();
+ }
+
+ /**
+ * NPV.
+ *
+ * Returns the Net Present Value of a cash flow series given a discount rate.
+ *
+ * @param mixed $rate
+ *
+ * @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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Constants.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Constants.php
new file mode 100644
index 00000000000..17740b0acd7
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Constants.php
@@ -0,0 +1,19 @@
+getMessage();
+ }
+
+ $daysPerYear = Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis);
+ if (is_string($daysPerYear)) {
+ return Functions::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 = Helpers::daysPerYear(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();
+ }
+
+ $daysPerYear = Helpers::daysPerYear(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);
+ } 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);
+ } 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);
+ } 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(Functions::NAN());
+ }
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Depreciation.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Depreciation.php
new file mode 100644
index 00000000000..650a4861b29
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Depreciation.php
@@ -0,0 +1,266 @@
+getMessage();
+ }
+
+ if ($cost === 0.0) {
+ 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 Functions::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 === 0.0) {
+ return Functions::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 Functions::NAN();
+ }
+
+ $syd = (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1));
+
+ return $syd;
+ }
+
+ private static function validateCost($cost, bool $negativeValueAllowed = false): float
+ {
+ $cost = FinancialValidations::validateFloat($cost);
+ if ($cost < 0.0 && $negativeValueAllowed === false) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $cost;
+ }
+
+ private static function validateSalvage($salvage, bool $negativeValueAllowed = false): float
+ {
+ $salvage = FinancialValidations::validateFloat($salvage);
+ if ($salvage < 0.0 && $negativeValueAllowed === false) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $salvage;
+ }
+
+ private static function validateLife($life, bool $negativeValueAllowed = false): float
+ {
+ $life = FinancialValidations::validateFloat($life);
+ if ($life < 0.0 && $negativeValueAllowed === false) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $life;
+ }
+
+ private static function validatePeriod($period, bool $negativeValueAllowed = false): float
+ {
+ $period = FinancialValidations::validateFloat($period);
+ if ($period <= 0.0 && $negativeValueAllowed === false) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $period;
+ }
+
+ private static function validateMonth($month): int
+ {
+ $month = FinancialValidations::validateInt($month);
+ if ($month < 1) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $month;
+ }
+
+ private static function validateFactor($factor): float
+ {
+ $factor = FinancialValidations::validateFloat($factor);
+ if ($factor <= 0.0) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $factor;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Dollar.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Dollar.php
new file mode 100644
index 00000000000..7bebb39178f
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Dollar.php
@@ -0,0 +1,97 @@
+ 4)) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $basis;
+ }
+
+ /**
+ * @param mixed $price
+ */
+ public static function validatePrice($price): float
+ {
+ $price = self::validateFloat($price);
+ if ($price < 0.0) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $price;
+ }
+
+ /**
+ * @param mixed $parValue
+ */
+ public static function validateParValue($parValue): float
+ {
+ $parValue = self::validateFloat($parValue);
+ if ($parValue < 0.0) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $parValue;
+ }
+
+ /**
+ * @param mixed $yield
+ */
+ public static function validateYield($yield): float
+ {
+ $yield = self::validateFloat($yield);
+ if ($yield < 0.0) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $yield;
+ }
+
+ /**
+ * @param mixed $discount
+ */
+ public static function validateDiscount($discount): float
+ {
+ $discount = self::validateFloat($discount);
+ if ($discount <= 0.0) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $discount;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Helpers.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Helpers.php
new file mode 100644
index 00000000000..d339b13416c
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Helpers.php
@@ -0,0 +1,58 @@
+format('d') === $date->format('t');
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/InterestRate.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/InterestRate.php
new file mode 100644
index 00000000000..72df31e1641
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/InterestRate.php
@@ -0,0 +1,72 @@
+getMessage();
+ }
+
+ if ($nominalRate <= 0 || $periodsPerYear < 1) {
+ return Functions::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 Functions::NAN();
+ }
+
+ // Calculate
+ return $periodsPerYear * (($effectiveRate + 1) ** (1 / $periodsPerYear) - 1);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php
new file mode 100644
index 00000000000..e167429b72b
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php
@@ -0,0 +1,151 @@
+getMessage();
+ }
+
+ $daysBetweenIssueAndSettlement = YearFrac::fraction($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
+ $daysBetweenFirstInterestAndSettlement = 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 = YearFrac::fraction($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
+
+ return $parValue * $rate * $daysBetweenIssueAndSettlement;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php
new file mode 100644
index 00000000000..7d8d5a3210e
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php
@@ -0,0 +1,283 @@
+getMessage();
+ }
+
+ $dsc = Coupons::COUPDAYSNC($settlement, $maturity, $frequency, $basis);
+ $e = Coupons::COUPDAYS($settlement, $maturity, $frequency, $basis);
+ $n = Coupons::COUPNUM($settlement, $maturity, $frequency, $basis);
+ $a = 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 = 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(DateTimeExcel\DateParts::year($settlement), $basis);
+ if (!is_numeric($daysPerYear)) {
+ return $daysPerYear;
+ }
+ $daysBetweenIssueAndSettlement = DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
+ $daysBetweenIssueAndSettlement *= $daysPerYear;
+ $daysBetweenIssueAndMaturity = DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis);
+ if (!is_numeric($daysBetweenIssueAndMaturity)) {
+ // return date error
+ return $daysBetweenIssueAndMaturity;
+ }
+ $daysBetweenIssueAndMaturity *= $daysPerYear;
+ $daysBetweenSettlementAndMaturity = 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 Functions::NAN();
+ }
+ $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+
+ return $investment / (1 - ($discount * $daysBetweenSettlementAndMaturity));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php
new file mode 100644
index 00000000000..c5c5211b70e
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php
@@ -0,0 +1,137 @@
+getMessage();
+ }
+
+ if ($price <= 0.0) {
+ return Functions::NAN();
+ }
+
+ $daysBetweenSettlementAndMaturity = 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 Functions::NAN();
+ }
+
+ $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis);
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
+ // return date error
+ return $daysBetweenSettlementAndMaturity;
+ }
+
+ return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php
new file mode 100644
index 00000000000..497197b843d
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php
@@ -0,0 +1,42 @@
+= $maturity) {
+ throw new Exception(Functions::NAN());
+ }
+ }
+
+ /**
+ * @param mixed $redemption
+ */
+ public static function validateRedemption($redemption): float
+ {
+ $redemption = self::validateFloat($redemption);
+ if ($redemption <= 0.0) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $redemption;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php
new file mode 100644
index 00000000000..aa6269354bb
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php
@@ -0,0 +1,153 @@
+getMessage();
+ }
+
+ $daysPerYear = Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis);
+ if (!is_numeric($daysPerYear)) {
+ return $daysPerYear;
+ }
+ $daysBetweenSettlementAndMaturity = 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(DateTimeExcel\DateParts::year($settlement), $basis);
+ if (!is_numeric($daysPerYear)) {
+ return $daysPerYear;
+ }
+ $daysBetweenIssueAndSettlement = DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis);
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
+ // return date error
+ return $daysBetweenIssueAndSettlement;
+ }
+ $daysBetweenIssueAndSettlement *= $daysPerYear;
+ $daysBetweenIssueAndMaturity = DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis);
+ if (!is_numeric($daysBetweenIssueAndMaturity)) {
+ // return date error
+ return $daysBetweenIssueAndMaturity;
+ }
+ $daysBetweenIssueAndMaturity *= $daysPerYear;
+ $daysBetweenSettlementAndMaturity = 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);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php
new file mode 100644
index 00000000000..c60af0b0d0c
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php
@@ -0,0 +1,147 @@
+getMessage();
+ }
+
+ if ($discount <= 0) {
+ return Functions::NAN();
+ }
+
+ $daysBetweenSettlementAndMaturity = $maturity - $settlement;
+ $daysPerYear = Helpers::daysPerYear(
+ DateTimeExcel\DateParts::year($maturity),
+ FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL
+ );
+
+ if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) {
+ return Functions::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 Functions::NAN();
+ }
+
+ $daysBetweenSettlementAndMaturity = $maturity - $settlement;
+ $daysPerYear = Helpers::daysPerYear(
+ DateTimeExcel\DateParts::year($maturity),
+ FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL
+ );
+
+ if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) {
+ return Functions::NAN();
+ }
+
+ $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360));
+ if ($price < 0.0) {
+ return Functions::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(
+ DateTimeExcel\DateParts::year($maturity),
+ FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL
+ );
+
+ if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) {
+ return Functions::NAN();
+ }
+
+ return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaParser.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaParser.php
index c11af834ff8..ddf45b23be8 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaParser.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaParser.php
@@ -61,17 +61,17 @@ class FormulaParser
/**
* Create a new FormulaParser.
*
- * @param string $pFormula Formula to parse
+ * @param string $formula Formula to parse
*/
- public function __construct($pFormula = '')
+ public function __construct($formula = '')
{
// Check parameters
- if ($pFormula === null) {
+ if ($formula === null) {
throw new Exception('Invalid parameter passed: formula');
}
// Initialise values
- $this->formula = trim($pFormula);
+ $this->formula = trim($formula);
// Parse!
$this->parseToTokens();
}
@@ -89,17 +89,15 @@ class FormulaParser
/**
* Get Token.
*
- * @param int $pId Token id
- *
- * @return string
+ * @param int $id Token id
*/
- public function getToken($pId = 0)
+ public function getToken(int $id = 0): FormulaToken
{
- if (isset($this->tokens[$pId])) {
- return $this->tokens[$pId];
+ if (isset($this->tokens[$id])) {
+ return $this->tokens[$id];
}
- throw new Exception("Token with id $pId does not exist.");
+ throw new Exception("Token with id $id does not exist.");
}
/**
@@ -492,7 +490,7 @@ class FormulaParser
if (
!(
- (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) ||
+ (($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)
)
@@ -506,7 +504,7 @@ class FormulaParser
if (
!(
- (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) ||
+ (($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)
)
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaToken.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaToken.php
index 4d225de2d5c..68e5eead81b 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaToken.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaToken.php
@@ -76,16 +76,16 @@ class FormulaToken
/**
* Create a new FormulaToken.
*
- * @param string $pValue
- * @param string $pTokenType Token type (represented by TOKEN_TYPE_*)
- * @param string $pTokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*)
+ * @param string $value
+ * @param string $tokenType Token type (represented by TOKEN_TYPE_*)
+ * @param string $tokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*)
*/
- public function __construct($pValue, $pTokenType = self::TOKEN_TYPE_UNKNOWN, $pTokenSubType = self::TOKEN_SUBTYPE_NOTHING)
+ public function __construct($value, $tokenType = self::TOKEN_TYPE_UNKNOWN, $tokenSubType = self::TOKEN_SUBTYPE_NOTHING)
{
// Initialise values
- $this->value = $pValue;
- $this->tokenType = $pTokenType;
- $this->tokenSubType = $pTokenSubType;
+ $this->value = $value;
+ $this->tokenType = $tokenType;
+ $this->tokenSubType = $tokenSubType;
}
/**
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php
index 2e8a7ecfccc..75d4582b2c7 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php
@@ -3,6 +3,8 @@
namespace PhpOffice\PhpSpreadsheet\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
+use PhpOffice\PhpSpreadsheet\Shared\Date;
+use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class Functions
{
@@ -13,12 +15,13 @@ class Functions
*/
const M_2DIVPI = 0.63661977236758134307553505349006;
- /** constants */
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';
@@ -250,11 +253,13 @@ class Functions
$condition = self::flattenSingleValue($condition);
if ($condition === '') {
- $condition = '=""';
+ return '=""';
}
-
if (!is_string($condition) || !in_array($condition[0], ['>', '<', '='])) {
- if (!is_numeric($condition)) {
+ $condition = self::operandSpecialHandling($condition);
+ if (is_bool($condition)) {
+ return '=' . ($condition ? 'TRUE' : 'FALSE');
+ } elseif (!is_numeric($condition)) {
$condition = Calculation::wrapResult(strtoupper($condition));
}
@@ -263,9 +268,10 @@ class Functions
preg_match('/(=|<[>=]?|>=?)(.*)/', $condition, $matches);
[, $operator, $operand] = $matches;
+ $operand = self::operandSpecialHandling($operand);
if (is_numeric(trim($operand, '"'))) {
$operand = trim($operand, '"');
- } elseif (!is_numeric($operand)) {
+ } elseif (!is_numeric($operand) && $operand !== 'FALSE' && $operand !== 'TRUE') {
$operand = str_replace('"', '""', $operand);
$operand = Calculation::wrapResult(strtoupper($operand));
}
@@ -273,12 +279,33 @@ class Functions
return str_replace('""""', '""', $operator . $operand);
}
+ 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;
+ }
+
/**
* ERROR_TYPE.
*
* @param mixed $value Value to check
*
- * @return bool
+ * @return int|string
*/
public static function errorType($value = '')
{
@@ -551,7 +578,7 @@ class Functions
/**
* Convert a multi-dimensional array to a simple 1-dimensional array.
*
- * @param array $array Array to be flattened
+ * @param array|mixed $array Array to be flattened
*
* @return array Flattened array
*/
@@ -584,7 +611,7 @@ class Functions
/**
* Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing.
*
- * @param array $array Array to be flattened
+ * @param array|mixed $array Array to be flattened
*
* @return array Flattened array
*/
@@ -634,15 +661,17 @@ class Functions
* ISFORMULA.
*
* @param mixed $cellReference The cell to check
- * @param Cell $pCell The current cell (containing this formula)
+ * @param ?Cell $cell The current cell (containing this formula)
*
* @return bool|string
*/
- public static function isFormula($cellReference = '', ?Cell $pCell = null)
+ public static function isFormula($cellReference = '', ?Cell $cell = null)
{
- if ($pCell === null) {
+ if ($cell === null) {
return self::REF();
}
+ $cellReference = self::expandDefinedName((string) $cellReference, $cell);
+ $cellReference = self::trimTrailingRange($cellReference);
preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellReference, $matches);
@@ -650,9 +679,33 @@ class Functions
$worksheetName = str_replace("''", "'", trim($matches[2], "'"));
$worksheet = (!empty($worksheetName))
- ? $pCell->getWorksheet()->getParent()->getSheetByName($worksheetName)
- : $pCell->getWorksheet();
+ ? $cell->getWorksheet()->getParent()->getSheetByName($worksheetName)
+ : $cell->getWorksheet();
return $worksheet->getCell($cellReference)->isFormula();
}
+
+ public static function expandDefinedName(string $coordinate, Cell $cell): string
+ {
+ $worksheet = $cell->getWorksheet();
+ $spreadsheet = $worksheet->getParent();
+ // Uppercase coordinate
+ $pCoordinatex = strtoupper($coordinate);
+ // Eliminate leading equal sign
+ $pCoordinatex = Worksheet::pregReplace('/^=/', '', $pCoordinatex);
+ $defined = $spreadsheet->getDefinedName($pCoordinatex, $worksheet);
+ if ($defined !== null) {
+ $worksheet2 = $defined->getWorkSheet();
+ if (!$defined->isFormula() && $worksheet2 !== null) {
+ $coordinate = "'" . $worksheet2->getTitle() . "'!" . Worksheet::pregReplace('/^=/', '', $defined->getValue());
+ }
+ }
+
+ return $coordinate;
+ }
+
+ public static function trimTrailingRange(string $coordinate): string
+ {
+ return Worksheet::pregReplace('/:[\\w\$]+$/', '', $coordinate);
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php
new file mode 100644
index 00000000000..8b53464fc47
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php
@@ -0,0 +1,11 @@
+ 0) && ($returnValue == $argCount);
+ return Logical\Operations::logicalAnd(...$args);
}
/**
@@ -114,8 +92,13 @@ class Logical
*
* 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
+ * 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
+ *
+ * @see Logical\Operations::logicalOr()
+ * Use the logicalOr() method in the Logical\Operations class instead
*
* @param mixed $args Data values
*
@@ -123,29 +106,15 @@ class Logical
*/
public static function logicalOr(...$args)
{
- $args = Functions::flattenArray($args);
-
- if (count($args) == 0) {
- return Functions::VALUE();
- }
-
- $args = array_filter($args, function ($value) {
- return $value !== null || (is_string($value) && trim($value) == '');
- });
-
- $returnValue = self::countTrueValues($args);
- if (is_string($returnValue)) {
- return $returnValue;
- }
-
- return $returnValue > 0;
+ 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.
+ * 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[, ...]])
@@ -155,8 +124,13 @@ class Logical
*
* 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
+ * 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
+ *
+ * @see Logical\Operations::logicalXor()
+ * Use the logicalXor() method in the Logical\Operations class instead
*
* @param mixed $args Data values
*
@@ -164,22 +138,7 @@ class Logical
*/
public static function logicalXor(...$args)
{
- $args = Functions::flattenArray($args);
-
- if (count($args) == 0) {
- return Functions::VALUE();
- }
-
- $args = array_filter($args, function ($value) {
- return $value !== null || (is_string($value) && trim($value) == '');
- });
-
- $returnValue = self::countTrueValues($args);
- if (is_string($returnValue)) {
- return $returnValue;
- }
-
- return $returnValue % 2 == 1;
+ return Logical\Operations::logicalXor(...$args);
}
/**
@@ -194,8 +153,13 @@ class Logical
*
* 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
+ * 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
+ *
+ * @see Logical\Operations::NOT()
+ * Use the NOT() method in the Logical\Operations class instead
*
* @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE
*
@@ -203,20 +167,7 @@ class Logical
*/
public static function NOT($logical = false)
{
- $logical = Functions::flattenSingleValue($logical);
-
- if (is_string($logical)) {
- $logical = strtoupper($logical);
- if (($logical == 'TRUE') || ($logical == Calculation::getTRUE())) {
- return false;
- } elseif (($logical == 'FALSE') || ($logical == Calculation::getFALSE())) {
- return true;
- }
-
- return Functions::VALUE();
- }
-
- return !$logical;
+ return Logical\Operations::NOT($logical);
}
/**
@@ -232,18 +183,23 @@ class Logical
* 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.
+ * 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".
+ * 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
+ *
+ * @see Logical\Conditional::statementIf()
+ * Use the statementIf() method in the Logical\Conditional class instead
+ *
* @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
@@ -252,15 +208,7 @@ class Logical
*/
public static function statementIf($condition = true, $returnIfTrue = 0, $returnIfFalse = false)
{
- if (Functions::isError($condition)) {
- return $condition;
- }
-
- $condition = ($condition === null) ? true : (bool) Functions::flattenSingleValue($condition);
- $returnIfTrue = ($returnIfTrue === null) ? 0 : Functions::flattenSingleValue($returnIfTrue);
- $returnIfFalse = ($returnIfFalse === null) ? false : Functions::flattenSingleValue($returnIfFalse);
-
- return ($condition) ? $returnIfTrue : $returnIfFalse;
+ return Logical\Conditional::statementIf($condition, $returnIfTrue, $returnIfFalse);
}
/**
@@ -274,11 +222,19 @@ class Logical
* 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.
+ * 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.
+ * 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).
+ * Optional. It is the default to return if expression does not match any of the values
+ * (value1, value2, ... value_n).
+ *
+ * @Deprecated 1.17.0
+ *
+ * @see Logical\Conditional::statementSwitch()
+ * Use the statementSwitch() method in the Logical\Conditional class instead
*
* @param mixed $arguments Statement arguments
*
@@ -286,33 +242,7 @@ class Logical
*/
public static function statementSwitch(...$arguments)
{
- $result = Functions::VALUE();
-
- if (count($arguments) > 0) {
- $targetValue = Functions::flattenSingleValue($arguments[0]);
- $argc = count($arguments) - 1;
- $switchCount = floor($argc / 2);
- $switchSatisfied = false;
- $hasDefaultClause = $argc % 2 !== 0;
- $defaultClause = $argc % 2 === 0 ? null : $arguments[count($arguments) - 1];
-
- if ($switchCount) {
- for ($index = 0; $index < $switchCount; ++$index) {
- if ($targetValue == $arguments[$index * 2 + 1]) {
- $result = $arguments[$index * 2 + 2];
- $switchSatisfied = true;
-
- break;
- }
- }
- }
-
- if (!$switchSatisfied) {
- $result = $hasDefaultClause ? $defaultClause : Functions::NA();
- }
- }
-
- return $result;
+ return Logical\Conditional::statementSwitch(...$arguments);
}
/**
@@ -321,6 +251,11 @@ class Logical
* Excel Function:
* =IFERROR(testValue,errorpart)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Logical\Conditional::IFERROR()
+ * Use the IFERROR() method in the Logical\Conditional class instead
+ *
* @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
*
@@ -328,10 +263,7 @@ class Logical
*/
public static function IFERROR($testValue = '', $errorpart = '')
{
- $testValue = ($testValue === null) ? '' : Functions::flattenSingleValue($testValue);
- $errorpart = ($errorpart === null) ? '' : Functions::flattenSingleValue($errorpart);
-
- return self::statementIf(Functions::isError($testValue), $errorpart, $testValue);
+ return Logical\Conditional::IFERROR($testValue, $errorpart);
}
/**
@@ -340,6 +272,11 @@ class Logical
* Excel Function:
* =IFNA(testValue,napart)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Logical\Conditional::IFNA()
+ * Use the IFNA() method in the Logical\Conditional class instead
+ *
* @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
*
@@ -347,10 +284,7 @@ class Logical
*/
public static function IFNA($testValue = '', $napart = '')
{
- $testValue = ($testValue === null) ? '' : Functions::flattenSingleValue($testValue);
- $napart = ($napart === null) ? '' : Functions::flattenSingleValue($napart);
-
- return self::statementIf(Functions::isNa($testValue), $napart, $testValue);
+ return Logical\Conditional::IFNA($testValue, $napart);
}
/**
@@ -364,27 +298,17 @@ class Logical
* returnIfTrue1 ... returnIfTrue_n
* Value returned if corresponding testValue (nth) was true
*
+ * @Deprecated 1.17.0
+ *
+ * @see Logical\Conditional::IFS()
+ * Use the IFS() method in the Logical\Conditional class instead
+ *
* @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)
{
- if (count($arguments) % 2 != 0) {
- return Functions::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 < count($arguments); $i += 2) {
- $testValue = ($arguments[$i] === null) ? '' : Functions::flattenSingleValue($arguments[$i]);
- $returnIfTrue = ($arguments[$i + 1] === null) ? '' : Functions::flattenSingleValue($arguments[$i + 1]);
- $result = self::statementIf($testValue, $returnIfTrue, $falseValueException);
-
- if ($result !== $falseValueException) {
- return $result;
- }
- }
-
- return Functions::NA();
+ return Logical\Conditional::IFS(...$arguments);
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Boolean.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Boolean.php
new file mode 100644
index 00000000000..8f1e9354d85
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Boolean.php
@@ -0,0 +1,36 @@
+ 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 == $arguments[$index * 2 + 1]) {
+ $result = $arguments[$index * 2 + 2];
+ $switchSatisfied = true;
+
+ break;
+ }
+ }
+ }
+
+ if ($switchSatisfied !== true) {
+ $result = $hasDefaultClause ? $defaultClause : Functions::NA();
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * IFERROR.
+ *
+ * Excel Function:
+ * =IFERROR(testValue,errorpart)
+ *
+ * @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 = '')
+ {
+ $testValue = ($testValue === null) ? '' : Functions::flattenSingleValue($testValue);
+ $errorpart = ($errorpart === null) ? '' : Functions::flattenSingleValue($errorpart);
+
+ return self::statementIf(Functions::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
+ * @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 = '')
+ {
+ $testValue = ($testValue === null) ? '' : Functions::flattenSingleValue($testValue);
+ $napart = ($napart === null) ? '' : Functions::flattenSingleValue($napart);
+
+ return self::statementIf(Functions::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
+ *
+ * @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 Functions::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) ? '' : Functions::flattenSingleValue($arguments[$i + 1]);
+ $result = self::statementIf($testValue, $returnIfTrue, $falseValueException);
+
+ if ($result !== $falseValueException) {
+ return $result;
+ }
+ }
+
+ return Functions::NA();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Operations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Operations.php
new file mode 100644
index 00000000000..6bfb6a545b6
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Operations.php
@@ -0,0 +1,198 @@
+ 0) && ($returnValue == $argCount);
+ }
+
+ /**
+ * 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)
+ {
+ $args = Functions::flattenArray($args);
+
+ if (count($args) == 0) {
+ return Functions::VALUE();
+ }
+
+ $args = array_filter($args, function ($value) {
+ return $value !== null || (is_string($value) && trim($value) == '');
+ });
+
+ $returnValue = self::countTrueValues($args);
+ if (is_string($returnValue)) {
+ return $returnValue;
+ }
+
+ return $returnValue > 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)
+ {
+ $args = Functions::flattenArray($args);
+
+ if (count($args) == 0) {
+ return Functions::VALUE();
+ }
+
+ $args = array_filter($args, function ($value) {
+ return $value !== null || (is_string($value) && trim($value) == '');
+ });
+
+ $returnValue = self::countTrueValues($args);
+ if (is_string($returnValue)) {
+ return $returnValue;
+ }
+
+ return $returnValue % 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
+ *
+ * @return bool|string the boolean inverse of the argument
+ */
+ public static function NOT($logical = false)
+ {
+ $logical = Functions::flattenSingleValue($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 Functions::VALUE();
+ }
+
+ return !$logical;
+ }
+
+ /**
+ * @return int|string
+ */
+ private static function countTrueValues(array $args)
+ {
+ $trueValueCount = 0;
+
+ foreach ($args as $arg) {
+ // Is it a boolean value?
+ if (is_bool($arg)) {
+ $trueValueCount += $arg;
+ } elseif ((is_numeric($arg)) && (!is_string($arg))) {
+ $trueValueCount += ((int) $arg != 0);
+ } elseif (is_string($arg)) {
+ $arg = mb_strtoupper($arg, 'UTF-8');
+ if (($arg == 'TRUE') || ($arg == Calculation::getTRUE())) {
+ $arg = true;
+ } elseif (($arg == 'FALSE') || ($arg == Calculation::getFALSE())) {
+ $arg = false;
+ } else {
+ return Functions::VALUE();
+ }
+ $trueValueCount += ($arg != 0);
+ }
+ }
+
+ return $trueValueCount;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef.php
index 45aa9239641..67650480fdc 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef.php
@@ -2,11 +2,20 @@
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\Cell\Coordinate;
-use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
+/**
+ * @deprecated 1.18.0
+ */
class LookupRef
{
/**
@@ -17,15 +26,20 @@ class LookupRef
* Excel Function:
* =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText])
*
+ * @Deprecated 1.18.0
+ *
+ * @see LookupRef\Address::cell()
+ * Use the cell() method in the LookupRef\Address class instead
+ *
* @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
+ * 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
+ * TRUE or omitted CELL_ADDRESS returns an A1-style reference
* FALSE CELL_ADDRESS returns an R1C1-style reference
* @param string $sheetText Optional Name of worksheet to use
*
@@ -33,87 +47,34 @@ class LookupRef
*/
public static function cellAddress($row, $column, $relativity = 1, $referenceStyle = true, $sheetText = '')
{
- $row = Functions::flattenSingleValue($row);
- $column = Functions::flattenSingleValue($column);
- $relativity = Functions::flattenSingleValue($relativity);
- $sheetText = Functions::flattenSingleValue($sheetText);
-
- if (($row < 1) || ($column < 1)) {
- return Functions::VALUE();
- }
-
- if ($sheetText > '') {
- if (strpos($sheetText, ' ') !== false) {
- $sheetText = "'" . $sheetText . "'";
- }
- $sheetText .= '!';
- }
- if ((!is_bool($referenceStyle)) || $referenceStyle) {
- $rowRelative = $columnRelative = '$';
- $column = Coordinate::stringFromColumnIndex($column);
- if (($relativity == 2) || ($relativity == 4)) {
- $columnRelative = '';
- }
- if (($relativity == 3) || ($relativity == 4)) {
- $rowRelative = '';
- }
-
- return $sheetText . $columnRelative . $column . $rowRelative . $row;
- }
- if (($relativity == 2) || ($relativity == 4)) {
- $column = '[' . $column . ']';
- }
- if (($relativity == 3) || ($relativity == 4)) {
- $row = '[' . $row . ']';
- }
-
- return $sheetText . 'R' . $row . 'C' . $column;
+ 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 0.
+ * 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
+ *
+ * @see LookupRef\RowColumnInformation::COLUMN()
+ * Use the COLUMN() method in the LookupRef\RowColumnInformation class instead
+ *
* @param null|array|string $cellAddress A reference to a range of cells for which you want the column numbers
*
- * @return int|int[]
+ * @return int|int[]|string
*/
- public static function COLUMN($cellAddress = null)
+ public static function COLUMN($cellAddress = null, ?Cell $cell = null)
{
- if ($cellAddress === null || trim($cellAddress) === '') {
- return 0;
- }
-
- if (is_array($cellAddress)) {
- foreach ($cellAddress as $columnKey => $value) {
- $columnKey = preg_replace('/[^a-z]/i', '', $columnKey);
-
- return (int) Coordinate::columnIndexFromString($columnKey);
- }
- } else {
- [$sheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
- if (strpos($cellAddress, ':') !== false) {
- [$startAddress, $endAddress] = explode(':', $cellAddress);
- $startAddress = preg_replace('/[^a-z]/i', '', $startAddress);
- $endAddress = preg_replace('/[^a-z]/i', '', $endAddress);
- $returnValue = [];
- do {
- $returnValue[] = (int) Coordinate::columnIndexFromString($startAddress);
- } while ($startAddress++ != $endAddress);
-
- return $returnValue;
- }
- $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress);
-
- return (int) Coordinate::columnIndexFromString($cellAddress);
- }
+ return RowColumnInformation::COLUMN($cellAddress, $cell);
}
/**
@@ -124,73 +85,46 @@ class LookupRef
* 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
+ * @Deprecated 1.18.0
+ *
+ * @see LookupRef\RowColumnInformation::COLUMNS()
+ * Use the COLUMNS() method in the LookupRef\RowColumnInformation class instead
+ *
+ * @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 ($cellAddress === null || $cellAddress === '') {
- return 1;
- } elseif (!is_array($cellAddress)) {
- return Functions::VALUE();
- }
-
- reset($cellAddress);
- $isMatrix = (is_numeric(key($cellAddress)));
- [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress);
-
- if ($isMatrix) {
- return $rows;
- }
-
- return $columns;
+ 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 0.
+ * 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
+ *
+ * @see LookupRef\RowColumnInformation::ROW()
+ * Use the ROW() method in the LookupRef\RowColumnInformation class instead
+ *
* @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)
+ public static function ROW($cellAddress = null, ?Cell $cell = null)
{
- if ($cellAddress === null || trim($cellAddress) === '') {
- return 0;
- }
-
- if (is_array($cellAddress)) {
- foreach ($cellAddress as $columnKey => $rowValue) {
- foreach ($rowValue as $rowKey => $cellValue) {
- return (int) preg_replace('/\D/', '', $rowKey);
- }
- }
- } else {
- [$sheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
- if (strpos($cellAddress, ':') !== false) {
- [$startAddress, $endAddress] = explode(':', $cellAddress);
- $startAddress = preg_replace('/\D/', '', $startAddress);
- $endAddress = preg_replace('/\D/', '', $endAddress);
- $returnValue = [];
- do {
- $returnValue[][] = (int) $startAddress;
- } while ($startAddress++ != $endAddress);
-
- return $returnValue;
- }
- [$cellAddress] = explode(':', $cellAddress);
-
- return (int) preg_replace('/\D/', '', $cellAddress);
- }
+ return RowColumnInformation::ROW($cellAddress, $cell);
}
/**
@@ -201,27 +135,19 @@ class LookupRef
* 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
+ * @Deprecated 1.18.0
+ *
+ * @see LookupRef\RowColumnInformation::ROWS()
+ * Use the ROWS() method in the LookupRef\RowColumnInformation class instead
+ *
+ * @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 ($cellAddress === null || $cellAddress === '') {
- return 1;
- } elseif (!is_array($cellAddress)) {
- return Functions::VALUE();
- }
-
- reset($cellAddress);
- $isMatrix = (is_numeric(key($cellAddress)));
- [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress);
-
- if ($isMatrix) {
- return $columns;
- }
-
- return $rows;
+ return RowColumnInformation::ROWS($cellAddress);
}
/**
@@ -230,29 +156,20 @@ class LookupRef
* Excel Function:
* =HYPERLINK(linkURL,displayName)
*
- * @param string $linkURL Value to check, is also the value returned when no error
- * @param string $displayName Value to return when testValue is an error condition
- * @param Cell $pCell The cell to set the hyperlink in
+ * @Deprecated 1.18.0
*
- * @return mixed The value of $displayName (or $linkURL if $displayName was blank)
+ * @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)
+ *
+ *@see LookupRef\Hyperlink::set()
+ * Use the set() method in the LookupRef\Hyperlink class instead
*/
- public static function HYPERLINK($linkURL = '', $displayName = null, ?Cell $pCell = null)
+ public static function HYPERLINK($linkURL = '', $displayName = null, ?Cell $cell = null)
{
- $linkURL = ($linkURL === null) ? '' : Functions::flattenSingleValue($linkURL);
- $displayName = ($displayName === null) ? '' : Functions::flattenSingleValue($displayName);
-
- if ((!is_object($pCell)) || (trim($linkURL) == '')) {
- return Functions::REF();
- }
-
- if ((is_object($displayName)) || trim($displayName) == '') {
- $displayName = $linkURL;
- }
-
- $pCell->getHyperlink()->setUrl($linkURL);
- $pCell->getHyperlink()->setTooltip($displayName);
-
- return $displayName;
+ return LookupRef\Hyperlink::set($linkURL, $displayName, $cell);
}
/**
@@ -264,56 +181,21 @@ class LookupRef
* Excel Function:
* =INDIRECT(cellAddress)
*
+ * @Deprecated 1.18.0
+ *
+ * @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
+ *
+ *@see LookupRef\Indirect::INDIRECT()
+ * Use the INDIRECT() method in the LookupRef\Indirect class instead
+ *
* NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010
- *
- * @param null|array|string $cellAddress $cellAddress The cell address of the current cell (containing this formula)
- * @param Cell $pCell The current cell (containing this formula)
- *
- * @return mixed The cells referenced by cellAddress
- *
- * @TODO Support for the optional a1 parameter introduced in Excel 2010
*/
- public static function INDIRECT($cellAddress = null, ?Cell $pCell = null)
+ public static function INDIRECT($cellAddress, Cell $cell)
{
- $cellAddress = Functions::flattenSingleValue($cellAddress);
- if ($cellAddress === null || $cellAddress === '') {
- return Functions::REF();
- }
-
- $cellAddress1 = $cellAddress;
- $cellAddress2 = null;
- if (strpos($cellAddress, ':') !== false) {
- [$cellAddress1, $cellAddress2] = explode(':', $cellAddress);
- }
-
- if (
- (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress1, $matches)) ||
- (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress2, $matches)))
- ) {
- if (!preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $cellAddress1, $matches)) {
- return Functions::REF();
- }
-
- if (strpos($cellAddress, '!') !== false) {
- [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
- $sheetName = trim($sheetName, "'");
- $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
- } else {
- $pSheet = $pCell->getWorksheet();
- }
-
- return Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, false);
- }
-
- if (strpos($cellAddress, '!') !== false) {
- [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
- $sheetName = trim($sheetName, "'");
- $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
- } else {
- $pSheet = $pCell->getWorksheet();
- }
-
- return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
+ return Indirect::INDIRECT($cellAddress, true, $cell);
}
/**
@@ -326,87 +208,34 @@ class LookupRef
* 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.
+ * @Deprecated 1.18.0
*
- * @return string A reference to a cell or range of cells
+ * @see LookupRef\Offset::OFFSET()
+ * Use the OFFSET() method in the LookupRef\Offset class instead
+ *
+ * @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|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 $pCell = null)
+ 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) {
- return 0;
- }
-
- if (!is_object($pCell)) {
- return Functions::REF();
- }
-
- $sheetName = null;
- if (strpos($cellAddress, '!')) {
- [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
- $sheetName = trim($sheetName, "'");
- }
- if (strpos($cellAddress, ':')) {
- [$startCell, $endCell] = explode(':', $cellAddress);
- } else {
- $startCell = $endCell = $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 Functions::REF();
- }
- $endCellColumn = Coordinate::columnIndexFromString($endCellColumn) - 1;
- if (($width != null) && (!is_object($width))) {
- $endCellColumn = $startCellColumn + $width - 1;
- } else {
- $endCellColumn += $columns;
- }
- $startCellColumn = Coordinate::stringFromColumnIndex($startCellColumn + 1);
-
- if (($height != null) && (!is_object($height))) {
- $endCellRow = $startCellRow + $height - 1;
- } else {
- $endCellRow += $rows;
- }
-
- if (($endCellRow <= 0) || ($endCellColumn < 0)) {
- return Functions::REF();
- }
- $endCellColumn = Coordinate::stringFromColumnIndex($endCellColumn + 1);
-
- $cellAddress = $startCellColumn . $startCellRow;
- if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) {
- $cellAddress .= ':' . $endCellColumn . $endCellRow;
- }
-
- if ($sheetName !== null) {
- $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
- } else {
- $pSheet = $pCell->getWorksheet();
- }
-
- return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
+ return Offset::OFFSET($cellAddress, $rows, $columns, $height, $width, $cell);
}
/**
@@ -418,31 +247,16 @@ class LookupRef
* Excel Function:
* =CHOOSE(index_num, value1, [value2], ...)
*
+ * @Deprecated 1.18.0
+ *
+ * @see LookupRef\Selection::choose()
+ * Use the choose() method in the LookupRef\Selection class instead
+ *
* @return mixed The selected value
*/
public static function CHOOSE(...$chooseArgs)
{
- $chosenEntry = Functions::flattenArray(array_shift($chooseArgs));
- $entryCount = count($chooseArgs) - 1;
-
- if (is_array($chosenEntry)) {
- $chosenEntry = array_shift($chosenEntry);
- }
- if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) {
- --$chosenEntry;
- } else {
- return Functions::VALUE();
- }
- $chosenEntry = floor($chosenEntry);
- if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) {
- return Functions::VALUE();
- }
-
- if (is_array($chooseArgs[$chosenEntry])) {
- return Functions::flattenArray($chooseArgs[$chosenEntry]);
- }
-
- return $chooseArgs[$chosenEntry];
+ return LookupRef\Selection::choose(...$chooseArgs);
}
/**
@@ -453,6 +267,11 @@ class LookupRef
* Excel Function:
* =MATCH(lookup_value, lookup_array, [match_type])
*
+ * @Deprecated 1.18.0
+ *
+ * @see LookupRef\ExcelMatch::MATCH()
+ * Use the MATCH() method in the LookupRef\ExcelMatch class instead
+ *
* @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.
@@ -462,145 +281,7 @@ class LookupRef
*/
public static function MATCH($lookupValue, $lookupArray, $matchType = 1)
{
- $lookupArray = Functions::flattenArray($lookupArray);
- $lookupValue = Functions::flattenSingleValue($lookupValue);
- $matchType = ($matchType === null) ? 1 : (int) Functions::flattenSingleValue($matchType);
-
- // MATCH is not case sensitive, so we convert lookup value to be lower cased in case it's string type.
- if (is_string($lookupValue)) {
- $lookupValue = StringHelper::strToLower($lookupValue);
- }
-
- // Lookup_value type has to be number, text, or logical values
- if ((!is_numeric($lookupValue)) && (!is_string($lookupValue)) && (!is_bool($lookupValue))) {
- return Functions::NA();
- }
-
- // Match_type is 0, 1 or -1
- if (($matchType !== 0) && ($matchType !== -1) && ($matchType !== 1)) {
- return Functions::NA();
- }
-
- // Lookup_array should not be empty
- $lookupArraySize = count($lookupArray);
- if ($lookupArraySize <= 0) {
- return Functions::NA();
- }
-
- if ($matchType == 1) {
- // If match_type is 1 the list has to be processed from last to first
-
- $lookupArray = array_reverse($lookupArray);
- $keySet = array_reverse(array_keys($lookupArray));
- }
-
- // Lookup_array should contain only number, text, or logical values, or empty (null) cells
- foreach ($lookupArray as $i => $lookupArrayValue) {
- // check the type of the value
- if (
- (!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) &&
- (!is_bool($lookupArrayValue)) && ($lookupArrayValue !== null)
- ) {
- return Functions::NA();
- }
- // Convert strings to lowercase for case-insensitive testing
- if (is_string($lookupArrayValue)) {
- $lookupArray[$i] = StringHelper::strToLower($lookupArrayValue);
- }
- if (($lookupArrayValue === null) && (($matchType == 1) || ($matchType == -1))) {
- unset($lookupArray[$i]);
- }
- }
-
- // **
- // find the match
- // **
-
- if ($matchType === 0 || $matchType === 1) {
- foreach ($lookupArray as $i => $lookupArrayValue) {
- $typeMatch = ((gettype($lookupValue) === gettype($lookupArrayValue)) || (is_numeric($lookupValue) && is_numeric($lookupArrayValue)));
- $exactTypeMatch = $typeMatch && $lookupArrayValue === $lookupValue;
- $nonOnlyNumericExactMatch = !$typeMatch && $lookupArrayValue === $lookupValue;
- $exactMatch = $exactTypeMatch || $nonOnlyNumericExactMatch;
-
- if ($matchType === 0) {
- if ($typeMatch && is_string($lookupValue) && (bool) preg_match('/([\?\*])/', $lookupValue)) {
- $splitString = $lookupValue;
- $chars = array_map(function ($i) use ($splitString) {
- return mb_substr($splitString, $i, 1);
- }, range(0, mb_strlen($splitString) - 1));
-
- $length = count($chars);
- $pattern = '/^';
- for ($j = 0; $j < $length; ++$j) {
- if ($chars[$j] === '~') {
- if (isset($chars[$j + 1])) {
- if ($chars[$j + 1] === '*') {
- $pattern .= preg_quote($chars[$j + 1], '/');
- ++$j;
- } elseif ($chars[$j + 1] === '?') {
- $pattern .= preg_quote($chars[$j + 1], '/');
- ++$j;
- }
- } else {
- $pattern .= preg_quote($chars[$j], '/');
- }
- } elseif ($chars[$j] === '*') {
- $pattern .= '.*';
- } elseif ($chars[$j] === '?') {
- $pattern .= '.{1}';
- } else {
- $pattern .= preg_quote($chars[$j], '/');
- }
- }
-
- $pattern .= '$/';
- if ((bool) preg_match($pattern, $lookupArrayValue)) {
- // exact match
- return $i + 1;
- }
- } elseif ($exactMatch) {
- // exact match
- return $i + 1;
- }
- } elseif (($matchType === 1) && $typeMatch && ($lookupArrayValue <= $lookupValue)) {
- $i = array_search($i, $keySet);
-
- // The current value is the (first) match
- return $i + 1;
- }
- }
- } else {
- $maxValueKey = null;
-
- // 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);
- $exactTypeMatch = $typeMatch && $lookupArrayValue === $lookupValue;
- $nonOnlyNumericExactMatch = !$typeMatch && $lookupArrayValue === $lookupValue;
- $exactMatch = $exactTypeMatch || $nonOnlyNumericExactMatch;
-
- if ($exactMatch) {
- // Another "special" case. If a perfect match is found,
- // the algorithm gives up immediately
- return $i + 1;
- } elseif ($typeMatch & $lookupArrayValue >= $lookupValue) {
- $maxValueKey = $i + 1;
- } elseif ($typeMatch & $lookupArrayValue < $lookupValue) {
- //Excel algorithm gives up immediately if the first element is smaller than the searched value
- break;
- }
- }
-
- if ($maxValueKey !== null) {
- return $maxValueKey;
- }
- }
-
- // Unsuccessful in finding a match, return #N/A error value
- return Functions::NA();
+ return LookupRef\ExcelMatch::MATCH($lookupValue, $lookupArray, $matchType);
}
/**
@@ -611,262 +292,99 @@ class LookupRef
* Excel Function:
* =INDEX(range_array, row_num, [column_num])
*
- * @param mixed $arrayValues A range of cells or an array constant
- * @param mixed $rowNum The row in array from which to return a value. If row_num is omitted, column_num is required.
- * @param mixed $columnNum The column in array from which to return a value. If column_num is omitted, row_num is required.
+ * @Deprecated 1.18.0
+ *
+ * @see LookupRef\Matrix::index()
+ * Use the index() method in the LookupRef\Matrix class instead
+ *
+ * @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($arrayValues, $rowNum = 0, $columnNum = 0)
+ public static function INDEX($matrix, $rowNum = 0, $columnNum = 0)
{
- $rowNum = Functions::flattenSingleValue($rowNum);
- $columnNum = Functions::flattenSingleValue($columnNum);
-
- if (($rowNum < 0) || ($columnNum < 0)) {
- return Functions::VALUE();
- }
-
- if (!is_array($arrayValues) || ($rowNum > count($arrayValues))) {
- return Functions::REF();
- }
-
- $rowKeys = array_keys($arrayValues);
- $columnKeys = @array_keys($arrayValues[$rowKeys[0]]);
-
- if ($columnNum > count($columnKeys)) {
- return Functions::VALUE();
- } elseif ($columnNum == 0) {
- if ($rowNum == 0) {
- return $arrayValues;
- }
- $rowNum = $rowKeys[--$rowNum];
- $returnArray = [];
- foreach ($arrayValues as $arrayColumn) {
- if (is_array($arrayColumn)) {
- if (isset($arrayColumn[$rowNum])) {
- $returnArray[] = $arrayColumn[$rowNum];
- } else {
- return [$rowNum => $arrayValues[$rowNum]];
- }
- } else {
- return $arrayValues[$rowNum];
- }
- }
-
- return $returnArray;
- }
- $columnNum = $columnKeys[--$columnNum];
- if ($rowNum > count($rowKeys)) {
- return Functions::VALUE();
- } elseif ($rowNum == 0) {
- return $arrayValues[$columnNum];
- }
- $rowNum = $rowKeys[--$rowNum];
-
- return $arrayValues[$rowNum][$columnNum];
+ return Matrix::index($matrix, $rowNum, $columnNum);
}
/**
* TRANSPOSE.
*
+ * @Deprecated 1.18.0
+ *
+ * @see LookupRef\Matrix::transpose()
+ * Use the transpose() method in the LookupRef\Matrix class instead
+ *
* @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
+ * 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)
{
- $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;
- }
-
- private static function vlookupSort($a, $b)
- {
- reset($a);
- $firstColumn = key($a);
- $aLower = StringHelper::strToLower($a[$firstColumn]);
- $bLower = StringHelper::strToLower($b[$firstColumn]);
- if ($aLower == $bLower) {
- return 0;
- }
-
- return ($aLower < $bLower) ? -1 : 1;
+ 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.
+ * 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
+ *
+ * @see LookupRef\VLookup::lookup()
+ * Use the lookup() method in the LookupRef\VLookup class instead
*
* @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 $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)
{
- $lookup_value = Functions::flattenSingleValue($lookup_value);
- $index_number = Functions::flattenSingleValue($index_number);
- $not_exact_match = Functions::flattenSingleValue($not_exact_match);
-
- // index_number must be greater than or equal to 1
- if ($index_number < 1) {
- return Functions::VALUE();
- }
-
- // index_number must be less than or equal to the number of columns in lookup_array
- if ((!is_array($lookup_array)) || (empty($lookup_array))) {
- return Functions::REF();
- }
- $f = array_keys($lookup_array);
- $firstRow = array_pop($f);
- if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
- return Functions::REF();
- }
- $columnKeys = array_keys($lookup_array[$firstRow]);
- $returnColumn = $columnKeys[--$index_number];
- $firstColumn = array_shift($columnKeys);
-
- if (!$not_exact_match) {
- uasort($lookup_array, ['self', 'vlookupSort']);
- }
-
- $lookupLower = StringHelper::strToLower($lookup_value);
- $rowNumber = $rowValue = false;
- foreach ($lookup_array as $rowKey => $rowData) {
- $firstLower = StringHelper::strToLower($rowData[$firstColumn]);
-
- // break if we have passed possible keys
- if (
- (is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) ||
- (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && ($firstLower > $lookupLower))
- ) {
- break;
- }
- // remember the last key, but only if datatypes match
- if (
- (is_numeric($lookup_value) && is_numeric($rowData[$firstColumn])) ||
- (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]))
- ) {
- if ($not_exact_match) {
- $rowNumber = $rowKey;
-
- continue;
- } elseif (
- ($firstLower == $lookupLower)
- // 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)
- && (($rowNumber == false) || ($rowKey < $rowNumber))
- ) {
- $rowNumber = $rowKey;
- }
- }
- }
-
- if ($rowNumber !== false) {
- // return the appropriate value
- return $lookup_array[$rowNumber][$returnColumn];
- }
-
- return Functions::NA();
+ 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.
+ * 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
+ *
+ * @see LookupRef\HLookup::lookup()
+ * Use the lookup() method in the LookupRef\HLookup class instead
*
* @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 $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)
{
- $lookup_value = Functions::flattenSingleValue($lookup_value);
- $index_number = Functions::flattenSingleValue($index_number);
- $not_exact_match = Functions::flattenSingleValue($not_exact_match);
-
- // index_number must be greater than or equal to 1
- if ($index_number < 1) {
- return Functions::VALUE();
- }
-
- // index_number must be less than or equal to the number of columns in lookup_array
- if ((!is_array($lookup_array)) || (empty($lookup_array))) {
- return Functions::REF();
- }
- $f = array_keys($lookup_array);
- $firstRow = reset($f);
- if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array))) {
- return Functions::REF();
- }
-
- $firstkey = $f[0] - 1;
- $returnColumn = $firstkey + $index_number;
- $firstColumn = array_shift($f);
- $rowNumber = null;
- foreach ($lookup_array[$firstColumn] as $rowKey => $rowData) {
- // break if we have passed possible keys
- $bothNumeric = is_numeric($lookup_value) && is_numeric($rowData);
- $bothNotNumeric = !is_numeric($lookup_value) && !is_numeric($rowData);
- $lookupLower = StringHelper::strToLower($lookup_value);
- $rowDataLower = StringHelper::strToLower($rowData);
-
- if (
- $not_exact_match && (
- ($bothNumeric && $rowData > $lookup_value) ||
- ($bothNotNumeric && $rowDataLower > $lookupLower)
- )
- ) {
- break;
- }
-
- // Remember the last key, but only if datatypes match (as in VLOOKUP)
- if ($bothNumeric || $bothNotNumeric) {
- if ($not_exact_match) {
- $rowNumber = $rowKey;
-
- continue;
- } elseif (
- $rowDataLower === $lookupLower
- && ($rowNumber === null || $rowKey < $rowNumber)
- ) {
- $rowNumber = $rowKey;
- }
- }
- }
-
- if ($rowNumber !== null) {
- // otherwise return the appropriate value
- return $lookup_array[$returnColumn][$rowNumber];
- }
-
- return Functions::NA();
+ 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
+ *
+ * @see LookupRef\Lookup::lookup()
+ * Use the lookup() method in the LookupRef\Lookup class instead
+ *
* @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
@@ -875,94 +393,24 @@ class LookupRef
*/
public static function LOOKUP($lookup_value, $lookup_vector, $result_vector = null)
{
- $lookup_value = Functions::flattenSingleValue($lookup_value);
-
- if (!is_array($lookup_vector)) {
- return Functions::NA();
- }
- $hasResultVector = isset($result_vector);
- $lookupRows = count($lookup_vector);
- $l = array_keys($lookup_vector);
- $l = array_shift($l);
- $lookupColumns = count($lookup_vector[$l]);
- // we correctly orient our results
- if (($lookupRows === 1 && $lookupColumns > 1) || (!$hasResultVector && $lookupRows === 2 && $lookupColumns !== 2)) {
- $lookup_vector = self::TRANSPOSE($lookup_vector);
- $lookupRows = count($lookup_vector);
- $l = array_keys($lookup_vector);
- $lookupColumns = count($lookup_vector[array_shift($l)]);
- }
-
- if ($result_vector === null) {
- $result_vector = $lookup_vector;
- }
- $resultRows = count($result_vector);
- $l = array_keys($result_vector);
- $l = array_shift($l);
- $resultColumns = count($result_vector[$l]);
- // we correctly orient our results
- if ($resultRows === 1 && $resultColumns > 1) {
- $result_vector = self::TRANSPOSE($result_vector);
- $resultRows = count($result_vector);
- $r = array_keys($result_vector);
- $resultColumns = count($result_vector[array_shift($r)]);
- }
-
- if ($lookupRows === 2 && !$hasResultVector) {
- $result_vector = array_pop($lookup_vector);
- $lookup_vector = array_shift($lookup_vector);
- }
-
- if ($lookupColumns !== 2) {
- foreach ($lookup_vector 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($result_vector);
- if (is_array($dataValue2)) {
- $dataValue2 = array_shift($dataValue2);
- }
- $value = [$key1 => $dataValue1, $key2 => $dataValue2];
- }
- unset($value);
- }
-
- return self::VLOOKUP($lookup_value, $lookup_vector, 2);
+ return Lookup::lookup($lookup_value, $lookup_vector, $result_vector);
}
/**
* FORMULATEXT.
*
+ * @Deprecated 1.18.0
+ *
* @param mixed $cellReference The cell to check
- * @param Cell $pCell The current cell (containing this formula)
+ * @param Cell $cell The current cell (containing this formula)
*
* @return string
+ *
+ *@see LookupRef\Formula::text()
+ * Use the text() method in the LookupRef\Formula class instead
*/
- public static function FORMULATEXT($cellReference = '', ?Cell $pCell = null)
+ public static function FORMULATEXT($cellReference = '', ?Cell $cell = null)
{
- if ($pCell === null) {
- return Functions::REF();
- }
-
- preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellReference, $matches);
-
- $cellReference = $matches[6] . $matches[7];
- $worksheetName = trim($matches[3], "'");
- $worksheet = (!empty($worksheetName))
- ? $pCell->getWorksheet()->getParent()->getSheetByName($worksheetName)
- : $pCell->getWorksheet();
-
- if (!$worksheet->getCell($cellReference)->isFormula()) {
- return Functions::NA();
- }
-
- return $worksheet->getCell($cellReference)->getValue();
+ return LookupRef\Formula::text($cellReference, $cell);
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Address.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Address.php
new file mode 100644
index 00000000000..58215f27481
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Address.php
@@ -0,0 +1,98 @@
+ '') {
+ 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}]";
+ }
+
+ return "{$sheetName}R{$row}C{$column}";
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php
new file mode 100644
index 00000000000..71358bf30a6
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php
@@ -0,0 +1,198 @@
+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 Functions::NA();
+ }
+
+ private static function matchFirstValue($lookupArray, $lookupValue)
+ {
+ $wildcardLookup = ((bool) preg_match('/([\?\*])/', $lookupValue));
+ $wildcard = WildcardMatch::wildcard($lookupValue);
+
+ foreach ($lookupArray as $i => $lookupArrayValue) {
+ $typeMatch = ((gettype($lookupValue) === gettype($lookupArrayValue)) ||
+ (is_numeric($lookupValue) && is_numeric($lookupArrayValue)));
+
+ if (
+ $typeMatch && is_string($lookupValue) &&
+ $wildcardLookup && WildcardMatch::compare($lookupArrayValue, $wildcard)
+ ) {
+ // wildcard match
+ return $i;
+ } elseif ($lookupArrayValue === $lookupValue) {
+ // exact match
+ return $i;
+ }
+ }
+
+ return null;
+ }
+
+ private static function matchLargestValue($lookupArray, $lookupValue, $keySet)
+ {
+ foreach ($lookupArray as $i => $lookupArrayValue) {
+ $typeMatch = ((gettype($lookupValue) === gettype($lookupArrayValue)) ||
+ (is_numeric($lookupValue) && is_numeric($lookupArrayValue)));
+
+ if ($typeMatch && ($lookupArrayValue <= $lookupValue)) {
+ return array_search($i, $keySet);
+ }
+ }
+
+ return null;
+ }
+
+ private static function matchSmallestValue($lookupArray, $lookupValue)
+ {
+ $valueKey = null;
+
+ // 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);
+
+ if ($lookupArrayValue === $lookupValue) {
+ // Another "special" case. If a perfect match is found,
+ // the algorithm gives up immediately
+ return $i;
+ } elseif ($typeMatch && $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;
+ }
+
+ 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(Functions::NA());
+ }
+ }
+
+ private static function validateMatchType($matchType): void
+ {
+ // Match_type is 0, 1 or -1
+ if (
+ ($matchType !== self::MATCHTYPE_FIRST_VALUE) &&
+ ($matchType !== self::MATCHTYPE_LARGEST_VALUE) && ($matchType !== self::MATCHTYPE_SMALLEST_VALUE)
+ ) {
+ throw new Exception(Functions::NA());
+ }
+ }
+
+ private static function validateLookupArray($lookupArray): void
+ {
+ // Lookup_array should not be empty
+ $lookupArraySize = count($lookupArray);
+ if ($lookupArraySize <= 0) {
+ throw new Exception(Functions::NA());
+ }
+ }
+
+ private static function prepareLookupArray($lookupArray, $matchType)
+ {
+ // 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(Functions::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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Formula.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Formula.php
new file mode 100644
index 00000000000..f3e6c4199d2
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Formula.php
@@ -0,0 +1,43 @@
+getWorksheet()->getParent()->getSheetByName($worksheetName)
+ : $cell->getWorksheet();
+
+ if (
+ $worksheet === null ||
+ !$worksheet->cellExists($cellReference) ||
+ !$worksheet->getCell($cellReference)->isFormula()
+ ) {
+ return Functions::NA();
+ }
+
+ return $worksheet->getCell($cellReference)->getValue();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php
new file mode 100644
index 00000000000..7db27804408
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php
@@ -0,0 +1,116 @@
+getMessage();
+ }
+
+ $f = array_keys($lookupArray);
+ $firstRow = reset($f);
+ if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray))) {
+ return Functions::REF();
+ }
+
+ $firstkey = $f[0] - 1;
+ $returnColumn = $firstkey + $indexNumber;
+ $firstColumn = array_shift($f);
+ $rowNumber = self::hLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch);
+
+ if ($rowNumber !== null) {
+ // otherwise return the appropriate value
+ return $lookupArray[$returnColumn][Coordinate::stringFromColumnIndex($rowNumber)];
+ }
+
+ return Functions::NA();
+ }
+
+ /**
+ * @param mixed $lookupValue The value that you want to match in lookup_array
+ * @param mixed $column The column to look up
+ * @param mixed $notExactMatch determines if you are looking for an exact match based on lookup_value
+ */
+ private static function hLookupSearch($lookupValue, array $lookupArray, $column, $notExactMatch): ?int
+ {
+ $lookupLower = StringHelper::strToLower($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($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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php
new file mode 100644
index 00000000000..28e8df890cb
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php
@@ -0,0 +1,74 @@
+getWorkSheet();
+ $sheetTitle = ($workSheet === null) ? '' : $workSheet->getTitle();
+ $value = 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);
+
+ 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()->getParent()->getSheetByName($sheetName)
+ : $cell->getWorksheet();
+
+ return [$cellAddress, $worksheet, $sheetName];
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php
new file mode 100644
index 00000000000..1448c089a85
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php
@@ -0,0 +1,40 @@
+getHyperlink()->setUrl($linkURL);
+ $cell->getHyperlink()->setTooltip($displayName);
+
+ return $displayName;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php
new file mode 100644
index 00000000000..b5a35410887
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php
@@ -0,0 +1,97 @@
+getMessage();
+ }
+
+ [$cellAddress, $worksheet, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell);
+
+ [$cellAddress1, $cellAddress2, $cellAddress] = Helpers::extractCellAddresses($cellAddress, $a1, $cell->getWorkSheet(), $sheetName);
+
+ if (
+ (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress1, $matches)) ||
+ (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress2, $matches)))
+ ) {
+ return Functions::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);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php
new file mode 100644
index 00000000000..e21d35dc56d
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php
@@ -0,0 +1,105 @@
+ 1) || (!$hasResultVector && $lookupRows === 2 && $lookupColumns !== 2)) {
+ $lookupVector = LookupRef\Matrix::transpose($lookupVector);
+ $lookupRows = self::rowCount($lookupVector);
+ $lookupColumns = self::columnCount($lookupVector);
+ }
+
+ $resultVector = self::verifyResultVector($lookupVector, $resultVector);
+
+ 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 $lookupVector, $resultVector)
+ {
+ if ($resultVector === null) {
+ $resultVector = $lookupVector;
+ }
+
+ $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]);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php
new file mode 100644
index 00000000000..80fc99ad37d
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php
@@ -0,0 +1,48 @@
+getMessage();
+ }
+
+ if (!is_array($matrix) || ($rowNum > count($matrix))) {
+ return Functions::REF();
+ }
+
+ $rowKeys = array_keys($matrix);
+ $columnKeys = @array_keys($matrix[$rowKeys[0]]);
+
+ if ($columnNum > count($columnKeys)) {
+ return Functions::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];
+ }
+
+ 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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php
new file mode 100644
index 00000000000..7e33f55acaf
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php
@@ -0,0 +1,136 @@
+getParent() : null)
+ ->extractCellRange($cellAddress, $worksheet, false);
+ }
+
+ private static function extractWorksheet($cellAddress, Cell $cell): array
+ {
+ $sheetName = '';
+ if (strpos($cellAddress, '!') !== false) {
+ [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
+ $sheetName = trim($sheetName, "'");
+ }
+
+ $worksheet = ($sheetName !== '')
+ ? $cell->getWorksheet()->getParent()->getSheetByName($sheetName)
+ : $cell->getWorksheet();
+
+ return [$cellAddress, $worksheet];
+ }
+
+ private static function adjustEndCellColumnForWidth(string $endCellColumn, $width, int $startCellColumn, $columns)
+ {
+ $endCellColumn = Coordinate::columnIndexFromString($endCellColumn) - 1;
+ if (($width !== null) && (!is_object($width))) {
+ $endCellColumn = $startCellColumn + (int) $width - 1;
+ } else {
+ $endCellColumn += (int) $columns;
+ }
+
+ return $endCellColumn;
+ }
+
+ 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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php
new file mode 100644
index 00000000000..9752d6730aa
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php
@@ -0,0 +1,209 @@
+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 = 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 = preg_replace('/[^a-z]/i', '', $startAddress);
+ $endAddress = preg_replace('/[^a-z]/i', '', $endAddress);
+
+ return range(
+ (int) Coordinate::columnIndexFromString($startAddress),
+ (int) Coordinate::columnIndexFromString($endAddress)
+ );
+ }
+
+ $cellAddress = 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 Functions::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 = preg_replace('/\D/', '', $startAddress);
+ $endAddress = 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 Functions::VALUE();
+ }
+
+ reset($cellAddress);
+ $isMatrix = (is_numeric(key($cellAddress)));
+ [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress);
+
+ if ($isMatrix) {
+ return $columns;
+ }
+
+ return $rows;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php
new file mode 100644
index 00000000000..6c18d73b83e
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php
@@ -0,0 +1,46 @@
+ $entryCount)) {
+ return Functions::VALUE();
+ }
+
+ if (is_array($chooseArgs[$chosenEntry])) {
+ return Functions::flattenArray($chooseArgs[$chosenEntry]);
+ }
+
+ return $chooseArgs[$chosenEntry];
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php
new file mode 100644
index 00000000000..ddd5d9ee362
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php
@@ -0,0 +1,105 @@
+getMessage();
+ }
+
+ $f = array_keys($lookupArray);
+ $firstRow = array_pop($f);
+ if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray[$firstRow]))) {
+ return Functions::REF();
+ }
+ $columnKeys = array_keys($lookupArray[$firstRow]);
+ $returnColumn = $columnKeys[--$indexNumber];
+ $firstColumn = array_shift($columnKeys);
+
+ if (!$notExactMatch) {
+ uasort($lookupArray, ['self', 'vlookupSort']);
+ }
+
+ $rowNumber = self::vLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch);
+
+ if ($rowNumber !== null) {
+ // return the appropriate value
+ return $lookupArray[$rowNumber][$returnColumn];
+ }
+
+ return Functions::NA();
+ }
+
+ private static function vlookupSort($a, $b)
+ {
+ reset($a);
+ $firstColumn = key($a);
+ $aLower = StringHelper::strToLower($a[$firstColumn]);
+ $bLower = StringHelper::strToLower($b[$firstColumn]);
+
+ if ($aLower == $bLower) {
+ return 0;
+ }
+
+ return ($aLower < $bLower) ? -1 : 1;
+ }
+
+ private static function vLookupSearch($lookupValue, $lookupArray, $column, $notExactMatch)
+ {
+ $lookupLower = StringHelper::strToLower($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($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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig.php
index 823f6ef2c8d..ec251f6d25e 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig.php
@@ -2,43 +2,11 @@
namespace PhpOffice\PhpSpreadsheet\Calculation;
-use Exception;
-use Matrix\Exception as MatrixException;
-use Matrix\Matrix;
-
+/**
+ * @deprecated 1.18.0
+ */
class MathTrig
{
- //
- // Private method to return an array of the factors of the input value
- //
- private static function factors($value)
- {
- $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];
- }
-
- private static function romanCut($num, $n)
- {
- return ($num - ($num % $n)) / $n;
- }
-
/**
* ARABIC.
*
@@ -47,75 +15,18 @@ class MathTrig
* Excel Function:
* ARABIC(text)
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Arabic::evaluate()
+ * Use the evaluate method in the MathTrig\Arabic class instead
+ *
* @param string $roman
*
* @return int|string the arabic numberal contrived from the roman numeral
*/
public static function ARABIC($roman)
{
- // An empty string should return 0
- $roman = substr(trim(strtoupper((string) Functions::flattenSingleValue($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(str_split($roman));
- } catch (Exception $e) {
- return Functions::VALUE(); // Invalid character detected
- }
-
- if ($negativeNumber) {
- $arabic *= -1; // The number should be negative
- }
-
- return $arabic;
- }
-
- /**
- * Recursively calculate the arabic value of a roman numeral.
- *
- * @param int $sum
- * @param int $subtract
- *
- * @return int
- */
- protected static function calculateArabic(array $roman, &$sum = 0, $subtract = 0)
- {
- $lookup = [
- 'M' => 1000,
- 'D' => 500,
- 'C' => 100,
- 'L' => 50,
- 'X' => 10,
- 'V' => 5,
- 'I' => 1,
- ];
-
- $numeral = array_shift($roman);
- if (!isset($lookup[$numeral])) {
- throw new Exception('Invalid character detected');
- }
-
- $arabic = $lookup[$numeral];
- if (count($roman) > 0 && isset($lookup[$roman[0]]) && $arabic < $lookup[$roman[0]]) {
- $subtract += $arabic;
- } else {
- $sum += ($arabic - $subtract);
- $subtract = 0;
- }
-
- if (count($roman) > 0) {
- self::calculateArabic($roman, $sum, $subtract);
- }
-
- return $sum;
+ return MathTrig\Arabic::evaluate($roman);
}
/**
@@ -134,6 +45,11 @@ class MathTrig
* Excel Function:
* ATAN2(xCoordinate,yCoordinate)
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Trig\Tangent::atan2()
+ * Use the atan2 method in the MathTrig\Trig\Tangent class instead
+ *
* @param float $xCoordinate the x-coordinate of the point
* @param float $yCoordinate the y-coordinate of the point
*
@@ -141,27 +57,7 @@ class MathTrig
*/
public static function ATAN2($xCoordinate = null, $yCoordinate = null)
{
- $xCoordinate = Functions::flattenSingleValue($xCoordinate);
- $yCoordinate = Functions::flattenSingleValue($yCoordinate);
-
- $xCoordinate = ($xCoordinate !== null) ? $xCoordinate : 0.0;
- $yCoordinate = ($yCoordinate !== null) ? $yCoordinate : 0.0;
-
- if (
- ((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) &&
- ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))
- ) {
- $xCoordinate = (float) $xCoordinate;
- $yCoordinate = (float) $yCoordinate;
-
- if (($xCoordinate == 0) && ($yCoordinate == 0)) {
- return Functions::DIV0();
- }
-
- return atan2($yCoordinate, $xCoordinate);
- }
-
- return Functions::VALUE();
+ return MathTrig\Trig\Tangent::atan2($xCoordinate, $yCoordinate);
}
/**
@@ -172,6 +68,11 @@ class MathTrig
* Excel Function:
* BASE(Number, Radix [Min_length])
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Base::evaluate()
+ * Use the evaluate method in the MathTrig\Base class instead
+ *
* @param float $number
* @param float $radix
* @param int $minLength
@@ -180,29 +81,7 @@ class MathTrig
*/
public static function BASE($number, $radix, $minLength = null)
{
- $number = Functions::flattenSingleValue($number);
- $radix = Functions::flattenSingleValue($radix);
- $minLength = Functions::flattenSingleValue($minLength);
-
- if (is_numeric($number) && is_numeric($radix) && ($minLength === null || is_numeric($minLength))) {
- // Truncate to an integer
- $number = (int) $number;
- $radix = (int) $radix;
- $minLength = (int) $minLength;
-
- if ($number < 0 || $number >= 2 ** 53 || $radix < 2 || $radix > 36) {
- return Functions::NAN(); // Numeric range constraints
- }
-
- $outcome = strtoupper((string) base_convert($number, 10, $radix));
- if ($minLength !== null) {
- $outcome = str_pad($outcome, $minLength, '0', STR_PAD_LEFT); // String padding
- }
-
- return $outcome;
- }
-
- return Functions::VALUE();
+ return MathTrig\Base::evaluate($number, $radix, $minLength);
}
/**
@@ -216,34 +95,19 @@ class MathTrig
* Excel Function:
* CEILING(number[,significance])
*
+ * @Deprecated 1.17.0
+ *
* @param float $number the number you want to round
* @param float $significance the multiple to which you want to round
*
* @return float|string Rounded Number, or a string containing an error
+ *
+ * @see MathTrig\Ceiling::ceiling()
+ * Use the ceiling() method in the MathTrig\Ceiling class instead
*/
public static function CEILING($number, $significance = null)
{
- $number = Functions::flattenSingleValue($number);
- $significance = Functions::flattenSingleValue($significance);
-
- if (
- ($significance === null) &&
- (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC)
- ) {
- $significance = $number / abs($number);
- }
-
- if ((is_numeric($number)) && (is_numeric($significance))) {
- if (($number == 0.0) || ($significance == 0.0)) {
- return 0.0;
- } elseif (self::SIGN($number) == self::SIGN($significance)) {
- return ceil($number / $significance) * $significance;
- }
-
- return Functions::NAN();
- }
-
- return Functions::VALUE();
+ return MathTrig\Ceiling::ceiling($number, $significance);
}
/**
@@ -255,27 +119,19 @@ class MathTrig
* Excel Function:
* COMBIN(numObjs,numInSet)
*
+ * @Deprecated 1.18.0
+ *
+ * @see MathTrig\Combinations::withoutRepetition()
+ * Use the withoutRepetition() method in the MathTrig\Combinations class instead
+ *
* @param int $numObjs Number of different objects
* @param int $numInSet Number of objects in each combination
*
- * @return int|string Number of combinations, or a string containing an error
+ * @return float|int|string Number of combinations, or a string containing an error
*/
public static function COMBIN($numObjs, $numInSet)
{
- $numObjs = Functions::flattenSingleValue($numObjs);
- $numInSet = Functions::flattenSingleValue($numInSet);
-
- if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
- if ($numObjs < $numInSet) {
- return Functions::NAN();
- } elseif ($numInSet < 0) {
- return Functions::NAN();
- }
-
- return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet);
- }
-
- return Functions::VALUE();
+ return MathTrig\Combinations::withoutRepetition($numObjs, $numInSet);
}
/**
@@ -290,27 +146,31 @@ class MathTrig
* Excel Function:
* EVEN(number)
*
+ * @Deprecated 1.18.0
+ *
+ * @see MathTrig\Round::even()
+ * Use the even() method in the MathTrig\Round class instead
+ *
* @param float $number Number to round
*
- * @return int|string Rounded Number, or a string containing an error
+ * @return float|int|string Rounded Number, or a string containing an error
*/
public static function EVEN($number)
{
- $number = Functions::flattenSingleValue($number);
+ return MathTrig\Round::even($number);
+ }
- if ($number === null) {
- return 0;
- } elseif (is_bool($number)) {
- $number = (int) $number;
- }
-
- if (is_numeric($number)) {
- $significance = 2 * self::SIGN($number);
-
- return (int) self::CEILING($number, $significance);
- }
-
- return Functions::VALUE();
+ /**
+ * Helper function for Even.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see MathTrig\Helpers::getEven()
+ * Use the evaluate() method in the MathTrig\Helpers class instead
+ */
+ public static function getEven(float $number): int
+ {
+ return (int) MathTrig\Helpers::getEven($number);
}
/**
@@ -322,35 +182,18 @@ class MathTrig
* Excel Function:
* FACT(factVal)
*
+ * @Deprecated 1.18.0
+ *
* @param float $factVal Factorial Value
*
- * @return int|string Factorial, or a string containing an error
+ * @return float|int|string Factorial, or a string containing an error
+ *
+ *@see MathTrig\Factorial::fact()
+ * Use the fact() method in the MathTrig\Factorial class instead
*/
public static function FACT($factVal)
{
- $factVal = Functions::flattenSingleValue($factVal);
-
- if (is_numeric($factVal)) {
- if ($factVal < 0) {
- return Functions::NAN();
- }
- $factLoop = floor($factVal);
- if (
- (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) &&
- ($factVal > $factLoop)
- ) {
- return Functions::NAN();
- }
-
- $factorial = 1;
- while ($factLoop > 1) {
- $factorial *= $factLoop--;
- }
-
- return $factorial;
- }
-
- return Functions::VALUE();
+ return MathTrig\Factorial::fact($factVal);
}
/**
@@ -361,29 +204,18 @@ class MathTrig
* Excel Function:
* FACTDOUBLE(factVal)
*
+ * @Deprecated 1.18.0
+ *
* @param float $factVal Factorial Value
*
- * @return int|string Double Factorial, or a string containing an error
+ * @return float|int|string Double Factorial, or a string containing an error
+ *
+ *@see MathTrig\Factorial::factDouble()
+ * Use the factDouble() method in the MathTrig\Factorial class instead
*/
public static function FACTDOUBLE($factVal)
{
- $factLoop = Functions::flattenSingleValue($factVal);
-
- if (is_numeric($factLoop)) {
- $factLoop = floor($factLoop);
- if ($factVal < 0) {
- return Functions::NAN();
- }
- $factorial = 1;
- while ($factLoop > 1) {
- $factorial *= $factLoop--;
- --$factLoop;
- }
-
- return $factorial;
- }
-
- return Functions::VALUE();
+ return MathTrig\Factorial::factDouble($factVal);
}
/**
@@ -394,38 +226,19 @@ class MathTrig
* Excel Function:
* FLOOR(number[,significance])
*
+ * @Deprecated 1.17.0
+ *
* @param float $number Number to round
* @param float $significance Significance
*
* @return float|string Rounded Number, or a string containing an error
+ *
+ *@see MathTrig\Floor::floor()
+ * Use the floor() method in the MathTrig\Floor class instead
*/
public static function FLOOR($number, $significance = null)
{
- $number = Functions::flattenSingleValue($number);
- $significance = Functions::flattenSingleValue($significance);
-
- if (
- ($significance === null) &&
- (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC)
- ) {
- $significance = $number / abs($number);
- }
-
- if ((is_numeric($number)) && (is_numeric($significance))) {
- if ($significance == 0.0) {
- return Functions::DIV0();
- } elseif ($number == 0.0) {
- return 0.0;
- } elseif (self::SIGN($significance) == 1) {
- return floor($number / $significance) * $significance;
- } elseif (self::SIGN($number) == -1 && self::SIGN($significance) == -1) {
- return floor($number / $significance) * $significance;
- }
-
- return Functions::NAN();
- }
-
- return Functions::VALUE();
+ return MathTrig\Floor::floor($number, $significance);
}
/**
@@ -436,35 +249,20 @@ class MathTrig
* Excel Function:
* FLOOR.MATH(number[,significance[,mode]])
*
+ * @Deprecated 1.17.0
+ *
* @param float $number Number to round
* @param float $significance Significance
* @param int $mode direction to round negative numbers
*
* @return float|string Rounded Number, or a string containing an error
+ *
+ *@see MathTrig\Floor::math()
+ * Use the math() method in the MathTrig\Floor class instead
*/
public static function FLOORMATH($number, $significance = null, $mode = 0)
{
- $number = Functions::flattenSingleValue($number);
- $significance = Functions::flattenSingleValue($significance);
- $mode = Functions::flattenSingleValue($mode);
-
- if (is_numeric($number) && $significance === null) {
- $significance = $number / abs($number);
- }
-
- if (is_numeric($number) && is_numeric($significance) && is_numeric($mode)) {
- if ($significance == 0.0) {
- return Functions::DIV0();
- } elseif ($number == 0.0) {
- return 0.0;
- } elseif (self::SIGN($significance) == -1 || (self::SIGN($number) == -1 && !empty($mode))) {
- return ceil($number / $significance) * $significance;
- }
-
- return floor($number / $significance) * $significance;
- }
-
- return Functions::VALUE();
+ return MathTrig\Floor::math($number, $significance, $mode);
}
/**
@@ -475,32 +273,41 @@ class MathTrig
* Excel Function:
* FLOOR.PRECISE(number[,significance])
*
+ * @Deprecated 1.17.0
+ *
* @param float $number Number to round
* @param float $significance Significance
*
* @return float|string Rounded Number, or a string containing an error
+ *
+ *@see MathTrig\Floor::precise()
+ * Use the precise() method in the MathTrig\Floor class instead
*/
public static function FLOORPRECISE($number, $significance = 1)
{
- $number = Functions::flattenSingleValue($number);
- $significance = Functions::flattenSingleValue($significance);
-
- if ((is_numeric($number)) && (is_numeric($significance))) {
- if ($significance == 0.0) {
- return Functions::DIV0();
- } elseif ($number == 0.0) {
- return 0.0;
- }
-
- return floor($number / abs($significance)) * abs($significance);
- }
-
- return Functions::VALUE();
+ return MathTrig\Floor::precise($number, $significance);
}
- private static function evaluateGCD($a, $b)
+ /**
+ * INT.
+ *
+ * Casts a floating point value to an integer
+ *
+ * Excel Function:
+ * INT(number)
+ *
+ * @Deprecated 1.17.0
+ *
+ * @see MathTrig\IntClass::evaluate()
+ * Use the evaluate() method in the MathTrig\IntClass class instead
+ *
+ * @param float $number Number to cast to an integer
+ *
+ * @return int|string Integer value, or a string containing an error
+ */
+ public static function INT($number)
{
- return $b ? self::evaluateGCD($b, $a % $b) : $a;
+ return MathTrig\IntClass::evaluate($number);
}
/**
@@ -513,56 +320,18 @@ class MathTrig
* Excel Function:
* GCD(number1[,number2[, ...]])
*
+ * @Deprecated 1.18.0
+ *
+ * @see MathTrig\Gcd::evaluate()
+ * Use the evaluate() method in the MathTrig\Gcd class instead
+ *
* @param mixed ...$args Data values
*
* @return int|mixed|string Greatest Common Divisor, or a string containing an error
*/
public static function GCD(...$args)
{
- $args = Functions::flattenArray($args);
- // Loop through arguments
- foreach (Functions::flattenArray($args) as $value) {
- if (!is_numeric($value)) {
- return Functions::VALUE();
- } elseif ($value < 0) {
- return Functions::NAN();
- }
- }
-
- $gcd = (int) array_pop($args);
- do {
- $gcd = self::evaluateGCD($gcd, (int) array_pop($args));
- } while (!empty($args));
-
- return $gcd;
- }
-
- /**
- * INT.
- *
- * Casts a floating point value to an integer
- *
- * Excel Function:
- * INT(number)
- *
- * @param float $number Number to cast to an integer
- *
- * @return int|string Integer value, or a string containing an error
- */
- public static function INT($number)
- {
- $number = Functions::flattenSingleValue($number);
-
- if ($number === null) {
- return 0;
- } elseif (is_bool($number)) {
- return (int) $number;
- }
- if (is_numeric($number)) {
- return (int) floor($number);
- }
-
- return Functions::VALUE();
+ return MathTrig\Gcd::evaluate(...$args);
}
/**
@@ -576,45 +345,18 @@ class MathTrig
* Excel Function:
* LCM(number1[,number2[, ...]])
*
+ * @Deprecated 1.18.0
+ *
+ * @see MathTrig\Lcm::evaluate()
+ * Use the evaluate() method in the MathTrig\Lcm class instead
+ *
* @param mixed ...$args Data values
*
* @return int|string Lowest Common Multiplier, or a string containing an error
*/
public static function LCM(...$args)
{
- $returnValue = 1;
- $allPoweredFactors = [];
- // Loop through arguments
- foreach (Functions::flattenArray($args) as $value) {
- if (!is_numeric($value)) {
- return Functions::VALUE();
- }
- if ($value == 0) {
- return 0;
- } elseif ($value < 0) {
- return Functions::NAN();
- }
- $myFactors = self::factors(floor($value));
- $myCountedFactors = array_count_values($myFactors);
- $myPoweredFactors = [];
- foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) {
- $myPoweredFactors[$myCountedFactor] = $myCountedFactor ** $myCountedPower;
- }
- foreach ($myPoweredFactors as $myPoweredValue => $myPoweredFactor) {
- if (isset($allPoweredFactors[$myPoweredValue])) {
- if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) {
- $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
- }
- } else {
- $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
- }
- }
- }
- foreach ($allPoweredFactors as $allPoweredFactor) {
- $returnValue *= (int) $allPoweredFactor;
- }
-
- return $returnValue;
+ return MathTrig\Lcm::evaluate(...$args);
}
/**
@@ -625,24 +367,19 @@ class MathTrig
* Excel Function:
* LOG(number[,base])
*
+ * @Deprecated 1.18.0
+ *
+ * @see MathTrig\Logarithms::withBase()
+ * Use the withBase() method in the MathTrig\Logarithms class instead
+ *
* @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 float|string The result, or a string containing an error
*/
- public static function logBase($number = null, $base = 10)
+ public static function logBase($number, $base = 10)
{
- $number = Functions::flattenSingleValue($number);
- $base = ($base === null) ? 10 : (float) Functions::flattenSingleValue($base);
-
- if ((!is_numeric($base)) || (!is_numeric($number))) {
- return Functions::VALUE();
- }
- if (($base <= 0) || ($number <= 0)) {
- return Functions::NAN();
- }
-
- return log($number, $base);
+ return MathTrig\Logarithms::withBase($number, $base);
}
/**
@@ -653,46 +390,18 @@ class MathTrig
* Excel Function:
* MDETERM(array)
*
+ * @Deprecated 1.18.0
+ *
+ * @see MathTrig\MatrixFunctions::determinant()
+ * Use the determinant() method in the MathTrig\MatrixFunctions class instead
+ *
* @param array $matrixValues A matrix of values
*
* @return float|string The result, or a string containing an error
*/
public static function MDETERM($matrixValues)
{
- $matrixData = [];
- if (!is_array($matrixValues)) {
- $matrixValues = [[$matrixValues]];
- }
-
- $row = $maxColumn = 0;
- foreach ($matrixValues as $matrixRow) {
- if (!is_array($matrixRow)) {
- $matrixRow = [$matrixRow];
- }
- $column = 0;
- foreach ($matrixRow as $matrixCell) {
- if ((is_string($matrixCell)) || ($matrixCell === null)) {
- return Functions::VALUE();
- }
- $matrixData[$row][$column] = $matrixCell;
- ++$column;
- }
- if ($column > $maxColumn) {
- $maxColumn = $column;
- }
- ++$row;
- }
-
- $matrix = new Matrix($matrixData);
- if (!$matrix->isSquare()) {
- return Functions::VALUE();
- }
-
- try {
- return $matrix->determinant();
- } catch (MatrixException $ex) {
- return Functions::VALUE();
- }
+ return MathTrig\MatrixFunctions::determinant($matrixValues);
}
/**
@@ -703,55 +412,28 @@ class MathTrig
* Excel Function:
* MINVERSE(array)
*
+ * @Deprecated 1.18.0
+ *
+ * @see MathTrig\MatrixFunctions::inverse()
+ * Use the inverse() method in the MathTrig\MatrixFunctions class instead
+ *
* @param array $matrixValues A matrix of values
*
* @return array|string The result, or a string containing an error
*/
public static function MINVERSE($matrixValues)
{
- $matrixData = [];
- if (!is_array($matrixValues)) {
- $matrixValues = [[$matrixValues]];
- }
-
- $row = $maxColumn = 0;
- foreach ($matrixValues as $matrixRow) {
- if (!is_array($matrixRow)) {
- $matrixRow = [$matrixRow];
- }
- $column = 0;
- foreach ($matrixRow as $matrixCell) {
- if ((is_string($matrixCell)) || ($matrixCell === null)) {
- return Functions::VALUE();
- }
- $matrixData[$row][$column] = $matrixCell;
- ++$column;
- }
- if ($column > $maxColumn) {
- $maxColumn = $column;
- }
- ++$row;
- }
-
- $matrix = new Matrix($matrixData);
- if (!$matrix->isSquare()) {
- return Functions::VALUE();
- }
-
- if ($matrix->determinant() == 0.0) {
- return Functions::NAN();
- }
-
- try {
- return $matrix->inverse()->toArray();
- } catch (MatrixException $ex) {
- return Functions::VALUE();
- }
+ return MathTrig\MatrixFunctions::inverse($matrixValues);
}
/**
* MMULT.
*
+ * @Deprecated 1.18.0
+ *
+ * @see MathTrig\MatrixFunctions::multiply()
+ * Use the multiply() method in the MathTrig\MatrixFunctions class instead
+ *
* @param array $matrixData1 A matrix of values
* @param array $matrixData2 A matrix of values
*
@@ -759,80 +441,25 @@ class MathTrig
*/
public static function MMULT($matrixData1, $matrixData2)
{
- $matrixAData = $matrixBData = [];
- if (!is_array($matrixData1)) {
- $matrixData1 = [[$matrixData1]];
- }
- if (!is_array($matrixData2)) {
- $matrixData2 = [[$matrixData2]];
- }
-
- try {
- $rowA = 0;
- foreach ($matrixData1 as $matrixRow) {
- if (!is_array($matrixRow)) {
- $matrixRow = [$matrixRow];
- }
- $columnA = 0;
- foreach ($matrixRow as $matrixCell) {
- if ((!is_numeric($matrixCell)) || ($matrixCell === null)) {
- return Functions::VALUE();
- }
- $matrixAData[$rowA][$columnA] = $matrixCell;
- ++$columnA;
- }
- ++$rowA;
- }
- $matrixA = new Matrix($matrixAData);
- $rowB = 0;
- foreach ($matrixData2 as $matrixRow) {
- if (!is_array($matrixRow)) {
- $matrixRow = [$matrixRow];
- }
- $columnB = 0;
- foreach ($matrixRow as $matrixCell) {
- if ((!is_numeric($matrixCell)) || ($matrixCell === null)) {
- return Functions::VALUE();
- }
- $matrixBData[$rowB][$columnB] = $matrixCell;
- ++$columnB;
- }
- ++$rowB;
- }
- $matrixB = new Matrix($matrixBData);
-
- if ($columnA != $rowB) {
- return Functions::VALUE();
- }
-
- return $matrixA->multiply($matrixB)->toArray();
- } catch (MatrixException $ex) {
- return Functions::VALUE();
- }
+ return MathTrig\MatrixFunctions::multiply($matrixData1, $matrixData2);
}
/**
* MOD.
*
+ * @Deprecated 1.18.0
+ *
+ * @see MathTrig\Operations::mod()
+ * Use the mod() method in the MathTrig\Operations class instead
+ *
* @param int $a Dividend
* @param int $b Divisor
*
- * @return int|string Remainder, or a string containing an error
+ * @return float|int|string Remainder, or a string containing an error
*/
public static function MOD($a = 1, $b = 1)
{
- $a = (float) Functions::flattenSingleValue($a);
- $b = (float) Functions::flattenSingleValue($b);
-
- if ($b == 0.0) {
- return Functions::DIV0();
- } elseif (($a < 0.0) && ($b > 0.0)) {
- return $b - fmod(abs($a), $b);
- } elseif (($a > 0.0) && ($b < 0.0)) {
- return $b + fmod($a, abs($b));
- }
-
- return fmod($a, $b);
+ return MathTrig\Operations::mod($a, $b);
}
/**
@@ -840,30 +467,19 @@ class MathTrig
*
* Rounds a number to the nearest multiple of a specified value
*
+ * @Deprecated 1.17.0
+ *
* @param float $number Number to round
* @param int $multiple Multiple to which you want to round $number
*
* @return float|string Rounded Number, or a string containing an error
+ *
+ *@see MathTrig\Round::multiple()
+ * Use the multiple() method in the MathTrig\Mround class instead
*/
public static function MROUND($number, $multiple)
{
- $number = Functions::flattenSingleValue($number);
- $multiple = Functions::flattenSingleValue($multiple);
-
- if ((is_numeric($number)) && (is_numeric($multiple))) {
- if ($multiple == 0) {
- return 0;
- }
- if ((self::SIGN($number)) == (self::SIGN($multiple))) {
- $multiplier = 1 / $multiple;
-
- return round($number * $multiplier) / $multiplier;
- }
-
- return Functions::NAN();
- }
-
- return Functions::VALUE();
+ return MathTrig\Round::multiple($number, $multiple);
}
/**
@@ -871,36 +487,18 @@ class MathTrig
*
* Returns the ratio of the factorial of a sum of values to the product of factorials.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Factorial::multinomial()
+ * Use the multinomial method in the MathTrig\Factorial class instead
+ *
* @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;
- // Loop through arguments
- foreach (Functions::flattenArray($args) as $arg) {
- // Is it a numeric value?
- if (is_numeric($arg)) {
- if ($arg < 1) {
- return Functions::NAN();
- }
- $summer += floor($arg);
- $divisor *= self::FACT($arg);
- } else {
- return Functions::VALUE();
- }
- }
-
- // Return
- if ($summer > 0) {
- $summer = self::FACT($summer);
-
- return $summer / $divisor;
- }
-
- return 0;
+ return MathTrig\Factorial::multinomial(...$args);
}
/**
@@ -908,33 +506,18 @@ class MathTrig
*
* Returns number rounded up to the nearest odd integer.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Round::odd()
+ * Use the odd method in the MathTrig\Round class instead
+ *
* @param float $number Number to round
*
- * @return int|string Rounded Number, or a string containing an error
+ * @return float|int|string Rounded Number, or a string containing an error
*/
public static function ODD($number)
{
- $number = Functions::flattenSingleValue($number);
-
- if ($number === null) {
- return 1;
- } elseif (is_bool($number)) {
- return 1;
- } elseif (is_numeric($number)) {
- $significance = self::SIGN($number);
- if ($significance == 0) {
- return 1;
- }
-
- $result = self::CEILING($number, $significance);
- if ($result == self::EVEN($result)) {
- $result += $significance;
- }
-
- return (int) $result;
- }
-
- return Functions::VALUE();
+ return MathTrig\Round::odd($number);
}
/**
@@ -942,27 +525,19 @@ class MathTrig
*
* Computes x raised to the power y.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Operations::power()
+ * Use the evaluate method in the MathTrig\Power class instead
+ *
* @param float $x
* @param float $y
*
- * @return float|string The result, or a string containing an error
+ * @return float|int|string The result, or a string containing an error
*/
public static function POWER($x = 0, $y = 2)
{
- $x = Functions::flattenSingleValue($x);
- $y = Functions::flattenSingleValue($y);
-
- // Validate parameters
- if ($x == 0.0 && $y == 0.0) {
- return Functions::NAN();
- } elseif ($x == 0.0 && $y < 0.0) {
- return Functions::DIV0();
- }
-
- // Return
- $result = $x ** $y;
-
- return (!is_nan($result) && !is_infinite($result)) ? $result : Functions::NAN();
+ return MathTrig\Operations::power($x, $y);
}
/**
@@ -970,36 +545,21 @@ class MathTrig
*
* PRODUCT returns the product of all the values and cells referenced in the argument list.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Operations::product()
+ * Use the product method in the MathTrig\Operations class instead
+ *
* Excel Function:
* PRODUCT(value1[,value2[, ...]])
*
* @param mixed ...$args Data values
*
- * @return float
+ * @return float|string
*/
public static function PRODUCT(...$args)
{
- // Return value
- $returnValue = null;
-
- // Loop through arguments
- foreach (Functions::flattenArray($args) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- if ($returnValue === null) {
- $returnValue = $arg;
- } else {
- $returnValue *= $arg;
- }
- }
- }
-
- // Return
- if ($returnValue === null) {
- return 0;
- }
-
- return $returnValue;
+ return MathTrig\Operations::product(...$args);
}
/**
@@ -1008,88 +568,60 @@ class MathTrig
* QUOTIENT function returns the integer portion of a division. Numerator is the divided number
* and denominator is the divisor.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Operations::quotient()
+ * Use the quotient method in the MathTrig\Operations class instead
+ *
* Excel Function:
* QUOTIENT(value1[,value2[, ...]])
*
- * @param mixed ...$args Data values
+ * @param mixed $numerator
+ * @param mixed $denominator
*
- * @return float
+ * @return int|string
*/
- public static function QUOTIENT(...$args)
+ public static function QUOTIENT($numerator, $denominator)
{
- // Return value
- $returnValue = null;
-
- // Loop through arguments
- foreach (Functions::flattenArray($args) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- if ($returnValue === null) {
- $returnValue = ($arg == 0) ? 0 : $arg;
- } else {
- if (($returnValue == 0) || ($arg == 0)) {
- $returnValue = 0;
- } else {
- $returnValue /= $arg;
- }
- }
- }
- }
-
- // Return
- return (int) $returnValue;
+ return MathTrig\Operations::quotient($numerator, $denominator);
}
/**
- * RAND.
+ * RAND/RANDBETWEEN.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Random::randBetween()
+ * Use the randBetween or randBetween method in the MathTrig\Random class instead
*
* @param int $min Minimal value
* @param int $max Maximal value
*
- * @return int Random number
+ * @return float|int|string Random number
*/
public static function RAND($min = 0, $max = 0)
{
- $min = Functions::flattenSingleValue($min);
- $max = Functions::flattenSingleValue($max);
-
- if ($min == 0 && $max == 0) {
- return (mt_rand(0, 10000000)) / 10000000;
- }
-
- return mt_rand($min, $max);
+ return MathTrig\Random::randBetween($min, $max);
}
+ /**
+ * ROMAN.
+ *
+ * Converts a number to Roman numeral
+ *
+ * @Deprecated 1.17.0
+ *
+ * @Ssee MathTrig\Roman::evaluate()
+ * Use the evaluate() method in the MathTrig\Roman class instead
+ *
+ * @param mixed $aValue Number to convert
+ * @param mixed $style Number indicating one of five possible forms
+ *
+ * @return string Roman numeral, or a string containing an error
+ */
public static function ROMAN($aValue, $style = 0)
{
- $aValue = Functions::flattenSingleValue($aValue);
- $style = ($style === null) ? 0 : (int) Functions::flattenSingleValue($style);
- if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) {
- return Functions::VALUE();
- }
- $aValue = (int) $aValue;
- if ($aValue == 0) {
- return '';
- }
-
- $mill = ['', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM'];
- $cent = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'];
- $tens = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'];
- $ones = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'];
-
- $roman = '';
- while ($aValue > 5999) {
- $roman .= 'M';
- $aValue -= 1000;
- }
- $m = self::romanCut($aValue, 1000);
- $aValue %= 1000;
- $c = self::romanCut($aValue, 100);
- $aValue %= 100;
- $t = self::romanCut($aValue, 10);
- $aValue %= 10;
-
- return $roman . $mill[$m] . $cent[$c] . $tens[$t] . $ones[$aValue];
+ return MathTrig\Roman::evaluate($aValue, $style);
}
/**
@@ -1097,6 +629,11 @@ class MathTrig
*
* Rounds a number up to a specified number of decimal places
*
+ * @Deprecated 1.17.0
+ *
+ * @See MathTrig\Round::up()
+ * Use the up() method in the MathTrig\Round class instead
+ *
* @param float $number Number to round
* @param int $digits Number of digits to which you want to round $number
*
@@ -1104,22 +641,7 @@ class MathTrig
*/
public static function ROUNDUP($number, $digits)
{
- $number = Functions::flattenSingleValue($number);
- $digits = Functions::flattenSingleValue($digits);
-
- if ((is_numeric($number)) && (is_numeric($digits))) {
- 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);
- }
-
- return Functions::VALUE();
+ return MathTrig\Round::up($number, $digits);
}
/**
@@ -1127,6 +649,11 @@ class MathTrig
*
* Rounds a number down to a specified number of decimal places
*
+ * @Deprecated 1.17.0
+ *
+ * @See MathTrig\Round::down()
+ * Use the down() method in the MathTrig\Round class instead
+ *
* @param float $number Number to round
* @param int $digits Number of digits to which you want to round $number
*
@@ -1134,22 +661,7 @@ class MathTrig
*/
public static function ROUNDDOWN($number, $digits)
{
- $number = Functions::flattenSingleValue($number);
- $digits = Functions::flattenSingleValue($digits);
-
- if ((is_numeric($number)) && (is_numeric($digits))) {
- 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);
- }
-
- return Functions::VALUE();
+ return MathTrig\Round::down($number, $digits);
}
/**
@@ -1157,37 +669,21 @@ class MathTrig
*
* Returns the sum of a power series
*
- * @param mixed[] $args An array of mixed values for the Data Series
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\SeriesSum::evaluate()
+ * Use the evaluate method in the MathTrig\SeriesSum class instead
+ *
+ * @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 float|string The result, or a string containing an error
*/
- public static function SERIESSUM(...$args)
+ public static function SERIESSUM($x, $n, $m, ...$args)
{
- $returnValue = 0;
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
-
- $x = array_shift($aArgs);
- $n = array_shift($aArgs);
- $m = array_shift($aArgs);
-
- if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) {
- // Calculate
- $i = 0;
- foreach ($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $returnValue += $arg * $x ** ($n + ($m * $i++));
- } else {
- return Functions::VALUE();
- }
- }
-
- return $returnValue;
- }
-
- return Functions::VALUE();
+ return MathTrig\SeriesSum::evaluate($x, $n, $m, ...$args);
}
/**
@@ -1196,26 +692,31 @@ class MathTrig
* 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
+ *
+ * @See MathTrig\Sign::evaluate()
+ * Use the evaluate method in the MathTrig\Sign class instead
+ *
* @param float $number Number to round
*
* @return int|string sign value, or a string containing an error
*/
public static function SIGN($number)
{
- $number = Functions::flattenSingleValue($number);
+ return MathTrig\Sign::evaluate($number);
+ }
- if (is_bool($number)) {
- return (int) $number;
- }
- if (is_numeric($number)) {
- if ($number == 0.0) {
- return 0;
- }
-
- return $number / abs($number);
- }
-
- return Functions::VALUE();
+ /**
+ * returnSign = returns 0/-1/+1.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Helpers::returnSign()
+ * Use the returnSign method in the MathTrig\Helpers class instead
+ */
+ public static function returnSign(float $number): int
+ {
+ return MathTrig\Helpers::returnSign($number);
}
/**
@@ -1223,57 +724,18 @@ class MathTrig
*
* Returns the square root of (number * pi).
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Sqrt::sqrt()
+ * Use the pi method in the MathTrig\Sqrt class instead
+ *
* @param float $number Number
*
* @return float|string Square Root of Number * Pi, or a string containing an error
*/
public static function SQRTPI($number)
{
- $number = Functions::flattenSingleValue($number);
-
- if (is_numeric($number)) {
- if ($number < 0) {
- return Functions::NAN();
- }
-
- return sqrt($number * M_PI);
- }
-
- return Functions::VALUE();
- }
-
- protected static function filterHiddenArgs($cellReference, $args)
- {
- return array_filter(
- $args,
- function ($index) use ($cellReference) {
- [, $row, $column] = explode('.', $index);
-
- return $cellReference->getWorksheet()->getRowDimension($row)->getVisible() &&
- $cellReference->getWorksheet()->getColumnDimension($column)->getVisible();
- },
- ARRAY_FILTER_USE_KEY
- );
- }
-
- protected static function filterFormulaArgs($cellReference, $args)
- {
- return array_filter(
- $args,
- function ($index) use ($cellReference) {
- [, $row, $column] = explode('.', $index);
- 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());
-
- return !$isFormula || $cellFormula;
- }
-
- return true;
- },
- ARRAY_FILTER_USE_KEY
- );
+ return MathTrig\Sqrt::pi($number);
}
/**
@@ -1281,6 +743,11 @@ class MathTrig
*
* Returns a subtotal in a list or database.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Subtotal::evaluate()
+ * Use the evaluate method in the MathTrig\Subtotal class instead
+ *
* @param int $functionType
* A number 1 to 11 that specifies which function to
* use in calculating subtotals within a range
@@ -1294,45 +761,7 @@ class MathTrig
*/
public static function SUBTOTAL($functionType, ...$args)
{
- $cellReference = array_pop($args);
- $aArgs = Functions::flattenArrayIndexed($args);
- $subtotal = Functions::flattenSingleValue($functionType);
-
- // Calculate
- if ((is_numeric($subtotal)) && (!is_string($subtotal))) {
- if ($subtotal > 100) {
- $aArgs = self::filterHiddenArgs($cellReference, $aArgs);
- $subtotal -= 100;
- }
-
- $aArgs = self::filterFormulaArgs($cellReference, $aArgs);
- switch ($subtotal) {
- case 1:
- return Statistical::AVERAGE($aArgs);
- case 2:
- return Statistical::COUNT($aArgs);
- case 3:
- return Statistical::COUNTA($aArgs);
- case 4:
- return Statistical::MAX($aArgs);
- case 5:
- return Statistical::MIN($aArgs);
- case 6:
- return self::PRODUCT($aArgs);
- case 7:
- return Statistical::STDEV($aArgs);
- case 8:
- return Statistical::STDEVP($aArgs);
- case 9:
- return self::SUM($aArgs);
- case 10:
- return Statistical::VARFunc($aArgs);
- case 11:
- return Statistical::VARP($aArgs);
- }
- }
-
- return Functions::VALUE();
+ return MathTrig\Subtotal::evaluate($functionType, ...$args);
}
/**
@@ -1340,131 +769,67 @@ class MathTrig
*
* SUM computes the sum of all the values and cells referenced in the argument list.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Sum::sumErroringStrings()
+ * Use the sumErroringStrings method in the MathTrig\Sum class instead
+ *
* Excel Function:
* SUM(value1[,value2[, ...]])
*
* @param mixed ...$args Data values
*
- * @return float
+ * @return float|string
*/
public static function SUM(...$args)
{
- $returnValue = 0;
-
- // Loop through the arguments
- foreach (Functions::flattenArray($args) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $returnValue += $arg;
- } elseif (Functions::isError($arg)) {
- return $arg;
- }
- }
-
- return $returnValue;
+ return MathTrig\Sum::sumIgnoringStrings(...$args);
}
/**
* SUMIF.
*
- * Counts the number of cells that contain numbers within the list of arguments
+ * Totals the values of cells that contain numbers within the list of arguments
*
* Excel Function:
- * SUMIF(value1[,value2[, ...]],condition)
+ * SUMIF(range, criteria, [sum_range])
*
- * @param mixed $aArgs Data values
- * @param string $condition the criteria that defines which cells will be summed
- * @param mixed $sumArgs
+ * @Deprecated 1.17.0
*
- * @return float
+ * @see Statistical\Conditional::SUMIF()
+ * Use the SUMIF() method in the Statistical\Conditional class instead
+ *
+ * @param mixed $range Data values
+ * @param string $criteria the criteria that defines which cells will be summed
+ * @param mixed $sumRange
+ *
+ * @return float|string
*/
- public static function SUMIF($aArgs, $condition, $sumArgs = [])
+ public static function SUMIF($range, $criteria, $sumRange = [])
{
- $returnValue = 0;
-
- $aArgs = Functions::flattenArray($aArgs);
- $sumArgs = Functions::flattenArray($sumArgs);
- if (empty($sumArgs)) {
- $sumArgs = $aArgs;
- }
- $condition = Functions::ifCondition($condition);
- // Loop through arguments
- foreach ($aArgs as $key => $arg) {
- if (!is_numeric($arg)) {
- $arg = str_replace('"', '""', $arg);
- $arg = Calculation::wrapResult(strtoupper($arg));
- }
-
- $testCondition = '=' . $arg . $condition;
- $sumValue = array_key_exists($key, $sumArgs) ? $sumArgs[$key] : 0;
-
- if (
- is_numeric($sumValue) &&
- Calculation::getInstance()->_calculateFormulaValue($testCondition)
- ) {
- // Is it a value within our criteria and only numeric can be added to the result
- $returnValue += $sumValue;
- }
- }
-
- return $returnValue;
+ return Statistical\Conditional::SUMIF($range, $criteria, $sumRange);
}
/**
* SUMIFS.
*
- * Counts the number of cells that contain numbers within the list of arguments
+ * Totals the values of cells that contain numbers within the list of arguments
*
* Excel Function:
- * SUMIFS(value1[,value2[, ...]],condition)
+ * SUMIFS(sum_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...)
+ *
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Conditional::SUMIFS()
+ * Use the SUMIFS() method in the Statistical\Conditional class instead
*
* @param mixed $args Data values
*
- * @return float
+ * @return null|float|string
*/
public static function SUMIFS(...$args)
{
- $arrayList = $args;
-
- // Return value
- $returnValue = 0;
-
- $sumArgs = Functions::flattenArray(array_shift($arrayList));
- $aArgsArray = [];
- $conditions = [];
-
- while (count($arrayList) > 0) {
- $aArgsArray[] = Functions::flattenArray(array_shift($arrayList));
- $conditions[] = Functions::ifCondition(array_shift($arrayList));
- }
-
- // Loop through each sum and see if arguments and conditions are true
- foreach ($sumArgs as $index => $value) {
- $valid = true;
-
- foreach ($conditions as $cidx => $condition) {
- $arg = $aArgsArray[$cidx][$index];
-
- // Loop through arguments
- if (!is_numeric($arg)) {
- $arg = Calculation::wrapResult(strtoupper($arg));
- }
- $testCondition = '=' . $arg . $condition;
- if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
- // Is not a value within our criteria
- $valid = false;
-
- break; // if false found, don't need to check other conditions
- }
- }
-
- if ($valid) {
- $returnValue += $value;
- }
- }
-
- // Return
- return $returnValue;
+ return Statistical\Conditional::SUMIFS(...$args);
}
/**
@@ -1473,39 +838,18 @@ class MathTrig
* Excel Function:
* SUMPRODUCT(value1[,value2[, ...]])
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Sum::product()
+ * Use the product method in the MathTrig\Sum class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string The result, or a string containing an error
*/
public static function SUMPRODUCT(...$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 Functions::VALUE();
- }
-
- foreach ($array2 as $i => $val) {
- if ((!is_numeric($val)) || (is_string($val))) {
- $val = 0;
- }
- $wrkArray[$i] *= $val;
- }
- }
-
- return array_sum($wrkArray);
+ return MathTrig\Sum::product(...$args);
}
/**
@@ -1513,107 +857,75 @@ class MathTrig
*
* SUMSQ returns the sum of the squares of the arguments
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\SumSquares::sumSquare()
+ * Use the sumSquare method in the MathTrig\SumSquares class instead
+ *
* Excel Function:
* SUMSQ(value1[,value2[, ...]])
*
* @param mixed ...$args Data values
*
- * @return float
+ * @return float|string
*/
public static function SUMSQ(...$args)
{
- $returnValue = 0;
-
- // Loop through arguments
- foreach (Functions::flattenArray($args) as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $returnValue += ($arg * $arg);
- }
- }
-
- return $returnValue;
+ return MathTrig\SumSquares::sumSquare(...$args);
}
/**
* SUMX2MY2.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\SumSquares::sumXSquaredMinusYSquared()
+ * Use the sumXSquaredMinusYSquared method in the MathTrig\SumSquares class instead
+ *
* @param mixed[] $matrixData1 Matrix #1
* @param mixed[] $matrixData2 Matrix #2
*
- * @return float
+ * @return float|string
*/
public static function SUMX2MY2($matrixData1, $matrixData2)
{
- $array1 = Functions::flattenArray($matrixData1);
- $array2 = Functions::flattenArray($matrixData2);
- $count = min(count($array1), count($array2));
-
- $result = 0;
- for ($i = 0; $i < $count; ++$i) {
- if (
- ((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
- ((is_numeric($array2[$i])) && (!is_string($array2[$i])))
- ) {
- $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]);
- }
- }
-
- return $result;
+ return MathTrig\SumSquares::sumXSquaredMinusYSquared($matrixData1, $matrixData2);
}
/**
* SUMX2PY2.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\SumSquares::sumXSquaredPlusYSquared()
+ * Use the sumXSquaredPlusYSquared method in the MathTrig\SumSquares class instead
+ *
* @param mixed[] $matrixData1 Matrix #1
* @param mixed[] $matrixData2 Matrix #2
*
- * @return float
+ * @return float|string
*/
public static function SUMX2PY2($matrixData1, $matrixData2)
{
- $array1 = Functions::flattenArray($matrixData1);
- $array2 = Functions::flattenArray($matrixData2);
- $count = min(count($array1), count($array2));
-
- $result = 0;
- for ($i = 0; $i < $count; ++$i) {
- if (
- ((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
- ((is_numeric($array2[$i])) && (!is_string($array2[$i])))
- ) {
- $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]);
- }
- }
-
- return $result;
+ return MathTrig\SumSquares::sumXSquaredPlusYSquared($matrixData1, $matrixData2);
}
/**
* SUMXMY2.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\SumSquares::sumXMinusYSquared()
+ * Use the sumXMinusYSquared method in the MathTrig\SumSquares class instead
+ *
* @param mixed[] $matrixData1 Matrix #1
* @param mixed[] $matrixData2 Matrix #2
*
- * @return float
+ * @return float|string
*/
public static function SUMXMY2($matrixData1, $matrixData2)
{
- $array1 = Functions::flattenArray($matrixData1);
- $array2 = Functions::flattenArray($matrixData2);
- $count = min(count($array1), count($array2));
-
- $result = 0;
- for ($i = 0; $i < $count; ++$i) {
- if (
- ((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
- ((is_numeric($array2[$i])) && (!is_string($array2[$i])))
- ) {
- $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]);
- }
- }
-
- return $result;
+ return MathTrig\SumSquares::sumXMinusYSquared($matrixData1, $matrixData2);
}
/**
@@ -1621,6 +933,11 @@ class MathTrig
*
* Truncates value to the number of fractional digits by number_digits.
*
+ * @Deprecated 1.17.0
+ *
+ * @see MathTrig\Trunc::evaluate()
+ * Use the evaluate() method in the MathTrig\Trunc class instead
+ *
* @param float $value
* @param int $digits
*
@@ -1628,23 +945,7 @@ class MathTrig
*/
public static function TRUNC($value = 0, $digits = 0)
{
- $value = Functions::flattenSingleValue($value);
- $digits = Functions::flattenSingleValue($digits);
-
- // Validate parameters
- if ((!is_numeric($value)) || (!is_numeric($digits))) {
- return Functions::VALUE();
- }
- $digits = floor($digits);
-
- // Truncate
- $adjust = 10 ** $digits;
-
- if (($digits > 0) && (rtrim((int) ((abs($value) - abs((int) $value)) * $adjust), '0') < $adjust / 10)) {
- return $value;
- }
-
- return ((int) ($value * $adjust)) / $adjust;
+ return MathTrig\Trunc::evaluate($value, $digits);
}
/**
@@ -1652,21 +953,18 @@ class MathTrig
*
* Returns the secant of an angle.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Trig\Secant::sec()
+ * Use the sec method in the MathTrig\Trig\Secant class instead
+ *
* @param float $angle Number
*
* @return float|string The secant of the angle
*/
public static function SEC($angle)
{
- $angle = Functions::flattenSingleValue($angle);
-
- if (!is_numeric($angle)) {
- return Functions::VALUE();
- }
-
- $result = cos($angle);
-
- return ($result == 0.0) ? Functions::DIV0() : 1 / $result;
+ return MathTrig\Trig\Secant::sec($angle);
}
/**
@@ -1674,21 +972,18 @@ class MathTrig
*
* Returns the hyperbolic secant of an angle.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Trig\Secant::sech()
+ * Use the sech method in the MathTrig\Trig\Secant class instead
+ *
* @param float $angle Number
*
* @return float|string The hyperbolic secant of the angle
*/
public static function SECH($angle)
{
- $angle = Functions::flattenSingleValue($angle);
-
- if (!is_numeric($angle)) {
- return Functions::VALUE();
- }
-
- $result = cosh($angle);
-
- return ($result == 0.0) ? Functions::DIV0() : 1 / $result;
+ return MathTrig\Trig\Secant::sech($angle);
}
/**
@@ -1696,21 +991,18 @@ class MathTrig
*
* Returns the cosecant of an angle.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Trig\Cosecant::csc()
+ * Use the csc method in the MathTrig\Trig\Cosecant class instead
+ *
* @param float $angle Number
*
* @return float|string The cosecant of the angle
*/
public static function CSC($angle)
{
- $angle = Functions::flattenSingleValue($angle);
-
- if (!is_numeric($angle)) {
- return Functions::VALUE();
- }
-
- $result = sin($angle);
-
- return ($result == 0.0) ? Functions::DIV0() : 1 / $result;
+ return MathTrig\Trig\Cosecant::csc($angle);
}
/**
@@ -1718,21 +1010,18 @@ class MathTrig
*
* Returns the hyperbolic cosecant of an angle.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Trig\Cosecant::csch()
+ * Use the csch method in the MathTrig\Trig\Cosecant class instead
+ *
* @param float $angle Number
*
* @return float|string The hyperbolic cosecant of the angle
*/
public static function CSCH($angle)
{
- $angle = Functions::flattenSingleValue($angle);
-
- if (!is_numeric($angle)) {
- return Functions::VALUE();
- }
-
- $result = sinh($angle);
-
- return ($result == 0.0) ? Functions::DIV0() : 1 / $result;
+ return MathTrig\Trig\Cosecant::csch($angle);
}
/**
@@ -1740,21 +1029,18 @@ class MathTrig
*
* Returns the cotangent of an angle.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Trig\Cotangent::cot()
+ * Use the cot method in the MathTrig\Trig\Cotangent class instead
+ *
* @param float $angle Number
*
* @return float|string The cotangent of the angle
*/
public static function COT($angle)
{
- $angle = Functions::flattenSingleValue($angle);
-
- if (!is_numeric($angle)) {
- return Functions::VALUE();
- }
-
- $result = tan($angle);
-
- return ($result == 0.0) ? Functions::DIV0() : 1 / $result;
+ return MathTrig\Trig\Cotangent::cot($angle);
}
/**
@@ -1762,21 +1048,18 @@ class MathTrig
*
* Returns the hyperbolic cotangent of an angle.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Trig\Cotangent::coth()
+ * Use the coth method in the MathTrig\Trig\Cotangent class instead
+ *
* @param float $angle Number
*
* @return float|string The hyperbolic cotangent of the angle
*/
public static function COTH($angle)
{
- $angle = Functions::flattenSingleValue($angle);
-
- if (!is_numeric($angle)) {
- return Functions::VALUE();
- }
-
- $result = tanh($angle);
-
- return ($result == 0.0) ? Functions::DIV0() : 1 / $result;
+ return MathTrig\Trig\Cotangent::coth($angle);
}
/**
@@ -1784,19 +1067,35 @@ class MathTrig
*
* Returns the arccotangent of a number.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Trig\Cotangent::acot()
+ * Use the acot method in the MathTrig\Trig\Cotangent class instead
+ *
* @param float $number Number
*
* @return float|string The arccotangent of the number
*/
public static function ACOT($number)
{
- $number = Functions::flattenSingleValue($number);
+ return MathTrig\Trig\Cotangent::acot($number);
+ }
- if (!is_numeric($number)) {
- return Functions::VALUE();
- }
-
- return (M_PI / 2) - atan($number);
+ /**
+ * Return NAN or value depending on argument.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Helpers::numberOrNan()
+ * Use the numberOrNan method in the MathTrig\Helpers class instead
+ *
+ * @param float $result Number
+ *
+ * @return float|string
+ */
+ public static function numberOrNan($result)
+ {
+ return MathTrig\Helpers::numberOrNan($result);
}
/**
@@ -1804,20 +1103,418 @@ class MathTrig
*
* Returns the hyperbolic arccotangent of a number.
*
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Trig\Cotangent::acoth()
+ * Use the acoth method in the MathTrig\Trig\Cotangent class instead
+ *
* @param float $number Number
*
* @return 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
+ *
+ * @See MathTrig\Round::round()
+ * Use the round() method in the MathTrig\Round class instead
+ *
+ * @param mixed $number Should be numeric
+ * @param mixed $precision Should be int
+ *
+ * @return 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
+ *
+ * @See MathTrig\Absolute::evaluate()
+ * Use the evaluate method in the MathTrig\Absolute class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return float|int|string Rounded number
+ */
+ public static function builtinABS($number)
+ {
+ return MathTrig\Absolute::evaluate($number);
+ }
+
+ /**
+ * ACOS.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @See MathTrig\Trig\Cosine::acos()
+ * Use the acos method in the MathTrig\Trig\Cosine class instead
+ *
+ * Returns the result of builtin function acos after validating args.
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Trig\Cosine::acosh()
+ * Use the acosh method in the MathTrig\Trig\Cosine class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Trig\Sine::asin()
+ * Use the asin method in the MathTrig\Trig\Sine class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Trig\Sine::asinh()
+ * Use the asinh method in the MathTrig\Trig\Sine class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Trig\Tangent::atan()
+ * Use the atan method in the MathTrig\Trig\Tangent class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Trig\Tangent::atanh()
+ * Use the atanh method in the MathTrig\Trig\Tangent class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Trig\Cosine::cos()
+ * Use the cos method in the MathTrig\Trig\Cosine class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Trig\Cosine::cosh()
+ * Use the cosh method in the MathTrig\Trig\Cosine class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Angle::toDegrees()
+ * Use the toDegrees method in the MathTrig\Angle class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Exp::evaluate()
+ * Use the evaluate method in the MathTrig\Exp class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Logarithms::natural()
+ * Use the natural method in the MathTrig\Logarithms class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Logarithms::base10()
+ * Use the natural method in the MathTrig\Logarithms class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Angle::toRadians()
+ * Use the toRadians method in the MathTrig\Angle class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Trig\Sine::evaluate()
+ * Use the sin method in the MathTrig\Trig\Sine class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Trig\Sine::sinh()
+ * Use the sinh method in the MathTrig\Trig\Sine class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Sqrt::sqrt()
+ * Use the sqrt method in the MathTrig\Sqrt class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Trig\Tangent::tan()
+ * Use the tan method in the MathTrig\Trig\Tangent class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Trig\Tangent::tanh()
+ * Use the tanh method in the MathTrig\Trig\Tangent class instead
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return 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
+ *
+ * @See MathTrig\Helpers::validateNumericNullBool()
+ * Use the validateNumericNullBool method in the MathTrig\Helpers class instead
+ *
+ * @param mixed $number
+ */
+ public static function nullFalseTrueToNumber(&$number): void
{
$number = Functions::flattenSingleValue($number);
-
- if (!is_numeric($number)) {
- return Functions::VALUE();
+ if ($number === null) {
+ $number = 0;
+ } elseif (is_bool($number)) {
+ $number = (int) $number;
}
-
- $result = log(($number + 1) / ($number - 1)) / 2;
-
- return is_nan($result) ? Functions::NAN() : $result;
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php
new file mode 100644
index 00000000000..9f1bd804970
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php
@@ -0,0 +1,28 @@
+getMessage();
+ }
+
+ return abs($number);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Angle.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Angle.php
new file mode 100644
index 00000000000..3062481f0e3
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Angle.php
@@ -0,0 +1,48 @@
+getMessage();
+ }
+
+ return rad2deg($number);
+ }
+
+ /**
+ * RADIANS.
+ *
+ * Returns the result of builtin function deg2rad after validating args.
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return float|string Rounded number
+ */
+ public static function toRadians($number)
+ {
+ try {
+ $number = Helpers::validateNumericNullBool($number);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return deg2rad($number);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php
new file mode 100644
index 00000000000..b852eeacf1d
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php
@@ -0,0 +1,103 @@
+ 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 string $roman
+ *
+ * @return int|string the arabic numberal contrived from the roman numeral
+ */
+ public static function evaluate($roman)
+ {
+ // An empty string should return 0
+ $roman = substr(trim(strtoupper((string) Functions::flattenSingleValue($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 Functions::VALUE(); // Invalid character detected
+ }
+
+ if ($negativeNumber) {
+ $arabic *= -1; // The number should be negative
+ }
+
+ return $arabic;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Base.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Base.php
new file mode 100644
index 00000000000..4be7b7c7986
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Base.php
@@ -0,0 +1,49 @@
+getMessage();
+ }
+ $minLength = Functions::flattenSingleValue($minLength);
+
+ if ($minLength === null || is_numeric($minLength)) {
+ if ($number < 0 || $number >= 2 ** 53 || $radix < 2 || $radix > 36) {
+ return Functions::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 Functions::VALUE();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php
new file mode 100644
index 00000000000..73f54a52f69
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php
@@ -0,0 +1,138 @@
+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
+ * @param mixed $significance Significance
+ * @param int $mode direction to round negative numbers
+ *
+ * @return float|string Rounded Number, or a string containing an error
+ */
+ public static function math($number, $significance = null, $mode = 0)
+ {
+ 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
+ * @param float $significance the multiple to which you want to round
+ *
+ * @return float|string Rounded Number, or a string containing an error
+ */
+ public static function precise($number, $significance = 1)
+ {
+ 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 Functions::NAN();
+ }
+
+ private static function floorCheck1Arg(): void
+ {
+ $compatibility = Functions::getCompatibilityMode();
+ if ($compatibility === Functions::COMPATIBILITY_EXCEL) {
+ throw new Exception('Excel requires 2 arguments for CEILING');
+ }
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php
new file mode 100644
index 00000000000..97508bb1ef0
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php
@@ -0,0 +1,74 @@
+getMessage();
+ }
+
+ return round(Factorial::fact($numObjs) / Factorial::fact($numObjs - $numInSet)) / Factorial::fact($numInSet);
+ }
+
+ /**
+ * 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
+ * @param mixed $numInSet Number of objects in each combination
+ *
+ * @return float|int|string Number of combinations, or a string containing an error
+ */
+ public static function withRepetition($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)) / Factorial::fact($numInSet);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Exp.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Exp.php
new file mode 100644
index 00000000000..ce930a83ab3
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Exp.php
@@ -0,0 +1,28 @@
+getMessage();
+ }
+
+ return exp($number);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php
new file mode 100644
index 00000000000..f443f8e59ca
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php
@@ -0,0 +1,110 @@
+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 float $factVal Factorial Value
+ *
+ * @return float|int|string Double Factorial, or a string containing an error
+ */
+ public static function factDouble($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 $summer / $divisor;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Floor.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Floor.php
new file mode 100644
index 00000000000..04e122058d5
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Floor.php
@@ -0,0 +1,166 @@
+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
+ * @param mixed $significance Significance
+ * @param mixed $mode direction to round negative numbers
+ *
+ * @return float|string Rounded Number, or a string containing an error
+ */
+ public static function math($number, $significance = null, $mode = 0)
+ {
+ 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 float $number Number to round
+ * @param float $significance Significance
+ *
+ * @return float|string Rounded Number, or a string containing an error
+ */
+ public static function precise($number, $significance = 1)
+ {
+ 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 Functions::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 Functions::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 Functions::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 Functions::NAN();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php
new file mode 100644
index 00000000000..1dd52faa752
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php
@@ -0,0 +1,69 @@
+getMessage();
+ }
+
+ if (count($arrayArgs) <= 0) {
+ return Functions::VALUE();
+ }
+ $gcd = (int) array_pop($arrayArgs);
+ do {
+ $gcd = self::evaluateGCD($gcd, (int) array_pop($arrayArgs));
+ } while (!empty($arrayArgs));
+
+ return $gcd;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php
new file mode 100644
index 00000000000..b89644a971b
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php
@@ -0,0 +1,129 @@
+= 0.
+ *
+ * @param float|int $number
+ */
+ public static function validateNotNegative($number, ?string $except = null): void
+ {
+ if ($number >= 0) {
+ return;
+ }
+
+ throw new Exception($except ?? Functions::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 ?? Functions::NAN());
+ }
+
+ /**
+ * Confirm number != 0.
+ *
+ * @param float|int $number
+ */
+ public static function validateNotZero($number): void
+ {
+ if ($number) {
+ return;
+ }
+
+ throw new Exception(Functions::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) ? Functions::NAN() : $result;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php
new file mode 100644
index 00000000000..7aa3d06ae27
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php
@@ -0,0 +1,31 @@
+getMessage();
+ }
+
+ return (int) floor($number);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php
new file mode 100644
index 00000000000..46e9816dc68
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php
@@ -0,0 +1,110 @@
+ 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(Functions::VALUE());
+ }
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php
new file mode 100644
index 00000000000..d6878d88c91
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php
@@ -0,0 +1,77 @@
+getMessage();
+ }
+
+ return log($number, $base);
+ }
+
+ /**
+ * LOG10.
+ *
+ * Returns the result of builtin function log after validating args.
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return float|string Rounded number
+ */
+ public static function base10($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
+ *
+ * @return float|string Rounded number
+ */
+ public static function natural($number)
+ {
+ try {
+ $number = Helpers::validateNumericNullBool($number);
+ Helpers::validatePositive($number);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return log($number);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php
new file mode 100644
index 00000000000..92e1ff8e7bb
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php
@@ -0,0 +1,138 @@
+determinant();
+ } catch (MatrixException $ex) {
+ return Functions::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 Functions::NAN();
+ } catch (MatrixException $e) {
+ return Functions::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 Functions::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, Functions::VALUE());
+ $matrix = Builder::createIdentityMatrix($dimension, 0)->toArray();
+
+ return $matrix;
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Operations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Operations.php
new file mode 100644
index 00000000000..595c7fdccec
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Operations.php
@@ -0,0 +1,136 @@
+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 float|int $x
+ * @param float|int $y
+ *
+ * @return float|int|string The result, or a string containing an error
+ */
+ public static function power($x, $y)
+ {
+ try {
+ $x = Helpers::validateNumericNullBool($x);
+ $y = Helpers::validateNumericNullBool($y);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ // Validate parameters
+ if (!$x && !$y) {
+ return Functions::NAN();
+ }
+ if (!$x && $y < 0.0) {
+ return Functions::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)
+ {
+ // Return value
+ $returnValue = null;
+
+ // Loop through arguments
+ foreach (Functions::flattenArray($args) as $arg) {
+ // Is it a numeric value?
+ if (is_numeric($arg)) {
+ if ($returnValue === null) {
+ $returnValue = $arg;
+ } else {
+ $returnValue *= $arg;
+ }
+ } else {
+ return Functions::VALUE();
+ }
+ }
+
+ // Return
+ if ($returnValue === null) {
+ return 0;
+ }
+
+ return $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
+ * @param mixed $denominator Expect float|int
+ *
+ * @return int|string
+ */
+ public static function quotient($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);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Random.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Random.php
new file mode 100644
index 00000000000..963a789ac52
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Random.php
@@ -0,0 +1,39 @@
+getMessage();
+ }
+
+ return mt_rand($min, $max);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Roman.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Roman.php
new file mode 100644
index 00000000000..71a6df3ad79
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Roman.php
@@ -0,0 +1,835 @@
+ ['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) ? Functions::VALUE() : self::valueOk($aValue, $style);
+ }
+
+ public static function calculateRoman(int $aValue, int $style): string
+ {
+ return ($style < 0 || $style > self::MAX_ROMAN_STYLE) ? Functions::VALUE() : self::styleOk($aValue, $style);
+ }
+
+ /**
+ * ROMAN.
+ *
+ * Converts a number to Roman numeral
+ *
+ * @param mixed $aValue Number to convert
+ * @param mixed $style Number indicating one of five possible forms
+ *
+ * @return string Roman numeral, or a string containing an error
+ */
+ public static function evaluate($aValue, $style = 0)
+ {
+ 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);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Round.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Round.php
new file mode 100644
index 00000000000..2ddde90008e
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Round.php
@@ -0,0 +1,179 @@
+getMessage();
+ }
+
+ return round($number, (int) $precision);
+ }
+
+ /**
+ * ROUNDUP.
+ *
+ * Rounds a number up to a specified number of decimal places
+ *
+ * @param float $number Number to round
+ * @param int $digits Number of digits to which you want to round $number
+ *
+ * @return float|string Rounded Number, or a string containing an error
+ */
+ public static function up($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 float $number Number to round
+ * @param int $digits Number of digits to which you want to round $number
+ *
+ * @return float|string Rounded Number, or a string containing an error
+ */
+ public static function down($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.
+ * @param mixed $multiple Expect int. Multiple to which you want to round.
+ *
+ * @return float|string Rounded Number, or a string containing an error
+ */
+ public static function multiple($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 Functions::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 float $number Number to round
+ *
+ * @return float|string Rounded Number, or a string containing an error
+ */
+ public static function even($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 float $number Number to round
+ *
+ * @return float|string Rounded Number, or a string containing an error
+ */
+ public static function odd($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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php
new file mode 100644
index 00000000000..2ada9df4ea9
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php
@@ -0,0 +1,46 @@
+getMessage();
+ }
+
+ return $returnValue;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sign.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sign.php
new file mode 100644
index 00000000000..a48cf0f9bb6
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sign.php
@@ -0,0 +1,29 @@
+getMessage();
+ }
+
+ return Helpers::returnSign($number);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php
new file mode 100644
index 00000000000..8ead578e325
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php
@@ -0,0 +1,49 @@
+getMessage();
+ }
+
+ return Helpers::numberOrNan(sqrt($number));
+ }
+
+ /**
+ * SQRTPI.
+ *
+ * Returns the square root of (number * pi).
+ *
+ * @param float $number Number
+ *
+ * @return float|string Square Root of Number * Pi, or a string containing an error
+ */
+ public static function pi($number)
+ {
+ try {
+ $number = Helpers::validateNumericNullSubstitution($number, 0);
+ Helpers::validateNotNegative($number);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return sqrt($number * M_PI);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php
new file mode 100644
index 00000000000..2edb86f7e76
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php
@@ -0,0 +1,111 @@
+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) {
+ [, $row, $column] = explode('.', $index);
+ $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
+ );
+ }
+
+ /** @var callable[] */
+ private const CALL_FUNCTIONS = [
+ 1 => [Statistical\Averages::class, 'average'],
+ [Statistical\Counts::class, 'COUNT'], // 2
+ [Statistical\Counts::class, 'COUNTA'], // 3
+ [Statistical\Maximum::class, 'max'], // 4
+ [Statistical\Minimum::class, 'min'], // 5
+ [Operations::class, 'product'], // 6
+ [Statistical\StandardDeviations::class, 'STDEV'], // 7
+ [Statistical\StandardDeviations::class, 'STDEVP'], // 8
+ [Sum::class, 'sumIgnoringStrings'], // 9
+ [Statistical\Variances::class, 'VAR'], // 10
+ [Statistical\Variances::class, 'VARP'], // 11
+ ];
+
+ /**
+ * 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);
+ $aArgs = Functions::flattenArrayIndexed($args);
+
+ 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 Functions::VALUE();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sum.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sum.php
new file mode 100644
index 00000000000..741734d90a7
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sum.php
@@ -0,0 +1,115 @@
+ $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 (Functions::isError($arg)) {
+ return $arg;
+ // ignore non-numerics from cell, but fail as literals (except null)
+ } elseif ($arg !== null && !Functions::isCellValue($k)) {
+ return Functions::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 Functions::VALUE();
+ }
+
+ foreach ($array2 as $i => $val) {
+ if ((!is_numeric($val)) || (is_string($val))) {
+ $val = 0;
+ }
+ $wrkArray[$i] *= $val;
+ }
+ }
+
+ return array_sum($wrkArray);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php
new file mode 100644
index 00000000000..49fa6381123
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php
@@ -0,0 +1,142 @@
+getMessage();
+ }
+
+ return $returnValue;
+ }
+
+ private static function getCount(array $array1, array $array2): int
+ {
+ $count = count($array1);
+ if ($count !== count($array2)) {
+ throw new Exception(Functions::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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php
new file mode 100644
index 00000000000..3038e6cc0e5
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php
@@ -0,0 +1,49 @@
+getMessage();
+ }
+
+ return Helpers::verySmallDenominator(1.0, sin($angle));
+ }
+
+ /**
+ * CSCH.
+ *
+ * Returns the hyperbolic cosecant of an angle.
+ *
+ * @param float $angle Number
+ *
+ * @return float|string The hyperbolic cosecant of the angle
+ */
+ public static function csch($angle)
+ {
+ try {
+ $angle = Helpers::validateNumericNullBool($angle);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return Helpers::verySmallDenominator(1.0, sinh($angle));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php
new file mode 100644
index 00000000000..6c69e126d73
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php
@@ -0,0 +1,89 @@
+getMessage();
+ }
+
+ return cos($number);
+ }
+
+ /**
+ * COSH.
+ *
+ * Returns the result of builtin function cosh after validating args.
+ *
+ * @param mixed $number Should be numeric
+ *
+ * @return float|string hyperbolic cosine
+ */
+ public static function cosh($number)
+ {
+ try {
+ $number = Helpers::validateNumericNullBool($number);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return cosh($number);
+ }
+
+ /**
+ * ACOS.
+ *
+ * Returns the arccosine of a number.
+ *
+ * @param float $number Number
+ *
+ * @return float|string The arccosine of the number
+ */
+ public static function acos($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 float $number Number
+ *
+ * @return float|string The inverse hyperbolic cosine of the number, or an error string
+ */
+ public static function acosh($number)
+ {
+ try {
+ $number = Helpers::validateNumericNullBool($number);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return Helpers::numberOrNan(acosh($number));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php
new file mode 100644
index 00000000000..1b796f50f65
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php
@@ -0,0 +1,91 @@
+getMessage();
+ }
+
+ return Helpers::verySmallDenominator(cos($angle), sin($angle));
+ }
+
+ /**
+ * COTH.
+ *
+ * Returns the hyperbolic cotangent of an angle.
+ *
+ * @param float $angle Number
+ *
+ * @return float|string The hyperbolic cotangent of the angle
+ */
+ public static function coth($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 float $number Number
+ *
+ * @return float|string The arccotangent of the number
+ */
+ public static function acot($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 float $number Number
+ *
+ * @return float|string The hyperbolic arccotangent of the number
+ */
+ public static function acoth($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);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php
new file mode 100644
index 00000000000..70299cb7e31
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php
@@ -0,0 +1,49 @@
+getMessage();
+ }
+
+ return Helpers::verySmallDenominator(1.0, cos($angle));
+ }
+
+ /**
+ * SECH.
+ *
+ * Returns the hyperbolic secant of an angle.
+ *
+ * @param float $angle Number
+ *
+ * @return float|string The hyperbolic secant of the angle
+ */
+ public static function sech($angle)
+ {
+ try {
+ $angle = Helpers::validateNumericNullBool($angle);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return Helpers::verySmallDenominator(1.0, cosh($angle));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php
new file mode 100644
index 00000000000..2c6a8a0718f
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php
@@ -0,0 +1,89 @@
+getMessage();
+ }
+
+ return sin($angle);
+ }
+
+ /**
+ * SINH.
+ *
+ * Returns the result of builtin function sinh after validating args.
+ *
+ * @param mixed $angle Should be numeric
+ *
+ * @return float|string hyperbolic sine
+ */
+ public static function sinh($angle)
+ {
+ try {
+ $angle = Helpers::validateNumericNullBool($angle);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return sinh($angle);
+ }
+
+ /**
+ * ASIN.
+ *
+ * Returns the arcsine of a number.
+ *
+ * @param float $number Number
+ *
+ * @return float|string The arcsine of the number
+ */
+ public static function asin($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 float $number Number
+ *
+ * @return float|string The inverse hyperbolic sine of the number
+ */
+ public static function asinh($number)
+ {
+ try {
+ $number = Helpers::validateNumericNullBool($number);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return Helpers::numberOrNan(asinh($number));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php
new file mode 100644
index 00000000000..6cd235fb702
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php
@@ -0,0 +1,127 @@
+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
+ *
+ * @return float|string hyperbolic tangent
+ */
+ public static function tanh($angle)
+ {
+ try {
+ $angle = Helpers::validateNumericNullBool($angle);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return tanh($angle);
+ }
+
+ /**
+ * ATAN.
+ *
+ * Returns the arctangent of a number.
+ *
+ * @param float $number Number
+ *
+ * @return float|string The arctangent of the number
+ */
+ public static function atan($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 float $number Number
+ *
+ * @return float|string The inverse hyperbolic tangent of the number
+ */
+ public static function atanh($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
+ * @param mixed $yCoordinate should be float, the y-coordinate of the point
+ *
+ * @return float|string the inverse tangent of the specified x- and y-coordinates, or a string containing an error
+ */
+ public static function atan2($xCoordinate, $yCoordinate)
+ {
+ try {
+ $xCoordinate = Helpers::validateNumericNullBool($xCoordinate);
+ $yCoordinate = Helpers::validateNumericNullBool($yCoordinate);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if (($xCoordinate == 0) && ($yCoordinate == 0)) {
+ return Functions::DIV0();
+ }
+
+ return atan2($yCoordinate, $xCoordinate);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php
new file mode 100644
index 00000000000..4b3670f680d
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php
@@ -0,0 +1,39 @@
+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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical.php
index 19f40f2d4a8..d43a85f9045 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical.php
@@ -2,564 +2,27 @@
namespace PhpOffice\PhpSpreadsheet\Calculation;
-use PhpOffice\PhpSpreadsheet\Shared\Trend\Trend;
+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 XMININ = 2.23e-308;
const EPS = 2.22e-16;
const MAX_VALUE = 1.2e308;
- const MAX_ITERATIONS = 256;
const SQRT2PI = 2.5066282746310005024157652848110452530069867406099;
- private static function checkTrendArrays(&$array1, &$array2)
- {
- if (!is_array($array1)) {
- $array1 = [$array1];
- }
- if (!is_array($array2)) {
- $array2 = [$array2];
- }
-
- $array1 = Functions::flattenArray($array1);
- $array2 = Functions::flattenArray($array2);
- foreach ($array1 as $key => $value) {
- if ((is_bool($value)) || (is_string($value)) || ($value === null)) {
- unset($array1[$key], $array2[$key]);
- }
- }
- foreach ($array2 as $key => $value) {
- if ((is_bool($value)) || (is_string($value)) || ($value === null)) {
- unset($array1[$key], $array2[$key]);
- }
- }
- $array1 = array_merge($array1);
- $array2 = array_merge($array2);
-
- return true;
- }
-
- /**
- * 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 mixed $x require 0<=x<=1
- * @param mixed $p require p>0
- * @param mixed $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
- */
- private static function incompleteBeta($x, $p, $q)
- {
- 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
- private static $logBetaCacheP = 0.0;
-
- private static $logBetaCacheQ = 0.0;
-
- private static $logBetaCacheResult = 0.0;
-
- /**
- * The natural logarithm of the beta function.
- *
- * @param mixed $p require p>0
- * @param mixed $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($p, $q)
- {
- 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 = self::logGamma($p) + self::logGamma($q) - self::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
- *
- * @param mixed $x
- * @param mixed $p
- * @param mixed $q
- *
- * @return float
- */
- private static function betaFraction($x, $p, $q)
- {
- $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;
- }
-
- /**
- * logGamma function.
- *
- * @version 1.1
- *
- * @author Jaco van Kooten
- *
- * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher.
- *
- * The natural logarithm of the gamma function.
- * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
- * Applied Mathematics Division
- * Argonne National Laboratory
- * Argonne, IL 60439
- *
- * References:
- *
- * - W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural
- * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.
- * - K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.
- * - Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.
- *
- *
- *
- * From the original documentation:
- *
- *
- * 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.
- *
- *
- * Error returns:
- * 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.
- *
- *
- * @return float MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305
- */
-
- // Function cache for logGamma
- private static $logGammaCacheResult = 0.0;
-
- private static $logGammaCacheX = 0.0;
-
- private static function logGamma($x)
- {
- // Log Gamma related constants
- static $lg_d1 = -0.5772156649015328605195174;
- static $lg_d2 = 0.4227843350984671393993777;
- static $lg_d4 = 1.791759469228055000094023;
-
- static $lg_p1 = [
- 4.945235359296727046734888,
- 201.8112620856775083915565,
- 2290.838373831346393026739,
- 11319.67205903380828685045,
- 28557.24635671635335736389,
- 38484.96228443793359990269,
- 26377.48787624195437963534,
- 7225.813979700288197698961,
- ];
- static $lg_p2 = [
- 4.974607845568932035012064,
- 542.4138599891070494101986,
- 15506.93864978364947665077,
- 184793.2904445632425417223,
- 1088204.76946882876749847,
- 3338152.967987029735917223,
- 5106661.678927352456275255,
- 3074109.054850539556250927,
- ];
- static $lg_p4 = [
- 14745.02166059939948905062,
- 2426813.369486704502836312,
- 121475557.4045093227939592,
- 2663432449.630976949898078,
- 29403789566.34553899906876,
- 170266573776.5398868392998,
- 492612579337.743088758812,
- 560625185622.3951465078242,
- ];
- static $lg_q1 = [
- 67.48212550303777196073036,
- 1113.332393857199323513008,
- 7738.757056935398733233834,
- 27639.87074403340708898585,
- 54993.10206226157329794414,
- 61611.22180066002127833352,
- 36351.27591501940507276287,
- 8785.536302431013170870835,
- ];
- static $lg_q2 = [
- 183.0328399370592604055942,
- 7765.049321445005871323047,
- 133190.3827966074194402448,
- 1136705.821321969608938755,
- 5267964.117437946917577538,
- 13467014.54311101692290052,
- 17827365.30353274213975932,
- 9533095.591844353613395747,
- ];
- static $lg_q4 = [
- 2690.530175870899333379843,
- 639388.5654300092398984238,
- 41355999.30241388052042842,
- 1120872109.61614794137657,
- 14886137286.78813811542398,
- 101680358627.2438228077304,
- 341747634550.7377132798597,
- 446315818741.9713286462081,
- ];
- static $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
- static $lg_frtbig = 2.25e76;
- static $pnt68 = 0.6796875;
-
- 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) {
- // ---------------------
- // EPS .LT. X .LE. 1.5
- // ---------------------
- if ($y < $pnt68) {
- $corr = -log($y);
- $xm1 = $y;
- } else {
- $corr = 0.0;
- $xm1 = $y - 1.0;
- }
- if ($y <= 0.5 || $y >= $pnt68) {
- $xden = 1.0;
- $xnum = 0.0;
- for ($i = 0; $i < 8; ++$i) {
- $xnum = $xnum * $xm1 + $lg_p1[$i];
- $xden = $xden * $xm1 + $lg_q1[$i];
- }
- $res = $corr + $xm1 * ($lg_d1 + $xm1 * ($xnum / $xden));
- } else {
- $xm2 = $y - 1.0;
- $xden = 1.0;
- $xnum = 0.0;
- for ($i = 0; $i < 8; ++$i) {
- $xnum = $xnum * $xm2 + $lg_p2[$i];
- $xden = $xden * $xm2 + $lg_q2[$i];
- }
- $res = $corr + $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden));
- }
- } elseif ($y <= 4.0) {
- // ---------------------
- // 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 + $lg_p2[$i];
- $xden = $xden * $xm2 + $lg_q2[$i];
- }
- $res = $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden));
- } elseif ($y <= 12.0) {
- // ----------------------
- // 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 + $lg_p4[$i];
- $xden = $xden * $xm4 + $lg_q4[$i];
- }
- $res = $lg_d4 + $xm4 * ($xnum / $xden);
- } else {
- // ---------------------------------
- // Evaluate for argument .GE. 12.0
- // ---------------------------------
- $res = 0.0;
- if ($y <= $lg_frtbig) {
- $res = $lg_c[6];
- $ysq = $y * $y;
- for ($i = 0; $i < 6; ++$i) {
- $res = $res / $ysq + $lg_c[$i];
- }
- $res /= $y;
- $corr = log($y);
- $res = $res + log(self::SQRT2PI) - 0.5 * $corr;
- $res += $y * ($corr - 1.0);
- }
- }
- } else {
- // --------------------------
- // Return for bad arguments
- // --------------------------
- $res = self::MAX_VALUE;
- }
- // ------------------------------
- // Final adjustments and return
- // ------------------------------
- self::$logGammaCacheX = $x;
- self::$logGammaCacheResult = $res;
-
- return $res;
- }
-
- //
- // Private implementation of the incomplete Gamma function
- //
- private static function incompleteGamma($a, $x)
- {
- 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;
- }
-
- //
- // Private implementation of the Gamma function
- //
- private static function gamma($data)
- {
- if ($data == 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 = $data;
- $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));
- }
-
- /*
- * inverse_ncdf.php
- * -------------------
- * begin : Friday, January 16, 2004
- * copyright : (C) 2004 Michael Nickerson
- * email : nickersonm@yahoo.com
- *
- */
- private static function inverseNcdf($p)
- {
- // 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_low <= $p && $p <= $p_high) {
- // 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);
- } 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);
- }
- // If 0 < p < 1, return a null value
- return Functions::NULL();
- }
-
- /**
- * 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
- */
- private static function testAcceptedBoolean($arg, $k)
- {
- 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
- */
- private static function isAcceptedCountable($arg, $k)
- {
- if (
- ((is_numeric($arg)) && (!is_string($arg))) ||
- ((is_numeric($arg)) && (!Functions::isCellValue($k)) &&
- (Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_GNUMERIC))
- ) {
- return true;
- }
-
- return false;
- }
-
/**
* AVEDEV.
*
@@ -569,45 +32,18 @@ class Statistical
* Excel Function:
* AVEDEV(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Averages::averageDeviations()
+ * Use the averageDeviations() method in the Statistical\Averages class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string
*/
public static function AVEDEV(...$args)
{
- $aArgs = Functions::flattenArrayIndexed($args);
-
- // Return value
- $returnValue = 0;
-
- $aMean = self::AVERAGE(...$args);
- if ($aMean === Functions::DIV0()) {
- return Functions::NAN();
- } elseif ($aMean === Functions::VALUE()) {
- return Functions::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 Functions::VALUE();
- }
- if (self::isAcceptedCountable($arg, $k)) {
- $returnValue += abs($arg - $aMean);
- ++$aCount;
- }
- }
-
- // Return
- if ($aCount === 0) {
- return Functions::DIV0();
- }
-
- return $returnValue / $aCount;
+ return Averages::averageDeviations(...$args);
}
/**
@@ -618,35 +54,18 @@ class Statistical
* Excel Function:
* AVERAGE(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Averages::average()
+ * Use the average() method in the Statistical\Averages class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string
*/
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 Functions::VALUE();
- }
- if (self::isAcceptedCountable($arg, $k)) {
- $returnValue += $arg;
- ++$aCount;
- }
- }
-
- // Return
- if ($aCount > 0) {
- return $returnValue / $aCount;
- }
-
- return Functions::DIV0();
+ return Averages::average(...$args);
}
/**
@@ -657,39 +76,18 @@ class Statistical
* Excel Function:
* AVERAGEA(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Averages::averageA()
+ * Use the averageA() method in the Statistical\Averages class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string
*/
public static function AVERAGEA(...$args)
{
- $returnValue = null;
-
- $aCount = 0;
- // Loop through arguments
- foreach (Functions::flattenArrayIndexed($args) as $k => $arg) {
- if (
- (is_bool($arg)) &&
- (!Functions::isMatrixValue($k))
- ) {
- } else {
- if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
- if (is_bool($arg)) {
- $arg = (int) $arg;
- } elseif (is_string($arg)) {
- $arg = 0;
- }
- $returnValue += $arg;
- ++$aCount;
- }
- }
- }
-
- if ($aCount > 0) {
- return $returnValue / $aCount;
- }
-
- return Functions::DIV0();
+ return Averages::averageA(...$args);
}
/**
@@ -700,47 +98,20 @@ class Statistical
* Excel Function:
* AVERAGEIF(value1[,value2[, ...]],condition)
*
- * @param mixed $aArgs Data values
- * @param string $condition the criteria that defines which cells will be checked
- * @param mixed[] $averageArgs Data values
+ * @Deprecated 1.17.0
*
- * @return float|string
+ * @see Statistical\Conditional::AVERAGEIF()
+ * Use the AVERAGEIF() method in the Statistical\Conditional class instead
+ *
+ * @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($aArgs, $condition, $averageArgs = [])
+ public static function AVERAGEIF($range, $condition, $averageRange = [])
{
- $returnValue = 0;
-
- $aArgs = Functions::flattenArray($aArgs);
- $averageArgs = Functions::flattenArray($averageArgs);
- if (empty($averageArgs)) {
- $averageArgs = $aArgs;
- }
- $condition = Functions::ifCondition($condition);
- $conditionIsNumeric = strpos($condition, '"') === false;
-
- // Loop through arguments
- $aCount = 0;
- foreach ($aArgs as $key => $arg) {
- if (!is_numeric($arg)) {
- if ($conditionIsNumeric) {
- continue;
- }
- $arg = Calculation::wrapResult(strtoupper($arg));
- } elseif (!$conditionIsNumeric) {
- continue;
- }
- $testCondition = '=' . $arg . $condition;
- if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
- $returnValue += $averageArgs[$key];
- ++$aCount;
- }
- }
-
- if ($aCount > 0) {
- return $returnValue / $aCount;
- }
-
- return Functions::DIV0();
+ return Conditional::AVERAGEIF($range, $condition, $averageRange);
}
/**
@@ -748,6 +119,11 @@ class Statistical
*
* Returns the beta distribution.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Beta::distribution()
+ * Use the distribution() method in the Statistical\Distributions\Beta class instead
+ *
* @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
@@ -758,28 +134,7 @@ class Statistical
*/
public static function BETADIST($value, $alpha, $beta, $rMin = 0, $rMax = 1)
{
- $value = Functions::flattenSingleValue($value);
- $alpha = Functions::flattenSingleValue($alpha);
- $beta = Functions::flattenSingleValue($beta);
- $rMin = Functions::flattenSingleValue($rMin);
- $rMax = Functions::flattenSingleValue($rMax);
-
- if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) {
- if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) {
- return Functions::NAN();
- }
- if ($rMin > $rMax) {
- $tmp = $rMin;
- $rMin = $rMax;
- $rMax = $tmp;
- }
- $value -= $rMin;
- $value /= ($rMax - $rMin);
-
- return self::incompleteBeta($value, $alpha, $beta);
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Beta::distribution($value, $alpha, $beta, $rMin, $rMax);
}
/**
@@ -787,6 +142,11 @@ class Statistical
*
* Returns the inverse of the Beta distribution.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Beta::inverse()
+ * Use the inverse() method in the Statistical\Distributions\Beta class instead
+ *
* @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
@@ -797,44 +157,7 @@ class Statistical
*/
public static function BETAINV($probability, $alpha, $beta, $rMin = 0, $rMax = 1)
{
- $probability = Functions::flattenSingleValue($probability);
- $alpha = Functions::flattenSingleValue($alpha);
- $beta = Functions::flattenSingleValue($beta);
- $rMin = Functions::flattenSingleValue($rMin);
- $rMax = Functions::flattenSingleValue($rMax);
-
- if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) {
- if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0) || ($probability > 1)) {
- return Functions::NAN();
- }
- if ($rMin > $rMax) {
- $tmp = $rMin;
- $rMin = $rMax;
- $rMax = $tmp;
- }
- $a = 0;
- $b = 2;
-
- $i = 0;
- while ((($b - $a) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) {
- $guess = ($a + $b) / 2;
- $result = self::BETADIST($guess, $alpha, $beta);
- if (($result == $probability) || ($result == 0)) {
- $b = $a;
- } elseif ($result > $probability) {
- $b = $guess;
- } else {
- $a = $guess;
- }
- }
- if ($i == self::MAX_ITERATIONS) {
- return Functions::NA();
- }
-
- return round($rMin + $guess * ($rMax - $rMin), 12);
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Beta::inverse($probability, $alpha, $beta, $rMin, $rMax);
}
/**
@@ -846,43 +169,21 @@ class Statistical
* experiment. For example, BINOMDIST can calculate the probability that two of the next three
* babies born are male.
*
- * @param float $value Number of successes in trials
- * @param float $trials Number of trials
- * @param float $probability Probability of success on each trial
- * @param bool $cumulative
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Binomial::distribution()
+ * Use the distribution() method in the Statistical\Distributions\Binomial class instead
+ *
+ * @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 float|string
*/
public static function BINOMDIST($value, $trials, $probability, $cumulative)
{
- $value = Functions::flattenSingleValue($value);
- $trials = Functions::flattenSingleValue($trials);
- $probability = Functions::flattenSingleValue($probability);
-
- if ((is_numeric($value)) && (is_numeric($trials)) && (is_numeric($probability))) {
- $value = floor($value);
- $trials = floor($trials);
- if (($value < 0) || ($value > $trials)) {
- return Functions::NAN();
- }
- if (($probability < 0) || ($probability > 1)) {
- return Functions::NAN();
- }
- if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
- if ($cumulative) {
- $summer = 0;
- for ($i = 0; $i <= $value; ++$i) {
- $summer += MathTrig::COMBIN($trials, $i) * $probability ** $i * (1 - $probability) ** ($trials - $i);
- }
-
- return $summer;
- }
-
- return MathTrig::COMBIN($trials, $value) * $probability ** $value * (1 - $probability) ** ($trials - $value);
- }
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Binomial::distribution($value, $trials, $probability, $cumulative);
}
/**
@@ -890,6 +191,11 @@ class Statistical
*
* Returns the one-tailed probability of the chi-squared distribution.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\ChiSquared::distributionRightTail()
+ * Use the distributionRightTail() method in the Statistical\Distributions\ChiSquared class instead
+ *
* @param float $value Value for the function
* @param float $degrees degrees of freedom
*
@@ -897,26 +203,7 @@ class Statistical
*/
public static function CHIDIST($value, $degrees)
{
- $value = Functions::flattenSingleValue($value);
- $degrees = Functions::flattenSingleValue($degrees);
-
- if ((is_numeric($value)) && (is_numeric($degrees))) {
- $degrees = floor($degrees);
- if ($degrees < 1) {
- return Functions::NAN();
- }
- if ($value < 0) {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
- return 1;
- }
-
- return Functions::NAN();
- }
-
- return 1 - (self::incompleteGamma($degrees / 2, $value / 2) / self::gamma($degrees / 2));
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\ChiSquared::distributionRightTail($value, $degrees);
}
/**
@@ -924,6 +211,11 @@ class Statistical
*
* Returns the one-tailed probability of the chi-squared distribution.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\ChiSquared::inverseRightTail()
+ * Use the inverseRightTail() method in the Statistical\Distributions\ChiSquared class instead
+ *
* @param float $probability Probability for the function
* @param float $degrees degrees of freedom
*
@@ -931,52 +223,7 @@ class Statistical
*/
public static function CHIINV($probability, $degrees)
{
- $probability = Functions::flattenSingleValue($probability);
- $degrees = Functions::flattenSingleValue($degrees);
-
- if ((is_numeric($probability)) && (is_numeric($degrees))) {
- $degrees = floor($degrees);
-
- $xLo = 100;
- $xHi = 0;
-
- $x = $xNew = 1;
- $dx = 1;
- $i = 0;
-
- while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) {
- // Apply Newton-Raphson step
- $result = 1 - (self::incompleteGamma($degrees / 2, $x / 2) / self::gamma($degrees / 2));
- $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 Functions::NA();
- }
-
- return round($x, 12);
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\ChiSquared::inverseRightTail($probability, $degrees);
}
/**
@@ -984,6 +231,11 @@ class Statistical
*
* Returns the confidence interval for a population mean
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Confidence::CONFIDENCE()
+ * Use the CONFIDENCE() method in the Statistical\Confidence class instead
+ *
* @param float $alpha
* @param float $stdDev Standard Deviation
* @param float $size
@@ -992,23 +244,7 @@ class Statistical
*/
public static function CONFIDENCE($alpha, $stdDev, $size)
{
- $alpha = Functions::flattenSingleValue($alpha);
- $stdDev = Functions::flattenSingleValue($stdDev);
- $size = Functions::flattenSingleValue($size);
-
- if ((is_numeric($alpha)) && (is_numeric($stdDev)) && (is_numeric($size))) {
- $size = floor($size);
- if (($alpha <= 0) || ($alpha >= 1)) {
- return Functions::NAN();
- }
- if (($stdDev <= 0) || ($size < 1)) {
- return Functions::NAN();
- }
-
- return self::NORMSINV(1 - $alpha / 2) * $stdDev / sqrt($size);
- }
-
- return Functions::VALUE();
+ return Confidence::CONFIDENCE($alpha, $stdDev, $size);
}
/**
@@ -1016,6 +252,11 @@ class Statistical
*
* Returns covariance, the average of the products of deviations for each data point pair.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Trends::CORREL()
+ * Use the CORREL() method in the Statistical\Trends class instead
+ *
* @param mixed $yValues array of mixed Data Series Y
* @param null|mixed $xValues array of mixed Data Series X
*
@@ -1023,24 +264,7 @@ class Statistical
*/
public static function CORREL($yValues, $xValues = null)
{
- if (($xValues === null) || (!is_array($yValues)) || (!is_array($xValues))) {
- return Functions::VALUE();
- }
- if (!self::checkTrendArrays($yValues, $xValues)) {
- return Functions::VALUE();
- }
- $yValueCount = count($yValues);
- $xValueCount = count($xValues);
-
- if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
- return Functions::NA();
- } elseif ($yValueCount == 1) {
- return Functions::DIV0();
- }
-
- $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
-
- return $bestFitLinear->getCorrelation();
+ return Trends::CORREL($xValues, $yValues);
}
/**
@@ -1051,27 +275,18 @@ class Statistical
* Excel Function:
* COUNT(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Counts::COUNT()
+ * Use the COUNT() method in the Statistical\Counts class instead
+ *
* @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)) {
- ++$returnValue;
- }
- }
-
- return $returnValue;
+ return Counts::COUNT(...$args);
}
/**
@@ -1082,24 +297,18 @@ class Statistical
* Excel Function:
* COUNTA(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Counts::COUNTA()
+ * Use the COUNTA() method in the Statistical\Counts class instead
+ *
* @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;
+ return Counts::COUNTA(...$args);
}
/**
@@ -1110,24 +319,18 @@ class Statistical
* Excel Function:
* COUNTBLANK(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Counts::COUNTBLANK()
+ * Use the COUNTBLANK() method in the Statistical\Counts class instead
+ *
* @param mixed ...$args Data values
*
* @return int
*/
public static function COUNTBLANK(...$args)
{
- $returnValue = 0;
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
- foreach ($aArgs as $arg) {
- // Is it a blank cell?
- if (($arg === null) || ((is_string($arg)) && ($arg == ''))) {
- ++$returnValue;
- }
- }
-
- return $returnValue;
+ return Counts::COUNTBLANK(...$args);
}
/**
@@ -1136,38 +339,21 @@ class Statistical
* Counts the number of cells that contain numbers within the list of arguments
*
* Excel Function:
- * COUNTIF(value1[,value2[, ...]],condition)
+ * COUNTIF(range,condition)
*
- * @param mixed $aArgs Data values
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Conditional::COUNTIF()
+ * Use the COUNTIF() method in the Statistical\Conditional class instead
+ *
+ * @param mixed $range Data values
* @param string $condition the criteria that defines which cells will be counted
*
* @return int
*/
- public static function COUNTIF($aArgs, $condition)
+ public static function COUNTIF($range, $condition)
{
- $returnValue = 0;
-
- $aArgs = Functions::flattenArray($aArgs);
- $condition = Functions::ifCondition($condition);
- $conditionIsNumeric = strpos($condition, '"') === false;
- // Loop through arguments
- foreach ($aArgs as $arg) {
- if (!is_numeric($arg)) {
- if ($conditionIsNumeric) {
- continue;
- }
- $arg = Calculation::wrapResult(strtoupper($arg));
- } elseif (!$conditionIsNumeric) {
- continue;
- }
- $testCondition = '=' . $arg . $condition;
- if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
- // Is it a value within our criteria
- ++$returnValue;
- }
- }
-
- return $returnValue;
+ return Conditional::COUNTIF($range, $condition);
}
/**
@@ -1178,66 +364,18 @@ class Statistical
* Excel Function:
* COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]…)
*
- * @param mixed $args Criterias
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Conditional::COUNTIFS()
+ * Use the COUNTIFS() method in the Statistical\Conditional class instead
+ *
+ * @param mixed $args Pairs of Ranges and Criteria
*
* @return int
*/
public static function COUNTIFS(...$args)
{
- $arrayList = $args;
-
- // Return value
- $returnValue = 0;
-
- if (empty($arrayList)) {
- return $returnValue;
- }
-
- $aArgsArray = [];
- $conditions = [];
-
- while (count($arrayList) > 0) {
- $aArgsArray[] = Functions::flattenArray(array_shift($arrayList));
- $conditions[] = Functions::ifCondition(array_shift($arrayList));
- }
-
- // Loop through each arg and see if arguments and conditions are true
- foreach (array_keys($aArgsArray[0]) as $index) {
- $valid = true;
-
- foreach ($conditions as $cidx => $condition) {
- $conditionIsNumeric = strpos($condition, '"') === false;
- $arg = $aArgsArray[$cidx][$index];
-
- // Loop through arguments
- if (!is_numeric($arg)) {
- if ($conditionIsNumeric) {
- $valid = false;
-
- break; // if false found, don't need to check other conditions
- }
- $arg = Calculation::wrapResult(strtoupper($arg));
- } elseif (!$conditionIsNumeric) {
- $valid = false;
-
- break; // if false found, don't need to check other conditions
- }
- $testCondition = '=' . $arg . $condition;
- if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
- // Is not a value within our criteria
- $valid = false;
-
- break; // if false found, don't need to check other conditions
- }
- }
-
- if ($valid) {
- ++$returnValue;
- }
- }
-
- // Return
- return $returnValue;
+ return Conditional::COUNTIFS(...$args);
}
/**
@@ -1245,6 +383,11 @@ class Statistical
*
* Returns covariance, the average of the products of deviations for each data point pair.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Trends::COVAR()
+ * Use the COVAR() method in the Statistical\Trends class instead
+ *
* @param mixed $yValues array of mixed Data Series Y
* @param mixed $xValues array of mixed Data Series X
*
@@ -1252,21 +395,7 @@ class Statistical
*/
public static function COVAR($yValues, $xValues)
{
- if (!self::checkTrendArrays($yValues, $xValues)) {
- return Functions::VALUE();
- }
- $yValueCount = count($yValues);
- $xValueCount = count($xValues);
-
- if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
- return Functions::NA();
- } elseif ($yValueCount == 1) {
- return Functions::DIV0();
- }
-
- $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
-
- return $bestFitLinear->getCovariance();
+ return Trends::COVAR($yValues, $xValues);
}
/**
@@ -1277,123 +406,20 @@ class Statistical
*
* See https://support.microsoft.com/en-us/help/828117/ for details of the algorithm used
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Binomial::inverse()
+ * Use the inverse() method in the Statistical\Distributions\Binomial class instead
+ *
* @param float $trials number of Bernoulli trials
* @param float $probability probability of a success on each trial
* @param float $alpha criterion value
*
* @return int|string
- *
- * @TODO Warning. This implementation differs from the algorithm detailed on the MS
- * web site in that $CumPGuessMinus1 = $CumPGuess - 1 rather than $CumPGuess - $PGuess
- * This eliminates a potential endless loop error, but may have an adverse affect on the
- * accuracy of the function (although all my tests have so far returned correct results).
*/
public static function CRITBINOM($trials, $probability, $alpha)
{
- $trials = floor(Functions::flattenSingleValue($trials));
- $probability = Functions::flattenSingleValue($probability);
- $alpha = Functions::flattenSingleValue($alpha);
-
- if ((is_numeric($trials)) && (is_numeric($probability)) && (is_numeric($alpha))) {
- $trials = (int) $trials;
- if ($trials < 0) {
- return Functions::NAN();
- } elseif (($probability < 0.0) || ($probability > 1.0)) {
- return Functions::NAN();
- } elseif (($alpha < 0.0) || ($alpha > 1.0)) {
- return Functions::NAN();
- }
-
- if ($alpha <= 0.5) {
- $t = sqrt(log(1 / ($alpha * $alpha)));
- $trialsApprox = 0 - ($t + (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t));
- } else {
- $t = sqrt(log(1 / (1 - $alpha) ** 2));
- $trialsApprox = $t - (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t);
- }
-
- $Guess = floor($trials * $probability + $trialsApprox * sqrt($trials * $probability * (1 - $probability)));
- if ($Guess < 0) {
- $Guess = 0;
- } elseif ($Guess > $trials) {
- $Guess = $trials;
- }
-
- $TotalUnscaledProbability = $UnscaledPGuess = $UnscaledCumPGuess = 0.0;
- $EssentiallyZero = 10e-12;
-
- $m = floor($trials * $probability);
- ++$TotalUnscaledProbability;
- if ($m == $Guess) {
- ++$UnscaledPGuess;
- }
- if ($m <= $Guess) {
- ++$UnscaledCumPGuess;
- }
-
- $PreviousValue = 1;
- $Done = false;
- $k = $m + 1;
- while ((!$Done) && ($k <= $trials)) {
- $CurrentValue = $PreviousValue * ($trials - $k + 1) * $probability / ($k * (1 - $probability));
- $TotalUnscaledProbability += $CurrentValue;
- if ($k == $Guess) {
- $UnscaledPGuess += $CurrentValue;
- }
- if ($k <= $Guess) {
- $UnscaledCumPGuess += $CurrentValue;
- }
- if ($CurrentValue <= $EssentiallyZero) {
- $Done = true;
- }
- $PreviousValue = $CurrentValue;
- ++$k;
- }
-
- $PreviousValue = 1;
- $Done = false;
- $k = $m - 1;
- while ((!$Done) && ($k >= 0)) {
- $CurrentValue = $PreviousValue * $k + 1 * (1 - $probability) / (($trials - $k) * $probability);
- $TotalUnscaledProbability += $CurrentValue;
- if ($k == $Guess) {
- $UnscaledPGuess += $CurrentValue;
- }
- if ($k <= $Guess) {
- $UnscaledCumPGuess += $CurrentValue;
- }
- if ($CurrentValue <= $EssentiallyZero) {
- $Done = true;
- }
- $PreviousValue = $CurrentValue;
- --$k;
- }
-
- $PGuess = $UnscaledPGuess / $TotalUnscaledProbability;
- $CumPGuess = $UnscaledCumPGuess / $TotalUnscaledProbability;
-
- $CumPGuessMinus1 = $CumPGuess - 1;
-
- while (true) {
- if (($CumPGuessMinus1 < $alpha) && ($CumPGuess >= $alpha)) {
- return $Guess;
- } elseif (($CumPGuessMinus1 < $alpha) && ($CumPGuess < $alpha)) {
- $PGuessPlus1 = $PGuess * ($trials - $Guess) * $probability / $Guess / (1 - $probability);
- $CumPGuessMinus1 = $CumPGuess;
- $CumPGuess = $CumPGuess + $PGuessPlus1;
- $PGuess = $PGuessPlus1;
- ++$Guess;
- } elseif (($CumPGuessMinus1 >= $alpha) && ($CumPGuess >= $alpha)) {
- $PGuessMinus1 = $PGuess * $Guess * (1 - $probability) / ($trials - $Guess + 1) / $probability;
- $CumPGuess = $CumPGuessMinus1;
- $CumPGuessMinus1 = $CumPGuessMinus1 - $PGuess;
- $PGuess = $PGuessMinus1;
- --$Guess;
- }
- }
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Binomial::inverse($trials, $probability, $alpha);
}
/**
@@ -1404,48 +430,18 @@ class Statistical
* Excel Function:
* DEVSQ(value1[,value2[, ...]])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Deviations::sumSquares()
+ * Use the sumSquares() method in the Statistical\Deviations class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string
*/
public static function DEVSQ(...$args)
{
- $aArgs = Functions::flattenArrayIndexed($args);
-
- // Return value
- $returnValue = null;
-
- $aMean = self::AVERAGE($aArgs);
- if ($aMean != Functions::DIV0()) {
- $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))) {
- if ($returnValue === null) {
- $returnValue = ($arg - $aMean) ** 2;
- } else {
- $returnValue += ($arg - $aMean) ** 2;
- }
- ++$aCount;
- }
- }
-
- // Return
- if ($returnValue === null) {
- return Functions::NAN();
- }
-
- return $returnValue;
- }
-
- return Functions::NA();
+ return Statistical\Deviations::sumSquares(...$args);
}
/**
@@ -1455,6 +451,11 @@ class Statistical
* 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
+ *
+ * @see Statistical\Distributions\Exponential::distribution()
+ * Use the distribution() method in the Statistical\Distributions\Exponential class instead
+ *
* @param float $value Value of the function
* @param float $lambda The parameter value
* @param bool $cumulative
@@ -1463,34 +464,7 @@ class Statistical
*/
public static function EXPONDIST($value, $lambda, $cumulative)
{
- $value = Functions::flattenSingleValue($value);
- $lambda = Functions::flattenSingleValue($lambda);
- $cumulative = Functions::flattenSingleValue($cumulative);
-
- if ((is_numeric($value)) && (is_numeric($lambda))) {
- if (($value < 0) || ($lambda < 0)) {
- return Functions::NAN();
- }
- if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
- if ($cumulative) {
- return 1 - exp(0 - $value * $lambda);
- }
-
- return $lambda * exp(0 - $value * $lambda);
- }
- }
-
- return Functions::VALUE();
- }
-
- private static function betaFunction($a, $b)
- {
- return (self::gamma($a) * self::gamma($b)) / self::gamma($a + $b);
- }
-
- private static function regularizedIncompleteBeta($value, $a, $b)
- {
- return self::incompleteBeta($value, $a, $b) / self::betaFunction($a, $b);
+ return Statistical\Distributions\Exponential::distribution($value, $lambda, $cumulative);
}
/**
@@ -1501,6 +475,11 @@ class Statistical
* 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
+ *
+ * @see Statistical\Distributions\F::distribution()
+ * Use the distribution() method in the Statistical\Distributions\Exponential class instead
+ *
* @param float $value Value of the function
* @param int $u The numerator degrees of freedom
* @param int $v The denominator degrees of freedom
@@ -1511,32 +490,7 @@ class Statistical
*/
public static function FDIST2($value, $u, $v, $cumulative)
{
- $value = Functions::flattenSingleValue($value);
- $u = Functions::flattenSingleValue($u);
- $v = Functions::flattenSingleValue($v);
- $cumulative = Functions::flattenSingleValue($cumulative);
-
- if (is_numeric($value) && is_numeric($u) && is_numeric($v)) {
- if ($value < 0 || $u < 1 || $v < 1) {
- return Functions::NAN();
- }
-
- $cumulative = (bool) $cumulative;
- $u = (int) $u;
- $v = (int) $v;
-
- if ($cumulative) {
- $adjustedValue = ($u * $value) / ($u * $value + $v);
-
- return self::incompleteBeta($adjustedValue, $u / 2, $v / 2);
- }
-
- return (self::gamma(($v + $u) / 2) / (self::gamma($u / 2) * self::gamma($v / 2))) *
- (($u / $v) ** ($u / 2)) *
- (($value ** (($u - 2) / 2)) / ((1 + ($u / $v) * $value) ** (($u + $v) / 2)));
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\F::distribution($value, $u, $v, $cumulative);
}
/**
@@ -1546,23 +500,18 @@ class Statistical
* is normally distributed rather than skewed. Use this function to perform hypothesis
* testing on the correlation coefficient.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Fisher::distribution()
+ * Use the distribution() method in the Statistical\Distributions\Fisher class instead
+ *
* @param float $value
*
* @return float|string
*/
public static function FISHER($value)
{
- $value = Functions::flattenSingleValue($value);
-
- if (is_numeric($value)) {
- if (($value <= -1) || ($value >= 1)) {
- return Functions::NAN();
- }
-
- return 0.5 * log((1 + $value) / (1 - $value));
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Fisher::distribution($value);
}
/**
@@ -1572,19 +521,18 @@ class Statistical
* analyzing correlations between ranges or arrays of data. If y = FISHER(x), then
* FISHERINV(y) = x.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Fisher::inverse()
+ * Use the inverse() method in the Statistical\Distributions\Fisher class instead
+ *
* @param float $value
*
* @return float|string
*/
public static function FISHERINV($value)
{
- $value = Functions::flattenSingleValue($value);
-
- if (is_numeric($value)) {
- return (exp(2 * $value) - 1) / (exp(2 * $value) + 1);
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Fisher::inverse($value);
}
/**
@@ -1592,6 +540,11 @@ class Statistical
*
* 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
+ *
+ * @see Statistical\Trends::FORECAST()
+ * Use the FORECAST() method in the Statistical\Trends class instead
+ *
* @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
@@ -1600,30 +553,18 @@ class Statistical
*/
public static function FORECAST($xValue, $yValues, $xValues)
{
- $xValue = Functions::flattenSingleValue($xValue);
- if (!is_numeric($xValue)) {
- return Functions::VALUE();
- } elseif (!self::checkTrendArrays($yValues, $xValues)) {
- return Functions::VALUE();
- }
- $yValueCount = count($yValues);
- $xValueCount = count($xValues);
-
- if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
- return Functions::NA();
- } elseif ($yValueCount == 1) {
- return Functions::DIV0();
- }
-
- $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
-
- return $bestFitLinear->getValueOfYForX($xValue);
+ return Trends::FORECAST($xValue, $yValues, $xValues);
}
/**
* GAMMA.
*
- * Return the gamma function value.
+ * Returns the gamma function value.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Gamma::gamma()
+ * Use the gamma() method in the Statistical\Distributions\Gamma class instead
*
* @param float $value
*
@@ -1631,14 +572,7 @@ class Statistical
*/
public static function GAMMAFunction($value)
{
- $value = Functions::flattenSingleValue($value);
- if (!is_numeric($value)) {
- return Functions::VALUE();
- } elseif ((((int) $value) == ((float) $value)) && $value <= 0.0) {
- return Functions::NAN();
- }
-
- return self::gamma($value);
+ return Statistical\Distributions\Gamma::gamma($value);
}
/**
@@ -1646,6 +580,11 @@ class Statistical
*
* Returns the gamma distribution.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Gamma::distribution()
+ * Use the distribution() method in the Statistical\Distributions\Gamma class instead
+ *
* @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
@@ -1655,24 +594,7 @@ class Statistical
*/
public static function GAMMADIST($value, $a, $b, $cumulative)
{
- $value = Functions::flattenSingleValue($value);
- $a = Functions::flattenSingleValue($a);
- $b = Functions::flattenSingleValue($b);
-
- if ((is_numeric($value)) && (is_numeric($a)) && (is_numeric($b))) {
- if (($value < 0) || ($a <= 0) || ($b <= 0)) {
- return Functions::NAN();
- }
- if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
- if ($cumulative) {
- return self::incompleteGamma($a, $value / $b) / self::gamma($a);
- }
-
- return (1 / ($b ** $a * self::gamma($a))) * $value ** ($a - 1) * exp(0 - ($value / $b));
- }
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Gamma::distribution($value, $a, $b, $cumulative);
}
/**
@@ -1680,6 +602,11 @@ class Statistical
*
* Returns the inverse of the Gamma distribution.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Gamma::inverse()
+ * Use the inverse() method in the Statistical\Distributions\Gamma class instead
+ *
* @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
@@ -1688,53 +615,7 @@ class Statistical
*/
public static function GAMMAINV($probability, $alpha, $beta)
{
- $probability = Functions::flattenSingleValue($probability);
- $alpha = Functions::flattenSingleValue($alpha);
- $beta = Functions::flattenSingleValue($beta);
-
- if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta))) {
- if (($alpha <= 0) || ($beta <= 0) || ($probability < 0) || ($probability > 1)) {
- return Functions::NAN();
- }
-
- $xLo = 0;
- $xHi = $alpha * $beta * 5;
-
- $x = $xNew = 1;
- $dx = 1024;
- $i = 0;
-
- while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) {
- // Apply Newton-Raphson step
- $error = self::GAMMADIST($x, $alpha, $beta, true) - $probability;
- if ($error < 0.0) {
- $xLo = $x;
- } else {
- $xHi = $x;
- }
- $pdf = self::GAMMADIST($x, $alpha, $beta, false);
- // Avoid division by zero
- 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 Functions::NA();
- }
-
- return $x;
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Gamma::inverse($probability, $alpha, $beta);
}
/**
@@ -1742,23 +623,18 @@ class Statistical
*
* Returns the natural logarithm of the gamma function.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Gamma::ln()
+ * Use the ln() method in the Statistical\Distributions\Gamma class instead
+ *
* @param float $value
*
* @return float|string
*/
public static function GAMMALN($value)
{
- $value = Functions::flattenSingleValue($value);
-
- if (is_numeric($value)) {
- if ($value <= 0) {
- return Functions::NAN();
- }
-
- return log(self::gamma($value));
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Gamma::ln($value);
}
/**
@@ -1767,18 +643,18 @@ class Statistical
* 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
+ *
+ * @see Statistical\Distributions\StandardNormal::gauss()
+ * Use the gauss() method in the Statistical\Distributions\StandardNormal class instead
+ *
* @param float $value
*
* @return float|string The result, or a string containing an error
*/
public static function GAUSS($value)
{
- $value = Functions::flattenSingleValue($value);
- if (!is_numeric($value)) {
- return Functions::VALUE();
- }
-
- return self::NORMDIST($value, 0, 1, true) - 0.5;
+ return Statistical\Distributions\StandardNormal::gauss($value);
}
/**
@@ -1791,23 +667,18 @@ class Statistical
* Excel Function:
* GEOMEAN(value1[,value2[, ...]])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Averages\Mean::geometric()
+ * Use the geometric() method in the Statistical\Averages\Mean class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string
*/
public static function GEOMEAN(...$args)
{
- $aArgs = Functions::flattenArray($args);
-
- $aMean = MathTrig::PRODUCT($aArgs);
- if (is_numeric($aMean) && ($aMean > 0)) {
- $aCount = self::COUNT($aArgs);
- if (self::MIN($aArgs) > 0) {
- return $aMean ** (1 / $aCount);
- }
- }
-
- return Functions::NAN();
+ return Statistical\Averages\Mean::geometric(...$args);
}
/**
@@ -1815,31 +686,21 @@ class Statistical
*
* Returns values along a predicted exponential Trend
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Trends::GROWTH()
+ * Use the GROWTH() method in the Statistical\Trends class instead
+ *
* @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 array of float
+ * @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;
+ return Trends::GROWTH($yValues, $xValues, $newValues, $const);
}
/**
@@ -1851,38 +712,18 @@ class Statistical
* Excel Function:
* HARMEAN(value1[,value2[, ...]])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Averages\Mean::harmonic()
+ * Use the harmonic() method in the Statistical\Averages\Mean class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string
*/
public static function HARMEAN(...$args)
{
- // Return value
- $returnValue = 0;
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
- if (self::MIN($aArgs) < 0) {
- return Functions::NAN();
- }
- $aCount = 0;
- foreach ($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- if ($arg <= 0) {
- return Functions::NAN();
- }
- $returnValue += (1 / $arg);
- ++$aCount;
- }
- }
-
- // Return
- if ($aCount > 0) {
- return 1 / ($returnValue / $aCount);
- }
-
- return Functions::NA();
+ return Statistical\Averages\Mean::harmonic(...$args);
}
/**
@@ -1891,42 +732,26 @@ class Statistical
* 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 float $sampleSuccesses Number of successes in the sample
- * @param float $sampleNumber Size of the sample
- * @param float $populationSuccesses Number of successes in the population
- * @param float $populationNumber Population size
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\HyperGeometric::distribution()
+ * Use the distribution() method in the Statistical\Distributions\HyperGeometric class instead
+ *
+ * @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 float|string
*/
public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber)
{
- $sampleSuccesses = Functions::flattenSingleValue($sampleSuccesses);
- $sampleNumber = Functions::flattenSingleValue($sampleNumber);
- $populationSuccesses = Functions::flattenSingleValue($populationSuccesses);
- $populationNumber = Functions::flattenSingleValue($populationNumber);
-
- if ((is_numeric($sampleSuccesses)) && (is_numeric($sampleNumber)) && (is_numeric($populationSuccesses)) && (is_numeric($populationNumber))) {
- $sampleSuccesses = floor($sampleSuccesses);
- $sampleNumber = floor($sampleNumber);
- $populationSuccesses = floor($populationSuccesses);
- $populationNumber = floor($populationNumber);
-
- if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) {
- return Functions::NAN();
- }
- if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) {
- return Functions::NAN();
- }
- if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) {
- return Functions::NAN();
- }
-
- return MathTrig::COMBIN($populationSuccesses, $sampleSuccesses) *
- MathTrig::COMBIN($populationNumber - $populationSuccesses, $sampleNumber - $sampleSuccesses) /
- MathTrig::COMBIN($populationNumber, $sampleNumber);
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\HyperGeometric::distribution(
+ $sampleSuccesses,
+ $sampleNumber,
+ $populationSuccesses,
+ $populationNumber
+ );
}
/**
@@ -1934,6 +759,11 @@ class Statistical
*
* Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Trends::INTERCEPT()
+ * Use the INTERCEPT() method in the Statistical\Trends class instead
+ *
* @param mixed[] $yValues Data Series Y
* @param mixed[] $xValues Data Series X
*
@@ -1941,21 +771,7 @@ class Statistical
*/
public static function INTERCEPT($yValues, $xValues)
{
- if (!self::checkTrendArrays($yValues, $xValues)) {
- return Functions::VALUE();
- }
- $yValueCount = count($yValues);
- $xValueCount = count($xValues);
-
- if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
- return Functions::NA();
- } elseif ($yValueCount == 1) {
- return Functions::DIV0();
- }
-
- $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
-
- return $bestFitLinear->getIntersect();
+ return Trends::INTERCEPT($yValues, $xValues);
}
/**
@@ -1966,40 +782,18 @@ class Statistical
* kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a
* relatively flat distribution.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Deviations::kurtosis()
+ * Use the kurtosis() method in the Statistical\Deviations class instead
+ *
* @param array ...$args Data Series
*
* @return float|string
*/
public static function KURT(...$args)
{
- $aArgs = Functions::flattenArrayIndexed($args);
- $mean = self::AVERAGE($aArgs);
- $stdDev = self::STDEV($aArgs);
-
- if ($stdDev > 0) {
- $count = $summer = 0;
- // Loop through arguments
- 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;
- }
- }
- }
-
- // Return
- if ($count > 3) {
- return $summer * ($count * ($count + 1) / (($count - 1) * ($count - 2) * ($count - 3))) - (3 * ($count - 1) ** 2 / (($count - 2) * ($count - 3)));
- }
- }
-
- return Functions::DIV0();
+ return Statistical\Deviations::kurtosis(...$args);
}
/**
@@ -2011,37 +805,18 @@ class Statistical
* Excel Function:
* LARGE(value1[,value2[, ...]],entry)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Size::large()
+ * Use the large() method in the Statistical\Size class instead
+ *
* @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);
-
- // Calculate
- $mArgs = [];
- foreach ($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $mArgs[] = $arg;
- }
- }
- $count = self::COUNT($mArgs);
- --$entry;
- if (($entry < 0) || ($entry >= $count) || ($count == 0)) {
- return Functions::NAN();
- }
- rsort($mArgs);
-
- return $mArgs[$entry];
- }
-
- return Functions::VALUE();
+ return Statistical\Size::large(...$args);
}
/**
@@ -2050,6 +825,11 @@ class Statistical
* 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
+ *
+ * @see Statistical\Trends::LINEST()
+ * Use the LINEST() method in the Statistical\Trends class instead
+ *
* @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
@@ -2059,48 +839,7 @@ class Statistical
*/
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 = range(1, count(Functions::flattenArray($yValues)));
- }
-
- if (!self::checkTrendArrays($yValues, $xValues)) {
- return Functions::VALUE();
- }
- $yValueCount = count($yValues);
- $xValueCount = count($xValues);
-
- if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
- return Functions::NA();
- } elseif ($yValueCount == 1) {
- return 0;
- }
-
- $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const);
- if ($stats) {
- return [
- [
- $bestFitLinear->getSlope(),
- $bestFitLinear->getSlopeSE(),
- $bestFitLinear->getGoodnessOfFit(),
- $bestFitLinear->getF(),
- $bestFitLinear->getSSRegression(),
- ],
- [
- $bestFitLinear->getIntersect(),
- $bestFitLinear->getIntersectSE(),
- $bestFitLinear->getStdevOfResiduals(),
- $bestFitLinear->getDFResiduals(),
- $bestFitLinear->getSSResiduals(),
- ],
- ];
- }
-
- return [
- $bestFitLinear->getSlope(),
- $bestFitLinear->getIntersect(),
- ];
+ return Trends::LINEST($yValues, $xValues, $const, $stats);
}
/**
@@ -2109,6 +848,11 @@ class Statistical
* 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
+ *
+ * @see Statistical\Trends::LOGEST()
+ * Use the LOGEST() method in the Statistical\Trends class instead
+ *
* @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
@@ -2118,54 +862,7 @@ class Statistical
*/
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 = range(1, count(Functions::flattenArray($yValues)));
- }
-
- if (!self::checkTrendArrays($yValues, $xValues)) {
- return Functions::VALUE();
- }
- $yValueCount = count($yValues);
- $xValueCount = count($xValues);
-
- foreach ($yValues as $value) {
- if ($value <= 0.0) {
- return Functions::NAN();
- }
- }
-
- if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
- return Functions::NA();
- } elseif ($yValueCount == 1) {
- return 1;
- }
-
- $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const);
- if ($stats) {
- return [
- [
- $bestFitExponential->getSlope(),
- $bestFitExponential->getSlopeSE(),
- $bestFitExponential->getGoodnessOfFit(),
- $bestFitExponential->getF(),
- $bestFitExponential->getSSRegression(),
- ],
- [
- $bestFitExponential->getIntersect(),
- $bestFitExponential->getIntersectSE(),
- $bestFitExponential->getStdevOfResiduals(),
- $bestFitExponential->getDFResiduals(),
- $bestFitExponential->getSSResiduals(),
- ],
- ];
- }
-
- return [
- $bestFitExponential->getSlope(),
- $bestFitExponential->getIntersect(),
- ];
+ return Trends::LOGEST($yValues, $xValues, $const, $stats);
}
/**
@@ -2173,6 +870,11 @@ class Statistical
*
* Returns the inverse of the normal cumulative distribution
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\LogNormal::inverse()
+ * Use the inverse() method in the Statistical\Distributions\LogNormal class instead
+ *
* @param float $probability
* @param float $mean
* @param float $stdDev
@@ -2185,19 +887,7 @@ class Statistical
*/
public static function LOGINV($probability, $mean, $stdDev)
{
- $probability = Functions::flattenSingleValue($probability);
- $mean = Functions::flattenSingleValue($mean);
- $stdDev = Functions::flattenSingleValue($stdDev);
-
- if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
- if (($probability < 0) || ($probability > 1) || ($stdDev <= 0)) {
- return Functions::NAN();
- }
-
- return exp($mean + $stdDev * self::NORMSINV($probability));
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\LogNormal::inverse($probability, $mean, $stdDev);
}
/**
@@ -2206,6 +896,11 @@ class Statistical
* Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed
* with parameters mean and standard_dev.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\LogNormal::cumulative()
+ * Use the cumulative() method in the Statistical\Distributions\LogNormal class instead
+ *
* @param float $value
* @param float $mean
* @param float $stdDev
@@ -2214,19 +909,7 @@ class Statistical
*/
public static function LOGNORMDIST($value, $mean, $stdDev)
{
- $value = Functions::flattenSingleValue($value);
- $mean = Functions::flattenSingleValue($mean);
- $stdDev = Functions::flattenSingleValue($stdDev);
-
- if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
- if (($value <= 0) || ($stdDev <= 0)) {
- return Functions::NAN();
- }
-
- return self::NORMSDIST((log($value) - $mean) / $stdDev);
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\LogNormal::cumulative($value, $mean, $stdDev);
}
/**
@@ -2235,6 +918,11 @@ class Statistical
* Returns the lognormal distribution of x, where ln(x) is normally distributed
* with parameters mean and standard_dev.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\LogNormal::distribution()
+ * Use the distribution() method in the Statistical\Distributions\LogNormal class instead
+ *
* @param float $value
* @param float $mean
* @param float $stdDev
@@ -2244,25 +932,7 @@ class Statistical
*/
public static function LOGNORMDIST2($value, $mean, $stdDev, $cumulative = false)
{
- $value = Functions::flattenSingleValue($value);
- $mean = Functions::flattenSingleValue($mean);
- $stdDev = Functions::flattenSingleValue($stdDev);
- $cumulative = (bool) Functions::flattenSingleValue($cumulative);
-
- if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
- if (($value <= 0) || ($stdDev <= 0)) {
- return Functions::NAN();
- }
-
- if ($cumulative === true) {
- return self::NORMSDIST2((log($value) - $mean) / $stdDev, true);
- }
-
- return (1 / (sqrt(2 * M_PI) * $stdDev * $value)) *
- exp(0 - ((log($value) - $mean) ** 2 / (2 * $stdDev ** 2)));
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\LogNormal::distribution($value, $mean, $stdDev, $cumulative);
}
/**
@@ -2272,32 +942,20 @@ class Statistical
* with negative numbers considered smaller than positive numbers.
*
* Excel Function:
- * MAX(value1[,value2[, ...]])
+ * max(value1[,value2[, ...]])
+ *
+ * @Deprecated 1.17.0
*
* @param mixed ...$args Data values
*
* @return float
+ *
+ *@see Statistical\Maximum::max()
+ * Use the MAX() method in the Statistical\Maximum class instead
*/
public static function MAX(...$args)
{
- $returnValue = null;
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
- foreach ($aArgs as $arg) {
- // 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;
+ return Maximum::max(...$args);
}
/**
@@ -2306,37 +964,20 @@ class Statistical
* Returns the greatest value in a list of arguments, including numbers, text, and logical values
*
* Excel Function:
- * MAXA(value1[,value2[, ...]])
+ * maxA(value1[,value2[, ...]])
+ *
+ * @Deprecated 1.17.0
*
* @param mixed ...$args Data values
*
* @return float
+ *
+ *@see Statistical\Maximum::maxA()
+ * Use the MAXA() method in the Statistical\Maximum class instead
*/
public static function MAXA(...$args)
{
- $returnValue = null;
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
- foreach ($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
- if (is_bool($arg)) {
- $arg = (int) $arg;
- } elseif (is_string($arg)) {
- $arg = 0;
- }
- if (($returnValue === null) || ($arg > $returnValue)) {
- $returnValue = $arg;
- }
- }
- }
-
- if ($returnValue === null) {
- return 0;
- }
-
- return $returnValue;
+ return Maximum::maxA(...$args);
}
/**
@@ -2347,53 +988,18 @@ class Statistical
* Excel Function:
* MAXIFS(max_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Conditional::MAXIFS()
+ * Use the MAXIFS() method in the Statistical\Conditional class instead
+ *
* @param mixed $args Data range and criterias
*
* @return float
*/
public static function MAXIFS(...$args)
{
- $arrayList = $args;
-
- // Return value
- $returnValue = null;
-
- $maxArgs = Functions::flattenArray(array_shift($arrayList));
- $aArgsArray = [];
- $conditions = [];
-
- while (count($arrayList) > 0) {
- $aArgsArray[] = Functions::flattenArray(array_shift($arrayList));
- $conditions[] = Functions::ifCondition(array_shift($arrayList));
- }
-
- // Loop through each arg and see if arguments and conditions are true
- foreach ($maxArgs as $index => $value) {
- $valid = true;
-
- foreach ($conditions as $cidx => $condition) {
- $arg = $aArgsArray[$cidx][$index];
-
- // Loop through arguments
- if (!is_numeric($arg)) {
- $arg = Calculation::wrapResult(strtoupper($arg));
- }
- $testCondition = '=' . $arg . $condition;
- if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
- // Is not a value within our criteria
- $valid = false;
-
- break; // if false found, don't need to check other conditions
- }
- }
-
- if ($valid) {
- $returnValue = $returnValue === null ? $value : max($value, $returnValue);
- }
- }
-
- // Return
- return $returnValue;
+ return Conditional::MAXIFS(...$args);
}
/**
@@ -2404,37 +1010,18 @@ class Statistical
* Excel Function:
* MEDIAN(value1[,value2[, ...]])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Averages::median()
+ * Use the median() method in the Statistical\Averages class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string The result, or a string containing an error
*/
public static function MEDIAN(...$args)
{
- $returnValue = Functions::NAN();
-
- $mArgs = [];
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
- foreach ($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $mArgs[] = $arg;
- }
- }
-
- $mValueCount = count($mArgs);
- if ($mValueCount > 0) {
- sort($mArgs, SORT_NUMERIC);
- $mValueCount = $mValueCount / 2;
- if ($mValueCount == floor($mValueCount)) {
- $returnValue = ($mArgs[$mValueCount--] + $mArgs[$mValueCount]) / 2;
- } else {
- $mValueCount = floor($mValueCount);
- $returnValue = $mArgs[$mValueCount];
- }
- }
-
- return $returnValue;
+ return Statistical\Averages::median(...$args);
}
/**
@@ -2446,30 +1033,18 @@ class Statistical
* Excel Function:
* MIN(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
* @param mixed ...$args Data values
*
* @return float
+ *
+ *@see Statistical\Minimum::min()
+ * Use the min() method in the Statistical\Minimum class instead
*/
public static function MIN(...$args)
{
- $returnValue = null;
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
- foreach ($aArgs as $arg) {
- // 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;
+ return Minimum::min(...$args);
}
/**
@@ -2480,35 +1055,18 @@ class Statistical
* Excel Function:
* MINA(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
* @param mixed ...$args Data values
*
* @return float
+ *
+ *@see Statistical\Minimum::minA()
+ * Use the minA() method in the Statistical\Minimum class instead
*/
public static function MINA(...$args)
{
- $returnValue = null;
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
- foreach ($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
- if (is_bool($arg)) {
- $arg = (int) $arg;
- } elseif (is_string($arg)) {
- $arg = 0;
- }
- if (($returnValue === null) || ($arg < $returnValue)) {
- $returnValue = $arg;
- }
- }
- }
-
- if ($returnValue === null) {
- return 0;
- }
-
- return $returnValue;
+ return Minimum::minA(...$args);
}
/**
@@ -2519,102 +1077,18 @@ class Statistical
* Excel Function:
* MINIFS(min_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...)
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Conditional::MINIFS()
+ * Use the MINIFS() method in the Statistical\Conditional class instead
+ *
* @param mixed $args Data range and criterias
*
* @return float
*/
public static function MINIFS(...$args)
{
- $arrayList = $args;
-
- // Return value
- $returnValue = null;
-
- $minArgs = Functions::flattenArray(array_shift($arrayList));
- $aArgsArray = [];
- $conditions = [];
-
- while (count($arrayList) > 0) {
- $aArgsArray[] = Functions::flattenArray(array_shift($arrayList));
- $conditions[] = Functions::ifCondition(array_shift($arrayList));
- }
-
- // Loop through each arg and see if arguments and conditions are true
- foreach ($minArgs as $index => $value) {
- $valid = true;
-
- foreach ($conditions as $cidx => $condition) {
- $arg = $aArgsArray[$cidx][$index];
-
- // Loop through arguments
- if (!is_numeric($arg)) {
- $arg = Calculation::wrapResult(strtoupper($arg));
- }
- $testCondition = '=' . $arg . $condition;
- if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
- // Is not a value within our criteria
- $valid = false;
-
- break; // if false found, don't need to check other conditions
- }
- }
-
- if ($valid) {
- $returnValue = $returnValue === null ? $value : min($value, $returnValue);
- }
- }
-
- // Return
- return $returnValue;
- }
-
- //
- // Special variant of array_count_values that isn't limited to strings and integers,
- // but can work with floating point numbers as values
- //
- private static function modeCalc($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) {
- $frequencyArray[] = [
- 'value' => $datum,
- 'frequency' => 1,
- 'index' => $index,
- ];
- }
- }
-
- if ($maxfreq <= 1) {
- return Functions::NA();
- }
-
- return $maxfreqdatum;
+ return Conditional::MINIFS(...$args);
}
/**
@@ -2625,30 +1099,18 @@ class Statistical
* Excel Function:
* MODE(value1[,value2[, ...]])
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Averages::mode()
+ * Use the mode() method in the Statistical\Averages class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string The result, or a string containing an error
*/
public static function MODE(...$args)
{
- $returnValue = Functions::NA();
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
-
- $mArgs = [];
- foreach ($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $mArgs[] = $arg;
- }
- }
-
- if (!empty($mArgs)) {
- return self::modeCalc($mArgs);
- }
-
- return $returnValue;
+ return Statistical\Averages::mode(...$args);
}
/**
@@ -2660,34 +1122,20 @@ class Statistical
* 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 float $failures Number of Failures
- * @param float $successes Threshold number of Successes
- * @param float $probability Probability of success on each trial
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Binomial::negative()
+ * Use the negative() method in the Statistical\Distributions\Binomial class instead
+ *
+ * @param mixed $failures Number of Failures
+ * @param mixed $successes Threshold number of Successes
+ * @param mixed $probability Probability of success on each trial
*
* @return float|string The result, or a string containing an error
*/
public static function NEGBINOMDIST($failures, $successes, $probability)
{
- $failures = floor(Functions::flattenSingleValue($failures));
- $successes = floor(Functions::flattenSingleValue($successes));
- $probability = Functions::flattenSingleValue($probability);
-
- if ((is_numeric($failures)) && (is_numeric($successes)) && (is_numeric($probability))) {
- if (($failures < 0) || ($successes < 1)) {
- return Functions::NAN();
- } elseif (($probability < 0) || ($probability > 1)) {
- return Functions::NAN();
- }
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
- if (($failures + $successes - 1) <= 0) {
- return Functions::NAN();
- }
- }
-
- return (MathTrig::COMBIN($failures + $successes - 1, $successes - 1)) * ($probability ** $successes) * ((1 - $probability) ** $failures);
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Binomial::negative($failures, $successes, $probability);
}
/**
@@ -2697,33 +1145,21 @@ class Statistical
* function has a very wide range of applications in statistics, including hypothesis
* testing.
*
- * @param float $value
- * @param float $mean Mean Value
- * @param float $stdDev Standard Deviation
- * @param bool $cumulative
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Normal::distribution()
+ * Use the distribution() method in the Statistical\Distributions\Normal class instead
+ *
+ * @param mixed $value
+ * @param mixed $mean Mean Value
+ * @param mixed $stdDev Standard Deviation
+ * @param mixed $cumulative
*
* @return float|string The result, or a string containing an error
*/
public static function NORMDIST($value, $mean, $stdDev, $cumulative)
{
- $value = Functions::flattenSingleValue($value);
- $mean = Functions::flattenSingleValue($mean);
- $stdDev = Functions::flattenSingleValue($stdDev);
-
- if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
- if ($stdDev < 0) {
- return Functions::NAN();
- }
- if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
- if ($cumulative) {
- return 0.5 * (1 + Engineering::erfVal(($value - $mean) / ($stdDev * sqrt(2))));
- }
-
- return (1 / (self::SQRT2PI * $stdDev)) * exp(0 - (($value - $mean) ** 2 / (2 * ($stdDev * $stdDev))));
- }
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Normal::distribution($value, $mean, $stdDev, $cumulative);
}
/**
@@ -2731,30 +1167,20 @@ class Statistical
*
* Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation.
*
- * @param float $probability
- * @param float $mean Mean Value
- * @param float $stdDev Standard Deviation
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Normal::inverse()
+ * Use the inverse() method in the Statistical\Distributions\Normal class instead
+ *
+ * @param mixed $probability
+ * @param mixed $mean Mean Value
+ * @param mixed $stdDev Standard Deviation
*
* @return float|string The result, or a string containing an error
*/
public static function NORMINV($probability, $mean, $stdDev)
{
- $probability = Functions::flattenSingleValue($probability);
- $mean = Functions::flattenSingleValue($mean);
- $stdDev = Functions::flattenSingleValue($stdDev);
-
- if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
- if (($probability < 0) || ($probability > 1)) {
- return Functions::NAN();
- }
- if ($stdDev < 0) {
- return Functions::NAN();
- }
-
- return (self::inverseNcdf($probability) * $stdDev) + $mean;
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Normal::inverse($probability, $mean, $stdDev);
}
/**
@@ -2764,18 +1190,18 @@ class Statistical
* a mean of 0 (zero) and a standard deviation of one. Use this function in place of a
* table of standard normal curve areas.
*
- * @param float $value
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\StandardNormal::cumulative()
+ * Use the cumulative() method in the Statistical\Distributions\StandardNormal class instead
+ *
+ * @param mixed $value
*
* @return float|string The result, or a string containing an error
*/
public static function NORMSDIST($value)
{
- $value = Functions::flattenSingleValue($value);
- if (!is_numeric($value)) {
- return Functions::VALUE();
- }
-
- return self::NORMDIST($value, 0, 1, true);
+ return Statistical\Distributions\StandardNormal::cumulative($value);
}
/**
@@ -2785,20 +1211,19 @@ class Statistical
* a mean of 0 (zero) and a standard deviation of one. Use this function in place of a
* table of standard normal curve areas.
*
- * @param float $value
- * @param bool $cumulative
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\StandardNormal::distribution()
+ * Use the distribution() method in the Statistical\Distributions\StandardNormal class instead
+ *
+ * @param mixed $value
+ * @param mixed $cumulative
*
* @return float|string The result, or a string containing an error
*/
public static function NORMSDIST2($value, $cumulative)
{
- $value = Functions::flattenSingleValue($value);
- if (!is_numeric($value)) {
- return Functions::VALUE();
- }
- $cumulative = (bool) Functions::flattenSingleValue($cumulative);
-
- return self::NORMDIST($value, 0, 1, $cumulative);
+ return Statistical\Distributions\StandardNormal::distribution($value, $cumulative);
}
/**
@@ -2806,13 +1231,18 @@ class Statistical
*
* Returns the inverse of the standard normal cumulative distribution
*
- * @param float $value
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\StandardNormal::inverse()
+ * Use the inverse() method in the Statistical\Distributions\StandardNormal class instead
+ *
+ * @param mixed $value
*
* @return float|string The result, or a string containing an error
*/
public static function NORMSINV($value)
{
- return self::NORMINV($value, 0, 1);
+ return Statistical\Distributions\StandardNormal::inverse($value);
}
/**
@@ -2823,92 +1253,42 @@ class Statistical
* Excel Function:
* PERCENTILE(value1[,value2[, ...]],entry)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Percentiles::PERCENTILE()
+ * Use the PERCENTILE() method in the Statistical\Percentiles class instead
+ *
* @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);
-
- if ((is_numeric($entry)) && (!is_string($entry))) {
- if (($entry < 0) || ($entry > 1)) {
- return Functions::NAN();
- }
- $mArgs = [];
- foreach ($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $mArgs[] = $arg;
- }
- }
- $mValueCount = count($mArgs);
- if ($mValueCount > 0) {
- sort($mArgs);
- $count = self::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 Functions::VALUE();
+ 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
*
- * @param float[] $valueSet An array of, or a reference to, a list of numbers
- * @param int $value the number whose rank you want to find
- * @param int $significance the number of significant digits for the returned percentage value
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Percentiles::PERCENTRANK()
+ * Use the PERCENTRANK() method in the Statistical\Percentiles class instead
+ *
+ * @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)
{
- $valueSet = Functions::flattenArray($valueSet);
- $value = Functions::flattenSingleValue($value);
- $significance = ($significance === null) ? 3 : (int) Functions::flattenSingleValue($significance);
-
- foreach ($valueSet as $key => $valueEntry) {
- if (!is_numeric($valueEntry)) {
- unset($valueSet[$key]);
- }
- }
- sort($valueSet, SORT_NUMERIC);
- $valueCount = count($valueSet);
- if ($valueCount == 0) {
- return Functions::NAN();
- }
-
- $valueAdjustor = $valueCount - 1;
- if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) {
- return Functions::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($pos / $valueAdjustor, $significance);
+ return Statistical\Percentiles::PERCENTRANK($valueSet, $value, $significance);
}
/**
@@ -2920,26 +1300,19 @@ class Statistical
* combinations, for which the internal order is not significant. Use this function
* for lottery-style probability calculations.
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Permutations::PERMUT()
+ * Use the PERMUT() method in the Statistical\Permutations class instead
+ *
* @param int $numObjs Number of different objects
* @param int $numInSet Number of objects in each permutation
*
- * @return int|string Number of permutations, or a string containing an error
+ * @return float|int|string Number of permutations, or a string containing an error
*/
public static function PERMUT($numObjs, $numInSet)
{
- $numObjs = Functions::flattenSingleValue($numObjs);
- $numInSet = Functions::flattenSingleValue($numInSet);
-
- if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
- $numInSet = floor($numInSet);
- if ($numObjs < $numInSet) {
- return Functions::NAN();
- }
-
- return round(MathTrig::FACT($numObjs) / MathTrig::FACT($numObjs - $numInSet));
- }
-
- return Functions::VALUE();
+ return Permutations::PERMUT($numObjs, $numInSet);
}
/**
@@ -2949,37 +1322,20 @@ class Statistical
* 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 float $value
- * @param float $mean Mean Value
- * @param bool $cumulative
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Poisson::distribution()
+ * Use the distribution() method in the Statistical\Distributions\Poisson class instead
+ *
+ * @param mixed $value
+ * @param mixed $mean Mean Value
+ * @param mixed $cumulative
*
* @return float|string The result, or a string containing an error
*/
public static function POISSON($value, $mean, $cumulative)
{
- $value = Functions::flattenSingleValue($value);
- $mean = Functions::flattenSingleValue($mean);
-
- if ((is_numeric($value)) && (is_numeric($mean))) {
- if (($value < 0) || ($mean <= 0)) {
- return Functions::NAN();
- }
- if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
- if ($cumulative) {
- $summer = 0;
- $floor = floor($value);
- for ($i = 0; $i <= $floor; ++$i) {
- $summer += $mean ** $i / MathTrig::FACT($i);
- }
-
- return exp(0 - $mean) * $summer;
- }
-
- return (exp(0 - $mean) * $mean ** $value) / MathTrig::FACT($value);
- }
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Poisson::distribution($value, $mean, $cumulative);
}
/**
@@ -2990,27 +1346,18 @@ class Statistical
* Excel Function:
* QUARTILE(value1[,value2[, ...]],entry)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Percentiles::QUARTILE()
+ * Use the QUARTILE() method in the Statistical\Percentiles class instead
+ *
* @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);
-
- // Calculate
- $entry = floor(array_pop($aArgs));
-
- if ((is_numeric($entry)) && (!is_string($entry))) {
- $entry /= 4;
- if (($entry < 0) || ($entry > 1)) {
- return Functions::NAN();
- }
-
- return self::PERCENTILE($aArgs, $entry);
- }
-
- return Functions::VALUE();
+ return Statistical\Percentiles::QUARTILE(...$args);
}
/**
@@ -3018,35 +1365,20 @@ class Statistical
*
* Returns the rank of a number in a list of numbers.
*
- * @param int $value the number whose rank you want to find
- * @param float[] $valueSet An array of, or a reference to, a list of numbers
- * @param int $order Order to sort the values in the value set
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Percentiles::RANK()
+ * Use the RANK() method in the Statistical\Percentiles class instead
+ *
+ * @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)
{
- $value = Functions::flattenSingleValue($value);
- $valueSet = Functions::flattenArray($valueSet);
- $order = ($order === null) ? 0 : (int) Functions::flattenSingleValue($order);
-
- foreach ($valueSet as $key => $valueEntry) {
- if (!is_numeric($valueEntry)) {
- unset($valueSet[$key]);
- }
- }
-
- if ($order == 0) {
- rsort($valueSet, SORT_NUMERIC);
- } else {
- sort($valueSet, SORT_NUMERIC);
- }
- $pos = array_search($value, $valueSet);
- if ($pos === false) {
- return Functions::NA();
- }
-
- return ++$pos;
+ return Statistical\Percentiles::RANK($value, $valueSet, $order);
}
/**
@@ -3054,6 +1386,11 @@ class Statistical
*
* 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
+ *
+ * @see Statistical\Trends::RSQ()
+ * Use the RSQ() method in the Statistical\Trends class instead
+ *
* @param mixed[] $yValues Data Series Y
* @param mixed[] $xValues Data Series X
*
@@ -3061,21 +1398,7 @@ class Statistical
*/
public static function RSQ($yValues, $xValues)
{
- if (!self::checkTrendArrays($yValues, $xValues)) {
- return Functions::VALUE();
- }
- $yValueCount = count($yValues);
- $xValueCount = count($xValues);
-
- if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
- return Functions::NA();
- } elseif ($yValueCount == 1) {
- return Functions::DIV0();
- }
-
- $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
-
- return $bestFitLinear->getGoodnessOfFit();
+ return Trends::RSQ($yValues, $xValues);
}
/**
@@ -3086,37 +1409,18 @@ class Statistical
* 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
+ *
+ * @see Statistical\Deviations::skew()
+ * Use the skew() method in the Statistical\Deviations class instead
+ *
* @param array ...$args Data Series
*
* @return float|string The result, or a string containing an error
*/
public static function SKEW(...$args)
{
- $aArgs = Functions::flattenArrayIndexed($args);
- $mean = self::AVERAGE($aArgs);
- $stdDev = self::STDEV($aArgs);
-
- $count = $summer = 0;
- // Loop through arguments
- 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) ** 3;
- ++$count;
- }
- }
- }
-
- if ($count > 2) {
- return $summer * ($count / (($count - 1) * ($count - 2)));
- }
-
- return Functions::DIV0();
+ return Statistical\Deviations::skew(...$args);
}
/**
@@ -3124,6 +1428,11 @@ class Statistical
*
* Returns the slope of the linear regression line through data points in known_y's and known_x's.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Trends::SLOPE()
+ * Use the SLOPE() method in the Statistical\Trends class instead
+ *
* @param mixed[] $yValues Data Series Y
* @param mixed[] $xValues Data Series X
*
@@ -3131,21 +1440,7 @@ class Statistical
*/
public static function SLOPE($yValues, $xValues)
{
- if (!self::checkTrendArrays($yValues, $xValues)) {
- return Functions::VALUE();
- }
- $yValueCount = count($yValues);
- $xValueCount = count($xValues);
-
- if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
- return Functions::NA();
- } elseif ($yValueCount == 1) {
- return Functions::DIV0();
- }
-
- $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
-
- return $bestFitLinear->getSlope();
+ return Trends::SLOPE($yValues, $xValues);
}
/**
@@ -3157,38 +1452,18 @@ class Statistical
* Excel Function:
* SMALL(value1[,value2[, ...]],entry)
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Size::small()
+ * Use the small() method in the Statistical\Size class instead
+ *
* @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);
-
- // Calculate
- $entry = array_pop($aArgs);
-
- if ((is_numeric($entry)) && (!is_string($entry))) {
- $entry = (int) floor($entry);
-
- $mArgs = [];
- foreach ($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $mArgs[] = $arg;
- }
- }
- $count = self::COUNT($mArgs);
- --$entry;
- if (($entry < 0) || ($entry >= $count) || ($count == 0)) {
- return Functions::NAN();
- }
- sort($mArgs);
-
- return $mArgs[$entry];
- }
-
- return Functions::VALUE();
+ return Statistical\Size::small(...$args);
}
/**
@@ -3196,6 +1471,11 @@ class Statistical
*
* Returns a normalized value from a distribution characterized by mean and standard_dev.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Standardize::execute()
+ * Use the execute() method in the Statistical\Standardize class instead
+ *
* @param float $value Value to normalize
* @param float $mean Mean Value
* @param float $stdDev Standard Deviation
@@ -3204,19 +1484,7 @@ class Statistical
*/
public static function STANDARDIZE($value, $mean, $stdDev)
{
- $value = Functions::flattenSingleValue($value);
- $mean = Functions::flattenSingleValue($mean);
- $stdDev = Functions::flattenSingleValue($stdDev);
-
- if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
- if ($stdDev <= 0) {
- return Functions::NAN();
- }
-
- return ($value - $mean) / $stdDev;
- }
-
- return Functions::VALUE();
+ return Statistical\Standardize::execute($value, $mean, $stdDev);
}
/**
@@ -3228,45 +1496,18 @@ class Statistical
* Excel Function:
* STDEV(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\StandardDeviations::STDEV()
+ * Use the STDEV() method in the Statistical\StandardDeviations class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string The result, or a string containing an error
*/
public static function STDEV(...$args)
{
- $aArgs = Functions::flattenArrayIndexed($args);
-
- // Return value
- $returnValue = null;
-
- $aMean = self::AVERAGE($aArgs);
- if ($aMean !== null) {
- $aCount = -1;
- foreach ($aArgs as $k => $arg) {
- if (
- (is_bool($arg)) &&
- ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE))
- ) {
- $arg = (int) $arg;
- }
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- if ($returnValue === null) {
- $returnValue = ($arg - $aMean) ** 2;
- } else {
- $returnValue += ($arg - $aMean) ** 2;
- }
- ++$aCount;
- }
- }
-
- // Return
- if (($aCount > 0) && ($returnValue >= 0)) {
- return sqrt($returnValue / $aCount);
- }
- }
-
- return Functions::DIV0();
+ return StandardDeviations::STDEV(...$args);
}
/**
@@ -3277,48 +1518,18 @@ class Statistical
* Excel Function:
* STDEVA(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\StandardDeviations::STDEVA()
+ * Use the STDEVA() method in the Statistical\StandardDeviations class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string
*/
public static function STDEVA(...$args)
{
- $aArgs = Functions::flattenArrayIndexed($args);
-
- $returnValue = null;
-
- $aMean = self::AVERAGEA($aArgs);
- if ($aMean !== null) {
- $aCount = -1;
- foreach ($aArgs as $k => $arg) {
- if (
- (is_bool($arg)) &&
- (!Functions::isMatrixValue($k))
- ) {
- } else {
- // Is it a numeric value?
- if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
- if (is_bool($arg)) {
- $arg = (int) $arg;
- } elseif (is_string($arg)) {
- $arg = 0;
- }
- if ($returnValue === null) {
- $returnValue = ($arg - $aMean) ** 2;
- } else {
- $returnValue += ($arg - $aMean) ** 2;
- }
- ++$aCount;
- }
- }
- }
-
- if (($aCount > 0) && ($returnValue >= 0)) {
- return sqrt($returnValue / $aCount);
- }
- }
-
- return Functions::DIV0();
+ return StandardDeviations::STDEVA(...$args);
}
/**
@@ -3329,43 +1540,18 @@ class Statistical
* Excel Function:
* STDEVP(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\StandardDeviations::STDEVP()
+ * Use the STDEVP() method in the Statistical\StandardDeviations class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string
*/
public static function STDEVP(...$args)
{
- $aArgs = Functions::flattenArrayIndexed($args);
-
- $returnValue = null;
-
- $aMean = self::AVERAGE($aArgs);
- if ($aMean !== null) {
- $aCount = 0;
- foreach ($aArgs as $k => $arg) {
- if (
- (is_bool($arg)) &&
- ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE))
- ) {
- $arg = (int) $arg;
- }
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- if ($returnValue === null) {
- $returnValue = ($arg - $aMean) ** 2;
- } else {
- $returnValue += ($arg - $aMean) ** 2;
- }
- ++$aCount;
- }
- }
-
- if (($aCount > 0) && ($returnValue >= 0)) {
- return sqrt($returnValue / $aCount);
- }
- }
-
- return Functions::DIV0();
+ return StandardDeviations::STDEVP(...$args);
}
/**
@@ -3376,53 +1562,28 @@ class Statistical
* Excel Function:
* STDEVPA(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\StandardDeviations::STDEVPA()
+ * Use the STDEVPA() method in the Statistical\StandardDeviations class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string
*/
public static function STDEVPA(...$args)
{
- $aArgs = Functions::flattenArrayIndexed($args);
-
- $returnValue = null;
-
- $aMean = self::AVERAGEA($aArgs);
- if ($aMean !== null) {
- $aCount = 0;
- foreach ($aArgs as $k => $arg) {
- if (
- (is_bool($arg)) &&
- (!Functions::isMatrixValue($k))
- ) {
- } else {
- // Is it a numeric value?
- if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
- if (is_bool($arg)) {
- $arg = (int) $arg;
- } elseif (is_string($arg)) {
- $arg = 0;
- }
- if ($returnValue === null) {
- $returnValue = ($arg - $aMean) ** 2;
- } else {
- $returnValue += ($arg - $aMean) ** 2;
- }
- ++$aCount;
- }
- }
- }
-
- if (($aCount > 0) && ($returnValue >= 0)) {
- return sqrt($returnValue / $aCount);
- }
- }
-
- return Functions::DIV0();
+ return StandardDeviations::STDEVPA(...$args);
}
/**
* STEYX.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Trends::STEYX()
+ * Use the STEYX() method in the Statistical\Trends class instead
+ *
* Returns the standard error of the predicted y-value for each x in the regression.
*
* @param mixed[] $yValues Data Series Y
@@ -3432,21 +1593,7 @@ class Statistical
*/
public static function STEYX($yValues, $xValues)
{
- if (!self::checkTrendArrays($yValues, $xValues)) {
- return Functions::VALUE();
- }
- $yValueCount = count($yValues);
- $xValueCount = count($xValues);
-
- if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
- return Functions::NA();
- } elseif ($yValueCount == 1) {
- return Functions::DIV0();
- }
-
- $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
-
- return $bestFitLinear->getStdevOfResiduals();
+ return Trends::STEYX($yValues, $xValues);
}
/**
@@ -3454,6 +1601,11 @@ class Statistical
*
* Returns the probability of Student's T distribution.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\StudentT::distribution()
+ * Use the distribution() method in the Statistical\Distributions\StudentT class instead
+ *
* @param float $value Value for the function
* @param float $degrees degrees of freedom
* @param float $tails number of tails (1 or 2)
@@ -3462,61 +1614,18 @@ class Statistical
*/
public static function TDIST($value, $degrees, $tails)
{
- $value = Functions::flattenSingleValue($value);
- $degrees = floor(Functions::flattenSingleValue($degrees));
- $tails = floor(Functions::flattenSingleValue($tails));
-
- if ((is_numeric($value)) && (is_numeric($degrees)) && (is_numeric($tails))) {
- if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) {
- return Functions::NAN();
- }
- // 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);
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\StudentT::distribution($value, $degrees, $tails);
}
/**
* TINV.
*
- * Returns the one-tailed probability of the chi-squared distribution.
+ * Returns the one-tailed probability of the Student-T distribution.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\StudentT::inverse()
+ * Use the inverse() method in the Statistical\Distributions\StudentT class instead
*
* @param float $probability Probability for the function
* @param float $degrees degrees of freedom
@@ -3525,50 +1634,7 @@ class Statistical
*/
public static function TINV($probability, $degrees)
{
- $probability = Functions::flattenSingleValue($probability);
- $degrees = floor(Functions::flattenSingleValue($degrees));
-
- if ((is_numeric($probability)) && (is_numeric($degrees))) {
- $xLo = 100;
- $xHi = 0;
-
- $x = $xNew = 1;
- $dx = 1;
- $i = 0;
-
- while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) {
- // Apply Newton-Raphson step
- $result = self::TDIST($x, $degrees, 2);
- $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 Functions::NA();
- }
-
- return round($x, 12);
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\StudentT::inverse($probability, $degrees);
}
/**
@@ -3576,31 +1642,21 @@ class Statistical
*
* Returns values along a linear Trend
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Trends::TREND()
+ * Use the TREND() method in the Statistical\Trends class instead
+ *
* @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 array of float
+ * @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;
+ return Trends::TREND($yValues, $xValues, $newValues, $const);
}
/**
@@ -3613,39 +1669,18 @@ class Statistical
* Excel Function:
* TRIMEAN(value1[,value2[, ...]], $discard)
*
+ * @Deprecated 1.18.0
+ *
+ *@see Statistical\Averages\Mean::trim()
+ * Use the trim() method in the Statistical\Averages\Mean class instead
+ *
* @param mixed $args Data values
*
* @return float|string
*/
public static function TRIMMEAN(...$args)
{
- $aArgs = Functions::flattenArray($args);
-
- // Calculate
- $percent = array_pop($aArgs);
-
- if ((is_numeric($percent)) && (!is_string($percent))) {
- if (($percent < 0) || ($percent > 1)) {
- return Functions::NAN();
- }
- $mArgs = [];
- foreach ($aArgs as $arg) {
- // Is it a numeric value?
- if ((is_numeric($arg)) && (!is_string($arg))) {
- $mArgs[] = $arg;
- }
- }
- $discard = floor(self::COUNT($mArgs) * $percent / 2);
- sort($mArgs);
- for ($i = 0; $i < $discard; ++$i) {
- array_pop($mArgs);
- array_shift($mArgs);
- }
-
- return self::AVERAGE($mArgs);
- }
-
- return Functions::VALUE();
+ return Statistical\Averages\Mean::trim(...$args);
}
/**
@@ -3656,38 +1691,18 @@ class Statistical
* Excel Function:
* VAR(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ *@see Statistical\Variances::VAR()
+ * Use the VAR() method in the Statistical\Variances class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string (string if result is an error)
*/
public static function VARFunc(...$args)
{
- $returnValue = Functions::DIV0();
-
- $summerA = $summerB = 0;
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
- $aCount = 0;
- foreach ($aArgs as $arg) {
- if (is_bool($arg)) {
- $arg = (int) $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;
- $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1));
- }
-
- return $returnValue;
+ return Variances::VAR(...$args);
}
/**
@@ -3698,51 +1713,18 @@ class Statistical
* Excel Function:
* VARA(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Variances::VARA()
+ * Use the VARA() method in the Statistical\Variances class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string (string if result is an error)
*/
public static function VARA(...$args)
{
- $returnValue = Functions::DIV0();
-
- $summerA = $summerB = 0;
-
- // Loop through arguments
- $aArgs = Functions::flattenArrayIndexed($args);
- $aCount = 0;
- foreach ($aArgs as $k => $arg) {
- if (
- (is_string($arg)) &&
- (Functions::isValue($k))
- ) {
- return Functions::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 != '')))) {
- if (is_bool($arg)) {
- $arg = (int) $arg;
- } elseif (is_string($arg)) {
- $arg = 0;
- }
- $summerA += ($arg * $arg);
- $summerB += $arg;
- ++$aCount;
- }
- }
- }
-
- if ($aCount > 1) {
- $summerA *= $aCount;
- $summerB *= $summerB;
- $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1));
- }
-
- return $returnValue;
+ return Variances::VARA(...$args);
}
/**
@@ -3753,39 +1735,18 @@ class Statistical
* Excel Function:
* VARP(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Variances::VARP()
+ * Use the VARP() method in the Statistical\Variances class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string (string if result is an error)
*/
public static function VARP(...$args)
{
- // Return value
- $returnValue = Functions::DIV0();
-
- $summerA = $summerB = 0;
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
- $aCount = 0;
- foreach ($aArgs as $arg) {
- if (is_bool($arg)) {
- $arg = (int) $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;
- $returnValue = ($summerA - $summerB) / ($aCount * $aCount);
- }
-
- return $returnValue;
+ return Variances::VARP(...$args);
}
/**
@@ -3796,51 +1757,18 @@ class Statistical
* Excel Function:
* VARPA(value1[,value2[, ...]])
*
+ * @Deprecated 1.17.0
+ *
+ * @see Statistical\Variances::VARPA()
+ * Use the VARPA() method in the Statistical\Variances class instead
+ *
* @param mixed ...$args Data values
*
* @return float|string (string if result is an error)
*/
public static function VARPA(...$args)
{
- $returnValue = Functions::DIV0();
-
- $summerA = $summerB = 0;
-
- // Loop through arguments
- $aArgs = Functions::flattenArrayIndexed($args);
- $aCount = 0;
- foreach ($aArgs as $k => $arg) {
- if (
- (is_string($arg)) &&
- (Functions::isValue($k))
- ) {
- return Functions::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 != '')))) {
- if (is_bool($arg)) {
- $arg = (int) $arg;
- } elseif (is_string($arg)) {
- $arg = 0;
- }
- $summerA += ($arg * $arg);
- $summerB += $arg;
- ++$aCount;
- }
- }
- }
-
- if ($aCount > 0) {
- $summerA *= $aCount;
- $summerB *= $summerB;
- $returnValue = ($summerA - $summerB) / ($aCount * $aCount);
- }
-
- return $returnValue;
+ return Variances::VARPA(...$args);
}
/**
@@ -3849,6 +1777,11 @@ class Statistical
* Returns the Weibull distribution. Use this distribution in reliability
* analysis, such as calculating a device's mean time to failure.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Statistical\Distributions\Weibull::distribution()
+ * Use the distribution() method in the Statistical\Distributions\Weibull class instead
+ *
* @param float $value
* @param float $alpha Alpha Parameter
* @param float $beta Beta Parameter
@@ -3858,31 +1791,21 @@ class Statistical
*/
public static function WEIBULL($value, $alpha, $beta, $cumulative)
{
- $value = Functions::flattenSingleValue($value);
- $alpha = Functions::flattenSingleValue($alpha);
- $beta = Functions::flattenSingleValue($beta);
-
- if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta))) {
- if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) {
- return Functions::NAN();
- }
- if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
- if ($cumulative) {
- return 1 - exp(0 - ($value / $beta) ** $alpha);
- }
-
- return ($alpha / $beta ** $alpha) * $value ** ($alpha - 1) * exp(0 - ($value / $beta) ** $alpha);
- }
- }
-
- return Functions::VALUE();
+ return Statistical\Distributions\Weibull::distribution($value, $alpha, $beta, $cumulative);
}
/**
* ZTEST.
*
- * Returns the Weibull distribution. Use this distribution in reliability
- * analysis, such as calculating a device's mean time to failure.
+ * 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
+ *
+ * @see Statistical\Distributions\StandardNormal::zTest()
+ * Use the zTest() method in the Statistical\Distributions\StandardNormal class instead
*
* @param float $dataSet
* @param float $m0 Alpha Parameter
@@ -3892,15 +1815,6 @@ class Statistical
*/
public static function ZTEST($dataSet, $m0, $sigma = null)
{
- $dataSet = Functions::flattenArrayIndexed($dataSet);
- $m0 = Functions::flattenSingleValue($m0);
- $sigma = Functions::flattenSingleValue($sigma);
-
- if ($sigma === null) {
- $sigma = self::STDEV($dataSet);
- }
- $n = count($dataSet);
-
- return 1 - self::NORMSDIST((self::AVERAGE($dataSet) - $m0) / ($sigma / sqrt($n)));
+ return Statistical\Distributions\StandardNormal::zTest($dataSet, $m0, $sigma);
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php
new file mode 100644
index 00000000000..75c012dc322
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php
@@ -0,0 +1,50 @@
+ $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 Functions::VALUE();
+ }
+ if (self::isAcceptedCountable($arg, $k)) {
+ $returnValue += abs($arg - $aMean);
+ ++$aCount;
+ }
+ }
+
+ // Return
+ if ($aCount === 0) {
+ return Functions::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 Functions::VALUE();
+ }
+ if (self::isAcceptedCountable($arg, $k)) {
+ $returnValue += $arg;
+ ++$aCount;
+ }
+ }
+
+ // Return
+ if ($aCount > 0) {
+ return $returnValue / $aCount;
+ }
+
+ return Functions::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_bool($arg)) && (!Functions::isMatrixValue($k))) {
+ } else {
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
+ if (is_bool($arg)) {
+ $arg = (int) $arg;
+ } elseif (is_string($arg)) {
+ $arg = 0;
+ }
+ $returnValue += $arg;
+ ++$aCount;
+ }
+ }
+ }
+
+ if ($aCount > 0) {
+ return $returnValue / $aCount;
+ }
+
+ return Functions::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 = Functions::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 = Functions::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($args)
+ {
+ 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
+ //
+ private static function modeCalc($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 Functions::NA();
+ }
+
+ return $maxfreqdatum;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Averages/Mean.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Averages/Mean.php
new file mode 100644
index 00000000000..d4d0c7ee504
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Averages/Mean.php
@@ -0,0 +1,131 @@
+ 0)) {
+ $aCount = Counts::COUNT($aArgs);
+ if (Minimum::min($aArgs) > 0) {
+ return $aMean ** (1 / $aCount);
+ }
+ }
+
+ return Functions::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 Functions::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 Functions::NAN();
+ }
+ $returnValue += (1 / $arg);
+ ++$aCount;
+ }
+ }
+
+ // Return
+ if ($aCount > 0) {
+ return 1 / ($returnValue / $aCount);
+ }
+
+ return Functions::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 Functions::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 Functions::VALUE();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php
new file mode 100644
index 00000000000..51e6b004304
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php
@@ -0,0 +1,304 @@
+getMessage();
+ }
+
+ if (($alpha <= 0) || ($alpha >= 1) || ($stdDev <= 0) || ($size < 1)) {
+ return Functions::NAN();
+ }
+
+ return Distributions\StandardNormal::inverse(1 - $alpha / 2) * $stdDev / sqrt($size);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Counts.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Counts.php
new file mode 100644
index 00000000000..13e7af79912
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Counts.php
@@ -0,0 +1,95 @@
+ $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)) {
+ ++$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 ...$args Data values
+ *
+ * @return int
+ */
+ public static function COUNTBLANK(...$args)
+ {
+ $returnValue = 0;
+
+ // Loop through arguments
+ $aArgs = Functions::flattenArray($args);
+ foreach ($aArgs as $arg) {
+ // Is it a blank cell?
+ if (($arg === null) || ((is_string($arg)) && ($arg == ''))) {
+ ++$returnValue;
+ }
+ }
+
+ return $returnValue;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php
new file mode 100644
index 00000000000..55da9f1ddf5
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php
@@ -0,0 +1,141 @@
+ $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 ? Functions::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 Functions::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 Functions::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 Functions::DIV0();
+ }
+ $stdDev = StandardDeviations::STDEV($aArgs);
+ if ($stdDev === 0.0 || is_string($stdDev)) {
+ return Functions::DIV0();
+ }
+
+ $count = $summer = 0;
+ // Loop through arguments
+ foreach ($aArgs as $k => $arg) {
+ if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) {
+ } elseif (!is_numeric($arg)) {
+ return Functions::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 Functions::DIV0();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php
new file mode 100644
index 00000000000..63e6eb4d659
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php
@@ -0,0 +1,260 @@
+getMessage();
+ }
+
+ if ($rMin > $rMax) {
+ $tmp = $rMin;
+ $rMin = $rMax;
+ $rMax = $tmp;
+ }
+ if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) {
+ return Functions::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
+ * @param mixed $alpha Parameter to the distribution as a float
+ * @param mixed $beta Parameter to the distribution as a float
+ * @param mixed $rMin Minimum value as a float
+ * @param mixed $rMax Maximum value as a float
+ *
+ * @return float|string
+ */
+ public static function inverse($probability, $alpha, $beta, $rMin = 0.0, $rMax = 1.0)
+ {
+ $probability = Functions::flattenSingleValue($probability);
+ $alpha = Functions::flattenSingleValue($alpha);
+ $beta = Functions::flattenSingleValue($beta);
+ $rMin = ($rMin === null) ? 0.0 : Functions::flattenSingleValue($rMin);
+ $rMax = ($rMax === null) ? 1.0 : Functions::flattenSingleValue($rMax);
+
+ 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 Functions::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;
+
+ $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 Functions::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
+ private static $logBetaCacheP = 0.0;
+
+ private static $logBetaCacheQ = 0.0;
+
+ 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);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php
new file mode 100644
index 00000000000..9631236ab89
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php
@@ -0,0 +1,202 @@
+getMessage();
+ }
+
+ if (($value < 0) || ($value > $trials)) {
+ return Functions::NAN();
+ }
+
+ if ($cumulative) {
+ return self::calculateCumulativeBinomial($value, $trials, $probability);
+ }
+
+ return Combinations::withoutRepetition($trials, $value) * $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
+ * @param mixed $probability Probability of success on each trial as a float
+ * @param mixed $successes The integer number of successes in trials
+ * @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
+ *
+ * @return float|string
+ */
+ public static function range($trials, $probability, $successes, $limit = null)
+ {
+ $trials = Functions::flattenSingleValue($trials);
+ $probability = Functions::flattenSingleValue($probability);
+ $successes = Functions::flattenSingleValue($successes);
+ $limit = ($limit === null) ? $successes : Functions::flattenSingleValue($limit);
+
+ 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 Functions::NAN();
+ }
+ if (($limit < 0) || ($limit > $trials) || $limit < $successes) {
+ return Functions::NAN();
+ }
+
+ $summer = 0;
+ for ($i = $successes; $i <= $limit; ++$i) {
+ $summer += Combinations::withoutRepetition($trials, $i) * $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
+ * @param mixed $successes Threshold number of Successes as an integer
+ * @param mixed $probability Probability of success on each trial as a float
+ *
+ * @return float|string The result, or a string containing an error
+ *
+ * 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)
+ {
+ $failures = Functions::flattenSingleValue($failures);
+ $successes = Functions::flattenSingleValue($successes);
+ $probability = Functions::flattenSingleValue($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 Functions::NAN();
+ }
+ if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
+ if (($failures + $successes - 1) <= 0) {
+ return Functions::NAN();
+ }
+ }
+
+ return (Combinations::withoutRepetition($failures + $successes - 1, $successes - 1))
+ * ($probability ** $successes) * ((1 - $probability) ** $failures);
+ }
+
+ /**
+ * CRITBINOM.
+ *
+ * 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
+ * @param mixed $probability probability of a success on each trial as a float
+ * @param mixed $alpha criterion value as a float
+ *
+ * @return int|string
+ */
+ public static function inverse($trials, $probability, $alpha)
+ {
+ $trials = Functions::flattenSingleValue($trials);
+ $probability = Functions::flattenSingleValue($probability);
+ $alpha = Functions::flattenSingleValue($alpha);
+
+ try {
+ $trials = DistributionValidations::validateInt($trials);
+ $probability = DistributionValidations::validateProbability($probability);
+ $alpha = DistributionValidations::validateFloat($alpha);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if ($trials < 0) {
+ return Functions::NAN();
+ } elseif (($alpha < 0.0) || ($alpha > 1.0)) {
+ return Functions::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) {
+ $summer += Combinations::withoutRepetition($trials, $i) * $probability ** $i
+ * (1 - $probability) ** ($trials - $i);
+ }
+
+ return $summer;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php
new file mode 100644
index 00000000000..5165d6397ed
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php
@@ -0,0 +1,311 @@
+getMessage();
+ }
+
+ if ($degrees < 1) {
+ return Functions::NAN();
+ }
+ if ($value < 0) {
+ if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
+ return 1;
+ }
+
+ return Functions::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
+ * @param mixed $degrees Integer degrees of freedom
+ * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false)
+ *
+ * @return float|string
+ */
+ public static function distributionLeftTail($value, $degrees, $cumulative)
+ {
+ $value = Functions::flattenSingleValue($value);
+ $degrees = Functions::flattenSingleValue($degrees);
+ $cumulative = Functions::flattenSingleValue($cumulative);
+
+ try {
+ $value = DistributionValidations::validateFloat($value);
+ $degrees = DistributionValidations::validateInt($degrees);
+ $cumulative = DistributionValidations::validateBool($cumulative);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if ($degrees < 1) {
+ return Functions::NAN();
+ }
+ if ($value < 0) {
+ if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
+ return 1;
+ }
+
+ return Functions::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
+ * @param mixed $degrees Integer degrees of freedom
+ *
+ * @return float|string
+ */
+ public static function inverseRightTail($probability, $degrees)
+ {
+ $probability = Functions::flattenSingleValue($probability);
+ $degrees = Functions::flattenSingleValue($degrees);
+
+ try {
+ $probability = DistributionValidations::validateProbability($probability);
+ $degrees = DistributionValidations::validateInt($degrees);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if ($degrees < 1) {
+ return Functions::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
+ * @param mixed $degrees Integer degrees of freedom
+ *
+ * @return float|string
+ */
+ public static function inverseLeftTail($probability, $degrees)
+ {
+ $probability = Functions::flattenSingleValue($probability);
+ $degrees = Functions::flattenSingleValue($degrees);
+
+ try {
+ $probability = DistributionValidations::validateProbability($probability);
+ $degrees = DistributionValidations::validateInt($degrees);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if ($degrees < 1) {
+ return Functions::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 = count($actual) / $rows;
+
+ $countActuals = count($actual);
+ $countExpected = count($expected);
+ if ($countActuals !== $countExpected || $countActuals === 1) {
+ return Functions::NAN();
+ }
+
+ $result = 0.0;
+ for ($i = 0; $i < $countActuals; ++$i) {
+ if ($expected[$i] == 0.0) {
+ return Functions::DIV0();
+ } elseif ($expected[$i] < 0.0) {
+ return Functions::NAN();
+ }
+ $result += (($actual[$i] - $expected[$i]) ** 2) / $expected[$i];
+ }
+
+ $degrees = self::degrees($rows, $columns);
+
+ $result = 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($chi2, $degrees)
+ {
+ return self::gammp($degrees, 0.5 * $chi2);
+ }
+
+ private static function gammp($n, $x)
+ {
+ 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($n, $x)
+ {
+ $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($n, $x)
+ {
+ $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);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php
new file mode 100644
index 00000000000..57ef00af04a
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php
@@ -0,0 +1,24 @@
+ 1.0) {
+ throw new Exception(Functions::NAN());
+ }
+
+ return $probability;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php
new file mode 100644
index 00000000000..b3fd9460c1e
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php
@@ -0,0 +1,47 @@
+getMessage();
+ }
+
+ if (($value < 0) || ($lambda < 0)) {
+ return Functions::NAN();
+ }
+
+ if ($cumulative === true) {
+ return 1 - exp(0 - $value * $lambda);
+ }
+
+ return $lambda * exp(0 - $value * $lambda);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php
new file mode 100644
index 00000000000..54b1950d6d9
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php
@@ -0,0 +1,56 @@
+getMessage();
+ }
+
+ if ($value < 0 || $u < 1 || $v < 1) {
+ return Functions::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)));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php
new file mode 100644
index 00000000000..923bf02d909
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php
@@ -0,0 +1,61 @@
+getMessage();
+ }
+
+ if (($value <= -1) || ($value >= 1)) {
+ return Functions::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
+ *
+ * @return float|string
+ */
+ public static function inverse($probability)
+ {
+ $probability = Functions::flattenSingleValue($probability);
+
+ try {
+ DistributionValidations::validateFloat($probability);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ return (exp(2 * $probability) - 1) / (exp(2 * $probability) + 1);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php
new file mode 100644
index 00000000000..2c6ed670a8e
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php
@@ -0,0 +1,127 @@
+getMessage();
+ }
+
+ if ((((int) $value) == ((float) $value)) && $value <= 0.0) {
+ return Functions::NAN();
+ }
+
+ return self::gammaValue($value);
+ }
+
+ /**
+ * GAMMADIST.
+ *
+ * Returns the gamma distribution.
+ *
+ * @param mixed $value Float Value at which you want to evaluate the distribution
+ * @param mixed $a Parameter to the distribution as a float
+ * @param mixed $b Parameter to the distribution as a float
+ * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false)
+ *
+ * @return float|string
+ */
+ public static function distribution($value, $a, $b, $cumulative)
+ {
+ $value = Functions::flattenSingleValue($value);
+ $a = Functions::flattenSingleValue($a);
+ $b = Functions::flattenSingleValue($b);
+
+ 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 Functions::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
+ * @param mixed $alpha Parameter to the distribution as a float
+ * @param mixed $beta Parameter to the distribution as a float
+ *
+ * @return float|string
+ */
+ public static function inverse($probability, $alpha, $beta)
+ {
+ $probability = Functions::flattenSingleValue($probability);
+ $alpha = Functions::flattenSingleValue($alpha);
+ $beta = Functions::flattenSingleValue($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 Functions::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
+ *
+ * @return float|string
+ */
+ public static function ln($value)
+ {
+ $value = Functions::flattenSingleValue($value);
+
+ try {
+ $value = DistributionValidations::validateFloat($value);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if ($value <= 0) {
+ return Functions::NAN();
+ }
+
+ return log(self::gammaValue($value));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php
new file mode 100644
index 00000000000..89170f7cada
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php
@@ -0,0 +1,381 @@
+ Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) {
+ // Apply Newton-Raphson step
+ $result = self::calculateDistribution($x, $alpha, $beta, true);
+ $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 ($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 Functions::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));
+ }
+
+ /**
+ * logGamma function.
+ *
+ * @version 1.1
+ *
+ * @author Jaco van Kooten
+ *
+ * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher.
+ *
+ * The natural logarithm of the gamma function.
+ * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
+ * Applied Mathematics Division
+ * Argonne National Laboratory
+ * Argonne, IL 60439
+ *
+ * References:
+ *
+ * - W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural
+ * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.
+ * - K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.
+ * - Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.
+ *
+ *
+ *
+ * From the original documentation:
+ *
+ *
+ * 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.
+ *
+ *
+ * Error returns:
+ * 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.
+ *
+ *
+ * @return float MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305
+ */
+
+ // Log Gamma related constants
+ 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
+ private static $logGammaCacheResult = 0.0;
+
+ private static $logGammaCacheX = 0.0;
+
+ 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)
+ {
+ // ---------------------
+ // 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)
+ {
+ // ---------------------
+ // 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)
+ {
+ // ----------------------
+ // 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)
+ {
+ // ---------------------------------
+ // 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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php
new file mode 100644
index 00000000000..fe30c0879e4
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php
@@ -0,0 +1,59 @@
+getMessage();
+ }
+
+ if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) {
+ return Functions::NAN();
+ }
+ if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) {
+ return Functions::NAN();
+ }
+ if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) {
+ return Functions::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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php
new file mode 100644
index 00000000000..e15237736ca
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php
@@ -0,0 +1,119 @@
+getMessage();
+ }
+
+ if (($value <= 0) || ($stdDev <= 0)) {
+ return Functions::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
+ * @param mixed $mean Mean value as a float
+ * @param mixed $stdDev Standard Deviation as a float
+ * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false)
+ *
+ * @return float|string The result, or a string containing an error
+ */
+ public static function distribution($value, $mean, $stdDev, $cumulative = false)
+ {
+ $value = Functions::flattenSingleValue($value);
+ $mean = Functions::flattenSingleValue($mean);
+ $stdDev = Functions::flattenSingleValue($stdDev);
+ $cumulative = Functions::flattenSingleValue($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 Functions::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
+ * @param mixed $mean Mean Value as a float
+ * @param mixed $stdDev Standard Deviation as a float
+ *
+ * @return 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 inverse($probability, $mean, $stdDev)
+ {
+ $probability = Functions::flattenSingleValue($probability);
+ $mean = Functions::flattenSingleValue($mean);
+ $stdDev = Functions::flattenSingleValue($stdDev);
+
+ try {
+ $probability = DistributionValidations::validateProbability($probability);
+ $mean = DistributionValidations::validateFloat($mean);
+ $stdDev = DistributionValidations::validateFloat($stdDev);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if ($stdDev <= 0) {
+ return Functions::NAN();
+ }
+
+ return exp($mean + $stdDev * StandardNormal::inverse($probability));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php
new file mode 100644
index 00000000000..26211672576
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php
@@ -0,0 +1,62 @@
+callback = $callback;
+ }
+
+ 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 Functions::NA();
+ }
+
+ return $x;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php
new file mode 100644
index 00000000000..4d158b8c8f7
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php
@@ -0,0 +1,166 @@
+getMessage();
+ }
+
+ if ($stdDev < 0) {
+ return Functions::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
+ * @param mixed $mean Mean Value as a float
+ * @param mixed $stdDev Standard Deviation as a float
+ *
+ * @return float|string The result, or a string containing an error
+ */
+ public static function inverse($probability, $mean, $stdDev)
+ {
+ $probability = Functions::flattenSingleValue($probability);
+ $mean = Functions::flattenSingleValue($mean);
+ $stdDev = Functions::flattenSingleValue($stdDev);
+
+ try {
+ $probability = DistributionValidations::validateProbability($probability);
+ $mean = DistributionValidations::validateFloat($mean);
+ $stdDev = DistributionValidations::validateFloat($stdDev);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if ($stdDev < 0) {
+ return Functions::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($p)
+ {
+ // 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);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php
new file mode 100644
index 00000000000..e7252e02898
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php
@@ -0,0 +1,53 @@
+getMessage();
+ }
+
+ if (($value < 0) || ($mean < 0)) {
+ return Functions::NAN();
+ }
+
+ if ($cumulative) {
+ $summer = 0;
+ $floor = floor($value);
+ for ($i = 0; $i <= $floor; ++$i) {
+ $summer += $mean ** $i / MathTrig\Factorial::fact($i);
+ }
+
+ return exp(0 - $mean) * $summer;
+ }
+
+ return (exp(0 - $mean) * $mean ** $value) / MathTrig\Factorial::fact($value);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php
new file mode 100644
index 00000000000..d10f02a5f74
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php
@@ -0,0 +1,110 @@
+getMessage();
+ }
+
+ if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) {
+ return Functions::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
+ * @param mixed $degrees Integer value for degrees of freedom
+ *
+ * @return float|string The result, or a string containing an error
+ */
+ public static function inverse($probability, $degrees)
+ {
+ $probability = Functions::flattenSingleValue($probability);
+ $degrees = Functions::flattenSingleValue($degrees);
+
+ try {
+ $probability = DistributionValidations::validateProbability($probability);
+ $degrees = DistributionValidations::validateInt($degrees);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if ($degrees <= 0) {
+ return Functions::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);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php
new file mode 100644
index 00000000000..ecec8a85640
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php
@@ -0,0 +1,49 @@
+getMessage();
+ }
+
+ if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) {
+ return Functions::NAN();
+ }
+
+ if ($cumulative) {
+ return 1 - exp(0 - ($value / $beta) ** $alpha);
+ }
+
+ return ($alpha / $beta ** $alpha) * $value ** ($alpha - 1) * exp(0 - ($value / $beta) ** $alpha);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php
new file mode 100644
index 00000000000..bd17b062923
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php
@@ -0,0 +1,17 @@
+ $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) {
+ // 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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php
new file mode 100644
index 00000000000..596aad78fdf
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php
@@ -0,0 +1,78 @@
+getMessage();
+ }
+
+ if (($entry < 0) || ($entry > 1)) {
+ return Functions::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 Functions::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 Functions::NA();
+ }
+ sort($valueSet, SORT_NUMERIC);
+
+ $valueAdjustor = $valueCount - 1;
+ if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) {
+ return Functions::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($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 Functions::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 Functions::NA();
+ }
+
+ return ++$pos;
+ }
+
+ protected static function percentileFilterValues(array $dataSet)
+ {
+ return array_filter(
+ $dataSet,
+ function ($value): bool {
+ return is_numeric($value) && !is_string($value);
+ }
+ );
+ }
+
+ protected static function rankFilterValues(array $dataSet)
+ {
+ return array_filter(
+ $dataSet,
+ function ($value): bool {
+ return is_numeric($value);
+ }
+ );
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php
new file mode 100644
index 00000000000..272a8a53dbf
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php
@@ -0,0 +1,77 @@
+getMessage();
+ }
+
+ if ($numObjs < $numInSet) {
+ return Functions::NAN();
+ }
+ $result = round(MathTrig\Factorial::fact($numObjs) / MathTrig\Factorial::fact($numObjs - $numInSet));
+
+ 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
+ * @param mixed $numInSet Integer number of objects in each permutation
+ *
+ * @return float|int|string Number of permutations, or a string containing an error
+ */
+ public static function PERMUTATIONA($numObjs, $numInSet)
+ {
+ $numObjs = Functions::flattenSingleValue($numObjs);
+ $numInSet = Functions::flattenSingleValue($numInSet);
+
+ try {
+ $numObjs = StatisticalValidations::validateInt($numObjs);
+ $numInSet = StatisticalValidations::validateInt($numInSet);
+ } catch (Exception $e) {
+ return $e->getMessage();
+ }
+
+ if ($numObjs < 0 || $numInSet < 0) {
+ return Functions::NAN();
+ }
+
+ $result = $numObjs ** $numInSet;
+
+ return IntOrFloat::evaluate($result);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Size.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Size.php
new file mode 100644
index 00000000000..de4b6d6c3d8
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Size.php
@@ -0,0 +1,96 @@
+= $count) || ($count == 0)) {
+ return Functions::NAN();
+ }
+ rsort($mArgs);
+
+ return $mArgs[$entry];
+ }
+
+ return Functions::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 (($entry < 0) || ($entry >= $count) || ($count == 0)) {
+ return Functions::NAN();
+ }
+ sort($mArgs);
+
+ return $mArgs[$entry];
+ }
+
+ return Functions::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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php
new file mode 100644
index 00000000000..af2712053f3
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php
@@ -0,0 +1,95 @@
+getMessage();
+ }
+
+ if ($stdDev <= 0) {
+ return Functions::NAN();
+ }
+
+ return ($value - $mean) / $stdDev;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php
new file mode 100644
index 00000000000..5b315da45c9
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php
@@ -0,0 +1,45 @@
+ $value) {
+ if ((is_bool($value)) || (is_string($value)) || ($value === null)) {
+ unset($array1[$key], $array2[$key]);
+ }
+ }
+ }
+
+ 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(Functions::NA());
+ } elseif ($yValueCount === 1) {
+ throw new Exception(Functions::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 Functions::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
+ * @param mixed $yValues array of mixed Data Series Y
+ * @param mixed $xValues of mixed Data Series X
+ *
+ * @return bool|float|string
+ */
+ public static function FORECAST($xValue, $yValues, $xValues)
+ {
+ $xValue = Functions::flattenSingleValue($xValue);
+
+ 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;
+ }
+
+ /**
+ * 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) ? Functions::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 Functions::NAN();
+ }
+ }
+
+ $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const);
+
+ if ($stats === true) {
+ return [
+ [
+ $bestFitExponential->getSlope(),
+ $bestFitExponential->getIntersect(),
+ ],
+ [
+ $bestFitExponential->getSlopeSE(),
+ ($const === false) ? Functions::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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php
new file mode 100644
index 00000000000..e53346719c6
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php
@@ -0,0 +1,28 @@
+ 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 = Functions::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 Functions::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 = Functions::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 = Functions::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 Functions::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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData.php
index f89744029e7..0bde3b7fe48 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData.php
@@ -3,141 +3,88 @@
namespace PhpOffice\PhpSpreadsheet\Calculation;
use DateTimeInterface;
-use PhpOffice\PhpSpreadsheet\Shared\Date;
-use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
-use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
+/**
+ * @deprecated 1.18.0
+ */
class TextData
{
- private static $invalidChars;
-
- private static function unicodeToOrd($character)
- {
- return unpack('V', iconv('UTF-8', 'UCS-4LE', $character))[1];
- }
-
/**
* CHARACTER.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the character() method in the TextData\CharacterConvert class instead
+ *
* @param string $character Value
*
* @return string
*/
public static function CHARACTER($character)
{
- $character = Functions::flattenSingleValue($character);
-
- if (!is_numeric($character)) {
- return Functions::VALUE();
- }
- $character = (int) $character;
- if ($character < 1 || $character > 255) {
- return Functions::VALUE();
- }
-
- return iconv('UCS-4LE', 'UTF-8', pack('V', $character));
+ return TextData\CharacterConvert::character($character);
}
/**
* TRIMNONPRINTABLE.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the nonPrintable() method in the TextData\Trim class instead
+ *
* @param mixed $stringValue Value to check
*
* @return string
*/
public static function TRIMNONPRINTABLE($stringValue = '')
{
- $stringValue = Functions::flattenSingleValue($stringValue);
-
- if (is_bool($stringValue)) {
- return ($stringValue) ? Calculation::getTRUE() : Calculation::getFALSE();
- }
-
- if (self::$invalidChars === null) {
- self::$invalidChars = range(chr(0), chr(31));
- }
-
- if (is_string($stringValue) || is_numeric($stringValue)) {
- return str_replace(self::$invalidChars, '', trim($stringValue, "\x00..\x1F"));
- }
-
- return null;
+ return TextData\Trim::nonPrintable($stringValue);
}
/**
* TRIMSPACES.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the spaces() method in the TextData\Trim class instead
+ *
* @param mixed $stringValue Value to check
*
* @return string
*/
public static function TRIMSPACES($stringValue = '')
{
- $stringValue = Functions::flattenSingleValue($stringValue);
- if (is_bool($stringValue)) {
- return ($stringValue) ? Calculation::getTRUE() : Calculation::getFALSE();
- }
-
- if (is_string($stringValue) || is_numeric($stringValue)) {
- return trim(preg_replace('/ +/', ' ', trim($stringValue, ' ')), ' ');
- }
-
- return null;
- }
-
- private static function convertBooleanValue($value)
- {
- if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) {
- return (int) $value;
- }
-
- return ($value) ? Calculation::getTRUE() : Calculation::getFALSE();
+ return TextData\Trim::spaces($stringValue);
}
/**
* ASCIICODE.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the code() method in the TextData\CharacterConvert class instead
+ *
* @param string $characters Value
*
* @return int|string A string if arguments are invalid
*/
public static function ASCIICODE($characters)
{
- if (($characters === null) || ($characters === '')) {
- return Functions::VALUE();
- }
- $characters = Functions::flattenSingleValue($characters);
- if (is_bool($characters)) {
- $characters = self::convertBooleanValue($characters);
- }
-
- $character = $characters;
- if (mb_strlen($characters, 'UTF-8') > 1) {
- $character = mb_substr($characters, 0, 1, 'UTF-8');
- }
-
- return self::unicodeToOrd($character);
+ return TextData\CharacterConvert::code($characters);
}
/**
* CONCATENATE.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the CONCATENATE() method in the TextData\Concatenate class instead
+ *
* @return string
*/
public static function CONCATENATE(...$args)
{
- $returnValue = '';
-
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
- foreach ($aArgs as $arg) {
- if (is_bool($arg)) {
- $arg = self::convertBooleanValue($arg);
- }
- $returnValue .= $arg;
- }
-
- return $returnValue;
+ return TextData\Concatenate::CONCATENATE(...$args);
}
/**
@@ -146,6 +93,10 @@ class TextData
* 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
+ *
+ * @see Use the DOLLAR() method in the TextData\Format class instead
+ *
* @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.
@@ -155,33 +106,16 @@ class TextData
*/
public static function DOLLAR($value = 0, $decimals = 2)
{
- $value = Functions::flattenSingleValue($value);
- $decimals = $decimals === null ? 0 : Functions::flattenSingleValue($decimals);
-
- // Validate parameters
- if (!is_numeric($value) || !is_numeric($decimals)) {
- return Functions::VALUE();
- }
- $decimals = floor($decimals);
-
- $mask = '$#,##0';
- if ($decimals > 0) {
- $mask .= '.' . str_repeat('0', $decimals);
- } else {
- $round = 10 ** abs($decimals);
- if ($value < 0) {
- $round = 0 - $round;
- }
- $value = MathTrig::MROUND($value, $round);
- }
- $mask = "$mask;($mask)";
-
- return NumberFormat::toFormattedString($value, $mask);
+ return TextData\Format::DOLLAR($value, $decimals);
}
/**
* SEARCHSENSITIVE.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the sensitive() method in the TextData\Search class instead
+ *
* @param string $needle The string to look for
* @param string $haystack The string in which to look
* @param int $offset Offset within $haystack
@@ -190,33 +124,16 @@ class TextData
*/
public static function SEARCHSENSITIVE($needle, $haystack, $offset = 1)
{
- $needle = Functions::flattenSingleValue($needle);
- $haystack = Functions::flattenSingleValue($haystack);
- $offset = Functions::flattenSingleValue($offset);
-
- if (!is_bool($needle)) {
- if (is_bool($haystack)) {
- $haystack = ($haystack) ? Calculation::getTRUE() : Calculation::getFALSE();
- }
-
- if (($offset > 0) && (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 Functions::VALUE();
+ return TextData\Search::sensitive($needle, $haystack, $offset);
}
/**
* SEARCHINSENSITIVE.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the insensitive() method in the TextData\Search class instead
+ *
* @param string $needle The string to look for
* @param string $haystack The string in which to look
* @param int $offset Offset within $haystack
@@ -225,33 +142,16 @@ class TextData
*/
public static function SEARCHINSENSITIVE($needle, $haystack, $offset = 1)
{
- $needle = Functions::flattenSingleValue($needle);
- $haystack = Functions::flattenSingleValue($haystack);
- $offset = Functions::flattenSingleValue($offset);
-
- if (!is_bool($needle)) {
- if (is_bool($haystack)) {
- $haystack = ($haystack) ? Calculation::getTRUE() : Calculation::getFALSE();
- }
-
- if (($offset > 0) && (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 Functions::VALUE();
+ return TextData\Search::insensitive($needle, $haystack, $offset);
}
/**
* FIXEDFORMAT.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the FIXEDFORMAT() method in the TextData\Format class instead
+ *
* @param mixed $value Value to check
* @param int $decimals
* @param bool $no_commas
@@ -260,35 +160,16 @@ class TextData
*/
public static function FIXEDFORMAT($value, $decimals = 2, $no_commas = false)
{
- $value = Functions::flattenSingleValue($value);
- $decimals = Functions::flattenSingleValue($decimals);
- $no_commas = Functions::flattenSingleValue($no_commas);
-
- // Validate parameters
- if (!is_numeric($value) || !is_numeric($decimals)) {
- return Functions::VALUE();
- }
- $decimals = (int) floor($decimals);
-
- $valueResult = round($value, $decimals);
- if ($decimals < 0) {
- $decimals = 0;
- }
- if (!$no_commas) {
- $valueResult = number_format(
- $valueResult,
- $decimals,
- StringHelper::getDecimalSeparator(),
- StringHelper::getThousandsSeparator()
- );
- }
-
- return (string) $valueResult;
+ return TextData\Format::FIXEDFORMAT($value, $decimals, $no_commas);
}
/**
* LEFT.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the left() method in the TextData\Extract class instead
+ *
* @param string $value Value
* @param int $chars Number of characters
*
@@ -296,23 +177,16 @@ class TextData
*/
public static function LEFT($value = '', $chars = 1)
{
- $value = Functions::flattenSingleValue($value);
- $chars = Functions::flattenSingleValue($chars);
-
- if ($chars < 0) {
- return Functions::VALUE();
- }
-
- if (is_bool($value)) {
- $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE();
- }
-
- return mb_substr($value, 0, $chars, 'UTF-8');
+ return TextData\Extract::left($value, $chars);
}
/**
* MID.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the mid() method in the TextData\Extract class instead
+ *
* @param string $value Value
* @param int $start Start character
* @param int $chars Number of characters
@@ -321,28 +195,16 @@ class TextData
*/
public static function MID($value = '', $start = 1, $chars = null)
{
- $value = Functions::flattenSingleValue($value);
- $start = Functions::flattenSingleValue($start);
- $chars = Functions::flattenSingleValue($chars);
-
- if (($start < 1) || ($chars < 0)) {
- return Functions::VALUE();
- }
-
- if (is_bool($value)) {
- $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE();
- }
-
- if (empty($chars)) {
- return '';
- }
-
- return mb_substr($value, --$start, $chars, 'UTF-8');
+ return TextData\Extract::mid($value, $start, $chars);
}
/**
* RIGHT.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the right() method in the TextData\Extract class instead
+ *
* @param string $value Value
* @param int $chars Number of characters
*
@@ -350,36 +212,23 @@ class TextData
*/
public static function RIGHT($value = '', $chars = 1)
{
- $value = Functions::flattenSingleValue($value);
- $chars = Functions::flattenSingleValue($chars);
-
- if ($chars < 0) {
- return Functions::VALUE();
- }
-
- if (is_bool($value)) {
- $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE();
- }
-
- return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8');
+ return TextData\Extract::right($value, $chars);
}
/**
* STRINGLENGTH.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the length() method in the TextData\Text class instead
+ *
* @param string $value Value
*
* @return int
*/
public static function STRINGLENGTH($value = '')
{
- $value = Functions::flattenSingleValue($value);
-
- if (is_bool($value)) {
- $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE();
- }
-
- return mb_strlen($value, 'UTF-8');
+ return TextData\Text::length($value);
}
/**
@@ -387,19 +236,17 @@ class TextData
*
* Converts a string value to upper case.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the lower() method in the TextData\CaseConvert class instead
+ *
* @param string $mixedCaseString
*
* @return string
*/
public static function LOWERCASE($mixedCaseString)
{
- $mixedCaseString = Functions::flattenSingleValue($mixedCaseString);
-
- if (is_bool($mixedCaseString)) {
- $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE();
- }
-
- return StringHelper::strToLower($mixedCaseString);
+ return TextData\CaseConvert::lower($mixedCaseString);
}
/**
@@ -407,19 +254,17 @@ class TextData
*
* Converts a string value to upper case.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the upper() method in the TextData\CaseConvert class instead
+ *
* @param string $mixedCaseString
*
* @return string
*/
public static function UPPERCASE($mixedCaseString)
{
- $mixedCaseString = Functions::flattenSingleValue($mixedCaseString);
-
- if (is_bool($mixedCaseString)) {
- $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE();
- }
-
- return StringHelper::strToUpper($mixedCaseString);
+ return TextData\CaseConvert::upper($mixedCaseString);
}
/**
@@ -427,24 +272,26 @@ class TextData
*
* Converts a string value to upper case.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the proper() method in the TextData\CaseConvert class instead
+ *
* @param string $mixedCaseString
*
* @return string
*/
public static function PROPERCASE($mixedCaseString)
{
- $mixedCaseString = Functions::flattenSingleValue($mixedCaseString);
-
- if (is_bool($mixedCaseString)) {
- $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE();
- }
-
- return StringHelper::strToTitle($mixedCaseString);
+ return TextData\CaseConvert::proper($mixedCaseString);
}
/**
* REPLACE.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the replace() method in the TextData\Replace class instead
+ *
* @param string $oldText String to modify
* @param int $start Start character
* @param int $chars Number of characters
@@ -454,20 +301,16 @@ class TextData
*/
public static function REPLACE($oldText, $start, $chars, $newText)
{
- $oldText = Functions::flattenSingleValue($oldText);
- $start = Functions::flattenSingleValue($start);
- $chars = Functions::flattenSingleValue($chars);
- $newText = Functions::flattenSingleValue($newText);
-
- $left = self::LEFT($oldText, $start - 1);
- $right = self::RIGHT($oldText, self::STRINGLENGTH($oldText) - ($start + $chars) + 1);
-
- return $left . $newText . $right;
+ return TextData\Replace::replace($oldText, $start, $chars, $newText);
}
/**
* SUBSTITUTE.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the substitute() method in the TextData\Replace class instead
+ *
* @param string $text Value
* @param string $fromText From Value
* @param string $toText To Value
@@ -477,52 +320,32 @@ class TextData
*/
public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0)
{
- $text = Functions::flattenSingleValue($text);
- $fromText = Functions::flattenSingleValue($fromText);
- $toText = Functions::flattenSingleValue($toText);
- $instance = floor(Functions::flattenSingleValue($instance));
-
- if ($instance == 0) {
- return str_replace($fromText, $toText, $text);
- }
-
- $pos = -1;
- while ($instance > 0) {
- $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8');
- if ($pos === false) {
- break;
- }
- --$instance;
- }
-
- if ($pos !== false) {
- return self::REPLACE($text, ++$pos, mb_strlen($fromText, 'UTF-8'), $toText);
- }
-
- return $text;
+ return TextData\Replace::substitute($text, $fromText, $toText, $instance);
}
/**
* RETURNSTRING.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the test() method in the TextData\Text class instead
+ *
* @param mixed $testValue Value to check
*
* @return null|string
*/
public static function RETURNSTRING($testValue = '')
{
- $testValue = Functions::flattenSingleValue($testValue);
-
- if (is_string($testValue)) {
- return $testValue;
- }
-
- return null;
+ return TextData\Text::test($testValue);
}
/**
* TEXTFORMAT.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the TEXTFORMAT() method in the TextData\Format class instead
+ *
* @param mixed $value Value to check
* @param string $format Format mask to use
*
@@ -530,65 +353,32 @@ class TextData
*/
public static function TEXTFORMAT($value, $format)
{
- $value = Functions::flattenSingleValue($value);
- $format = Functions::flattenSingleValue($format);
-
- if ((is_string($value)) && (!is_numeric($value)) && Date::isDateTimeFormatCode($format)) {
- $value = DateTime::DATEVALUE($value);
- }
-
- return (string) NumberFormat::toFormattedString($value, $format);
+ return TextData\Format::TEXTFORMAT($value, $format);
}
/**
* VALUE.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the VALUE() method in the TextData\Format class instead
+ *
* @param mixed $value Value to check
*
* @return DateTimeInterface|float|int|string A string if arguments are invalid
*/
public static function VALUE($value = '')
{
- $value = Functions::flattenSingleValue($value);
-
- if (!is_numeric($value)) {
- $numberValue = str_replace(
- StringHelper::getThousandsSeparator(),
- '',
- trim($value, " \t\n\r\0\x0B" . StringHelper::getCurrencyCode())
- );
- if (is_numeric($numberValue)) {
- return (float) $numberValue;
- }
-
- $dateSetting = Functions::getReturnDateType();
- Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
-
- if (strpos($value, ':') !== false) {
- $timeValue = DateTime::TIMEVALUE($value);
- if ($timeValue !== Functions::VALUE()) {
- Functions::setReturnDateType($dateSetting);
-
- return $timeValue;
- }
- }
- $dateValue = DateTime::DATEVALUE($value);
- if ($dateValue !== Functions::VALUE()) {
- Functions::setReturnDateType($dateSetting);
-
- return $dateValue;
- }
- Functions::setReturnDateType($dateSetting);
-
- return Functions::VALUE();
- }
-
- return (float) $value;
+ return TextData\Format::VALUE($value);
}
/**
* NUMBERVALUE.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the NUMBERVALUE() method in the TextData\Format class instead
+ *
* @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
@@ -597,39 +387,7 @@ class TextData
*/
public static function NUMBERVALUE($value = '', $decimalSeparator = null, $groupSeparator = null)
{
- $value = Functions::flattenSingleValue($value);
- $decimalSeparator = Functions::flattenSingleValue($decimalSeparator);
- $groupSeparator = Functions::flattenSingleValue($groupSeparator);
-
- if (!is_numeric($value)) {
- $decimalSeparator = empty($decimalSeparator) ? StringHelper::getDecimalSeparator() : $decimalSeparator;
- $groupSeparator = empty($groupSeparator) ? StringHelper::getThousandsSeparator() : $groupSeparator;
-
- $decimalPositions = preg_match_all('/' . preg_quote($decimalSeparator) . '/', $value, $matches, PREG_OFFSET_CAPTURE);
- if ($decimalPositions > 1) {
- return Functions::VALUE();
- }
- $decimalOffset = array_pop($matches[0])[1];
- if (strpos($value, $groupSeparator, $decimalOffset) !== false) {
- return Functions::VALUE();
- }
-
- $value = str_replace([$groupSeparator, $decimalSeparator], ['', '.'], $value);
-
- // Handle the special case of trailing % signs
- $percentageString = rtrim($value, '%');
- if (!is_numeric($percentageString)) {
- return Functions::VALUE();
- }
-
- $percentageAdjustment = strlen($value) - strlen($percentageString);
- if ($percentageAdjustment) {
- $value = (float) $percentageString;
- $value /= 10 ** ($percentageAdjustment * 2);
- }
- }
-
- return (float) $value;
+ return TextData\Format::NUMBERVALUE($value, $decimalSeparator, $groupSeparator);
}
/**
@@ -637,22 +395,27 @@ class TextData
* EXACT is case-sensitive but ignores formatting differences.
* Use EXACT to test text being entered into a document.
*
- * @param $value1
- * @param $value2
+ * @Deprecated 1.18.0
+ *
+ * @see Use the exact() method in the TextData\Text class instead
+ *
+ * @param mixed $value1
+ * @param mixed $value2
*
* @return bool
*/
public static function EXACT($value1, $value2)
{
- $value1 = Functions::flattenSingleValue($value1);
- $value2 = Functions::flattenSingleValue($value2);
-
- return (string) $value2 === (string) $value1;
+ return TextData\Text::exact($value1, $value2);
}
/**
* TEXTJOIN.
*
+ * @Deprecated 1.18.0
+ *
+ * @see Use the TEXTJOIN() method in the TextData\Concatenate class instead
+ *
* @param mixed $delimiter
* @param mixed $ignoreEmpty
* @param mixed $args
@@ -661,16 +424,25 @@ class TextData
*/
public static function TEXTJOIN($delimiter, $ignoreEmpty, ...$args)
{
- // Loop through arguments
- $aArgs = Functions::flattenArray($args);
- foreach ($aArgs as $key => &$arg) {
- if ($ignoreEmpty && trim($arg) == '') {
- unset($aArgs[$key]);
- } elseif (is_bool($arg)) {
- $arg = self::convertBooleanValue($arg);
- }
- }
+ return TextData\Concatenate::TEXTJOIN($delimiter, $ignoreEmpty, ...$args);
+ }
- return implode($delimiter, $aArgs);
+ /**
+ * REPT.
+ *
+ * Returns the result of builtin function repeat after validating args.
+ *
+ * @Deprecated 1.18.0
+ *
+ * @see Use the builtinREPT() method in the TextData\Concatenate class instead
+ *
+ * @param string $str Should be numeric
+ * @param mixed $number Should be int
+ *
+ * @return string
+ */
+ public static function builtinREPT($str, $number)
+ {
+ return TextData\Concatenate::builtinREPT($str, $number);
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php
new file mode 100644
index 00000000000..664cc2d883f
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php
@@ -0,0 +1,54 @@
+ 255) {
+ return Functions::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
+ *
+ * @return int|string A string if arguments are invalid
+ */
+ public static function code($characters)
+ {
+ $characters = Helpers::extractString($characters);
+ if ($characters === '') {
+ return Functions::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;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Concatenate.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Concatenate.php
new file mode 100644
index 00000000000..d53fc822898
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Concatenate.php
@@ -0,0 +1,71 @@
+ &$arg) {
+ if ($ignoreEmpty === true && is_string($arg) && trim($arg) === '') {
+ unset($aArgs[$key]);
+ } elseif (is_bool($arg)) {
+ $arg = Helpers::convertBooleanValue($arg);
+ }
+ }
+
+ return implode($delimiter, $aArgs);
+ }
+
+ /**
+ * REPT.
+ *
+ * Returns the result of builtin function round after validating args.
+ *
+ * @param mixed $stringValue The value to repeat
+ * @param mixed $repeatCount The number of times the string value should be repeated
+ */
+ public static function builtinREPT($stringValue, $repeatCount): string
+ {
+ $repeatCount = Functions::flattenSingleValue($repeatCount);
+ $stringValue = Helpers::extractString($stringValue);
+
+ if (!is_numeric($repeatCount) || $repeatCount < 0) {
+ return Functions::VALUE();
+ }
+
+ return str_repeat($stringValue, (int) $repeatCount);
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php
new file mode 100644
index 00000000000..7f18e0c6e7c
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php
@@ -0,0 +1,64 @@
+getMessage();
+ }
+
+ return mb_substr($value ?? '', 0, $chars, 'UTF-8');
+ }
+
+ /**
+ * MID.
+ *
+ * @param mixed $value String value from which to extract characters
+ * @param mixed $start Integer offset of the first character that we want to extract
+ * @param mixed $chars The number of characters to extract (as an integer)
+ */
+ public static function mid($value, $start, $chars): string
+ {
+ 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
+ * @param mixed $chars The number of characters to extract (as an integer)
+ */
+ public static function right($value, $chars = 1): string
+ {
+ 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');
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php
new file mode 100644
index 00000000000..3286de0cb03
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php
@@ -0,0 +1,236 @@
+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
+ * @param mixed $decimals Integer value for the number of decimal places that should be formatted
+ * @param mixed $noCommas Boolean value indicating whether the value should have thousands separators or not
+ */
+ public static function FIXEDFORMAT($value, $decimals = 2, $noCommas = false): string
+ {
+ try {
+ $value = Helpers::extractFloat($value);
+ $decimals = Helpers::extractInt($decimals, -100, 0, true);
+ $noCommas = Functions::flattenSingleValue($noCommas);
+ } 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
+ * @param mixed $format A string with the Format mask that should be used
+ */
+ public static function TEXTFORMAT($value, $format): string
+ {
+ $value = Helpers::extractString($value);
+ $format = Helpers::extractString($format);
+
+ if (!is_numeric($value) && Date::isDateTimeFormatCode($format)) {
+ $value = DateTimeExcel\DateValue::fromString($value);
+ }
+
+ return (string) NumberFormat::toFormattedString($value, $format);
+ }
+
+ /**
+ * @param mixed $value Value to check
+ *
+ * @return mixed
+ */
+ private static function convertValue($value)
+ {
+ $value = ($value === null) ? 0 : Functions::flattenSingleValue($value);
+ if (is_bool($value)) {
+ if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) {
+ $value = (int) $value;
+ } else {
+ throw new CalcExp(Functions::VALUE());
+ }
+ }
+
+ return $value;
+ }
+
+ /**
+ * VALUE.
+ *
+ * @param mixed $value Value to check
+ *
+ * @return DateTimeInterface|float|int|string A string if arguments are invalid
+ */
+ public static function VALUE($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 (is_numeric($numberValue)) {
+ return (float) $numberValue;
+ }
+
+ $dateSetting = Functions::getReturnDateType();
+ Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
+
+ if (strpos($value, ':') !== false) {
+ $timeValue = DateTimeExcel\TimeValue::fromString($value);
+ if ($timeValue !== Functions::VALUE()) {
+ Functions::setReturnDateType($dateSetting);
+
+ return $timeValue;
+ }
+ }
+ $dateValue = DateTimeExcel\DateValue::fromString($value);
+ if ($dateValue !== Functions::VALUE()) {
+ Functions::setReturnDateType($dateSetting);
+
+ return $dateValue;
+ }
+ Functions::setReturnDateType($dateSetting);
+
+ return Functions::VALUE();
+ }
+
+ return (float) $value;
+ }
+
+ /**
+ * @param mixed $decimalSeparator
+ */
+ private static function getDecimalSeparator($decimalSeparator): string
+ {
+ $decimalSeparator = Functions::flattenSingleValue($decimalSeparator);
+
+ return empty($decimalSeparator) ? StringHelper::getDecimalSeparator() : (string) $decimalSeparator;
+ }
+
+ /**
+ * @param mixed $groupSeparator
+ */
+ private static function getGroupSeparator($groupSeparator): string
+ {
+ $groupSeparator = Functions::flattenSingleValue($groupSeparator);
+
+ return empty($groupSeparator) ? StringHelper::getThousandsSeparator() : (string) $groupSeparator;
+ }
+
+ /**
+ * NUMBERVALUE.
+ *
+ * @param mixed $value The value to format
+ * @param mixed $decimalSeparator A string with the decimal separator to use, defaults to locale defined value
+ * @param mixed $groupSeparator A string with the group/thousands separator to use, defaults to locale defined value
+ *
+ * @return float|string
+ */
+ public static function NUMBERVALUE($value = '', $decimalSeparator = null, $groupSeparator = null)
+ {
+ try {
+ $value = self::convertValue($value);
+ $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 Functions::VALUE();
+ }
+ $decimalOffset = array_pop($matches[0])[1];
+ if (strpos($value, $groupSeparator, $decimalOffset) !== false) {
+ return Functions::VALUE();
+ }
+
+ $value = str_replace([$groupSeparator, $decimalSeparator], ['', '.'], $value);
+
+ // Handle the special case of trailing % signs
+ $percentageString = rtrim($value, '%');
+ if (!is_numeric($percentageString)) {
+ return Functions::VALUE();
+ }
+
+ $percentageAdjustment = strlen($value) - strlen($percentageString);
+ if ($percentageAdjustment) {
+ $value = (float) $percentageString;
+ $value /= 10 ** ($percentageAdjustment * 2);
+ }
+ }
+
+ return is_array($value) ? Functions::VALUE() : (float) $value;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Helpers.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Helpers.php
new file mode 100644
index 00000000000..423b6d3f90b
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Helpers.php
@@ -0,0 +1,90 @@
+getMessage();
+ }
+
+ return $left . $newText . $right;
+ }
+
+ /**
+ * SUBSTITUTE.
+ *
+ * @param mixed $text The text string value to modify
+ * @param mixed $fromText The string value that we want to replace in $text
+ * @param mixed $toText The string value that we want to replace with in $text
+ * @param mixed $instance Integer instance Number for the occurrence of frmText to change
+ */
+ public static function substitute($text = '', $fromText = '', $toText = '', $instance = null): string
+ {
+ try {
+ $text = Helpers::extractString($text);
+ $fromText = Helpers::extractString($fromText);
+ $toText = Helpers::extractString($toText);
+ $instance = Functions::flattenSingleValue($instance);
+ if ($instance === null) {
+ return str_replace($fromText, $toText, $text);
+ }
+ if (is_bool($instance)) {
+ if ($instance === false || Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE) {
+ return Functions::Value();
+ }
+ $instance = 1;
+ }
+ $instance = Helpers::extractInt($instance, 1, 0, true);
+ } catch (CalcExp $e) {
+ return $e->getMessage();
+ }
+
+ $pos = -1;
+ while ($instance > 0) {
+ $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8');
+ if ($pos === false) {
+ break;
+ }
+ --$instance;
+ }
+
+ if ($pos !== false) {
+ return self::REPLACE($text, ++$pos, mb_strlen($fromText, 'UTF-8'), $toText);
+ }
+
+ return $text;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Search.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Search.php
new file mode 100644
index 00000000000..c9eed2e5a5a
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Search.php
@@ -0,0 +1,76 @@
+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 Functions::VALUE();
+ }
+
+ /**
+ * SEARCH (case insensitive search).
+ *
+ * @param mixed $needle The string to look for
+ * @param mixed $haystack The string in which to look
+ * @param mixed $offset Integer offset within $haystack to start searching from
+ *
+ * @return int|string
+ */
+ public static function insensitive($needle, $haystack, $offset = 1)
+ {
+ 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 Functions::VALUE();
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Text.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Text.php
new file mode 100644
index 00000000000..6f8253eabe8
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Text.php
@@ -0,0 +1,54 @@
+ 2048) {
- return Functions::VALUE(); // Invalid URL length
- }
-
- if (!preg_match('/^http[s]?:\/\//', $url)) {
- return Functions::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 Functions::VALUE(); // cURL error
- }
-
- if ($response->getStatusCode() != 200) {
- return Functions::VALUE(); // cURL error
- }
-
- $output = $response->getBody()->getContents();
- if (strlen($output) > 32767) {
- return Functions::VALUE(); // Output not a string or too long
- }
-
- return $output;
+ return Web\Service::webService($url);
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Web/Service.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Web/Service.php
new file mode 100644
index 00000000000..05e04bf912c
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Web/Service.php
@@ -0,0 +1,75 @@
+ 2048) {
+ return Functions::VALUE(); // Invalid URL length
+ }
+
+ if (!preg_match('/^http[s]?:\/\//', $url)) {
+ return Functions::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 Functions::VALUE(); // cURL error
+ }
+
+ if ($response->getStatusCode() != 200) {
+ return Functions::VALUE(); // cURL error
+ }
+
+ $output = $response->getBody()->getContents();
+ if (strlen($output) > 32767) {
+ return Functions::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 Functions::VALUE();
+ }
+
+ return str_replace('+', '%20', urlencode($text));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/functionlist.txt b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/functionlist.txt
index e71d18f4541..270715cd094 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/functionlist.txt
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/functionlist.txt
@@ -40,6 +40,8 @@ BITOR
BITRSHIFT
BITXOR
CEILING
+CEILING.MATH
+CEILING.PRECISE
CELL
CHAR
CHIDIST
@@ -51,6 +53,7 @@ CODE
COLUMN
COLUMNS
COMBIN
+COMBINA
COMPLEX
CONCAT
CONCATENATE
@@ -247,6 +250,7 @@ MODE
MONTH
MROUND
MULTINOMIAL
+MUNIT
N
NA
NEGBINOMDIST
@@ -276,6 +280,7 @@ PEARSON
PERCENTILE
PERCENTRANK
PERMUT
+PERMUTATIONA
PHONETIC
PI
PMT
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/Translations.xlsx b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/Translations.xlsx
new file mode 100644
index 00000000000..518176ab9fb
Binary files /dev/null and b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/Translations.xlsx differ
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/config
index df513734c3f..49f40fcb5e9 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/config
@@ -1,23 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Ceština (Czech)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = Kč
-
-
-##
-## Excel Error Codes (For future use)
-##
-NULL = #NULL!
-DIV0 = #DIV/0!
-VALUE = #HODNOTA!
-REF = #REF!
-NAME = #NÁZEV?
-NUM = #NUM!
-NA = #N/A
+NULL
+DIV0 = #DĚLENÍ_NULOU!
+VALUE = #HODNOTA!
+REF = #ODKAZ!
+NAME = #NÁZEV?
+NUM = #ČÍSLO!
+NA = #NENÍ_K_DISPOZICI
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/functions
index 733d406f14f..49c4945c326 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/functions
@@ -1,416 +1,520 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
+## PhpSpreadsheet - function name translations
##
+## Ceština (Czech)
##
+############################################################
##
-## Add-in and Automation functions Funkce doplňků a automatizace
+## Funkce pro práci s datovými krychlemi (Cube Functions)
##
-GETPIVOTDATA = ZÍSKATKONTDATA ## Vrátí data uložená v kontingenční tabulce. Pomocí funkce ZÍSKATKONTDATA můžete načíst souhrnná data z kontingenční tabulky, pokud jsou tato data v kontingenční sestavě zobrazena.
-
+CUBEKPIMEMBER = CUBEKPIMEMBER
+CUBEMEMBER = CUBEMEMBER
+CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY
+CUBERANKEDMEMBER = CUBERANKEDMEMBER
+CUBESET = CUBESET
+CUBESETCOUNT = CUBESETCOUNT
+CUBEVALUE = CUBEVALUE
##
-## Cube functions Funkce pro práci s krychlemi
+## Funkce databáze (Database Functions)
##
-CUBEKPIMEMBER = CUBEKPIMEMBER ## Vrátí název, vlastnost a velikost klíčového ukazatele výkonu (KUV) a zobrazí v buňce název a vlastnost. Klíčový ukazatel výkonu je kvantifikovatelná veličina, například hrubý měsíční zisk nebo čtvrtletní obrat na zaměstnance, která se používá pro sledování výkonnosti organizace.
-CUBEMEMBER = CUBEMEMBER ## Vrátí člen nebo n-tici v hierarchii krychle. Slouží k ověření, zda v krychli existuje člen nebo n-tice.
-CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY ## Vrátí hodnotu vlastnosti člena v krychli. Slouží k ověření, zda v krychli existuje člen s daným názvem, a k vrácení konkrétní vlastnosti tohoto člena.
-CUBERANKEDMEMBER = CUBERANKEDMEMBER ## Vrátí n-tý nebo pořadový člen sady. Použijte ji pro vrácení jednoho nebo více prvků sady, například obchodníka s nejvyšším obratem nebo deseti nejlepších studentů.
-CUBESET = CUBESET ## Definuje vypočtenou sadu členů nebo n-tic odesláním výrazu sady do krychle na serveru, který vytvoří sadu a potom ji vrátí do aplikace Microsoft Office Excel.
-CUBESETCOUNT = CUBESETCOUNT ## Vrátí počet položek v množině
-CUBEVALUE = CUBEVALUE ## Vrátí úhrnnou hodnotu z krychle.
-
+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
##
-## Database functions Funkce databáze
+## Funkce data a času (Date & Time Functions)
##
-DAVERAGE = DPRŮMĚR ## Vrátí průměr vybraných položek databáze.
-DCOUNT = DPOČET ## Spočítá buňky databáze obsahující čísla.
-DCOUNTA = DPOČET2 ## Spočítá buňky databáze, které nejsou prázdné.
-DGET = DZÍSKAT ## Extrahuje z databáze jeden záznam splňující zadaná kritéria.
-DMAX = DMAX ## Vrátí maximální hodnotu z vybraných položek databáze.
-DMIN = DMIN ## Vrátí minimální hodnotu z vybraných položek databáze.
-DPRODUCT = DSOUČIN ## Vynásobí hodnoty určitého pole záznamů v databázi, které splňují daná kritéria.
-DSTDEV = DSMODCH.VÝBĚR ## Odhadne směrodatnou odchylku výběru vybraných položek databáze.
-DSTDEVP = DSMODCH ## Vypočte směrodatnou odchylku základního souboru vybraných položek databáze.
-DSUM = DSUMA ## Sečte čísla ve sloupcovém poli záznamů databáze, která splňují daná kritéria.
-DVAR = DVAR.VÝBĚR ## Odhadne rozptyl výběru vybraných položek databáze.
-DVARP = DVAR ## Vypočte rozptyl základního souboru vybraných položek databáze.
-
+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
##
-## Date and time functions Funkce data a času
+## Inženýrské funkce (Engineering Functions)
##
-DATE = DATUM ## Vrátí pořadové číslo určitého data.
-DATEVALUE = DATUMHODN ## Převede datum ve formě textu na pořadové číslo.
-DAY = DEN ## Převede pořadové číslo na den v měsíci.
-DAYS360 = ROK360 ## Vrátí počet dní mezi dvěma daty na základě roku s 360 dny.
-EDATE = EDATE ## Vrátí pořadové číslo data, které označuje určený počet měsíců před nebo po počátečním datu.
-EOMONTH = EOMONTH ## Vrátí pořadové číslo posledního dne měsíce před nebo po zadaném počtu měsíců.
-HOUR = HODINA ## Převede pořadové číslo na hodinu.
-MINUTE = MINUTA ## Převede pořadové číslo na minutu.
-MONTH = MĚSÍC ## Převede pořadové číslo na měsíc.
-NETWORKDAYS = NETWORKDAYS ## Vrátí počet celých pracovních dní mezi dvěma daty.
-NOW = NYNÍ ## Vrátí pořadové číslo aktuálního data a času.
-SECOND = SEKUNDA ## Převede pořadové číslo na sekundu.
-TIME = ČAS ## Vrátí pořadové číslo určitého času.
-TIMEVALUE = ČASHODN ## Převede čas ve formě textu na pořadové číslo.
-TODAY = DNES ## Vrátí pořadové číslo dnešního data.
-WEEKDAY = DENTÝDNE ## Převede pořadové číslo na den v týdnu.
-WEEKNUM = WEEKNUM ## Převede pořadové číslo na číslo představující číselnou pozici týdne v roce.
-WORKDAY = WORKDAY ## Vrátí pořadové číslo data před nebo po zadaném počtu pracovních dní.
-YEAR = ROK ## Převede pořadové číslo na rok.
-YEARFRAC = YEARFRAC ## Vrátí část roku vyjádřenou zlomkem a představující počet celých dní mezi počátečním a koncovým datem.
-
+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
##
-## Engineering functions Inženýrské funkce (Technické funkce)
+## Finanční funkce (Financial Functions)
##
-BESSELI = BESSELI ## Vrátí modifikovanou Besselovu funkci In(x).
-BESSELJ = BESSELJ ## Vrátí modifikovanou Besselovu funkci Jn(x).
-BESSELK = BESSELK ## Vrátí modifikovanou Besselovu funkci Kn(x).
-BESSELY = BESSELY ## Vrátí Besselovu funkci Yn(x).
-BIN2DEC = BIN2DEC ## Převede binární číslo na desítkové.
-BIN2HEX = BIN2HEX ## Převede binární číslo na šestnáctkové.
-BIN2OCT = BIN2OCT ## Převede binární číslo na osmičkové.
-COMPLEX = COMPLEX ## Převede reálnou a imaginární část na komplexní číslo.
-CONVERT = CONVERT ## Převede číslo do jiného jednotkového měrného systému.
-DEC2BIN = DEC2BIN ## Převede desítkového čísla na dvojkové
-DEC2HEX = DEC2HEX ## Převede desítkové číslo na šestnáctkové.
-DEC2OCT = DEC2OCT ## Převede desítkové číslo na osmičkové.
-DELTA = DELTA ## Testuje rovnost dvou hodnot.
-ERF = ERF ## Vrátí chybovou funkci.
-ERFC = ERFC ## Vrátí doplňkovou chybovou funkci.
-GESTEP = GESTEP ## Testuje, zda je číslo větší než mezní hodnota.
-HEX2BIN = HEX2BIN ## Převede šestnáctkové číslo na binární.
-HEX2DEC = HEX2DEC ## Převede šestnáctkové číslo na desítkové.
-HEX2OCT = HEX2OCT ## Převede šestnáctkové číslo na osmičkové.
-IMABS = IMABS ## Vrátí absolutní hodnotu (modul) komplexního čísla.
-IMAGINARY = IMAGINARY ## Vrátí imaginární část komplexního čísla.
-IMARGUMENT = IMARGUMENT ## Vrátí argument théta, úhel vyjádřený v radiánech.
-IMCONJUGATE = IMCONJUGATE ## Vrátí komplexně sdružené číslo ke komplexnímu číslu.
-IMCOS = IMCOS ## Vrátí kosinus komplexního čísla.
-IMDIV = IMDIV ## Vrátí podíl dvou komplexních čísel.
-IMEXP = IMEXP ## Vrátí exponenciální tvar komplexního čísla.
-IMLN = IMLN ## Vrátí přirozený logaritmus komplexního čísla.
-IMLOG10 = IMLOG10 ## Vrátí dekadický logaritmus komplexního čísla.
-IMLOG2 = IMLOG2 ## Vrátí logaritmus komplexního čísla při základu 2.
-IMPOWER = IMPOWER ## Vrátí komplexní číslo umocněné na celé číslo.
-IMPRODUCT = IMPRODUCT ## Vrátí součin komplexních čísel.
-IMREAL = IMREAL ## Vrátí reálnou část komplexního čísla.
-IMSIN = IMSIN ## Vrátí sinus komplexního čísla.
-IMSQRT = IMSQRT ## Vrátí druhou odmocninu komplexního čísla.
-IMSUB = IMSUB ## Vrátí rozdíl mezi dvěma komplexními čísly.
-IMSUM = IMSUM ## Vrátí součet dvou komplexních čísel.
-OCT2BIN = OCT2BIN ## Převede osmičkové číslo na binární.
-OCT2DEC = OCT2DEC ## Převede osmičkové číslo na desítkové.
-OCT2HEX = OCT2HEX ## Převede osmičkové číslo na šestnáctkové.
-
+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
##
-## Financial functions Finanční funkce
+## Informační funkce (Information Functions)
##
-ACCRINT = ACCRINT ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen v pravidelných termínech.
-ACCRINTM = ACCRINTM ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen k datu splatnosti.
-AMORDEGRC = AMORDEGRC ## Vrátí lineární amortizaci v každém účetním období pomocí koeficientu amortizace.
-AMORLINC = AMORLINC ## Vrátí lineární amortizaci v každém účetním období.
-COUPDAYBS = COUPDAYBS ## Vrátí počet dnů od začátku období placení kupónů do data splatnosti.
-COUPDAYS = COUPDAYS ## Vrátí počet dnů v období placení kupónů, které obsahuje den zúčtování.
-COUPDAYSNC = COUPDAYSNC ## Vrátí počet dnů od data zúčtování do následujícího data placení kupónu.
-COUPNCD = COUPNCD ## Vrátí následující datum placení kupónu po datu zúčtování.
-COUPNUM = COUPNUM ## Vrátí počet kupónů splatných mezi datem zúčtování a datem splatnosti.
-COUPPCD = COUPPCD ## Vrátí předchozí datum placení kupónu před datem zúčtování.
-CUMIPMT = CUMIPMT ## Vrátí kumulativní úrok splacený mezi dvěma obdobími.
-CUMPRINC = CUMPRINC ## Vrátí kumulativní jistinu splacenou mezi dvěma obdobími půjčky.
-DB = ODPIS.ZRYCH ## Vrátí odpis aktiva za určité období pomocí degresivní metody odpisu s pevným zůstatkem.
-DDB = ODPIS.ZRYCH2 ## Vrátí odpis aktiva za určité období pomocí dvojité degresivní metody odpisu nebo jiné metody, kterou zadáte.
-DISC = DISC ## Vrátí diskontní sazbu cenného papíru.
-DOLLARDE = DOLLARDE ## Převede částku v korunách vyjádřenou zlomkem na částku v korunách vyjádřenou desetinným číslem.
-DOLLARFR = DOLLARFR ## Převede částku v korunách vyjádřenou desetinným číslem na částku v korunách vyjádřenou zlomkem.
-DURATION = DURATION ## Vrátí roční dobu cenného papíru s pravidelnými úrokovými sazbami.
-EFFECT = EFFECT ## Vrátí efektivní roční úrokovou sazbu.
-FV = BUDHODNOTA ## Vrátí budoucí hodnotu investice.
-FVSCHEDULE = FVSCHEDULE ## Vrátí budoucí hodnotu počáteční jistiny po použití série sazeb složitého úroku.
-INTRATE = INTRATE ## Vrátí úrokovou sazbu plně investovaného cenného papíru.
-IPMT = PLATBA.ÚROK ## Vrátí výšku úroku investice za dané období.
-IRR = MÍRA.VÝNOSNOSTI ## Vrátí vnitřní výnosové procento série peněžních toků.
-ISPMT = ISPMT ## Vypočte výši úroku z investice zaplaceného během určitého období.
-MDURATION = MDURATION ## Vrátí Macauleyho modifikovanou dobu cenného papíru o nominální hodnotě 100 Kč.
-MIRR = MOD.MÍRA.VÝNOSNOSTI ## Vrátí vnitřní sazbu výnosu, přičemž kladné a záporné hodnoty peněžních prostředků jsou financovány podle různých sazeb.
-NOMINAL = NOMINAL ## Vrátí nominální roční úrokovou sazbu.
-NPER = POČET.OBDOBÍ ## Vrátí počet období pro investici.
-NPV = ČISTÁ.SOUČHODNOTA ## Vrátí čistou současnou hodnotu investice vypočítanou na základě série pravidelných peněžních toků a diskontní sazby.
-ODDFPRICE = ODDFPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným prvním obdobím.
-ODDFYIELD = ODDFYIELD ## Vrátí výnos cenného papíru s odlišným prvním obdobím.
-ODDLPRICE = ODDLPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným posledním obdobím.
-ODDLYIELD = ODDLYIELD ## Vrátí výnos cenného papíru s odlišným posledním obdobím.
-PMT = PLATBA ## Vrátí hodnotu pravidelné splátky anuity.
-PPMT = PLATBA.ZÁKLAD ## Vrátí hodnotu splátky jistiny pro zadanou investici za dané období.
-PRICE = PRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen v pravidelných termínech.
-PRICEDISC = PRICEDISC ## Vrátí cenu diskontního cenného papíru o nominální hodnotě 100 Kč.
-PRICEMAT = PRICEMAT ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen k datu splatnosti.
-PV = SOUČHODNOTA ## Vrátí současnou hodnotu investice.
-RATE = ÚROKOVÁ.MÍRA ## Vrátí úrokovou sazbu vztaženou na období anuity.
-RECEIVED = RECEIVED ## Vrátí částku obdrženou k datu splatnosti plně investovaného cenného papíru.
-SLN = ODPIS.LIN ## Vrátí přímé odpisy aktiva pro jedno období.
-SYD = ODPIS.NELIN ## Vrátí směrné číslo ročních odpisů aktiva pro zadané období.
-TBILLEQ = TBILLEQ ## Vrátí výnos směnky státní pokladny ekvivalentní výnosu obligace.
-TBILLPRICE = TBILLPRICE ## Vrátí cenu směnky státní pokladny o nominální hodnotě 100 Kč.
-TBILLYIELD = TBILLYIELD ## Vrátí výnos směnky státní pokladny.
-VDB = ODPIS.ZA.INT ## Vrátí odpis aktiva pro určité období nebo část období pomocí degresivní metody odpisu.
-XIRR = XIRR ## Vrátí vnitřní výnosnost pro harmonogram peněžních toků, který nemusí být nutně periodický.
-XNPV = XNPV ## Vrátí čistou současnou hodnotu pro harmonogram peněžních toků, který nemusí být nutně periodický.
-YIELD = YIELD ## Vrátí výnos cenného papíru, ze kterého je úrok placen v pravidelných termínech.
-YIELDDISC = YIELDDISC ## Vrátí roční výnos diskontního cenného papíru, například směnky státní pokladny.
-YIELDMAT = YIELDMAT ## Vrátí roční výnos cenného papíru, ze kterého je úrok placen k datu splatnosti.
-
+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
##
-## Information functions Informační funkce
+## Logické funkce (Logical Functions)
##
-CELL = POLÍČKO ## Vrátí informace o formátování, umístění nebo obsahu buňky.
-ERROR.TYPE = CHYBA.TYP ## Vrátí číslo odpovídající typu chyby.
-INFO = O.PROSTŘEDÍ ## Vrátí informace o aktuálním pracovním prostředí.
-ISBLANK = JE.PRÁZDNÉ ## Vrátí hodnotu PRAVDA, pokud se argument hodnota odkazuje na prázdnou buňku.
-ISERR = JE.CHYBA ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota (kromě #N/A).
-ISERROR = JE.CHYBHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota.
-ISEVEN = ISEVEN ## Vrátí hodnotu PRAVDA, pokud je číslo sudé.
-ISLOGICAL = JE.LOGHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota logická hodnota.
-ISNA = JE.NEDEF ## Vrátí hodnotu PRAVDA, pokud je argument hodnota chybová hodnota #N/A.
-ISNONTEXT = JE.NETEXT ## Vrátí hodnotu PRAVDA, pokud argument hodnota není text.
-ISNUMBER = JE.ČÍSLO ## Vrátí hodnotu PRAVDA, pokud je argument hodnota číslo.
-ISODD = ISODD ## Vrátí hodnotu PRAVDA, pokud je číslo liché.
-ISREF = JE.ODKAZ ## Vrátí hodnotu PRAVDA, pokud je argument hodnota odkaz.
-ISTEXT = JE.TEXT ## Vrátí hodnotu PRAVDA, pokud je argument hodnota text.
-N = N ## Vrátí hodnotu převedenou na číslo.
-NA = NEDEF ## Vrátí chybovou hodnotu #N/A.
-TYPE = TYP ## Vrátí číslo označující datový typ hodnoty.
-
+AND = A
+FALSE = NEPRAVDA
+IF = KDYŽ
+IFERROR = IFERROR
+IFNA = IFNA
+IFS = IFS
+NOT = NE
+OR = NEBO
+SWITCH = SWITCH
+TRUE = PRAVDA
+XOR = XOR
##
-## Logical functions Logické funkce
+## Vyhledávací funkce a funkce pro odkazy (Lookup & Reference Functions)
##
-AND = A ## Vrátí hodnotu PRAVDA, mají-li všechny argumenty hodnotu PRAVDA.
-FALSE = NEPRAVDA ## Vrátí logickou hodnotu NEPRAVDA.
-IF = KDYŽ ## Určí, který logický test má proběhnout.
-IFERROR = IFERROR ## Pokud je vzorec vyhodnocen jako chyba, vrátí zadanou hodnotu. V opačném případě vrátí výsledek vzorce.
-NOT = NE ## Provede logickou negaci argumentu funkce.
-OR = NEBO ## Vrátí hodnotu PRAVDA, je-li alespoň jeden argument roven hodnotě PRAVDA.
-TRUE = PRAVDA ## Vrátí logickou hodnotu PRAVDA.
-
+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
##
-## Lookup and reference functions Vyhledávací funkce
+## Matematické a trigonometrické funkce (Math & Trig Functions)
##
-ADDRESS = ODKAZ ## Vrátí textový odkaz na jednu buňku listu.
-AREAS = POČET.BLOKŮ ## Vrátí počet oblastí v odkazu.
-CHOOSE = ZVOLIT ## Zvolí hodnotu ze seznamu hodnot.
-COLUMN = SLOUPEC ## Vrátí číslo sloupce odkazu.
-COLUMNS = SLOUPCE ## Vrátí počet sloupců v odkazu.
-HLOOKUP = VVYHLEDAT ## Prohledá horní řádek matice a vrátí hodnotu určené buňky.
-HYPERLINK = HYPERTEXTOVÝ.ODKAZ ## Vytvoří zástupce nebo odkaz, který otevře dokument uložený na síťovém serveru, v síti intranet nebo Internet.
-INDEX = INDEX ## Pomocí rejstříku zvolí hodnotu z odkazu nebo matice.
-INDIRECT = NEPŘÍMÝ.ODKAZ ## Vrátí odkaz určený textovou hodnotou.
-LOOKUP = VYHLEDAT ## Vyhledá hodnoty ve vektoru nebo matici.
-MATCH = POZVYHLEDAT ## Vyhledá hodnoty v odkazu nebo matici.
-OFFSET = POSUN ## Vrátí posun odkazu od zadaného odkazu.
-ROW = ŘÁDEK ## Vrátí číslo řádku odkazu.
-ROWS = ŘÁDKY ## Vrátí počet řádků v odkazu.
-RTD = RTD ## Načte data reálného času z programu, který podporuje automatizaci modelu COM (Automatizace: Způsob práce s objekty určité aplikace z jiné aplikace nebo nástroje pro vývoj. Automatizace (dříve nazývaná automatizace OLE) je počítačovým standardem a je funkcí modelu COM (Component Object Model).).
-TRANSPOSE = TRANSPOZICE ## Vrátí transponovanou matici.
-VLOOKUP = SVYHLEDAT ## Prohledá první sloupec matice, přesune kurzor v řádku a vrátí hodnotu buňky.
-
+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
##
-## Math and trigonometry functions Matematické a trigonometrické funkce
+## Statistické funkce (Statistical Functions)
##
-ABS = ABS ## Vrátí absolutní hodnotu čísla.
-ACOS = ARCCOS ## Vrátí arkuskosinus čísla.
-ACOSH = ARCCOSH ## Vrátí hyperbolický arkuskosinus čísla.
-ASIN = ARCSIN ## Vrátí arkussinus čísla.
-ASINH = ARCSINH ## Vrátí hyperbolický arkussinus čísla.
-ATAN = ARCTG ## Vrátí arkustangens čísla.
-ATAN2 = ARCTG2 ## Vrátí arkustangens x-ové a y-ové souřadnice.
-ATANH = ARCTGH ## Vrátí hyperbolický arkustangens čísla.
-CEILING = ZAOKR.NAHORU ## Zaokrouhlí číslo na nejbližší celé číslo nebo na nejbližší násobek zadané hodnoty.
-COMBIN = KOMBINACE ## Vrátí počet kombinací pro daný počet položek.
-COS = COS ## Vrátí kosinus čísla.
-COSH = COSH ## Vrátí hyperbolický kosinus čísla.
-DEGREES = DEGREES ## Převede radiány na stupně.
-EVEN = ZAOKROUHLIT.NA.SUDÉ ## Zaokrouhlí číslo nahoru na nejbližší celé sudé číslo.
-EXP = EXP ## Vrátí základ přirozeného logaritmu e umocněný na zadané číslo.
-FACT = FAKTORIÁL ## Vrátí faktoriál čísla.
-FACTDOUBLE = FACTDOUBLE ## Vrátí dvojitý faktoriál čísla.
-FLOOR = ZAOKR.DOLŮ ## Zaokrouhlí číslo dolů, směrem k nule.
-GCD = GCD ## Vrátí největší společný dělitel.
-INT = CELÁ.ČÁST ## Zaokrouhlí číslo dolů na nejbližší celé číslo.
-LCM = LCM ## Vrátí nejmenší společný násobek.
-LN = LN ## Vrátí přirozený logaritmus čísla.
-LOG = LOGZ ## Vrátí logaritmus čísla při zadaném základu.
-LOG10 = LOG ## Vrátí dekadický logaritmus čísla.
-MDETERM = DETERMINANT ## Vrátí determinant matice.
-MINVERSE = INVERZE ## Vrátí inverzní matici.
-MMULT = SOUČIN.MATIC ## Vrátí součin dvou matic.
-MOD = MOD ## Vrátí zbytek po dělení.
-MROUND = MROUND ## Vrátí číslo zaokrouhlené na požadovaný násobek.
-MULTINOMIAL = MULTINOMIAL ## Vrátí mnohočlen z množiny čísel.
-ODD = ZAOKROUHLIT.NA.LICHÉ ## Zaokrouhlí číslo nahoru na nejbližší celé liché číslo.
-PI = PI ## Vrátí hodnotu čísla pí.
-POWER = POWER ## Umocní číslo na zadanou mocninu.
-PRODUCT = SOUČIN ## Vynásobí argumenty funkce.
-QUOTIENT = QUOTIENT ## Vrátí celou část dělení.
-RADIANS = RADIANS ## Převede stupně na radiány.
-RAND = NÁHČÍSLO ## Vrátí náhodné číslo mezi 0 a 1.
-RANDBETWEEN = RANDBETWEEN ## Vrátí náhodné číslo mezi zadanými čísly.
-ROMAN = ROMAN ## Převede arabskou číslici na římskou ve formátu textu.
-ROUND = ZAOKROUHLIT ## Zaokrouhlí číslo na zadaný počet číslic.
-ROUNDDOWN = ROUNDDOWN ## Zaokrouhlí číslo dolů, směrem k nule.
-ROUNDUP = ROUNDUP ## Zaokrouhlí číslo nahoru, směrem od nuly.
-SERIESSUM = SERIESSUM ## Vrátí součet mocninné řady určené podle vzorce.
-SIGN = SIGN ## Vrátí znaménko čísla.
-SIN = SIN ## Vrátí sinus daného úhlu.
-SINH = SINH ## Vrátí hyperbolický sinus čísla.
-SQRT = ODMOCNINA ## Vrátí kladnou druhou odmocninu.
-SQRTPI = SQRTPI ## Vrátí druhou odmocninu výrazu (číslo * pí).
-SUBTOTAL = SUBTOTAL ## Vrátí souhrn v seznamu nebo databázi.
-SUM = SUMA ## Sečte argumenty funkce.
-SUMIF = SUMIF ## Sečte buňky vybrané podle zadaných kritérií.
-SUMIFS = SUMIFS ## Sečte buňky určené více zadanými podmínkami.
-SUMPRODUCT = SOUČIN.SKALÁRNÍ ## Vrátí součet součinů odpovídajících prvků matic.
-SUMSQ = SUMA.ČTVERCŮ ## Vrátí součet čtverců argumentů.
-SUMX2MY2 = SUMX2MY2 ## Vrátí součet rozdílu čtverců odpovídajících hodnot ve dvou maticích.
-SUMX2PY2 = SUMX2PY2 ## Vrátí součet součtu čtverců odpovídajících hodnot ve dvou maticích.
-SUMXMY2 = SUMXMY2 ## Vrátí součet čtverců rozdílů odpovídajících hodnot ve dvou maticích.
-TAN = TGTG ## Vrátí tangens čísla.
-TANH = TGH ## Vrátí hyperbolický tangens čísla.
-TRUNC = USEKNOUT ## Zkrátí číslo na celé číslo.
-
+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
##
-## Statistical functions Statistické funkce
+## Textové funkce (Text Functions)
##
-AVEDEV = PRŮMODCHYLKA ## Vrátí průměrnou hodnotu absolutních odchylek datových bodů od jejich střední hodnoty.
-AVERAGE = PRŮMĚR ## Vrátí průměrnou hodnotu argumentů.
-AVERAGEA = AVERAGEA ## Vrátí průměrnou hodnotu argumentů včetně čísel, textu a logických hodnot.
-AVERAGEIF = AVERAGEIF ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk v oblasti, které vyhovují příslušné podmínce.
-AVERAGEIFS = AVERAGEIFS ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk vyhovujících několika podmínkám.
-BETADIST = BETADIST ## Vrátí hodnotu součtového rozdělení beta.
-BETAINV = BETAINV ## Vrátí inverzní hodnotu součtového rozdělení pro zadané rozdělení beta.
-BINOMDIST = BINOMDIST ## Vrátí hodnotu binomického rozdělení pravděpodobnosti jednotlivých veličin.
-CHIDIST = CHIDIST ## Vrátí jednostrannou pravděpodobnost rozdělení chí-kvadrát.
-CHIINV = CHIINV ## Vrátí hodnotu funkce inverzní k distribuční funkci jednostranné pravděpodobnosti rozdělení chí-kvadrát.
-CHITEST = CHITEST ## Vrátí test nezávislosti.
-CONFIDENCE = CONFIDENCE ## Vrátí interval spolehlivosti pro střední hodnotu základního souboru.
-CORREL = CORREL ## Vrátí korelační koeficient mezi dvěma množinami dat.
-COUNT = POČET ## Vrátí počet čísel v seznamu argumentů.
-COUNTA = POČET2 ## Vrátí počet hodnot v seznamu argumentů.
-COUNTBLANK = COUNTBLANK ## Spočítá počet prázdných buněk v oblasti.
-COUNTIF = COUNTIF ## Spočítá buňky v oblasti, které odpovídají zadaným kritériím.
-COUNTIFS = COUNTIFS ## Spočítá buňky v oblasti, které odpovídají více kritériím.
-COVAR = COVAR ## Vrátí hodnotu kovariance, průměrnou hodnotu součinů párových odchylek
-CRITBINOM = CRITBINOM ## Vrátí nejmenší hodnotu, pro kterou má součtové binomické rozdělení hodnotu větší nebo rovnu hodnotě kritéria.
-DEVSQ = DEVSQ ## Vrátí součet čtverců odchylek.
-EXPONDIST = EXPONDIST ## Vrátí hodnotu exponenciálního rozdělení.
-FDIST = FDIST ## Vrátí hodnotu rozdělení pravděpodobnosti F.
-FINV = FINV ## Vrátí hodnotu inverzní funkce k distribuční funkci rozdělení F.
-FISHER = FISHER ## Vrátí hodnotu Fisherovy transformace.
-FISHERINV = FISHERINV ## Vrátí hodnotu inverzní funkce k Fisherově transformaci.
-FORECAST = FORECAST ## Vrátí hodnotu lineárního trendu.
-FREQUENCY = ČETNOSTI ## Vrátí četnost rozdělení jako svislou matici.
-FTEST = FTEST ## Vrátí výsledek F-testu.
-GAMMADIST = GAMMADIST ## Vrátí hodnotu rozdělení gama.
-GAMMAINV = GAMMAINV ## Vrátí hodnotu inverzní funkce k distribuční funkci součtového rozdělení gama.
-GAMMALN = GAMMALN ## Vrátí přirozený logaritmus funkce gama, Γ(x).
-GEOMEAN = GEOMEAN ## Vrátí geometrický průměr.
-GROWTH = LOGLINTREND ## Vrátí hodnoty exponenciálního trendu.
-HARMEAN = HARMEAN ## Vrátí harmonický průměr.
-HYPGEOMDIST = HYPGEOMDIST ## Vrátí hodnotu hypergeometrického rozdělení.
-INTERCEPT = INTERCEPT ## Vrátí úsek lineární regresní čáry.
-KURT = KURT ## Vrátí hodnotu excesu množiny dat.
-LARGE = LARGE ## Vrátí k-tou největší hodnotu množiny dat.
-LINEST = LINREGRESE ## Vrátí parametry lineárního trendu.
-LOGEST = LOGLINREGRESE ## Vrátí parametry exponenciálního trendu.
-LOGINV = LOGINV ## Vrátí inverzní funkci k distribuční funkci logaritmicko-normálního rozdělení.
-LOGNORMDIST = LOGNORMDIST ## Vrátí hodnotu součtového logaritmicko-normálního rozdělení.
-MAX = MAX ## Vrátí maximální hodnotu seznamu argumentů.
-MAXA = MAXA ## Vrátí maximální hodnotu seznamu argumentů včetně čísel, textu a logických hodnot.
-MEDIAN = MEDIAN ## Vrátí střední hodnotu zadaných čísel.
-MIN = MIN ## Vrátí minimální hodnotu seznamu argumentů.
-MINA = MINA ## Vrátí nejmenší hodnotu v seznamu argumentů včetně čísel, textu a logických hodnot.
-MODE = MODE ## Vrátí hodnotu, která se v množině dat vyskytuje nejčastěji.
-NEGBINOMDIST = NEGBINOMDIST ## Vrátí hodnotu negativního binomického rozdělení.
-NORMDIST = NORMDIST ## Vrátí hodnotu normálního součtového rozdělení.
-NORMINV = NORMINV ## Vrátí inverzní funkci k funkci normálního součtového rozdělení.
-NORMSDIST = NORMSDIST ## Vrátí hodnotu standardního normálního součtového rozdělení.
-NORMSINV = NORMSINV ## Vrátí inverzní funkci k funkci standardního normálního součtového rozdělení.
-PEARSON = PEARSON ## Vrátí Pearsonův výsledný momentový korelační koeficient.
-PERCENTILE = PERCENTIL ## Vrátí hodnotu k-tého percentilu hodnot v oblasti.
-PERCENTRANK = PERCENTRANK ## Vrátí pořadí hodnoty v množině dat vyjádřené procentuální částí množiny dat.
-PERMUT = PERMUTACE ## Vrátí počet permutací pro zadaný počet objektů.
-POISSON = POISSON ## Vrátí hodnotu distribuční funkce Poissonova rozdělení.
-PROB = PROB ## Vrátí pravděpodobnost výskytu hodnot v oblasti mezi dvěma mezními hodnotami.
-QUARTILE = QUARTIL ## Vrátí hodnotu kvartilu množiny dat.
-RANK = RANK ## Vrátí pořadí čísla v seznamu čísel.
-RSQ = RKQ ## Vrátí druhou mocninu Pearsonova výsledného momentového korelačního koeficientu.
-SKEW = SKEW ## Vrátí zešikmení rozdělení.
-SLOPE = SLOPE ## Vrátí směrnici lineární regresní čáry.
-SMALL = SMALL ## Vrátí k-tou nejmenší hodnotu množiny dat.
-STANDARDIZE = STANDARDIZE ## Vrátí normalizovanou hodnotu.
-STDEV = SMODCH.VÝBĚR ## Vypočte směrodatnou odchylku výběru.
-STDEVA = STDEVA ## Vypočte směrodatnou odchylku výběru včetně čísel, textu a logických hodnot.
-STDEVP = SMODCH ## Vypočte směrodatnou odchylku základního souboru.
-STDEVPA = STDEVPA ## Vypočte směrodatnou odchylku základního souboru včetně čísel, textu a logických hodnot.
-STEYX = STEYX ## Vrátí standardní chybu předpovězené hodnoty y pro každou hodnotu x v regresi.
-TDIST = TDIST ## Vrátí hodnotu Studentova t-rozdělení.
-TINV = TINV ## Vrátí inverzní funkci k distribuční funkci Studentova t-rozdělení.
-TREND = LINTREND ## Vrátí hodnoty lineárního trendu.
-TRIMMEAN = TRIMMEAN ## Vrátí střední hodnotu vnitřní části množiny dat.
-TTEST = TTEST ## Vrátí pravděpodobnost spojenou se Studentovým t-testem.
-VAR = VAR.VÝBĚR ## Vypočte rozptyl výběru.
-VARA = VARA ## Vypočte rozptyl výběru včetně čísel, textu a logických hodnot.
-VARP = VAR ## Vypočte rozptyl základního souboru.
-VARPA = VARPA ## Vypočte rozptyl základního souboru včetně čísel, textu a logických hodnot.
-WEIBULL = WEIBULL ## Vrátí hodnotu Weibullova rozdělení.
-ZTEST = ZTEST ## Vrátí jednostrannou P-hodnotu z-testu.
-
+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
##
-## Text functions Textové funkce
+## Webové funkce (Web Functions)
##
-ASC = ASC ## Změní znaky s plnou šířkou (dvoubajtové)v řetězci znaků na znaky s poloviční šířkou (jednobajtové).
-BAHTTEXT = BAHTTEXT ## Převede číslo na text ve formátu, měny ß (baht).
-CHAR = ZNAK ## Vrátí znak určený číslem kódu.
-CLEAN = VYČISTIT ## Odebere z textu všechny netisknutelné znaky.
-CODE = KÓD ## Vrátí číselný kód prvního znaku zadaného textového řetězce.
-CONCATENATE = CONCATENATE ## Spojí několik textových položek do jedné.
-DOLLAR = KČ ## Převede číslo na text ve formátu měny Kč (česká koruna).
-EXACT = STEJNÉ ## Zkontroluje, zda jsou dvě textové hodnoty shodné.
-FIND = NAJÍT ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena).
-FINDB = FINDB ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena).
-FIXED = ZAOKROUHLIT.NA.TEXT ## Zformátuje číslo jako text s pevným počtem desetinných míst.
-JIS = JIS ## Změní znaky s poloviční šířkou (jednobajtové) v řetězci znaků na znaky s plnou šířkou (dvoubajtové).
-LEFT = ZLEVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo.
-LEFTB = LEFTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo.
-LEN = DÉLKA ## Vrátí počet znaků textového řetězce.
-LENB = LENB ## Vrátí počet znaků textového řetězce.
-LOWER = MALÁ ## Převede text na malá písmena.
-MID = ČÁST ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem.
-MIDB = MIDB ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem.
-PHONETIC = ZVUKOVÉ ## Extrahuje fonetické znaky (furigana) z textového řetězce.
-PROPER = VELKÁ2 ## Převede první písmeno každého slova textové hodnoty na velké.
-REPLACE = NAHRADIT ## Nahradí znaky uvnitř textu.
-REPLACEB = NAHRADITB ## Nahradí znaky uvnitř textu.
-REPT = OPAKOVAT ## Zopakuje text podle zadaného počtu opakování.
-RIGHT = ZPRAVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo.
-RIGHTB = RIGHTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo.
-SEARCH = HLEDAT ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována).
-SEARCHB = SEARCHB ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována).
-SUBSTITUTE = DOSADIT ## V textovém řetězci nahradí starý text novým.
-T = T ## Převede argumenty na text.
-TEXT = HODNOTA.NA.TEXT ## Zformátuje číslo a převede ho na text.
-TRIM = PROČISTIT ## Odstraní z textu mezery.
-UPPER = VELKÁ ## Převede text na velká písmena.
-VALUE = HODNOTA ## Převede textový argument na číslo.
+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
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/config
index a7aa8fee9d9..284b2490388 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/config
@@ -1,25 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Dansk (Danish)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = kr
-
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #NUL!
-DIV0 = #DIVISION/0!
-VALUE = #VÆRDI!
-REF = #REFERENCE!
-NAME = #NAVN?
-NUM = #NUM!
-NA = #I/T
+NULL = #NUL!
+DIV0
+VALUE = #VÆRDI!
+REF = #REFERENCE!
+NAME = #NAVN?
+NUM
+NA = #I/T
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/functions
index d02aa2ec9be..6260760bc74 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/functions
@@ -1,416 +1,537 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
+## PhpSpreadsheet - function name translations
##
+## Dansk (Danish)
##
+############################################################
##
-## Add-in and Automation functions Tilføjelsesprogram- og automatiseringsfunktioner
+## Kubefunktioner (Cube Functions)
##
-GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data, der er lagret i en pivottabelrapport
-
+CUBEKPIMEMBER = KUBE.KPI.MEDLEM
+CUBEMEMBER = KUBEMEDLEM
+CUBEMEMBERPROPERTY = KUBEMEDLEM.EGENSKAB
+CUBERANKEDMEMBER = KUBERANGERET.MEDLEM
+CUBESET = KUBESÆT
+CUBESETCOUNT = KUBESÆT.ANTAL
+CUBEVALUE = KUBEVÆRDI
##
-## Cube functions Kubefunktioner
+## Databasefunktioner (Database Functions)
##
-CUBEKPIMEMBER = KUBE.KPI.MEDLEM ## Returnerer navn, egenskab og mål for en KPI-indikator og viser navnet og egenskaben i cellen. En KPI-indikator er en målbar størrelse, f.eks. bruttooverskud pr. måned eller personaleudskiftning pr. kvartal, der bruges til at overvåge en organisations præstationer.
-CUBEMEMBER = KUBE.MEDLEM ## Returnerer et medlem eller en tupel fra kubehierarkiet. Bruges til at validere, om et medlem eller en tupel findes i kuben.
-CUBEMEMBERPROPERTY = KUBEMEDLEM.EGENSKAB ## Returnerer værdien af en egenskab for et medlem i kuben. Bruges til at validere, om et medlemsnavn findes i kuben, og returnere den angivne egenskab for medlemmet.
-CUBERANKEDMEMBER = KUBEMEDLEM.RANG ## Returnerer det n'te eller rangordnede medlem i et sæt. Bruges til at returnere et eller flere elementer i et sæt, f.eks. topsælgere eller de 10 bedste elever.
-CUBESET = KUBESÆT ## Definerer et beregnet sæt medlemmer eller tupler ved at sende et sætudtryk til kuben på serveren, som opretter sættet og returnerer det til Microsoft Office Excel.
-CUBESETCOUNT = KUBESÆT.TÆL ## Returnerer antallet af elementer i et sæt.
-CUBEVALUE = KUBEVÆRDI ## Returnerer en sammenlagt (aggregeret) værdi fra en kube.
-
+DAVERAGE = DMIDDEL
+DCOUNT = DTÆL
+DCOUNTA = DTÆLV
+DGET = DHENT
+DMAX = DMAKS
+DMIN = DMIN
+DPRODUCT = DPRODUKT
+DSTDEV = DSTDAFV
+DSTDEVP = DSTDAFVP
+DSUM = DSUM
+DVAR = DVARIANS
+DVARP = DVARIANSP
##
-## Database functions Databasefunktioner
+## Dato- og klokkeslætfunktioner (Date & Time Functions)
##
-DAVERAGE = DMIDDEL ## Returnerer gennemsnittet af markerede databaseposter
-DCOUNT = DTÆL ## Tæller de celler, der indeholder tal, i en database
-DCOUNTA = DTÆLV ## Tæller udfyldte celler i en database
-DGET = DHENT ## Uddrager en enkelt post, der opfylder de angivne kriterier, fra en database
-DMAX = DMAKS ## Returnerer den største værdi blandt markerede databaseposter
-DMIN = DMIN ## Returnerer den mindste værdi blandt markerede databaseposter
-DPRODUCT = DPRODUKT ## Ganger værdierne i et bestemt felt med poster, der opfylder kriterierne i en database
-DSTDEV = DSTDAFV ## Beregner et skøn over standardafvigelsen baseret på en stikprøve af markerede databaseposter
-DSTDEVP = DSTDAFVP ## Beregner standardafvigelsen baseret på hele populationen af markerede databaseposter
-DSUM = DSUM ## Sammenlægger de tal i feltkolonnen i databasen, der opfylder kriterierne
-DVAR = DVARIANS ## Beregner varians baseret på en stikprøve af markerede databaseposter
-DVARP = DVARIANSP ## Beregner varians baseret på hele populationen af markerede databaseposter
-
+DATE = DATO
+DATEDIF = DATO.FORSKEL
+DATESTRING = DATOSTRENG
+DATEVALUE = DATOVÆRDI
+DAY = DAG
+DAYS = DAGE
+DAYS360 = DAGE360
+EDATE = EDATO
+EOMONTH = SLUT.PÅ.MÅNED
+HOUR = TIME
+ISOWEEKNUM = ISOUGE.NR
+MINUTE = MINUT
+MONTH = MÅNED
+NETWORKDAYS = ANTAL.ARBEJDSDAGE
+NETWORKDAYS.INTL = ANTAL.ARBEJDSDAGE.INTL
+NOW = NU
+SECOND = SEKUND
+THAIDAYOFWEEK = THAILANDSKUGEDAG
+THAIMONTHOFYEAR = THAILANDSKMÅNED
+THAIYEAR = THAILANDSKÅR
+TIME = TID
+TIMEVALUE = TIDSVÆRDI
+TODAY = IDAG
+WEEKDAY = UGEDAG
+WEEKNUM = UGE.NR
+WORKDAY = ARBEJDSDAG
+WORKDAY.INTL = ARBEJDSDAG.INTL
+YEAR = ÅR
+YEARFRAC = ÅR.BRØK
##
-## Date and time functions Dato- og klokkeslætsfunktioner
+## Tekniske funktioner (Engineering Functions)
##
-DATE = DATO ## Returnerer serienummeret for en bestemt dato
-DATEVALUE = DATOVÆRDI ## Konverterer en dato i form af tekst til et serienummer
-DAY = DAG ## Konverterer et serienummer til en dag i måneden
-DAYS360 = DAGE360 ## Beregner antallet af dage mellem to datoer på grundlag af et år med 360 dage
-EDATE = EDATO ## Returnerer serienummeret for den dato, der ligger det angivne antal måneder før eller efter startdatoen
-EOMONTH = SLUT.PÅ.MÅNED ## Returnerer serienummeret på den sidste dag i måneden før eller efter et angivet antal måneder
-HOUR = TIME ## Konverterer et serienummer til en time
-MINUTE = MINUT ## Konverterer et serienummer til et minut
-MONTH = MÅNED ## Konverterer et serienummer til en måned
-NETWORKDAYS = ANTAL.ARBEJDSDAGE ## Returnerer antallet af hele arbejdsdage mellem to datoer
-NOW = NU ## Returnerer serienummeret for den aktuelle dato eller det aktuelle klokkeslæt
-SECOND = SEKUND ## Konverterer et serienummer til et sekund
-TIME = KLOKKESLÆT ## Returnerer serienummeret for et bestemt klokkeslæt
-TIMEVALUE = TIDSVÆRDI ## Konverterer et klokkeslæt i form af tekst til et serienummer
-TODAY = IDAG ## Returnerer serienummeret for dags dato
-WEEKDAY = UGEDAG ## Konverterer et serienummer til en ugedag
-WEEKNUM = UGE.NR ## Konverterer et serienummer til et tal, der angiver ugenummeret i året
-WORKDAY = ARBEJDSDAG ## Returnerer serienummeret for dagen før eller efter det angivne antal arbejdsdage
-YEAR = ÅR ## Konverterer et serienummer til et år
-YEARFRAC = ÅR.BRØK ## Returnerer årsbrøken, der repræsenterer antallet af hele dage mellem startdato og slutdato
-
+BESSELI = BESSELI
+BESSELJ = BESSELJ
+BESSELK = BESSELK
+BESSELY = BESSELY
+BIN2DEC = BIN.TIL.DEC
+BIN2HEX = BIN.TIL.HEX
+BIN2OCT = BIN.TIL.OKT
+BITAND = BITOG
+BITLSHIFT = BITLSKIFT
+BITOR = BITELLER
+BITRSHIFT = BITRSKIFT
+BITXOR = BITXELLER
+COMPLEX = KOMPLEKS
+CONVERT = KONVERTER
+DEC2BIN = DEC.TIL.BIN
+DEC2HEX = DEC.TIL.HEX
+DEC2OCT = DEC.TIL.OKT
+DELTA = DELTA
+ERF = FEJLFUNK
+ERF.PRECISE = ERF.PRECISE
+ERFC = FEJLFUNK.KOMP
+ERFC.PRECISE = ERFC.PRECISE
+GESTEP = GETRIN
+HEX2BIN = HEX.TIL.BIN
+HEX2DEC = HEX.TIL.DEC
+HEX2OCT = HEX.TIL.OKT
+IMABS = IMAGABS
+IMAGINARY = IMAGINÆR
+IMARGUMENT = IMAGARGUMENT
+IMCONJUGATE = IMAGKONJUGERE
+IMCOS = IMAGCOS
+IMCOSH = IMAGCOSH
+IMCOT = IMAGCOT
+IMCSC = IMAGCSC
+IMCSCH = IMAGCSCH
+IMDIV = IMAGDIV
+IMEXP = IMAGEKSP
+IMLN = IMAGLN
+IMLOG10 = IMAGLOG10
+IMLOG2 = IMAGLOG2
+IMPOWER = IMAGPOTENS
+IMPRODUCT = IMAGPRODUKT
+IMREAL = IMAGREELT
+IMSEC = IMAGSEC
+IMSECH = IMAGSECH
+IMSIN = IMAGSIN
+IMSINH = IMAGSINH
+IMSQRT = IMAGKVROD
+IMSUB = IMAGSUB
+IMSUM = IMAGSUM
+IMTAN = IMAGTAN
+OCT2BIN = OKT.TIL.BIN
+OCT2DEC = OKT.TIL.DEC
+OCT2HEX = OKT.TIL.HEX
##
-## Engineering functions Tekniske funktioner
+## Finansielle funktioner (Financial Functions)
##
-BESSELI = BESSELI ## Returnerer den modificerede Bessel-funktion In(x)
-BESSELJ = BESSELJ ## Returnerer Bessel-funktionen Jn(x)
-BESSELK = BESSELK ## Returnerer den modificerede Bessel-funktion Kn(x)
-BESSELY = BESSELY ## Returnerer Bessel-funktionen Yn(x)
-BIN2DEC = BIN.TIL.DEC ## Konverterer et binært tal til et decimaltal
-BIN2HEX = BIN.TIL.HEX ## Konverterer et binært tal til et heksadecimalt tal
-BIN2OCT = BIN.TIL.OKT ## Konverterer et binært tal til et oktaltal.
-COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koefficienter til et komplekst tal
-CONVERT = KONVERTER ## Konverterer et tal fra én måleenhed til en anden
-DEC2BIN = DEC.TIL.BIN ## Konverterer et decimaltal til et binært tal
-DEC2HEX = DEC.TIL.HEX ## Konverterer et decimaltal til et heksadecimalt tal
-DEC2OCT = DEC.TIL.OKT ## Konverterer et decimaltal til et oktaltal
-DELTA = DELTA ## Tester, om to værdier er ens
-ERF = FEJLFUNK ## Returner fejlfunktionen
-ERFC = FEJLFUNK.KOMP ## Returnerer den komplementære fejlfunktion
-GESTEP = GETRIN ## Tester, om et tal er større end en grænseværdi
-HEX2BIN = HEX.TIL.BIN ## Konverterer et heksadecimalt tal til et binært tal
-HEX2DEC = HEX.TIL.DEC ## Konverterer et decimaltal til et heksadecimalt tal
-HEX2OCT = HEX.TIL.OKT ## Konverterer et heksadecimalt tal til et oktaltal
-IMABS = IMAGABS ## Returnerer den absolutte værdi (modulus) for et komplekst tal
-IMAGINARY = IMAGINÆR ## Returnerer den imaginære koefficient for et komplekst tal
-IMARGUMENT = IMAGARGUMENT ## Returnerer argumentet theta, en vinkel udtrykt i radianer
-IMCONJUGATE = IMAGKONJUGERE ## Returnerer den komplekse konjugation af et komplekst tal
-IMCOS = IMAGCOS ## Returnerer et komplekst tals cosinus
-IMDIV = IMAGDIV ## Returnerer kvotienten for to komplekse tal
-IMEXP = IMAGEKSP ## Returnerer et komplekst tals eksponentialfunktion
-IMLN = IMAGLN ## Returnerer et komplekst tals naturlige logaritme
-IMLOG10 = IMAGLOG10 ## Returnerer et komplekst tals sædvanlige logaritme (titalslogaritme)
-IMLOG2 = IMAGLOG2 ## Returnerer et komplekst tals sædvanlige logaritme (totalslogaritme)
-IMPOWER = IMAGPOTENS ## Returnerer et komplekst tal opløftet i en heltalspotens
-IMPRODUCT = IMAGPRODUKT ## Returnerer produktet af komplekse tal
-IMREAL = IMAGREELT ## Returnerer den reelle koefficient for et komplekst tal
-IMSIN = IMAGSIN ## Returnerer et komplekst tals sinus
-IMSQRT = IMAGKVROD ## Returnerer et komplekst tals kvadratrod
-IMSUB = IMAGSUB ## Returnerer forskellen mellem to komplekse tal
-IMSUM = IMAGSUM ## Returnerer summen af komplekse tal
-OCT2BIN = OKT.TIL.BIN ## Konverterer et oktaltal til et binært tal
-OCT2DEC = OKT.TIL.DEC ## Konverterer et oktaltal til et decimaltal
-OCT2HEX = OKT.TIL.HEX ## Konverterer et oktaltal til et heksadecimalt tal
-
+ACCRINT = PÅLØBRENTE
+ACCRINTM = PÅLØBRENTE.UDLØB
+AMORDEGRC = AMORDEGRC
+AMORLINC = AMORLINC
+COUPDAYBS = KUPONDAGE.SA
+COUPDAYS = KUPONDAGE.A
+COUPDAYSNC = KUPONDAGE.ANK
+COUPNCD = KUPONDAG.NÆSTE
+COUPNUM = KUPONBETALINGER
+COUPPCD = KUPONDAG.FORRIGE
+CUMIPMT = AKKUM.RENTE
+CUMPRINC = AKKUM.HOVEDSTOL
+DB = DB
+DDB = DSA
+DISC = DISKONTO
+DOLLARDE = KR.DECIMAL
+DOLLARFR = KR.BRØK
+DURATION = VARIGHED
+EFFECT = EFFEKTIV.RENTE
+FV = FV
+FVSCHEDULE = FVTABEL
+INTRATE = RENTEFOD
+IPMT = R.YDELSE
+IRR = IA
+ISPMT = ISPMT
+MDURATION = MVARIGHED
+MIRR = MIA
+NOMINAL = NOMINEL
+NPER = NPER
+NPV = NUTIDSVÆRDI
+ODDFPRICE = ULIGE.KURS.PÅLYDENDE
+ODDFYIELD = ULIGE.FØRSTE.AFKAST
+ODDLPRICE = ULIGE.SIDSTE.KURS
+ODDLYIELD = ULIGE.SIDSTE.AFKAST
+PDURATION = PVARIGHED
+PMT = YDELSE
+PPMT = H.YDELSE
+PRICE = KURS
+PRICEDISC = KURS.DISKONTO
+PRICEMAT = KURS.UDLØB
+PV = NV
+RATE = RENTE
+RECEIVED = MODTAGET.VED.UDLØB
+RRI = RRI
+SLN = LA
+SYD = ÅRSAFSKRIVNING
+TBILLEQ = STATSOBLIGATION
+TBILLPRICE = STATSOBLIGATION.KURS
+TBILLYIELD = STATSOBLIGATION.AFKAST
+VDB = VSA
+XIRR = INTERN.RENTE
+XNPV = NETTO.NUTIDSVÆRDI
+YIELD = AFKAST
+YIELDDISC = AFKAST.DISKONTO
+YIELDMAT = AFKAST.UDLØBSDATO
##
-## Financial functions Finansielle funktioner
+## Informationsfunktioner (Information Functions)
##
-ACCRINT = PÅLØBRENTE ## Returnerer den påløbne rente for et værdipapir med periodiske renteudbetalinger
-ACCRINTM = PÅLØBRENTE.UDLØB ## Returnerer den påløbne rente for et værdipapir, hvor renteudbetalingen finder sted ved papirets udløb
-AMORDEGRC = AMORDEGRC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode ved hjælp af en afskrivningskoefficient
-AMORLINC = AMORLINC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode
-COUPDAYBS = KUPONDAGE.SA ## Returnerer antallet af dage fra starten af kuponperioden til afregningsdatoen
-COUPDAYS = KUPONDAGE.A ## Returnerer antallet af dage fra begyndelsen af kuponperioden til afregningsdatoen
-COUPDAYSNC = KUPONDAGE.ANK ## Returnerer antallet af dage i den kuponperiode, der indeholder afregningsdatoen
-COUPNCD = KUPONDAG.NÆSTE ## Returnerer den næste kupondato efter afregningsdatoen
-COUPNUM = KUPONBETALINGER ## Returnerer antallet af kuponudbetalinger mellem afregnings- og udløbsdatoen
-COUPPCD = KUPONDAG.FORRIGE ## Returnerer den forrige kupondato før afregningsdatoen
-CUMIPMT = AKKUM.RENTE ## Returnerer den akkumulerede rente, der betales på et lån mellem to perioder
-CUMPRINC = AKKUM.HOVEDSTOL ## Returnerer den akkumulerede nedbringelse af hovedstol mellem to perioder
-DB = DB ## Returnerer afskrivningen på et aktiv i en angivet periode ved anvendelse af saldometoden
-DDB = DSA ## Returnerer afskrivningsbeløbet for et aktiv over en bestemt periode ved anvendelse af dobbeltsaldometoden eller en anden afskrivningsmetode, som du angiver
-DISC = DISKONTO ## Returnerer et værdipapirs diskonto
-DOLLARDE = KR.DECIMAL ## Konverterer en kronepris udtrykt som brøk til en kronepris udtrykt som decimaltal
-DOLLARFR = KR.BRØK ## Konverterer en kronepris udtrykt som decimaltal til en kronepris udtrykt som brøk
-DURATION = VARIGHED ## Returnerer den årlige løbetid for et værdipapir med periodiske renteudbetalinger
-EFFECT = EFFEKTIV.RENTE ## Returnerer den årlige effektive rente
-FV = FV ## Returnerer fremtidsværdien af en investering
-FVSCHEDULE = FVTABEL ## Returnerer den fremtidige værdi af en hovedstol, når der er tilskrevet rente og rentes rente efter forskellige rentesatser
-INTRATE = RENTEFOD ## Returnerer renten på et fuldt ud investeret værdipapir
-IPMT = R.YDELSE ## Returnerer renten fra en investering for en given periode
-IRR = IA ## Returnerer den interne rente for en række pengestrømme
-ISPMT = ISPMT ## Beregner den betalte rente i løbet af en bestemt investeringsperiode
-MDURATION = MVARIGHED ## Returnerer Macauleys modificerede løbetid for et værdipapir med en formodet pari på kr. 100
-MIRR = MIA ## Returnerer den interne forrentning, hvor positive og negative pengestrømme finansieres til forskellig rente
-NOMINAL = NOMINEL ## Returnerer den årlige nominelle rente
-NPER = NPER ## Returnerer antallet af perioder for en investering
-NPV = NUTIDSVÆRDI ## Returnerer nettonutidsværdien for en investering baseret på en række periodiske pengestrømme og en diskonteringssats
-ODDFPRICE = ULIGE.KURS.PÅLYDENDE ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med en ulige (kort eller lang) første periode
-ODDFYIELD = ULIGE.FØRSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige første periode
-ODDLPRICE = ULIGE.SIDSTE.KURS ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med ulige sidste periode
-ODDLYIELD = ULIGE.SIDSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige sidste periode
-PMT = YDELSE ## Returnerer renten fra en investering for en given periode
-PPMT = H.YDELSE ## Returnerer ydelsen på hovedstolen for en investering i en given periode
-PRICE = KURS ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir med periodiske renteudbetalinger
-PRICEDISC = KURS.DISKONTO ## Returnerer kursen pr. kr 100 nominel værdi for et diskonteret værdipapir
-PRICEMAT = KURS.UDLØB ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir, hvor renten udbetales ved papirets udløb
-PV = NV ## Returnerer den nuværende værdi af en investering
-RATE = RENTE ## Returnerer renten i hver periode for en annuitet
-RECEIVED = MODTAGET.VED.UDLØB ## Returnerer det beløb, der modtages ved udløbet af et fuldt ud investeret værdipapir
-SLN = LA ## Returnerer den lineære afskrivning for et aktiv i en enkelt periode
-SYD = ÅRSAFSKRIVNING ## Returnerer den årlige afskrivning på et aktiv i en bestemt periode
-TBILLEQ = STATSOBLIGATION ## Returnerer det obligationsækvivalente afkast for en statsobligation
-TBILLPRICE = STATSOBLIGATION.KURS ## Returnerer kursen pr. kr 100 nominel værdi for en statsobligation
-TBILLYIELD = STATSOBLIGATION.AFKAST ## Returnerer en afkastet på en statsobligation
-VDB = VSA ## Returnerer afskrivningen på et aktiv i en angivet periode, herunder delperioder, ved brug af dobbeltsaldometoden
-XIRR = INTERN.RENTE ## Returnerer den interne rente for en plan over pengestrømme, der ikke behøver at være periodiske
-XNPV = NETTO.NUTIDSVÆRDI ## Returnerer nutidsværdien for en plan over pengestrømme, der ikke behøver at være periodiske
-YIELD = AFKAST ## Returnerer afkastet for et værdipapir med periodiske renteudbetalinger
-YIELDDISC = AFKAST.DISKONTO ## Returnerer det årlige afkast for et diskonteret værdipapir, f.eks. en statsobligation
-YIELDMAT = AFKAST.UDLØBSDATO ## Returnerer det årlige afkast for et værdipapir, hvor renten udbetales ved papirets udløb
-
+CELL = CELLE
+ERROR.TYPE = FEJLTYPE
+INFO = INFO
+ISBLANK = ER.TOM
+ISERR = ER.FJL
+ISERROR = ER.FEJL
+ISEVEN = ER.LIGE
+ISFORMULA = ER.FORMEL
+ISLOGICAL = ER.LOGISK
+ISNA = ER.IKKE.TILGÆNGELIG
+ISNONTEXT = ER.IKKE.TEKST
+ISNUMBER = ER.TAL
+ISODD = ER.ULIGE
+ISREF = ER.REFERENCE
+ISTEXT = ER.TEKST
+N = TAL
+NA = IKKE.TILGÆNGELIG
+SHEET = ARK
+SHEETS = ARK.FLERE
+TYPE = VÆRDITYPE
##
-## Information functions Informationsfunktioner
+## Logiske funktioner (Logical Functions)
##
-CELL = CELLE ## Returnerer oplysninger om formatering, placering eller indhold af en celle
-ERROR.TYPE = FEJLTYPE ## Returnerer et tal, der svarer til en fejltype
-INFO = INFO ## Returnerer oplysninger om det aktuelle operativmiljø
-ISBLANK = ER.TOM ## Returnerer SAND, hvis værdien er tom
-ISERR = ER.FJL ## Returnerer SAND, hvis værdien er en fejlværdi undtagen #I/T
-ISERROR = ER.FEJL ## Returnerer SAND, hvis værdien er en fejlværdi
-ISEVEN = ER.LIGE ## Returnerer SAND, hvis tallet er lige
-ISLOGICAL = ER.LOGISK ## Returnerer SAND, hvis værdien er en logisk værdi
-ISNA = ER.IKKE.TILGÆNGELIG ## Returnerer SAND, hvis værdien er fejlværdien #I/T
-ISNONTEXT = ER.IKKE.TEKST ## Returnerer SAND, hvis værdien ikke er tekst
-ISNUMBER = ER.TAL ## Returnerer SAND, hvis værdien er et tal
-ISODD = ER.ULIGE ## Returnerer SAND, hvis tallet er ulige
-ISREF = ER.REFERENCE ## Returnerer SAND, hvis værdien er en reference
-ISTEXT = ER.TEKST ## Returnerer SAND, hvis værdien er tekst
-N = TAL ## Returnerer en værdi konverteret til et tal
-NA = IKKE.TILGÆNGELIG ## Returnerer fejlværdien #I/T
-TYPE = VÆRDITYPE ## Returnerer et tal, der angiver datatypen for en værdi
-
+AND = OG
+FALSE = FALSK
+IF = HVIS
+IFERROR = HVIS.FEJL
+IFNA = HVISIT
+IFS = HVISER
+NOT = IKKE
+OR = ELLER
+SWITCH = SKIFT
+TRUE = SAND
+XOR = XELLER
##
-## Logical functions Logiske funktioner
+## Opslags- og referencefunktioner (Lookup & Reference Functions)
##
-AND = OG ## Returnerer SAND, hvis alle argumenterne er sande
-FALSE = FALSK ## Returnerer den logiske værdi FALSK
-IF = HVIS ## Angiver en logisk test, der skal udføres
-IFERROR = HVIS.FEJL ## Returnerer en værdi, du angiver, hvis en formel evauleres som en fejl. Returnerer i modsat fald resultatet af formlen
-NOT = IKKE ## Vender argumentets logik om
-OR = ELLER ## Returneret værdien SAND, hvis mindst ét argument er sandt
-TRUE = SAND ## Returnerer den logiske værdi SAND
-
+ADDRESS = ADRESSE
+AREAS = OMRÅDER
+CHOOSE = VÆLG
+COLUMN = KOLONNE
+COLUMNS = KOLONNER
+FORMULATEXT = FORMELTEKST
+GETPIVOTDATA = GETPIVOTDATA
+HLOOKUP = VOPSLAG
+HYPERLINK = HYPERLINK
+INDEX = INDEKS
+INDIRECT = INDIREKTE
+LOOKUP = SLÅ.OP
+MATCH = SAMMENLIGN
+OFFSET = FORSKYDNING
+ROW = RÆKKE
+ROWS = RÆKKER
+RTD = RTD
+TRANSPOSE = TRANSPONER
+VLOOKUP = LOPSLAG
##
-## Lookup and reference functions Opslags- og referencefunktioner
+## Matematiske og trigonometriske funktioner (Math & Trig Functions)
##
-ADDRESS = ADRESSE ## Returnerer en reference som tekst til en enkelt celle i et regneark
-AREAS = OMRÅDER ## Returnerer antallet af områder i en reference
-CHOOSE = VÆLG ## Vælger en værdi på en liste med værdier
-COLUMN = KOLONNE ## Returnerer kolonnenummeret i en reference
-COLUMNS = KOLONNER ## Returnerer antallet af kolonner i en reference
-HLOOKUP = VOPSLAG ## Søger i den øverste række af en matrix og returnerer værdien af den angivne celle
-HYPERLINK = HYPERLINK ## Opretter en genvej kaldet et hyperlink, der åbner et dokument, som er lagret på en netværksserver, på et intranet eller på internettet
-INDEX = INDEKS ## Anvender et indeks til at vælge en værdi fra en reference eller en matrix
-INDIRECT = INDIREKTE ## Returnerer en reference, der er angivet af en tekstværdi
-LOOKUP = SLÅ.OP ## Søger værdier i en vektor eller en matrix
-MATCH = SAMMENLIGN ## Søger værdier i en reference eller en matrix
-OFFSET = FORSKYDNING ## Returnerer en reference forskudt i forhold til en given reference
-ROW = RÆKKE ## Returnerer rækkenummeret for en reference
-ROWS = RÆKKER ## Returnerer antallet af rækker i en reference
-RTD = RTD ## Henter realtidsdata fra et program, der understøtter COM-automatisering (Automation: En metode til at arbejde med objekter fra et andet program eller udviklingsværktøj. Automation, som tidligere blev kaldt OLE Automation, er en industristandard og en funktion i COM (Component Object Model).)
-TRANSPOSE = TRANSPONER ## Returnerer en transponeret matrix
-VLOOKUP = LOPSLAG ## Søger i øverste række af en matrix og flytter på tværs af rækken for at returnere en celleværdi
-
+ABS = ABS
+ACOS = ARCCOS
+ACOSH = ARCCOSH
+ACOT = ARCCOT
+ACOTH = ARCCOTH
+AGGREGATE = SAMLING
+ARABIC = ARABISK
+ASIN = ARCSIN
+ASINH = ARCSINH
+ATAN = ARCTAN
+ATAN2 = ARCTAN2
+ATANH = ARCTANH
+BASE = BASIS
+CEILING.MATH = LOFT.MAT
+CEILING.PRECISE = LOFT.PRECISE
+COMBIN = KOMBIN
+COMBINA = KOMBINA
+COS = COS
+COSH = COSH
+COT = COT
+COTH = COTH
+CSC = CSC
+CSCH = CSCH
+DECIMAL = DECIMAL
+DEGREES = GRADER
+ECMA.CEILING = ECMA.LOFT
+EVEN = LIGE
+EXP = EKSP
+FACT = FAKULTET
+FACTDOUBLE = DOBBELT.FAKULTET
+FLOOR.MATH = AFRUND.BUND.MAT
+FLOOR.PRECISE = AFRUND.GULV.PRECISE
+GCD = STØRSTE.FÆLLES.DIVISOR
+INT = HELTAL
+ISO.CEILING = ISO.LOFT
+LCM = MINDSTE.FÆLLES.MULTIPLUM
+LN = LN
+LOG = LOG
+LOG10 = LOG10
+MDETERM = MDETERM
+MINVERSE = MINVERT
+MMULT = MPRODUKT
+MOD = REST
+MROUND = MAFRUND
+MULTINOMIAL = MULTINOMIAL
+MUNIT = MENHED
+ODD = ULIGE
+PI = PI
+POWER = POTENS
+PRODUCT = PRODUKT
+QUOTIENT = KVOTIENT
+RADIANS = RADIANER
+RAND = SLUMP
+RANDBETWEEN = SLUMPMELLEM
+ROMAN = ROMERTAL
+ROUND = AFRUND
+ROUNDBAHTDOWN = RUNDBAHTNED
+ROUNDBAHTUP = RUNDBAHTOP
+ROUNDDOWN = RUND.NED
+ROUNDUP = RUND.OP
+SEC = SEC
+SECH = SECH
+SERIESSUM = SERIESUM
+SIGN = FORTEGN
+SIN = SIN
+SINH = SINH
+SQRT = KVROD
+SQRTPI = KVRODPI
+SUBTOTAL = SUBTOTAL
+SUM = SUM
+SUMIF = SUM.HVIS
+SUMIFS = SUM.HVISER
+SUMPRODUCT = SUMPRODUKT
+SUMSQ = SUMKV
+SUMX2MY2 = SUMX2MY2
+SUMX2PY2 = SUMX2PY2
+SUMXMY2 = SUMXMY2
+TAN = TAN
+TANH = TANH
+TRUNC = AFKORT
##
-## Math and trigonometry functions Matematiske og trigonometriske funktioner
+## Statistiske funktioner (Statistical Functions)
##
-ABS = ABS ## Returnerer den absolutte værdi af et tal
-ACOS = ARCCOS ## Returnerer et tals arcus cosinus
-ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus af tal
-ASIN = ARCSIN ## Returnerer et tals arcus sinus
-ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus for tal
-ATAN = ARCTAN ## Returnerer et tals arcus tangens
-ATAN2 = ARCTAN2 ## Returnerer de angivne x- og y-koordinaters arcus tangens
-ATANH = ARCTANH ## Returnerer et tals inverse hyperbolske tangens
-CEILING = AFRUND.LOFT ## Afrunder et tal til nærmeste heltal eller til nærmeste multiplum af betydning
-COMBIN = KOMBIN ## Returnerer antallet af kombinationer for et givet antal objekter
-COS = COS ## Returnerer et tals cosinus
-COSH = COSH ## Returnerer den inverse hyperbolske cosinus af et tal
-DEGREES = GRADER ## Konverterer radianer til grader
-EVEN = LIGE ## Runder et tal op til nærmeste lige heltal
-EXP = EKSP ## Returnerer e opløftet til en potens af et angivet tal
-FACT = FAKULTET ## Returnerer et tals fakultet
-FACTDOUBLE = DOBBELT.FAKULTET ## Returnerer et tals dobbelte fakultet
-FLOOR = AFRUND.GULV ## Runder et tal ned mod nul
-GCD = STØRSTE.FÆLLES.DIVISOR ## Returnerer den største fælles divisor
-INT = HELTAL ## Nedrunder et tal til det nærmeste heltal
-LCM = MINDSTE.FÆLLES.MULTIPLUM ## Returnerer det mindste fælles multiplum
-LN = LN ## Returnerer et tals naturlige logaritme
-LOG = LOG ## Returnerer logaritmen for et tal på grundlag af et angivet grundtal
-LOG10 = LOG10 ## Returnerer titalslogaritmen af et tal
-MDETERM = MDETERM ## Returnerer determinanten for en matrix
-MINVERSE = MINVERT ## Returnerer den inverse matrix for en matrix
-MMULT = MPRODUKT ## Returnerer matrixproduktet af to matrixer
-MOD = REST ## Returnerer restværdien fra division
-MROUND = MAFRUND ## Returnerer et tal afrundet til det ønskede multiplum
-MULTINOMIAL = MULTINOMIAL ## Returnerer et multinomialt talsæt
-ODD = ULIGE ## Runder et tal op til nærmeste ulige heltal
-PI = PI ## Returnerer værdien af pi
-POWER = POTENS ## Returnerer resultatet af et tal opløftet til en potens
-PRODUCT = PRODUKT ## Multiplicerer argumenterne
-QUOTIENT = KVOTIENT ## Returnerer heltalsdelen ved division
-RADIANS = RADIANER ## Konverterer grader til radianer
-RAND = SLUMP ## Returnerer et tilfældigt tal mellem 0 og 1
-RANDBETWEEN = SLUMP.MELLEM ## Returnerer et tilfældigt tal mellem de tal, der angives
-ROMAN = ROMERTAL ## Konverterer et arabertal til romertal som tekst
-ROUND = AFRUND ## Afrunder et tal til et angivet antal decimaler
-ROUNDDOWN = RUND.NED ## Runder et tal ned mod nul
-ROUNDUP = RUND.OP ## Runder et tal op, væk fra 0 (nul)
-SERIESSUM = SERIESUM ## Returnerer summen af en potensserie baseret på en formel
-SIGN = FORTEGN ## Returnerer et tals fortegn
-SIN = SIN ## Returnerer en given vinkels sinusværdi
-SINH = SINH ## Returnerer den hyperbolske sinus af et tal
-SQRT = KVROD ## Returnerer en positiv kvadratrod
-SQRTPI = KVRODPI ## Returnerer kvadratroden af (tal * pi;)
-SUBTOTAL = SUBTOTAL ## Returnerer en subtotal på en liste eller i en database
-SUM = SUM ## Lægger argumenterne sammen
-SUMIF = SUM.HVIS ## Lægger de celler sammen, der er specificeret af et givet kriterium.
-SUMIFS = SUM.HVISER ## Lægger de celler i et område sammen, der opfylder flere kriterier.
-SUMPRODUCT = SUMPRODUKT ## Returnerer summen af produkter af ens matrixkomponenter
-SUMSQ = SUMKV ## Returnerer summen af argumenternes kvadrater
-SUMX2MY2 = SUMX2MY2 ## Returnerer summen af differensen mellem kvadrater af ens værdier i to matrixer
-SUMX2PY2 = SUMX2PY2 ## Returnerer summen af summen af kvadrater af tilsvarende værdier i to matrixer
-SUMXMY2 = SUMXMY2 ## Returnerer summen af kvadrater af differenser mellem ens værdier i to matrixer
-TAN = TAN ## Returnerer et tals tangens
-TANH = TANH ## Returnerer et tals hyperbolske tangens
-TRUNC = AFKORT ## Afkorter et tal til et heltal
-
+AVEDEV = MAD
+AVERAGE = MIDDEL
+AVERAGEA = MIDDELV
+AVERAGEIF = MIDDEL.HVIS
+AVERAGEIFS = MIDDEL.HVISER
+BETA.DIST = BETA.FORDELING
+BETA.INV = BETA.INV
+BINOM.DIST = BINOMIAL.FORDELING
+BINOM.DIST.RANGE = BINOMIAL.DIST.INTERVAL
+BINOM.INV = BINOMIAL.INV
+CHISQ.DIST = CHI2.FORDELING
+CHISQ.DIST.RT = CHI2.FORD.RT
+CHISQ.INV = CHI2.INV
+CHISQ.INV.RT = CHI2.INV.RT
+CHISQ.TEST = CHI2.TEST
+CONFIDENCE.NORM = KONFIDENS.NORM
+CONFIDENCE.T = KONFIDENST
+CORREL = KORRELATION
+COUNT = TÆL
+COUNTA = TÆLV
+COUNTBLANK = ANTAL.BLANKE
+COUNTIF = TÆL.HVIS
+COUNTIFS = TÆL.HVISER
+COVARIANCE.P = KOVARIANS.P
+COVARIANCE.S = KOVARIANS.S
+DEVSQ = SAK
+EXPON.DIST = EKSP.FORDELING
+F.DIST = F.FORDELING
+F.DIST.RT = F.FORDELING.RT
+F.INV = F.INV
+F.INV.RT = F.INV.RT
+F.TEST = F.TEST
+FISHER = FISHER
+FISHERINV = FISHERINV
+FORECAST.ETS = PROGNOSE.ETS
+FORECAST.ETS.CONFINT = PROGNOSE.ETS.CONFINT
+FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SÆSONUDSVING
+FORECAST.ETS.STAT = PROGNOSE.ETS.STAT
+FORECAST.LINEAR = PROGNOSE.LINEÆR
+FREQUENCY = FREKVENS
+GAMMA = GAMMA
+GAMMA.DIST = GAMMA.FORDELING
+GAMMA.INV = GAMMA.INV
+GAMMALN = GAMMALN
+GAMMALN.PRECISE = GAMMALN.PRECISE
+GAUSS = GAUSS
+GEOMEAN = GEOMIDDELVÆRDI
+GROWTH = FORØGELSE
+HARMEAN = HARMIDDELVÆRDI
+HYPGEOM.DIST = HYPGEO.FORDELING
+INTERCEPT = SKÆRING
+KURT = TOPSTEJL
+LARGE = STØRSTE
+LINEST = LINREGR
+LOGEST = LOGREGR
+LOGNORM.DIST = LOGNORM.FORDELING
+LOGNORM.INV = LOGNORM.INV
+MAX = MAKS
+MAXA = MAKSV
+MAXIFS = MAKSHVISER
+MEDIAN = MEDIAN
+MIN = MIN
+MINA = MINV
+MINIFS = MINHVISER
+MODE.MULT = HYPPIGST.FLERE
+MODE.SNGL = HYPPIGST.ENKELT
+NEGBINOM.DIST = NEGBINOM.FORDELING
+NORM.DIST = NORMAL.FORDELING
+NORM.INV = NORM.INV
+NORM.S.DIST = STANDARD.NORM.FORDELING
+NORM.S.INV = STANDARD.NORM.INV
+PEARSON = PEARSON
+PERCENTILE.EXC = FRAKTIL.UDELAD
+PERCENTILE.INC = FRAKTIL.MEDTAG
+PERCENTRANK.EXC = PROCENTPLADS.UDELAD
+PERCENTRANK.INC = PROCENTPLADS.MEDTAG
+PERMUT = PERMUT
+PERMUTATIONA = PERMUTATIONA
+PHI = PHI
+POISSON.DIST = POISSON.FORDELING
+PROB = SANDSYNLIGHED
+QUARTILE.EXC = KVARTIL.UDELAD
+QUARTILE.INC = KVARTIL.MEDTAG
+RANK.AVG = PLADS.GNSN
+RANK.EQ = PLADS.LIGE
+RSQ = FORKLARINGSGRAD
+SKEW = SKÆVHED
+SKEW.P = SKÆVHED.P
+SLOPE = STIGNING
+SMALL = MINDSTE
+STANDARDIZE = STANDARDISER
+STDEV.P = STDAFV.P
+STDEV.S = STDAFV.S
+STDEVA = STDAFVV
+STDEVPA = STDAFVPV
+STEYX = STFYX
+T.DIST = T.FORDELING
+T.DIST.2T = T.FORDELING.2T
+T.DIST.RT = T.FORDELING.RT
+T.INV = T.INV
+T.INV.2T = T.INV.2T
+T.TEST = T.TEST
+TREND = TENDENS
+TRIMMEAN = TRIMMIDDELVÆRDI
+VAR.P = VARIANS.P
+VAR.S = VARIANS.S
+VARA = VARIANSV
+VARPA = VARIANSPV
+WEIBULL.DIST = WEIBULL.FORDELING
+Z.TEST = Z.TEST
##
-## Statistical functions Statistiske funktioner
+## Tekstfunktioner (Text Functions)
##
-AVEDEV = MAD ## Returnerer den gennemsnitlige numeriske afvigelse fra stikprøvens middelværdi
-AVERAGE = MIDDEL ## Returnerer middelværdien af argumenterne
-AVERAGEA = MIDDELV ## Returnerer middelværdien af argumenterne og medtager tal, tekst og logiske værdier
-AVERAGEIF = MIDDEL.HVIS ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder et givet kriterium, i et område
-AVERAGEIFS = MIDDEL.HVISER ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder flere kriterier.
-BETADIST = BETAFORDELING ## Returnerer den kumulative betafordelingsfunktion
-BETAINV = BETAINV ## Returnerer den inverse kumulative fordelingsfunktion for en angivet betafordeling
-BINOMDIST = BINOMIALFORDELING ## Returnerer punktsandsynligheden for binomialfordelingen
-CHIDIST = CHIFORDELING ## Returnerer fraktilsandsynligheden for en chi2-fordeling
-CHIINV = CHIINV ## Returnerer den inverse fraktilsandsynlighed for en chi2-fordeling
-CHITEST = CHITEST ## Foretager en test for uafhængighed
-CONFIDENCE = KONFIDENSINTERVAL ## Returnerer et konfidensinterval for en population
-CORREL = KORRELATION ## Returnerer korrelationskoefficienten mellem to datasæt
-COUNT = TÆL ## Tæller antallet af tal på en liste med argumenter
-COUNTA = TÆLV ## Tæller antallet af værdier på en liste med argumenter
-COUNTBLANK = ANTAL.BLANKE ## Tæller antallet af tomme celler i et område
-COUNTIF = TÆLHVIS ## Tæller antallet af celler, som opfylder de givne kriterier, i et område
-COUNTIFS = TÆL.HVISER ## Tæller antallet af de celler, som opfylder flere kriterier, i et område
-COVAR = KOVARIANS ## Beregner kovariansen mellem to stokastiske variabler
-CRITBINOM = KRITBINOM ## Returnerer den mindste værdi for x, for hvilken det gælder, at fordelingsfunktionen er mindre end eller lig med kriterieværdien.
-DEVSQ = SAK ## Returnerer summen af de kvadrerede afvigelser fra middelværdien
-EXPONDIST = EKSPFORDELING ## Returnerer eksponentialfordelingen
-FDIST = FFORDELING ## Returnerer fraktilsandsynligheden for F-fordelingen
-FINV = FINV ## Returnerer den inverse fraktilsandsynlighed for F-fordelingen
-FISHER = FISHER ## Returnerer Fisher-transformationen
-FISHERINV = FISHERINV ## Returnerer den inverse Fisher-transformation
-FORECAST = PROGNOSE ## Returnerer en prognoseværdi baseret på lineær tendens
-FREQUENCY = FREKVENS ## Returnerer en frekvensfordeling i en søjlevektor
-FTEST = FTEST ## Returnerer resultatet af en F-test til sammenligning af varians
-GAMMADIST = GAMMAFORDELING ## Returnerer fordelingsfunktionen for gammafordelingen
-GAMMAINV = GAMMAINV ## Returnerer den inverse fordelingsfunktion for gammafordelingen
-GAMMALN = GAMMALN ## Returnerer den naturlige logaritme til gammafordelingen, G(x)
-GEOMEAN = GEOMIDDELVÆRDI ## Returnerer det geometriske gennemsnit
-GROWTH = FORØGELSE ## Returnerer værdier langs en eksponentiel tendens
-HARMEAN = HARMIDDELVÆRDI ## Returnerer det harmoniske gennemsnit
-HYPGEOMDIST = HYPGEOFORDELING ## Returnerer punktsandsynligheden i en hypergeometrisk fordeling
-INTERCEPT = SKÆRING ## Returnerer afskæringsværdien på y-aksen i en lineær regression
-KURT = TOPSTEJL ## Returnerer kurtosisværdien for en stokastisk variabel
-LARGE = STOR ## Returnerer den k'te største værdi i et datasæt
-LINEST = LINREGR ## Returnerer parameterestimaterne for en lineær tendens
-LOGEST = LOGREGR ## Returnerer parameterestimaterne for en eksponentiel tendens
-LOGINV = LOGINV ## Returnerer den inverse fordelingsfunktion for lognormalfordelingen
-LOGNORMDIST = LOGNORMFORDELING ## Returnerer fordelingsfunktionen for lognormalfordelingen
-MAX = MAKS ## Returnerer den maksimale værdi på en liste med argumenter.
-MAXA = MAKSV ## Returnerer den maksimale værdi på en liste med argumenter og medtager tal, tekst og logiske værdier
-MEDIAN = MEDIAN ## Returnerer medianen for de angivne tal
-MIN = MIN ## Returnerer den mindste værdi på en liste med argumenter.
-MINA = MINV ## Returnerer den mindste værdi på en liste med argumenter og medtager tal, tekst og logiske værdier
-MODE = HYPPIGST ## Returnerer den hyppigste værdi i et datasæt
-NEGBINOMDIST = NEGBINOMFORDELING ## Returnerer den negative binomialfordeling
-NORMDIST = NORMFORDELING ## Returnerer fordelingsfunktionen for normalfordelingen
-NORMINV = NORMINV ## Returnerer den inverse fordelingsfunktion for normalfordelingen
-NORMSDIST = STANDARDNORMFORDELING ## Returnerer fordelingsfunktionen for standardnormalfordelingen
-NORMSINV = STANDARDNORMINV ## Returnerer den inverse fordelingsfunktion for standardnormalfordelingen
-PEARSON = PEARSON ## Returnerer Pearsons korrelationskoefficient
-PERCENTILE = FRAKTIL ## Returnerer den k'te fraktil for datasættet
-PERCENTRANK = PROCENTPLADS ## Returnerer den procentuelle rang for en given værdi i et datasæt
-PERMUT = PERMUT ## Returnerer antallet af permutationer for et givet sæt objekter
-POISSON = POISSON ## Returnerer fordelingsfunktionen for en Poisson-fordeling
-PROB = SANDSYNLIGHED ## Returnerer intervalsandsynligheden
-QUARTILE = KVARTIL ## Returnerer kvartilen i et givet datasæt
-RANK = PLADS ## Returnerer rangen for et tal på en liste med tal
-RSQ = FORKLARINGSGRAD ## Returnerer R2-værdien fra en simpel lineær regression
-SKEW = SKÆVHED ## Returnerer skævheden for en stokastisk variabel
-SLOPE = HÆLDNING ## Returnerer estimatet på hældningen fra en simpel lineær regression
-SMALL = MINDSTE ## Returnerer den k'te mindste værdi i datasættet
-STANDARDIZE = STANDARDISER ## Returnerer en standardiseret værdi
-STDEV = STDAFV ## Estimerer standardafvigelsen på basis af en stikprøve
-STDEVA = STDAFVV ## Beregner standardafvigelsen på basis af en prøve og medtager tal, tekst og logiske værdier
-STDEVP = STDAFVP ## Beregner standardafvigelsen på basis af en hel population
-STDEVPA = STDAFVPV ## Beregner standardafvigelsen på basis af en hel population og medtager tal, tekst og logiske værdier
-STEYX = STFYX ## Returnerer standardafvigelsen for de estimerede y-værdier i den simple lineære regression
-TDIST = TFORDELING ## Returnerer fordelingsfunktionen for Student's t-fordeling
-TINV = TINV ## Returnerer den inverse fordelingsfunktion for Student's t-fordeling
-TREND = TENDENS ## Returnerer værdi under antagelse af en lineær tendens
-TRIMMEAN = TRIMMIDDELVÆRDI ## Returnerer den trimmede middelværdi for datasættet
-TTEST = TTEST ## Returnerer den sandsynlighed, der er forbundet med Student's t-test
-VAR = VARIANS ## Beregner variansen på basis af en prøve
-VARA = VARIANSV ## Beregner variansen på basis af en prøve og medtager tal, tekst og logiske værdier
-VARP = VARIANSP ## Beregner variansen på basis af hele populationen
-VARPA = VARIANSPV ## Beregner variansen på basis af hele populationen og medtager tal, tekst og logiske værdier
-WEIBULL = WEIBULL ## Returnerer fordelingsfunktionen for Weibull-fordelingen
-ZTEST = ZTEST ## Returnerer sandsynlighedsværdien ved en en-sidet z-test
-
+BAHTTEXT = BAHTTEKST
+CHAR = TEGN
+CLEAN = RENS
+CODE = KODE
+CONCAT = CONCAT
+DOLLAR = KR
+EXACT = EKSAKT
+FIND = FIND
+FIXED = FAST
+ISTHAIDIGIT = ERTHAILANDSKCIFFER
+LEFT = VENSTRE
+LEN = LÆNGDE
+LOWER = SMÅ.BOGSTAVER
+MID = MIDT
+NUMBERSTRING = TALSTRENG
+NUMBERVALUE = TALVÆRDI
+PHONETIC = FONETISK
+PROPER = STORT.FORBOGSTAV
+REPLACE = ERSTAT
+REPT = GENTAG
+RIGHT = HØJRE
+SEARCH = SØG
+SUBSTITUTE = UDSKIFT
+T = T
+TEXT = TEKST
+TEXTJOIN = TEKST.KOMBINER
+THAIDIGIT = THAILANDSKCIFFER
+THAINUMSOUND = THAILANDSKNUMLYD
+THAINUMSTRING = THAILANDSKNUMSTRENG
+THAISTRINGLENGTH = THAILANDSKSTRENGLÆNGDE
+TRIM = FJERN.OVERFLØDIGE.BLANKE
+UNICHAR = UNICHAR
+UNICODE = UNICODE
+UPPER = STORE.BOGSTAVER
+VALUE = VÆRDI
##
-## Text functions Tekstfunktioner
+## Webfunktioner (Web Functions)
##
-ASC = ASC ## Ændrer engelske tegn i fuld bredde (dobbelt-byte) eller katakana i en tegnstreng til tegn i halv bredde (enkelt-byte)
-BAHTTEXT = BAHTTEKST ## Konverterer et tal til tekst ved hjælp af valutaformatet ß (baht)
-CHAR = TEGN ## Returnerer det tegn, der svarer til kodenummeret
-CLEAN = RENS ## Fjerner alle tegn, der ikke kan udskrives, fra tekst
-CODE = KODE ## Returnerer en numerisk kode for det første tegn i en tekststreng
-CONCATENATE = SAMMENKÆDNING ## Sammenkæder adskillige tekstelementer til ét tekstelement
-DOLLAR = KR ## Konverterer et tal til tekst ved hjælp af valutaformatet kr. (kroner)
-EXACT = EKSAKT ## Kontrollerer, om to tekstværdier er identiske
-FIND = FIND ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver)
-FINDB = FINDB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver)
-FIXED = FAST ## Formaterer et tal som tekst med et fast antal decimaler
-JIS = JIS ## Ændrer engelske tegn i halv bredde (enkelt-byte) eller katakana i en tegnstreng til tegn i fuld bredde (dobbelt-byte)
-LEFT = VENSTRE ## Returnerer tegnet længst til venstre i en tekstværdi
-LEFTB = VENSTREB ## Returnerer tegnet længst til venstre i en tekstværdi
-LEN = LÆNGDE ## Returnerer antallet af tegn i en tekststreng
-LENB = LÆNGDEB ## Returnerer antallet af tegn i en tekststreng
-LOWER = SMÅ.BOGSTAVER ## Konverterer tekst til små bogstaver
-MID = MIDT ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition
-MIDB = MIDTB ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition
-PHONETIC = FONETISK ## Uddrager de fonetiske (furigana) tegn fra en tekststreng
-PROPER = STORT.FORBOGSTAV ## Konverterer første bogstav i hvert ord i teksten til stort bogstav
-REPLACE = ERSTAT ## Erstatter tegn i tekst
-REPLACEB = ERSTATB ## Erstatter tegn i tekst
-REPT = GENTAG ## Gentager tekst et givet antal gange
-RIGHT = HØJRE ## Returnerer tegnet længste til højre i en tekstværdi
-RIGHTB = HØJREB ## Returnerer tegnet længste til højre i en tekstværdi
-SEARCH = SØG ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver)
-SEARCHB = SØGB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver)
-SUBSTITUTE = UDSKIFT ## Udskifter gammel tekst med ny tekst i en tekststreng
-T = T ## Konverterer argumenterne til tekst
-TEXT = TEKST ## Formaterer et tal og konverterer det til tekst
-TRIM = FJERN.OVERFLØDIGE.BLANKE ## Fjerner mellemrum fra tekst
-UPPER = STORE.BOGSTAVER ## Konverterer tekst til store bogstaver
-VALUE = VÆRDI ## Konverterer et tekstargument til et tal
+ENCODEURL = KODNINGSURL
+FILTERXML = FILTRERXML
+WEBSERVICE = WEBTJENESTE
+
+##
+## Kompatibilitetsfunktioner (Compatibility Functions)
+##
+BETADIST = BETAFORDELING
+BETAINV = BETAINV
+BINOMDIST = BINOMIALFORDELING
+CEILING = AFRUND.LOFT
+CHIDIST = CHIFORDELING
+CHIINV = CHIINV
+CHITEST = CHITEST
+CONCATENATE = SAMMENKÆDNING
+CONFIDENCE = KONFIDENSINTERVAL
+COVAR = KOVARIANS
+CRITBINOM = KRITBINOM
+EXPONDIST = EKSPFORDELING
+FDIST = FFORDELING
+FINV = FINV
+FLOOR = AFRUND.GULV
+FORECAST = PROGNOSE
+FTEST = FTEST
+GAMMADIST = GAMMAFORDELING
+GAMMAINV = GAMMAINV
+HYPGEOMDIST = HYPGEOFORDELING
+LOGINV = LOGINV
+LOGNORMDIST = LOGNORMFORDELING
+MODE = HYPPIGST
+NEGBINOMDIST = NEGBINOMFORDELING
+NORMDIST = NORMFORDELING
+NORMINV = NORMINV
+NORMSDIST = STANDARDNORMFORDELING
+NORMSINV = STANDARDNORMINV
+PERCENTILE = FRAKTIL
+PERCENTRANK = PROCENTPLADS
+POISSON = POISSON
+QUARTILE = KVARTIL
+RANK = PLADS
+STDEV = STDAFV
+STDEVP = STDAFVP
+TDIST = TFORDELING
+TINV = TINV
+TTEST = TTEST
+VAR = VARIANS
+VARP = VARIANSP
+WEIBULL = WEIBULL
+ZTEST = ZTEST
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/config
index 9751c4b6b41..4ca2b82b538 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Deutsch (German)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = €
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #NULL!
-DIV0 = #DIV/0!
-VALUE = #WERT!
-REF = #BEZUG!
-NAME = #NAME?
-NUM = #ZAHL!
-NA = #NV
+NULL
+DIV0
+VALUE = #WERT!
+REF = #BEZUG!
+NAME
+NUM = #ZAHL!
+NA = #NV
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/functions
index 01df42f6412..331232f7e59 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/functions
@@ -1,416 +1,533 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
+## PhpSpreadsheet - function name translations
##
+## Deutsch (German)
##
+############################################################
##
-## Add-in and Automation functions Add-In- und Automatisierungsfunktionen
+## Cubefunktionen (Cube Functions)
##
-GETPIVOTDATA = PIVOTDATENZUORDNEN ## In einem PivotTable-Bericht gespeicherte Daten werden zurückgegeben.
-
+CUBEKPIMEMBER = CUBEKPIELEMENT
+CUBEMEMBER = CUBEELEMENT
+CUBEMEMBERPROPERTY = CUBEELEMENTEIGENSCHAFT
+CUBERANKEDMEMBER = CUBERANGELEMENT
+CUBESET = CUBEMENGE
+CUBESETCOUNT = CUBEMENGENANZAHL
+CUBEVALUE = CUBEWERT
##
-## Cube functions Cubefunktionen
+## Datenbankfunktionen (Database Functions)
##
-CUBEKPIMEMBER = CUBEKPIELEMENT ## Gibt Name, Eigenschaft und Measure eines Key Performance Indicators (KPI) zurück und zeigt den Namen und die Eigenschaft in der Zelle an. Ein KPI ist ein quantifizierbares Maß, wie z. B. der monatliche Bruttogewinn oder die vierteljährliche Mitarbeiterfluktuation, mit dessen Hilfe das Leistungsverhalten eines Unternehmens überwacht werden kann.
-CUBEMEMBER = CUBEELEMENT ## Gibt ein Element oder ein Tuple in einer Cubehierarchie zurück. Wird verwendet, um zu überprüfen, ob das Element oder Tuple im Cube vorhanden ist.
-CUBEMEMBERPROPERTY = CUBEELEMENTEIGENSCHAFT ## Gibt den Wert einer Elementeigenschaft im Cube zurück. Wird verwendet, um zu überprüfen, ob ein Elementname im Cube vorhanden ist, und um die für dieses Element angegebene Eigenschaft zurückzugeben.
-CUBERANKEDMEMBER = CUBERANGELEMENT ## Gibt das n-te oder n-rangige Element in einer Menge zurück. Wird verwendet, um mindestens ein Element in einer Menge zurückzugeben, wie z. B. bester Vertriebsmitarbeiter oder 10 beste Kursteilnehmer.
-CUBESET = CUBEMENGE ## Definiert eine berechnete Menge Elemente oder Tuples durch Senden eines Mengenausdrucks an den Cube auf dem Server, der die Menge erstellt und an Microsoft Office Excel zurückgibt.
-CUBESETCOUNT = CUBEMENGENANZAHL ## Gibt die Anzahl der Elemente in einer Menge zurück.
-CUBEVALUE = CUBEWERT ## Gibt einen Aggregatwert aus einem Cube zurück.
-
+DAVERAGE = DBMITTELWERT
+DCOUNT = DBANZAHL
+DCOUNTA = DBANZAHL2
+DGET = DBAUSZUG
+DMAX = DBMAX
+DMIN = DBMIN
+DPRODUCT = DBPRODUKT
+DSTDEV = DBSTDABW
+DSTDEVP = DBSTDABWN
+DSUM = DBSUMME
+DVAR = DBVARIANZ
+DVARP = DBVARIANZEN
##
-## Database functions Datenbankfunktionen
+## Datums- und Uhrzeitfunktionen (Date & Time Functions)
##
-DAVERAGE = DBMITTELWERT ## Gibt den Mittelwert der ausgewählten Datenbankeinträge zurück
-DCOUNT = DBANZAHL ## Zählt die Zellen mit Zahlen in einer Datenbank
-DCOUNTA = DBANZAHL2 ## Zählt nicht leere Zellen in einer Datenbank
-DGET = DBAUSZUG ## Extrahiert aus einer Datenbank einen einzelnen Datensatz, der den angegebenen Kriterien entspricht
-DMAX = DBMAX ## Gibt den größten Wert aus ausgewählten Datenbankeinträgen zurück
-DMIN = DBMIN ## Gibt den kleinsten Wert aus ausgewählten Datenbankeinträgen zurück
-DPRODUCT = DBPRODUKT ## Multipliziert die Werte in einem bestimmten Feld mit Datensätzen, die den Kriterien in einer Datenbank entsprechen
-DSTDEV = DBSTDABW ## Schätzt die Standardabweichung auf der Grundlage einer Stichprobe aus ausgewählten Datenbankeinträgen
-DSTDEVP = DBSTDABWN ## Berechnet die Standardabweichung auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge
-DSUM = DBSUMME ## Addiert die Zahlen in der Feldspalte mit Datensätzen in der Datenbank, die den Kriterien entsprechen
-DVAR = DBVARIANZ ## Schätzt die Varianz auf der Grundlage ausgewählter Datenbankeinträge
-DVARP = DBVARIANZEN ## Berechnet die Varianz auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge
-
+DATE = DATUM
+DATEVALUE = DATWERT
+DAY = TAG
+DAYS = TAGE
+DAYS360 = TAGE360
+EDATE = EDATUM
+EOMONTH = MONATSENDE
+HOUR = STUNDE
+ISOWEEKNUM = ISOKALENDERWOCHE
+MINUTE = MINUTE
+MONTH = MONAT
+NETWORKDAYS = NETTOARBEITSTAGE
+NETWORKDAYS.INTL = NETTOARBEITSTAGE.INTL
+NOW = JETZT
+SECOND = SEKUNDE
+THAIDAYOFWEEK = THAIWOCHENTAG
+THAIMONTHOFYEAR = THAIMONATDESJAHRES
+THAIYEAR = THAIJAHR
+TIME = ZEIT
+TIMEVALUE = ZEITWERT
+TODAY = HEUTE
+WEEKDAY = WOCHENTAG
+WEEKNUM = KALENDERWOCHE
+WORKDAY = ARBEITSTAG
+WORKDAY.INTL = ARBEITSTAG.INTL
+YEAR = JAHR
+YEARFRAC = BRTEILJAHRE
##
-## Date and time functions Datums- und Zeitfunktionen
+## Technische Funktionen (Engineering Functions)
##
-DATE = DATUM ## Gibt die fortlaufende Zahl eines bestimmten Datums zurück
-DATEVALUE = DATWERT ## Wandelt ein Datum in Form von Text in eine fortlaufende Zahl um
-DAY = TAG ## Wandelt eine fortlaufende Zahl in den Tag des Monats um
-DAYS360 = TAGE360 ## Berechnet die Anzahl der Tage zwischen zwei Datumsangaben ausgehend von einem Jahr, das 360 Tage hat
-EDATE = EDATUM ## Gibt die fortlaufende Zahl des Datums zurück, bei dem es sich um die angegebene Anzahl von Monaten vor oder nach dem Anfangstermin handelt
-EOMONTH = MONATSENDE ## Gibt die fortlaufende Zahl des letzten Tags des Monats vor oder nach einer festgelegten Anzahl von Monaten zurück
-HOUR = STUNDE ## Wandelt eine fortlaufende Zahl in eine Stunde um
-MINUTE = MINUTE ## Wandelt eine fortlaufende Zahl in eine Minute um
-MONTH = MONAT ## Wandelt eine fortlaufende Zahl in einen Monat um
-NETWORKDAYS = NETTOARBEITSTAGE ## Gibt die Anzahl von ganzen Arbeitstagen zwischen zwei Datumswerten zurück
-NOW = JETZT ## Gibt die fortlaufende Zahl des aktuellen Datums und der aktuellen Uhrzeit zurück
-SECOND = SEKUNDE ## Wandelt eine fortlaufende Zahl in eine Sekunde um
-TIME = ZEIT ## Gibt die fortlaufende Zahl einer bestimmten Uhrzeit zurück
-TIMEVALUE = ZEITWERT ## Wandelt eine Uhrzeit in Form von Text in eine fortlaufende Zahl um
-TODAY = HEUTE ## Gibt die fortlaufende Zahl des heutigen Datums zurück
-WEEKDAY = WOCHENTAG ## Wandelt eine fortlaufende Zahl in den Wochentag um
-WEEKNUM = KALENDERWOCHE ## Wandelt eine fortlaufende Zahl in eine Zahl um, die angibt, in welche Woche eines Jahres das angegebene Datum fällt
-WORKDAY = ARBEITSTAG ## Gibt die fortlaufende Zahl des Datums vor oder nach einer bestimmten Anzahl von Arbeitstagen zurück
-YEAR = JAHR ## Wandelt eine fortlaufende Zahl in ein Jahr um
-YEARFRAC = BRTEILJAHRE ## Gibt die Anzahl der ganzen Tage zwischen Ausgangsdatum und Enddatum in Bruchteilen von Jahren zurück
-
+BESSELI = BESSELI
+BESSELJ = BESSELJ
+BESSELK = BESSELK
+BESSELY = BESSELY
+BIN2DEC = BININDEZ
+BIN2HEX = BININHEX
+BIN2OCT = BININOKT
+BITAND = BITUND
+BITLSHIFT = BITLVERSCHIEB
+BITOR = BITODER
+BITRSHIFT = BITRVERSCHIEB
+BITXOR = BITXODER
+COMPLEX = KOMPLEXE
+CONVERT = UMWANDELN
+DEC2BIN = DEZINBIN
+DEC2HEX = DEZINHEX
+DEC2OCT = DEZINOKT
+DELTA = DELTA
+ERF = GAUSSFEHLER
+ERF.PRECISE = GAUSSF.GENAU
+ERFC = GAUSSFKOMPL
+ERFC.PRECISE = GAUSSFKOMPL.GENAU
+GESTEP = GGANZZAHL
+HEX2BIN = HEXINBIN
+HEX2DEC = HEXINDEZ
+HEX2OCT = HEXINOKT
+IMABS = IMABS
+IMAGINARY = IMAGINÄRTEIL
+IMARGUMENT = IMARGUMENT
+IMCONJUGATE = IMKONJUGIERTE
+IMCOS = IMCOS
+IMCOSH = IMCOSHYP
+IMCOT = IMCOT
+IMCSC = IMCOSEC
+IMCSCH = IMCOSECHYP
+IMDIV = IMDIV
+IMEXP = IMEXP
+IMLN = IMLN
+IMLOG10 = IMLOG10
+IMLOG2 = IMLOG2
+IMPOWER = IMAPOTENZ
+IMPRODUCT = IMPRODUKT
+IMREAL = IMREALTEIL
+IMSEC = IMSEC
+IMSECH = IMSECHYP
+IMSIN = IMSIN
+IMSINH = IMSINHYP
+IMSQRT = IMWURZEL
+IMSUB = IMSUB
+IMSUM = IMSUMME
+IMTAN = IMTAN
+OCT2BIN = OKTINBIN
+OCT2DEC = OKTINDEZ
+OCT2HEX = OKTINHEX
##
-## Engineering functions Konstruktionsfunktionen
+## Finanzmathematische Funktionen (Financial Functions)
##
-BESSELI = BESSELI ## Gibt die geänderte Besselfunktion In(x) zurück
-BESSELJ = BESSELJ ## Gibt die Besselfunktion Jn(x) zurück
-BESSELK = BESSELK ## Gibt die geänderte Besselfunktion Kn(x) zurück
-BESSELY = BESSELY ## Gibt die Besselfunktion Yn(x) zurück
-BIN2DEC = BININDEZ ## Wandelt eine binäre Zahl (Dualzahl) in eine dezimale Zahl um
-BIN2HEX = BININHEX ## Wandelt eine binäre Zahl (Dualzahl) in eine hexadezimale Zahl um
-BIN2OCT = BININOKT ## Wandelt eine binäre Zahl (Dualzahl) in eine oktale Zahl um
-COMPLEX = KOMPLEXE ## Wandelt den Real- und Imaginärteil in eine komplexe Zahl um
-CONVERT = UMWANDELN ## Wandelt eine Zahl von einem Maßsystem in ein anderes um
-DEC2BIN = DEZINBIN ## Wandelt eine dezimale Zahl in eine binäre Zahl (Dualzahl) um
-DEC2HEX = DEZINHEX ## Wandelt eine dezimale Zahl in eine hexadezimale Zahl um
-DEC2OCT = DEZINOKT ## Wandelt eine dezimale Zahl in eine oktale Zahl um
-DELTA = DELTA ## Überprüft, ob zwei Werte gleich sind
-ERF = GAUSSFEHLER ## Gibt die Gauss'sche Fehlerfunktion zurück
-ERFC = GAUSSFKOMPL ## Gibt das Komplement zur Gauss'schen Fehlerfunktion zurück
-GESTEP = GGANZZAHL ## Überprüft, ob eine Zahl größer als ein gegebener Schwellenwert ist
-HEX2BIN = HEXINBIN ## Wandelt eine hexadezimale Zahl in eine Binärzahl um
-HEX2DEC = HEXINDEZ ## Wandelt eine hexadezimale Zahl in eine dezimale Zahl um
-HEX2OCT = HEXINOKT ## Wandelt eine hexadezimale Zahl in eine Oktalzahl um
-IMABS = IMABS ## Gibt den Absolutbetrag (Modulo) einer komplexen Zahl zurück
-IMAGINARY = IMAGINÄRTEIL ## Gibt den Imaginärteil einer komplexen Zahl zurück
-IMARGUMENT = IMARGUMENT ## Gibt das Argument Theta zurück, einen Winkel, der als Bogenmaß ausgedrückt wird
-IMCONJUGATE = IMKONJUGIERTE ## Gibt die konjugierte komplexe Zahl zu einer komplexen Zahl zurück
-IMCOS = IMCOS ## Gibt den Kosinus einer komplexen Zahl zurück
-IMDIV = IMDIV ## Gibt den Quotienten zweier komplexer Zahlen zurück
-IMEXP = IMEXP ## Gibt die algebraische Form einer in exponentieller Schreibweise vorliegenden komplexen Zahl zurück
-IMLN = IMLN ## Gibt den natürlichen Logarithmus einer komplexen Zahl zurück
-IMLOG10 = IMLOG10 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 10 zurück
-IMLOG2 = IMLOG2 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 2 zurück
-IMPOWER = IMAPOTENZ ## Potenziert eine komplexe Zahl mit einer ganzen Zahl
-IMPRODUCT = IMPRODUKT ## Gibt das Produkt von komplexen Zahlen zurück
-IMREAL = IMREALTEIL ## Gibt den Realteil einer komplexen Zahl zurück
-IMSIN = IMSIN ## Gibt den Sinus einer komplexen Zahl zurück
-IMSQRT = IMWURZEL ## Gibt die Quadratwurzel einer komplexen Zahl zurück
-IMSUB = IMSUB ## Gibt die Differenz zwischen zwei komplexen Zahlen zurück
-IMSUM = IMSUMME ## Gibt die Summe von komplexen Zahlen zurück
-OCT2BIN = OKTINBIN ## Wandelt eine oktale Zahl in eine binäre Zahl (Dualzahl) um
-OCT2DEC = OKTINDEZ ## Wandelt eine oktale Zahl in eine dezimale Zahl um
-OCT2HEX = OKTINHEX ## Wandelt eine oktale Zahl in eine hexadezimale Zahl um
-
+ACCRINT = AUFGELZINS
+ACCRINTM = AUFGELZINSF
+AMORDEGRC = AMORDEGRK
+AMORLINC = AMORLINEARK
+COUPDAYBS = ZINSTERMTAGVA
+COUPDAYS = ZINSTERMTAGE
+COUPDAYSNC = ZINSTERMTAGNZ
+COUPNCD = ZINSTERMNZ
+COUPNUM = ZINSTERMZAHL
+COUPPCD = ZINSTERMVZ
+CUMIPMT = KUMZINSZ
+CUMPRINC = KUMKAPITAL
+DB = GDA2
+DDB = GDA
+DISC = DISAGIO
+DOLLARDE = NOTIERUNGDEZ
+DOLLARFR = NOTIERUNGBRU
+DURATION = DURATION
+EFFECT = EFFEKTIV
+FV = ZW
+FVSCHEDULE = ZW2
+INTRATE = ZINSSATZ
+IPMT = ZINSZ
+IRR = IKV
+ISPMT = ISPMT
+MDURATION = MDURATION
+MIRR = QIKV
+NOMINAL = NOMINAL
+NPER = ZZR
+NPV = NBW
+ODDFPRICE = UNREGER.KURS
+ODDFYIELD = UNREGER.REND
+ODDLPRICE = UNREGLE.KURS
+ODDLYIELD = UNREGLE.REND
+PDURATION = PDURATION
+PMT = RMZ
+PPMT = KAPZ
+PRICE = KURS
+PRICEDISC = KURSDISAGIO
+PRICEMAT = KURSFÄLLIG
+PV = BW
+RATE = ZINS
+RECEIVED = AUSZAHLUNG
+RRI = ZSATZINVEST
+SLN = LIA
+SYD = DIA
+TBILLEQ = TBILLÄQUIV
+TBILLPRICE = TBILLKURS
+TBILLYIELD = TBILLRENDITE
+VDB = VDB
+XIRR = XINTZINSFUSS
+XNPV = XKAPITALWERT
+YIELD = RENDITE
+YIELDDISC = RENDITEDIS
+YIELDMAT = RENDITEFÄLL
##
-## Financial functions Finanzmathematische Funktionen
+## Informationsfunktionen (Information Functions)
##
-ACCRINT = AUFGELZINS ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers mit periodischen Zinszahlungen zurück
-ACCRINTM = AUFGELZINSF ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers zurück, die bei Fälligkeit ausgezahlt werden
-AMORDEGRC = AMORDEGRK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume mithilfe eines Abschreibungskoeffizienten zurück
-AMORLINC = AMORLINEARK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume zurück
-COUPDAYBS = ZINSTERMTAGVA ## Gibt die Anzahl der Tage vom Anfang des Zinstermins bis zum Abrechnungstermin zurück
-COUPDAYS = ZINSTERMTAGE ## Gibt die Anzahl der Tage der Zinsperiode zurück, die den Abrechnungstermin einschließt
-COUPDAYSNC = ZINSTERMTAGNZ ## Gibt die Anzahl der Tage vom Abrechnungstermin bis zum nächsten Zinstermin zurück
-COUPNCD = ZINSTERMNZ ## Gibt das Datum des ersten Zinstermins nach dem Abrechnungstermin zurück
-COUPNUM = ZINSTERMZAHL ## Gibt die Anzahl der Zinstermine zwischen Abrechnungs- und Fälligkeitsdatum zurück
-COUPPCD = ZINSTERMVZ ## Gibt das Datum des letzten Zinstermins vor dem Abrechnungstermin zurück
-CUMIPMT = KUMZINSZ ## Berechnet die kumulierten Zinsen, die zwischen zwei Perioden zu zahlen sind
-CUMPRINC = KUMKAPITAL ## Berechnet die aufgelaufene Tilgung eines Darlehens, die zwischen zwei Perioden zu zahlen ist
-DB = GDA2 ## Gibt die geometrisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück
-DDB = GDA ## Gibt die Abschreibung eines Anlageguts für einen angegebenen Zeitraum unter Verwendung der degressiven Doppelraten-Abschreibung oder eines anderen von Ihnen angegebenen Abschreibungsverfahrens zurück
-DISC = DISAGIO ## Gibt den in Prozent ausgedrückten Abzinsungssatz eines Wertpapiers zurück
-DOLLARDE = NOTIERUNGDEZ ## Wandelt eine Notierung, die als Dezimalbruch ausgedrückt wurde, in eine Dezimalzahl um
-DOLLARFR = NOTIERUNGBRU ## Wandelt eine Notierung, die als Dezimalzahl ausgedrückt wurde, in einen Dezimalbruch um
-DURATION = DURATION ## Gibt die jährliche Duration eines Wertpapiers mit periodischen Zinszahlungen zurück
-EFFECT = EFFEKTIV ## Gibt die jährliche Effektivverzinsung zurück
-FV = ZW ## Gibt den zukünftigen Wert (Endwert) einer Investition zurück
-FVSCHEDULE = ZW2 ## Gibt den aufgezinsten Wert des Anfangskapitals für eine Reihe periodisch unterschiedlicher Zinssätze zurück
-INTRATE = ZINSSATZ ## Gibt den Zinssatz eines voll investierten Wertpapiers zurück
-IPMT = ZINSZ ## Gibt die Zinszahlung einer Investition für die angegebene Periode zurück
-IRR = IKV ## Gibt den internen Zinsfuß einer Investition ohne Finanzierungskosten oder Reinvestitionsgewinne zurück
-ISPMT = ISPMT ## Berechnet die während eines bestimmten Zeitraums für eine Investition gezahlten Zinsen
-MDURATION = MDURATION ## Gibt die geänderte Dauer für ein Wertpapier mit einem angenommenen Nennwert von 100 € zurück
-MIRR = QIKV ## Gibt den internen Zinsfuß zurück, wobei positive und negative Zahlungen zu unterschiedlichen Sätzen finanziert werden
-NOMINAL = NOMINAL ## Gibt die jährliche Nominalverzinsung zurück
-NPER = ZZR ## Gibt die Anzahl der Zahlungsperioden einer Investition zurück
-NPV = NBW ## Gibt den Nettobarwert einer Investition auf Basis periodisch anfallender Zahlungen und eines Abzinsungsfaktors zurück
-ODDFPRICE = UNREGER.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück
-ODDFYIELD = UNREGER.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück
-ODDLPRICE = UNREGLE.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück
-ODDLYIELD = UNREGLE.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück
-PMT = RMZ ## Gibt die periodische Zahlung für eine Annuität zurück
-PPMT = KAPZ ## Gibt die Kapitalrückzahlung einer Investition für eine angegebene Periode zurück
-PRICE = KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das periodisch Zinsen auszahlt
-PRICEDISC = KURSDISAGIO ## Gibt den Kurs pro 100 € Nennwert eines unverzinslichen Wertpapiers zurück
-PRICEMAT = KURSFÄLLIG ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt
-PV = BW ## Gibt den Barwert einer Investition zurück
-RATE = ZINS ## Gibt den Zinssatz pro Zeitraum einer Annuität zurück
-RECEIVED = AUSZAHLUNG ## Gibt den Auszahlungsbetrag eines voll investierten Wertpapiers am Fälligkeitstermin zurück
-SLN = LIA ## Gibt die lineare Abschreibung eines Wirtschaftsguts pro Periode zurück
-SYD = DIA ## Gibt die arithmetisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück
-TBILLEQ = TBILLÄQUIV ## Gibt die Rendite für ein Wertpapier zurück
-TBILLPRICE = TBILLKURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück
-TBILLYIELD = TBILLRENDITE ## Gibt die Rendite für ein Wertpapier zurück
-VDB = VDB ## Gibt die degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode oder Teilperiode zurück
-XIRR = XINTZINSFUSS ## Gibt den internen Zinsfuß einer Reihe nicht periodisch anfallender Zahlungen zurück
-XNPV = XKAPITALWERT ## Gibt den Nettobarwert (Kapitalwert) einer Reihe nicht periodisch anfallender Zahlungen zurück
-YIELD = RENDITE ## Gibt die Rendite eines Wertpapiers zurück, das periodisch Zinsen auszahlt
-YIELDDISC = RENDITEDIS ## Gibt die jährliche Rendite eines unverzinslichen Wertpapiers zurück
-YIELDMAT = RENDITEFÄLL ## Gibt die jährliche Rendite eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt
-
+CELL = ZELLE
+ERROR.TYPE = FEHLER.TYP
+INFO = INFO
+ISBLANK = ISTLEER
+ISERR = ISTFEHL
+ISERROR = ISTFEHLER
+ISEVEN = ISTGERADE
+ISFORMULA = ISTFORMEL
+ISLOGICAL = ISTLOG
+ISNA = ISTNV
+ISNONTEXT = ISTKTEXT
+ISNUMBER = ISTZAHL
+ISODD = ISTUNGERADE
+ISREF = ISTBEZUG
+ISTEXT = ISTTEXT
+N = N
+NA = NV
+SHEET = BLATT
+SHEETS = BLÄTTER
+TYPE = TYP
##
-## Information functions Informationsfunktionen
+## Logische Funktionen (Logical Functions)
##
-CELL = ZELLE ## Gibt Informationen zu Formatierung, Position oder Inhalt einer Zelle zurück
-ERROR.TYPE = FEHLER.TYP ## Gibt eine Zahl zurück, die einem Fehlertyp entspricht
-INFO = INFO ## Gibt Informationen zur aktuellen Betriebssystemumgebung zurück
-ISBLANK = ISTLEER ## Gibt WAHR zurück, wenn der Wert leer ist
-ISERR = ISTFEHL ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert außer #N/V ist
-ISERROR = ISTFEHLER ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert ist
-ISEVEN = ISTGERADE ## Gibt WAHR zurück, wenn es sich um eine gerade Zahl handelt
-ISLOGICAL = ISTLOG ## Gibt WAHR zurück, wenn der Wert ein Wahrheitswert ist
-ISNA = ISTNV ## Gibt WAHR zurück, wenn der Wert der Fehlerwert #N/V ist
-ISNONTEXT = ISTKTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das keinen Text enthält
-ISNUMBER = ISTZAHL ## Gibt WAHR zurück, wenn der Wert eine Zahl ist
-ISODD = ISTUNGERADE ## Gibt WAHR zurück, wenn es sich um eine ungerade Zahl handelt
-ISREF = ISTBEZUG ## Gibt WAHR zurück, wenn der Wert ein Bezug ist
-ISTEXT = ISTTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das Text enthält
-N = N ## Gibt den in eine Zahl umgewandelten Wert zurück
-NA = NV ## Gibt den Fehlerwert #NV zurück
-TYPE = TYP ## Gibt eine Zahl zurück, die den Datentyp des angegebenen Werts anzeigt
-
+AND = UND
+FALSE = FALSCH
+IF = WENN
+IFERROR = WENNFEHLER
+IFNA = WENNNV
+IFS = WENNS
+NOT = NICHT
+OR = ODER
+SWITCH = ERSTERWERT
+TRUE = WAHR
+XOR = XODER
##
-## Logical functions Logische Funktionen
+## Nachschlage- und Verweisfunktionen (Lookup & Reference Functions)
##
-AND = UND ## Gibt WAHR zurück, wenn alle zugehörigen Argumente WAHR sind
-FALSE = FALSCH ## Gibt den Wahrheitswert FALSCH zurück
-IF = WENN ## Gibt einen logischen Test zum Ausführen an
-IFERROR = WENNFEHLER ## Gibt einen von Ihnen festgelegten Wert zurück, wenn die Auswertung der Formel zu einem Fehler führt; andernfalls wird das Ergebnis der Formel zurückgegeben
-NOT = NICHT ## Kehrt den Wahrheitswert der zugehörigen Argumente um
-OR = ODER ## Gibt WAHR zurück, wenn ein Argument WAHR ist
-TRUE = WAHR ## Gibt den Wahrheitswert WAHR zurück
-
+ADDRESS = ADRESSE
+AREAS = BEREICHE
+CHOOSE = WAHL
+COLUMN = SPALTE
+COLUMNS = SPALTEN
+FORMULATEXT = FORMELTEXT
+GETPIVOTDATA = PIVOTDATENZUORDNEN
+HLOOKUP = WVERWEIS
+HYPERLINK = HYPERLINK
+INDEX = INDEX
+INDIRECT = INDIREKT
+LOOKUP = VERWEIS
+MATCH = VERGLEICH
+OFFSET = BEREICH.VERSCHIEBEN
+ROW = ZEILE
+ROWS = ZEILEN
+RTD = RTD
+TRANSPOSE = MTRANS
+VLOOKUP = SVERWEIS
##
-## Lookup and reference functions Nachschlage- und Verweisfunktionen
+## Mathematische und trigonometrische Funktionen (Math & Trig Functions)
##
-ADDRESS = ADRESSE ## Gibt einen Bezug auf eine einzelne Zelle in einem Tabellenblatt als Text zurück
-AREAS = BEREICHE ## Gibt die Anzahl der innerhalb eines Bezugs aufgeführten Bereiche zurück
-CHOOSE = WAHL ## Wählt einen Wert aus eine Liste mit Werten aus
-COLUMN = SPALTE ## Gibt die Spaltennummer eines Bezugs zurück
-COLUMNS = SPALTEN ## Gibt die Anzahl der Spalten in einem Bezug zurück
-HLOOKUP = HVERWEIS ## Sucht in der obersten Zeile einer Matrix und gibt den Wert der angegebenen Zelle zurück
-HYPERLINK = HYPERLINK ## Erstellt eine Verknüpfung, über die ein auf einem Netzwerkserver, in einem Intranet oder im Internet gespeichertes Dokument geöffnet wird
-INDEX = INDEX ## Verwendet einen Index, um einen Wert aus einem Bezug oder einer Matrix auszuwählen
-INDIRECT = INDIREKT ## Gibt einen Bezug zurück, der von einem Textwert angegeben wird
-LOOKUP = LOOKUP ## Sucht Werte in einem Vektor oder einer Matrix
-MATCH = VERGLEICH ## Sucht Werte in einem Bezug oder einer Matrix
-OFFSET = BEREICH.VERSCHIEBEN ## Gibt einen Bezugoffset aus einem gegebenen Bezug zurück
-ROW = ZEILE ## Gibt die Zeilennummer eines Bezugs zurück
-ROWS = ZEILEN ## Gibt die Anzahl der Zeilen in einem Bezug zurück
-RTD = RTD ## Ruft Echtzeitdaten von einem Programm ab, das die COM-Automatisierung (Automatisierung: Ein Verfahren, bei dem aus einer Anwendung oder einem Entwicklungstool heraus mit den Objekten einer anderen Anwendung gearbeitet wird. Die früher als OLE-Automatisierung bezeichnete Automatisierung ist ein Industriestandard und eine Funktion von COM (Component Object Model).) unterstützt
-TRANSPOSE = MTRANS ## Gibt die transponierte Matrix einer Matrix zurück
-VLOOKUP = SVERWEIS ## Sucht in der ersten Spalte einer Matrix und arbeitet sich durch die Zeile, um den Wert einer Zelle zurückzugeben
-
+ABS = ABS
+ACOS = ARCCOS
+ACOSH = ARCCOSHYP
+ACOT = ARCCOT
+ACOTH = ARCCOTHYP
+AGGREGATE = AGGREGAT
+ARABIC = ARABISCH
+ASIN = ARCSIN
+ASINH = ARCSINHYP
+ATAN = ARCTAN
+ATAN2 = ARCTAN2
+ATANH = ARCTANHYP
+BASE = BASIS
+CEILING.MATH = OBERGRENZE.MATHEMATIK
+CEILING.PRECISE = OBERGRENZE.GENAU
+COMBIN = KOMBINATIONEN
+COMBINA = KOMBINATIONEN2
+COS = COS
+COSH = COSHYP
+COT = COT
+COTH = COTHYP
+CSC = COSEC
+CSCH = COSECHYP
+DECIMAL = DEZIMAL
+DEGREES = GRAD
+ECMA.CEILING = ECMA.OBERGRENZE
+EVEN = GERADE
+EXP = EXP
+FACT = FAKULTÄT
+FACTDOUBLE = ZWEIFAKULTÄT
+FLOOR.MATH = UNTERGRENZE.MATHEMATIK
+FLOOR.PRECISE = UNTERGRENZE.GENAU
+GCD = GGT
+INT = GANZZAHL
+ISO.CEILING = ISO.OBERGRENZE
+LCM = KGV
+LN = LN
+LOG = LOG
+LOG10 = LOG10
+MDETERM = MDET
+MINVERSE = MINV
+MMULT = MMULT
+MOD = REST
+MROUND = VRUNDEN
+MULTINOMIAL = POLYNOMIAL
+MUNIT = MEINHEIT
+ODD = UNGERADE
+PI = PI
+POWER = POTENZ
+PRODUCT = PRODUKT
+QUOTIENT = QUOTIENT
+RADIANS = BOGENMASS
+RAND = ZUFALLSZAHL
+RANDBETWEEN = ZUFALLSBEREICH
+ROMAN = RÖMISCH
+ROUND = RUNDEN
+ROUNDBAHTDOWN = RUNDBAHTNED
+ROUNDBAHTUP = BAHTAUFRUNDEN
+ROUNDDOWN = ABRUNDEN
+ROUNDUP = AUFRUNDEN
+SEC = SEC
+SECH = SECHYP
+SERIESSUM = POTENZREIHE
+SIGN = VORZEICHEN
+SIN = SIN
+SINH = SINHYP
+SQRT = WURZEL
+SQRTPI = WURZELPI
+SUBTOTAL = TEILERGEBNIS
+SUM = SUMME
+SUMIF = SUMMEWENN
+SUMIFS = SUMMEWENNS
+SUMPRODUCT = SUMMENPRODUKT
+SUMSQ = QUADRATESUMME
+SUMX2MY2 = SUMMEX2MY2
+SUMX2PY2 = SUMMEX2PY2
+SUMXMY2 = SUMMEXMY2
+TAN = TAN
+TANH = TANHYP
+TRUNC = KÜRZEN
##
-## Math and trigonometry functions Mathematische und trigonometrische Funktionen
+## Statistische Funktionen (Statistical Functions)
##
-ABS = ABS ## Gibt den Absolutwert einer Zahl zurück
-ACOS = ARCCOS ## Gibt den Arkuskosinus einer Zahl zurück
-ACOSH = ARCCOSHYP ## Gibt den umgekehrten hyperbolischen Kosinus einer Zahl zurück
-ASIN = ARCSIN ## Gibt den Arkussinus einer Zahl zurück
-ASINH = ARCSINHYP ## Gibt den umgekehrten hyperbolischen Sinus einer Zahl zurück
-ATAN = ARCTAN ## Gibt den Arkustangens einer Zahl zurück
-ATAN2 = ARCTAN2 ## Gibt den Arkustangens einer x- und einer y-Koordinate zurück
-ATANH = ARCTANHYP ## Gibt den umgekehrten hyperbolischen Tangens einer Zahl zurück
-CEILING = OBERGRENZE ## Rundet eine Zahl auf die nächste ganze Zahl oder das nächste Vielfache von Schritt
-COMBIN = KOMBINATIONEN ## Gibt die Anzahl der Kombinationen für eine bestimmte Anzahl von Objekten zurück
-COS = COS ## Gibt den Kosinus einer Zahl zurück
-COSH = COSHYP ## Gibt den hyperbolischen Kosinus einer Zahl zurück
-DEGREES = GRAD ## Wandelt Bogenmaß (Radiant) in Grad um
-EVEN = GERADE ## Rundet eine Zahl auf die nächste gerade ganze Zahl auf
-EXP = EXP ## Potenziert die Basis e mit der als Argument angegebenen Zahl
-FACT = FAKULTÄT ## Gibt die Fakultät einer Zahl zurück
-FACTDOUBLE = ZWEIFAKULTÄT ## Gibt die Fakultät zu Zahl mit Schrittlänge 2 zurück
-FLOOR = UNTERGRENZE ## Rundet die Zahl auf Anzahl_Stellen ab
-GCD = GGT ## Gibt den größten gemeinsamen Teiler zurück
-INT = GANZZAHL ## Rundet eine Zahl auf die nächstkleinere ganze Zahl ab
-LCM = KGV ## Gibt das kleinste gemeinsame Vielfache zurück
-LN = LN ## Gibt den natürlichen Logarithmus einer Zahl zurück
-LOG = LOG ## Gibt den Logarithmus einer Zahl zu der angegebenen Basis zurück
-LOG10 = LOG10 ## Gibt den Logarithmus einer Zahl zur Basis 10 zurück
-MDETERM = MDET ## Gibt die Determinante einer Matrix zurück
-MINVERSE = MINV ## Gibt die inverse Matrix einer Matrix zurück
-MMULT = MMULT ## Gibt das Produkt zweier Matrizen zurück
-MOD = REST ## Gibt den Rest einer Division zurück
-MROUND = VRUNDEN ## Gibt eine auf das gewünschte Vielfache gerundete Zahl zurück
-MULTINOMIAL = POLYNOMIAL ## Gibt den Polynomialkoeffizienten einer Gruppe von Zahlen zurück
-ODD = UNGERADE ## Rundet eine Zahl auf die nächste ungerade ganze Zahl auf
-PI = PI ## Gibt den Wert Pi zurück
-POWER = POTENZ ## Gibt als Ergebnis eine potenzierte Zahl zurück
-PRODUCT = PRODUKT ## Multipliziert die zugehörigen Argumente
-QUOTIENT = QUOTIENT ## Gibt den ganzzahligen Anteil einer Division zurück
-RADIANS = BOGENMASS ## Wandelt Grad in Bogenmaß (Radiant) um
-RAND = ZUFALLSZAHL ## Gibt eine Zufallszahl zwischen 0 und 1 zurück
-RANDBETWEEN = ZUFALLSBEREICH ## Gibt eine Zufallszahl aus dem festgelegten Bereich zurück
-ROMAN = RÖMISCH ## Wandelt eine arabische Zahl in eine römische Zahl als Text um
-ROUND = RUNDEN ## Rundet eine Zahl auf eine bestimmte Anzahl von Dezimalstellen
-ROUNDDOWN = ABRUNDEN ## Rundet die Zahl auf Anzahl_Stellen ab
-ROUNDUP = AUFRUNDEN ## Rundet die Zahl auf Anzahl_Stellen auf
-SERIESSUM = POTENZREIHE ## Gibt die Summe von Potenzen (zur Berechnung von Potenzreihen und dichotomen Wahrscheinlichkeiten) zurück
-SIGN = VORZEICHEN ## Gibt das Vorzeichen einer Zahl zurück
-SIN = SIN ## Gibt den Sinus einer Zahl zurück
-SINH = SINHYP ## Gibt den hyperbolischen Sinus einer Zahl zurück
-SQRT = WURZEL ## Gibt die Quadratwurzel einer Zahl zurück
-SQRTPI = WURZELPI ## Gibt die Wurzel aus der mit Pi (pi) multiplizierten Zahl zurück
-SUBTOTAL = TEILERGEBNIS ## Gibt ein Teilergebnis in einer Liste oder Datenbank zurück
-SUM = SUMME ## Addiert die zugehörigen Argumente
-SUMIF = SUMMEWENN ## Addiert Zahlen, die mit den Suchkriterien übereinstimmen
-SUMIFS = SUMMEWENNS ## Die Zellen, die mehrere Kriterien erfüllen, werden in einem Bereich hinzugefügt
-SUMPRODUCT = SUMMENPRODUKT ## Gibt die Summe der Produkte zusammengehöriger Matrixkomponenten zurück
-SUMSQ = QUADRATESUMME ## Gibt die Summe der quadrierten Argumente zurück
-SUMX2MY2 = SUMMEX2MY2 ## Gibt die Summe der Differenzen der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück
-SUMX2PY2 = SUMMEX2PY2 ## Gibt die Summe der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück
-SUMXMY2 = SUMMEXMY2 ## Gibt die Summe der quadrierten Differenzen für zusammengehörige Komponenten zweier Matrizen zurück
-TAN = TAN ## Gibt den Tangens einer Zahl zurück
-TANH = TANHYP ## Gibt den hyperbolischen Tangens einer Zahl zurück
-TRUNC = KÜRZEN ## Schneidet die Kommastellen einer Zahl ab und gibt als Ergebnis eine ganze Zahl zurück
-
+AVEDEV = MITTELABW
+AVERAGE = MITTELWERT
+AVERAGEA = MITTELWERTA
+AVERAGEIF = MITTELWERTWENN
+AVERAGEIFS = MITTELWERTWENNS
+BETA.DIST = BETA.VERT
+BETA.INV = BETA.INV
+BINOM.DIST = BINOM.VERT
+BINOM.DIST.RANGE = BINOM.VERT.BEREICH
+BINOM.INV = BINOM.INV
+CHISQ.DIST = CHIQU.VERT
+CHISQ.DIST.RT = CHIQU.VERT.RE
+CHISQ.INV = CHIQU.INV
+CHISQ.INV.RT = CHIQU.INV.RE
+CHISQ.TEST = CHIQU.TEST
+CONFIDENCE.NORM = KONFIDENZ.NORM
+CONFIDENCE.T = KONFIDENZ.T
+CORREL = KORREL
+COUNT = ANZAHL
+COUNTA = ANZAHL2
+COUNTBLANK = ANZAHLLEEREZELLEN
+COUNTIF = ZÄHLENWENN
+COUNTIFS = ZÄHLENWENNS
+COVARIANCE.P = KOVARIANZ.P
+COVARIANCE.S = KOVARIANZ.S
+DEVSQ = SUMQUADABW
+EXPON.DIST = EXPON.VERT
+F.DIST = F.VERT
+F.DIST.RT = F.VERT.RE
+F.INV = F.INV
+F.INV.RT = F.INV.RE
+F.TEST = F.TEST
+FISHER = FISHER
+FISHERINV = FISHERINV
+FORECAST.ETS = PROGNOSE.ETS
+FORECAST.ETS.CONFINT = PROGNOSE.ETS.KONFINT
+FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SAISONALITÄT
+FORECAST.ETS.STAT = PROGNOSE.ETS.STAT
+FORECAST.LINEAR = PROGNOSE.LINEAR
+FREQUENCY = HÄUFIGKEIT
+GAMMA = GAMMA
+GAMMA.DIST = GAMMA.VERT
+GAMMA.INV = GAMMA.INV
+GAMMALN = GAMMALN
+GAMMALN.PRECISE = GAMMALN.GENAU
+GAUSS = GAUSS
+GEOMEAN = GEOMITTEL
+GROWTH = VARIATION
+HARMEAN = HARMITTEL
+HYPGEOM.DIST = HYPGEOM.VERT
+INTERCEPT = ACHSENABSCHNITT
+KURT = KURT
+LARGE = KGRÖSSTE
+LINEST = RGP
+LOGEST = RKP
+LOGNORM.DIST = LOGNORM.VERT
+LOGNORM.INV = LOGNORM.INV
+MAX = MAX
+MAXA = MAXA
+MAXIFS = MAXWENNS
+MEDIAN = MEDIAN
+MIN = MIN
+MINA = MINA
+MINIFS = MINWENNS
+MODE.MULT = MODUS.VIELF
+MODE.SNGL = MODUS.EINF
+NEGBINOM.DIST = NEGBINOM.VERT
+NORM.DIST = NORM.VERT
+NORM.INV = NORM.INV
+NORM.S.DIST = NORM.S.VERT
+NORM.S.INV = NORM.S.INV
+PEARSON = PEARSON
+PERCENTILE.EXC = QUANTIL.EXKL
+PERCENTILE.INC = QUANTIL.INKL
+PERCENTRANK.EXC = QUANTILSRANG.EXKL
+PERCENTRANK.INC = QUANTILSRANG.INKL
+PERMUT = VARIATIONEN
+PERMUTATIONA = VARIATIONEN2
+PHI = PHI
+POISSON.DIST = POISSON.VERT
+PROB = WAHRSCHBEREICH
+QUARTILE.EXC = QUARTILE.EXKL
+QUARTILE.INC = QUARTILE.INKL
+RANK.AVG = RANG.MITTELW
+RANK.EQ = RANG.GLEICH
+RSQ = BESTIMMTHEITSMASS
+SKEW = SCHIEFE
+SKEW.P = SCHIEFE.P
+SLOPE = STEIGUNG
+SMALL = KKLEINSTE
+STANDARDIZE = STANDARDISIERUNG
+STDEV.P = STABW.N
+STDEV.S = STABW.S
+STDEVA = STABWA
+STDEVPA = STABWNA
+STEYX = STFEHLERYX
+T.DIST = T.VERT
+T.DIST.2T = T.VERT.2S
+T.DIST.RT = T.VERT.RE
+T.INV = T.INV
+T.INV.2T = T.INV.2S
+T.TEST = T.TEST
+TREND = TREND
+TRIMMEAN = GESTUTZTMITTEL
+VAR.P = VAR.P
+VAR.S = VAR.S
+VARA = VARIANZA
+VARPA = VARIANZENA
+WEIBULL.DIST = WEIBULL.VERT
+Z.TEST = G.TEST
##
-## Statistical functions Statistische Funktionen
+## Textfunktionen (Text Functions)
##
-AVEDEV = MITTELABW ## Gibt die durchschnittliche absolute Abweichung einer Reihe von Merkmalsausprägungen und ihrem Mittelwert zurück
-AVERAGE = MITTELWERT ## Gibt den Mittelwert der zugehörigen Argumente zurück
-AVERAGEA = MITTELWERTA ## Gibt den Mittelwert der zugehörigen Argumente, die Zahlen, Text und Wahrheitswerte enthalten, zurück
-AVERAGEIF = MITTELWERTWENN ## Der Durchschnittswert (arithmetisches Mittel) für alle Zellen in einem Bereich, die einem angegebenen Kriterium entsprechen, wird zurückgegeben
-AVERAGEIFS = MITTELWERTWENNS ## Gibt den Durchschnittswert (arithmetisches Mittel) aller Zellen zurück, die mehreren Kriterien entsprechen
-BETADIST = BETAVERT ## Gibt die Werte der kumulierten Betaverteilungsfunktion zurück
-BETAINV = BETAINV ## Gibt das Quantil der angegebenen Betaverteilung zurück
-BINOMDIST = BINOMVERT ## Gibt Wahrscheinlichkeiten einer binomialverteilten Zufallsvariablen zurück
-CHIDIST = CHIVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer Chi-Quadrat-verteilten Zufallsgröße zurück
-CHIINV = CHIINV ## Gibt Quantile der Verteilungsfunktion (1-Alpha) der Chi-Quadrat-Verteilung zurück
-CHITEST = CHITEST ## Gibt die Teststatistik eines Unabhängigkeitstests zurück
-CONFIDENCE = KONFIDENZ ## Ermöglicht die Berechnung des 1-Alpha Konfidenzintervalls für den Erwartungswert einer Zufallsvariablen
-CORREL = KORREL ## Gibt den Korrelationskoeffizienten zweier Reihen von Merkmalsausprägungen zurück
-COUNT = ANZAHL ## Gibt die Anzahl der Zahlen in der Liste mit Argumenten an
-COUNTA = ANZAHL2 ## Gibt die Anzahl der Werte in der Liste mit Argumenten an
-COUNTBLANK = ANZAHLLEEREZELLEN ## Gibt die Anzahl der leeren Zellen in einem Bereich an
-COUNTIF = ZÄHLENWENN ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit den Suchkriterien übereinstimmen
-COUNTIFS = ZÄHLENWENNS ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit mehreren Suchkriterien übereinstimmen
-COVAR = KOVAR ## Gibt die Kovarianz zurück, den Mittelwert der für alle Datenpunktpaare gebildeten Produkte der Abweichungen
-CRITBINOM = KRITBINOM ## Gibt den kleinsten Wert zurück, für den die kumulierten Wahrscheinlichkeiten der Binomialverteilung kleiner oder gleich einer Grenzwahrscheinlichkeit sind
-DEVSQ = SUMQUADABW ## Gibt die Summe der quadrierten Abweichungen der Datenpunkte von ihrem Stichprobenmittelwert zurück
-EXPONDIST = EXPONVERT ## Gibt Wahrscheinlichkeiten einer exponential verteilten Zufallsvariablen zurück
-FDIST = FVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer F-verteilten Zufallsvariablen zurück
-FINV = FINV ## Gibt Quantile der F-Verteilung zurück
-FISHER = FISHER ## Gibt die Fisher-Transformation zurück
-FISHERINV = FISHERINV ## Gibt die Umkehrung der Fisher-Transformation zurück
-FORECAST = PROGNOSE ## Gibt einen Wert zurück, der sich aus einem linearen Trend ergibt
-FREQUENCY = HÄUFIGKEIT ## Gibt eine Häufigkeitsverteilung als vertikale Matrix zurück
-FTEST = FTEST ## Gibt die Teststatistik eines F-Tests zurück
-GAMMADIST = GAMMAVERT ## Gibt Wahrscheinlichkeiten einer gammaverteilten Zufallsvariablen zurück
-GAMMAINV = GAMMAINV ## Gibt Quantile der Gammaverteilung zurück
-GAMMALN = GAMMALN ## Gibt den natürlichen Logarithmus der Gammafunktion zurück, Γ(x)
-GEOMEAN = GEOMITTEL ## Gibt das geometrische Mittel zurück
-GROWTH = VARIATION ## Gibt Werte zurück, die sich aus einem exponentiellen Trend ergeben
-HARMEAN = HARMITTEL ## Gibt das harmonische Mittel zurück
-HYPGEOMDIST = HYPGEOMVERT ## Gibt Wahrscheinlichkeiten einer hypergeometrisch-verteilten Zufallsvariablen zurück
-INTERCEPT = ACHSENABSCHNITT ## Gibt den Schnittpunkt der Regressionsgeraden zurück
-KURT = KURT ## Gibt die Kurtosis (Exzess) einer Datengruppe zurück
-LARGE = KGRÖSSTE ## Gibt den k-größten Wert einer Datengruppe zurück
-LINEST = RGP ## Gibt die Parameter eines linearen Trends zurück
-LOGEST = RKP ## Gibt die Parameter eines exponentiellen Trends zurück
-LOGINV = LOGINV ## Gibt Quantile der Lognormalverteilung zurück
-LOGNORMDIST = LOGNORMVERT ## Gibt Werte der Verteilungsfunktion einer lognormalverteilten Zufallsvariablen zurück
-MAX = MAX ## Gibt den Maximalwert einer Liste mit Argumenten zurück
-MAXA = MAXA ## Gibt den Maximalwert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten
-MEDIAN = MEDIAN ## Gibt den Median der angegebenen Zahlen zurück
-MIN = MIN ## Gibt den Minimalwert einer Liste mit Argumenten zurück
-MINA = MINA ## Gibt den kleinsten Wert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten
-MODE = MODALWERT ## Gibt den am häufigsten vorkommenden Wert in einer Datengruppe zurück
-NEGBINOMDIST = NEGBINOMVERT ## Gibt Wahrscheinlichkeiten einer negativen, binominal verteilten Zufallsvariablen zurück
-NORMDIST = NORMVERT ## Gibt Wahrscheinlichkeiten einer normal verteilten Zufallsvariablen zurück
-NORMINV = NORMINV ## Gibt Quantile der Normalverteilung zurück
-NORMSDIST = STANDNORMVERT ## Gibt Werte der Verteilungsfunktion einer standardnormalverteilten Zufallsvariablen zurück
-NORMSINV = STANDNORMINV ## Gibt Quantile der Standardnormalverteilung zurück
-PEARSON = PEARSON ## Gibt den Pearsonschen Korrelationskoeffizienten zurück
-PERCENTILE = QUANTIL ## Gibt das Alpha-Quantil einer Gruppe von Daten zurück
-PERCENTRANK = QUANTILSRANG ## Gibt den prozentualen Rang (Alpha) eines Werts in einer Datengruppe zurück
-PERMUT = VARIATIONEN ## Gibt die Anzahl der Möglichkeiten zurück, um k Elemente aus einer Menge von n Elementen ohne Zurücklegen zu ziehen
-POISSON = POISSON ## Gibt Wahrscheinlichkeiten einer poissonverteilten Zufallsvariablen zurück
-PROB = WAHRSCHBEREICH ## Gibt die Wahrscheinlichkeit für ein von zwei Werten eingeschlossenes Intervall zurück
-QUARTILE = QUARTILE ## Gibt die Quartile der Datengruppe zurück
-RANK = RANG ## Gibt den Rang zurück, den eine Zahl innerhalb einer Liste von Zahlen einnimmt
-RSQ = BESTIMMTHEITSMASS ## Gibt das Quadrat des Pearsonschen Korrelationskoeffizienten zurück
-SKEW = SCHIEFE ## Gibt die Schiefe einer Verteilung zurück
-SLOPE = STEIGUNG ## Gibt die Steigung der Regressionsgeraden zurück
-SMALL = KKLEINSTE ## Gibt den k-kleinsten Wert einer Datengruppe zurück
-STANDARDIZE = STANDARDISIERUNG ## Gibt den standardisierten Wert zurück
-STDEV = STABW ## Schätzt die Standardabweichung ausgehend von einer Stichprobe
-STDEVA = STABWA ## Schätzt die Standardabweichung ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält
-STDEVP = STABWN ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit
-STDEVPA = STABWNA ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält
-STEYX = STFEHLERYX ## Gibt den Standardfehler der geschätzten y-Werte für alle x-Werte der Regression zurück
-TDIST = TVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer (Student) t-verteilten Zufallsvariablen zurück
-TINV = TINV ## Gibt Quantile der t-Verteilung zurück
-TREND = TREND ## Gibt Werte zurück, die sich aus einem linearen Trend ergeben
-TRIMMEAN = GESTUTZTMITTEL ## Gibt den Mittelwert einer Datengruppe zurück, ohne die Randwerte zu berücksichtigen
-TTEST = TTEST ## Gibt die Teststatistik eines Student'schen t-Tests zurück
-VAR = VARIANZ ## Schätzt die Varianz ausgehend von einer Stichprobe
-VARA = VARIANZA ## Schätzt die Varianz ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält
-VARP = VARIANZEN ## Berechnet die Varianz ausgehend von der Grundgesamtheit
-VARPA = VARIANZENA ## Berechnet die Varianz ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält
-WEIBULL = WEIBULL ## Gibt Wahrscheinlichkeiten einer weibullverteilten Zufallsvariablen zurück
-ZTEST = GTEST ## Gibt den einseitigen Wahrscheinlichkeitswert für einen Gausstest (Normalverteilung) zurück
-
+BAHTTEXT = BAHTTEXT
+CHAR = ZEICHEN
+CLEAN = SÄUBERN
+CODE = CODE
+CONCAT = TEXTKETTE
+DOLLAR = DM
+EXACT = IDENTISCH
+FIND = FINDEN
+FIXED = FEST
+ISTHAIDIGIT = ISTTHAIZAHLENWORT
+LEFT = LINKS
+LEN = LÄNGE
+LOWER = KLEIN
+MID = TEIL
+NUMBERVALUE = ZAHLENWERT
+PROPER = GROSS2
+REPLACE = ERSETZEN
+REPT = WIEDERHOLEN
+RIGHT = RECHTS
+SEARCH = SUCHEN
+SUBSTITUTE = WECHSELN
+T = T
+TEXT = TEXT
+TEXTJOIN = TEXTVERKETTEN
+THAIDIGIT = THAIZAHLENWORT
+THAINUMSOUND = THAIZAHLSOUND
+THAINUMSTRING = THAILANDSKNUMSTRENG
+THAISTRINGLENGTH = THAIZEICHENFOLGENLÄNGE
+TRIM = GLÄTTEN
+UNICHAR = UNIZEICHEN
+UNICODE = UNICODE
+UPPER = GROSS
+VALUE = WERT
##
-## Text functions Textfunktionen
+## Webfunktionen (Web Functions)
##
-ASC = ASC ## Konvertiert DB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in SB-Text
-BAHTTEXT = BAHTTEXT ## Wandelt eine Zahl in Text im Währungsformat ß (Baht) um
-CHAR = ZEICHEN ## Gibt das der Codezahl entsprechende Zeichen zurück
-CLEAN = SÄUBERN ## Löscht alle nicht druckbaren Zeichen aus einem Text
-CODE = CODE ## Gibt die Codezahl des ersten Zeichens in einem Text zurück
-CONCATENATE = VERKETTEN ## Verknüpft mehrere Textelemente zu einem Textelement
-DOLLAR = DM ## Wandelt eine Zahl in Text im Währungsformat € (Euro) um
-EXACT = IDENTISCH ## Prüft, ob zwei Textwerte identisch sind
-FIND = FINDEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden)
-FINDB = FINDENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden)
-FIXED = FEST ## Formatiert eine Zahl als Text mit einer festen Anzahl von Dezimalstellen
-JIS = JIS ## Konvertiert SB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in DB-Text
-LEFT = LINKS ## Gibt die Zeichen ganz links in einem Textwert zurück
-LEFTB = LINKSB ## Gibt die Zeichen ganz links in einem Textwert zurück
-LEN = LÄNGE ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück
-LENB = LÄNGEB ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück
-LOWER = KLEIN ## Wandelt Text in Kleinbuchstaben um
-MID = TEIL ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück
-MIDB = TEILB ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück
-PHONETIC = PHONETIC ## Extrahiert die phonetischen (Furigana-)Zeichen aus einer Textzeichenfolge
-PROPER = GROSS2 ## Wandelt den ersten Buchstaben aller Wörter eines Textwerts in Großbuchstaben um
-REPLACE = ERSETZEN ## Ersetzt Zeichen in Text
-REPLACEB = ERSETZENB ## Ersetzt Zeichen in Text
-REPT = WIEDERHOLEN ## Wiederholt einen Text so oft wie angegeben
-RIGHT = RECHTS ## Gibt die Zeichen ganz rechts in einem Textwert zurück
-RIGHTB = RECHTSB ## Gibt die Zeichen ganz rechts in einem Textwert zurück
-SEARCH = SUCHEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden)
-SEARCHB = SUCHENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden)
-SUBSTITUTE = WECHSELN ## Ersetzt in einer Zeichenfolge neuen Text gegen alten
-T = T ## Wandelt die zugehörigen Argumente in Text um
-TEXT = TEXT ## Formatiert eine Zahl und wandelt sie in Text um
-TRIM = GLÄTTEN ## Entfernt Leerzeichen aus Text
-UPPER = GROSS ## Wandelt Text in Großbuchstaben um
-VALUE = WERT ## Wandelt ein Textargument in eine Zahl um
+ENCODEURL = URLCODIEREN
+FILTERXML = XMLFILTERN
+WEBSERVICE = WEBDIENST
+
+##
+## Kompatibilitätsfunktionen (Compatibility Functions)
+##
+BETADIST = BETAVERT
+BETAINV = BETAINV
+BINOMDIST = BINOMVERT
+CEILING = OBERGRENZE
+CHIDIST = CHIVERT
+CHIINV = CHIINV
+CHITEST = CHITEST
+CONCATENATE = VERKETTEN
+CONFIDENCE = KONFIDENZ
+COVAR = KOVAR
+CRITBINOM = KRITBINOM
+EXPONDIST = EXPONVERT
+FDIST = FVERT
+FINV = FINV
+FLOOR = UNTERGRENZE
+FORECAST = SCHÄTZER
+FTEST = FTEST
+GAMMADIST = GAMMAVERT
+GAMMAINV = GAMMAINV
+HYPGEOMDIST = HYPGEOMVERT
+LOGINV = LOGINV
+LOGNORMDIST = LOGNORMVERT
+MODE = MODALWERT
+NEGBINOMDIST = NEGBINOMVERT
+NORMDIST = NORMVERT
+NORMINV = NORMINV
+NORMSDIST = STANDNORMVERT
+NORMSINV = STANDNORMINV
+PERCENTILE = QUANTIL
+PERCENTRANK = QUANTILSRANG
+POISSON = POISSON
+QUARTILE = QUARTILE
+RANK = RANG
+STDEV = STABW
+STDEVP = STABWN
+TDIST = TVERT
+TINV = TINV
+TTEST = TTEST
+VAR = VARIANZ
+VARP = VARIANZEN
+WEIBULL = WEIBULL
+ZTEST = GTEST
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/config
index 5b9b9488d37..fe044efaf36 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Español (Spanish)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = $ ## I'm surprised that the Excel Documentation suggests $ rather than €
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #¡NULO!
-DIV0 = #¡DIV/0!
-VALUE = #¡VALOR!
-REF = #¡REF!
-NAME = #¿NOMBRE?
-NUM = #¡NÚM!
-NA = #N/A
+NULL = #¡NULO!
+DIV0 = #¡DIV/0!
+VALUE = #¡VALOR!
+REF = #¡REF!
+NAME = #¿NOMBRE?
+NUM = #¡NUM!
+NA
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/functions
index ac1ac86a55f..1f9f2891e6d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/functions
@@ -1,416 +1,537 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
+## PhpSpreadsheet - function name translations
##
+## Español (Spanish)
##
+############################################################
##
-## Add-in and Automation functions Funciones de complementos y automatización
+## Funciones de cubo (Cube Functions)
##
-GETPIVOTDATA = IMPORTARDATOSDINAMICOS ## Devuelve los datos almacenados en un informe de tabla dinámica.
-
+CUBEKPIMEMBER = MIEMBROKPICUBO
+CUBEMEMBER = MIEMBROCUBO
+CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO
+CUBERANKEDMEMBER = MIEMBRORANGOCUBO
+CUBESET = CONJUNTOCUBO
+CUBESETCOUNT = RECUENTOCONJUNTOCUBO
+CUBEVALUE = VALORCUBO
##
-## Cube functions Funciones de cubo
+## Funciones de base de datos (Database Functions)
##
-CUBEKPIMEMBER = MIEMBROKPICUBO ## Devuelve un nombre, propiedad y medida de indicador de rendimiento clave (KPI) y muestra el nombre y la propiedad en la celda. Un KPI es una medida cuantificable, como los beneficios brutos mensuales o la facturación trimestral por empleado, que se usa para supervisar el rendimiento de una organización.
-CUBEMEMBER = MIEMBROCUBO ## Devuelve un miembro o tupla en una jerarquía de cubo. Se usa para validar la existencia del miembro o la tupla en el cubo.
-CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO ## Devuelve el valor de una propiedad de miembro del cubo Se usa para validar la existencia de un nombre de miembro en el cubo y para devolver la propiedad especificada para este miembro.
-CUBERANKEDMEMBER = MIEMBRORANGOCUBO ## Devuelve el miembro n, o clasificado, de un conjunto. Se usa para devolver uno o más elementos de un conjunto, por ejemplo, el representante con mejores ventas o los diez mejores alumnos.
-CUBESET = CONJUNTOCUBO ## Define un conjunto calculado de miembros o tuplas mediante el envío de una expresión de conjunto al cubo en el servidor, lo que crea el conjunto y, después, devuelve dicho conjunto a Microsoft Office Excel.
-CUBESETCOUNT = RECUENTOCONJUNTOCUBO ## Devuelve el número de elementos de un conjunto.
-CUBEVALUE = VALORCUBO ## Devuelve un valor agregado de un cubo.
-
+DAVERAGE = BDPROMEDIO
+DCOUNT = BDCONTAR
+DCOUNTA = BDCONTARA
+DGET = BDEXTRAER
+DMAX = BDMAX
+DMIN = BDMIN
+DPRODUCT = BDPRODUCTO
+DSTDEV = BDDESVEST
+DSTDEVP = BDDESVESTP
+DSUM = BDSUMA
+DVAR = BDVAR
+DVARP = BDVARP
##
-## Database functions Funciones de base de datos
+## Funciones de fecha y hora (Date & Time Functions)
##
-DAVERAGE = BDPROMEDIO ## Devuelve el promedio de las entradas seleccionadas en la base de datos.
-DCOUNT = BDCONTAR ## Cuenta el número de celdas que contienen números en una base de datos.
-DCOUNTA = BDCONTARA ## Cuenta el número de celdas no vacías en una base de datos.
-DGET = BDEXTRAER ## Extrae de una base de datos un único registro que cumple los criterios especificados.
-DMAX = BDMAX ## Devuelve el valor máximo de las entradas seleccionadas de la base de datos.
-DMIN = BDMIN ## Devuelve el valor mínimo de las entradas seleccionadas de la base de datos.
-DPRODUCT = BDPRODUCTO ## Multiplica los valores de un campo concreto de registros de una base de datos que cumplen los criterios especificados.
-DSTDEV = BDDESVEST ## Calcula la desviación estándar a partir de una muestra de entradas seleccionadas en la base de datos.
-DSTDEVP = BDDESVESTP ## Calcula la desviación estándar en función de la población total de las entradas seleccionadas de la base de datos.
-DSUM = BDSUMA ## Suma los números de la columna de campo de los registros de la base de datos que cumplen los criterios.
-DVAR = BDVAR ## Calcula la varianza a partir de una muestra de entradas seleccionadas de la base de datos.
-DVARP = BDVARP ## Calcula la varianza a partir de la población total de entradas seleccionadas de la base de datos.
-
+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
##
-## Date and time functions Funciones de fecha y hora
+## Funciones de ingeniería (Engineering Functions)
##
-DATE = FECHA ## Devuelve el número de serie correspondiente a una fecha determinada.
-DATEVALUE = FECHANUMERO ## Convierte una fecha con formato de texto en un valor de número de serie.
-DAY = DIA ## Convierte un número de serie en un valor de día del mes.
-DAYS360 = DIAS360 ## Calcula el número de días entre dos fechas a partir de un año de 360 días.
-EDATE = FECHA.MES ## Devuelve el número de serie de la fecha equivalente al número indicado de meses anteriores o posteriores a la fecha inicial.
-EOMONTH = FIN.MES ## Devuelve el número de serie correspondiente al último día del mes anterior o posterior a un número de meses especificado.
-HOUR = HORA ## Convierte un número de serie en un valor de hora.
-MINUTE = MINUTO ## Convierte un número de serie en un valor de minuto.
-MONTH = MES ## Convierte un número de serie en un valor de mes.
-NETWORKDAYS = DIAS.LAB ## Devuelve el número de todos los días laborables existentes entre dos fechas.
-NOW = AHORA ## Devuelve el número de serie correspondiente a la fecha y hora actuales.
-SECOND = SEGUNDO ## Convierte un número de serie en un valor de segundo.
-TIME = HORA ## Devuelve el número de serie correspondiente a una hora determinada.
-TIMEVALUE = HORANUMERO ## Convierte una hora con formato de texto en un valor de número de serie.
-TODAY = HOY ## Devuelve el número de serie correspondiente al día actual.
-WEEKDAY = DIASEM ## Convierte un número de serie en un valor de día de la semana.
-WEEKNUM = NUM.DE.SEMANA ## Convierte un número de serie en un número que representa el lugar numérico correspondiente a una semana de un año.
-WORKDAY = DIA.LAB ## Devuelve el número de serie de la fecha que tiene lugar antes o después de un número determinado de días laborables.
-YEAR = AÑO ## Convierte un número de serie en un valor de año.
-YEARFRAC = FRAC.AÑO ## Devuelve la fracción de año que representa el número total de días existentes entre el valor de fecha_inicial y el de fecha_final.
-
+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
##
-## Engineering functions Funciones de ingeniería
+## Funciones financieras (Financial Functions)
##
-BESSELI = BESSELI ## Devuelve la función Bessel In(x) modificada.
-BESSELJ = BESSELJ ## Devuelve la función Bessel Jn(x).
-BESSELK = BESSELK ## Devuelve la función Bessel Kn(x) modificada.
-BESSELY = BESSELY ## Devuelve la función Bessel Yn(x).
-BIN2DEC = BIN.A.DEC ## Convierte un número binario en decimal.
-BIN2HEX = BIN.A.HEX ## Convierte un número binario en hexadecimal.
-BIN2OCT = BIN.A.OCT ## Convierte un número binario en octal.
-COMPLEX = COMPLEJO ## Convierte coeficientes reales e imaginarios en un número complejo.
-CONVERT = CONVERTIR ## Convierte un número de un sistema de medida a otro.
-DEC2BIN = DEC.A.BIN ## Convierte un número decimal en binario.
-DEC2HEX = DEC.A.HEX ## Convierte un número decimal en hexadecimal.
-DEC2OCT = DEC.A.OCT ## Convierte un número decimal en octal.
-DELTA = DELTA ## Comprueba si dos valores son iguales.
-ERF = FUN.ERROR ## Devuelve la función de error.
-ERFC = FUN.ERROR.COMPL ## Devuelve la función de error complementario.
-GESTEP = MAYOR.O.IGUAL ## Comprueba si un número es mayor que un valor de umbral.
-HEX2BIN = HEX.A.BIN ## Convierte un número hexadecimal en binario.
-HEX2DEC = HEX.A.DEC ## Convierte un número hexadecimal en decimal.
-HEX2OCT = HEX.A.OCT ## Convierte un número hexadecimal en octal.
-IMABS = IM.ABS ## Devuelve el valor absoluto (módulo) de un número complejo.
-IMAGINARY = IMAGINARIO ## Devuelve el coeficiente imaginario de un número complejo.
-IMARGUMENT = IM.ANGULO ## Devuelve el argumento theta, un ángulo expresado en radianes.
-IMCONJUGATE = IM.CONJUGADA ## Devuelve la conjugada compleja de un número complejo.
-IMCOS = IM.COS ## Devuelve el coseno de un número complejo.
-IMDIV = IM.DIV ## Devuelve el cociente de dos números complejos.
-IMEXP = IM.EXP ## Devuelve el valor exponencial de un número complejo.
-IMLN = IM.LN ## Devuelve el logaritmo natural (neperiano) de un número complejo.
-IMLOG10 = IM.LOG10 ## Devuelve el logaritmo en base 10 de un número complejo.
-IMLOG2 = IM.LOG2 ## Devuelve el logaritmo en base 2 de un número complejo.
-IMPOWER = IM.POT ## Devuelve un número complejo elevado a una potencia entera.
-IMPRODUCT = IM.PRODUCT ## Devuelve el producto de números complejos.
-IMREAL = IM.REAL ## Devuelve el coeficiente real de un número complejo.
-IMSIN = IM.SENO ## Devuelve el seno de un número complejo.
-IMSQRT = IM.RAIZ2 ## Devuelve la raíz cuadrada de un número complejo.
-IMSUB = IM.SUSTR ## Devuelve la diferencia entre dos números complejos.
-IMSUM = IM.SUM ## Devuelve la suma de números complejos.
-OCT2BIN = OCT.A.BIN ## Convierte un número octal en binario.
-OCT2DEC = OCT.A.DEC ## Convierte un número octal en decimal.
-OCT2HEX = OCT.A.HEX ## Convierte un número octal en hexadecimal.
-
+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
##
-## Financial functions Funciones financieras
+## Funciones de información (Information Functions)
##
-ACCRINT = INT.ACUM ## Devuelve el interés acumulado de un valor bursátil con pagos de interés periódicos.
-ACCRINTM = INT.ACUM.V ## Devuelve el interés acumulado de un valor bursátil con pagos de interés al vencimiento.
-AMORDEGRC = AMORTIZ.PROGRE ## Devuelve la amortización de cada período contable mediante el uso de un coeficiente de amortización.
-AMORLINC = AMORTIZ.LIN ## Devuelve la amortización de cada uno de los períodos contables.
-COUPDAYBS = CUPON.DIAS.L1 ## Devuelve el número de días desde el principio del período de un cupón hasta la fecha de liquidación.
-COUPDAYS = CUPON.DIAS ## Devuelve el número de días del período (entre dos cupones) donde se encuentra la fecha de liquidación.
-COUPDAYSNC = CUPON.DIAS.L2 ## Devuelve el número de días desde la fecha de liquidación hasta la fecha del próximo cupón.
-COUPNCD = CUPON.FECHA.L2 ## Devuelve la fecha del próximo cupón después de la fecha de liquidación.
-COUPNUM = CUPON.NUM ## Devuelve el número de pagos de cupón entre la fecha de liquidación y la fecha de vencimiento.
-COUPPCD = CUPON.FECHA.L1 ## Devuelve la fecha de cupón anterior a la fecha de liquidación.
-CUMIPMT = PAGO.INT.ENTRE ## Devuelve el interés acumulado pagado entre dos períodos.
-CUMPRINC = PAGO.PRINC.ENTRE ## Devuelve el capital acumulado pagado de un préstamo entre dos períodos.
-DB = DB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización de saldo fijo.
-DDB = DDB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización por doble disminución de saldo u otro método que se especifique.
-DISC = TASA.DESC ## Devuelve la tasa de descuento de un valor bursátil.
-DOLLARDE = MONEDA.DEC ## Convierte una cotización de un valor bursátil expresada en forma fraccionaria en una cotización de un valor bursátil expresada en forma decimal.
-DOLLARFR = MONEDA.FRAC ## Convierte una cotización de un valor bursátil expresada en forma decimal en una cotización de un valor bursátil expresada en forma fraccionaria.
-DURATION = DURACION ## Devuelve la duración anual de un valor bursátil con pagos de interés periódico.
-EFFECT = INT.EFECTIVO ## Devuelve la tasa de interés anual efectiva.
-FV = VF ## Devuelve el valor futuro de una inversión.
-FVSCHEDULE = VF.PLAN ## Devuelve el valor futuro de un capital inicial después de aplicar una serie de tasas de interés compuesto.
-INTRATE = TASA.INT ## Devuelve la tasa de interés para la inversión total de un valor bursátil.
-IPMT = PAGOINT ## Devuelve el pago de intereses de una inversión durante un período determinado.
-IRR = TIR ## Devuelve la tasa interna de retorno para una serie de flujos de efectivo periódicos.
-ISPMT = INT.PAGO.DIR ## Calcula el interés pagado durante un período específico de una inversión.
-MDURATION = DURACION.MODIF ## Devuelve la duración de Macauley modificada de un valor bursátil con un valor nominal supuesto de 100 $.
-MIRR = TIRM ## Devuelve la tasa interna de retorno donde se financian flujos de efectivo positivos y negativos a tasas diferentes.
-NOMINAL = TASA.NOMINAL ## Devuelve la tasa nominal de interés anual.
-NPER = NPER ## Devuelve el número de períodos de una inversión.
-NPV = VNA ## Devuelve el valor neto actual de una inversión en función de una serie de flujos periódicos de efectivo y una tasa de descuento.
-ODDFPRICE = PRECIO.PER.IRREGULAR.1 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un primer período impar.
-ODDFYIELD = RENDTO.PER.IRREGULAR.1 ## Devuelve el rendimiento de un valor bursátil con un primer período impar.
-ODDLPRICE = PRECIO.PER.IRREGULAR.2 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un último período impar.
-ODDLYIELD = RENDTO.PER.IRREGULAR.2 ## Devuelve el rendimiento de un valor bursátil con un último período impar.
-PMT = PAGO ## Devuelve el pago periódico de una anualidad.
-PPMT = PAGOPRIN ## Devuelve el pago de capital de una inversión durante un período determinado.
-PRICE = PRECIO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga una tasa de interés periódico.
-PRICEDISC = PRECIO.DESCUENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con descuento.
-PRICEMAT = PRECIO.VENCIMIENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga interés a su vencimiento.
-PV = VALACT ## Devuelve el valor actual de una inversión.
-RATE = TASA ## Devuelve la tasa de interés por período de una anualidad.
-RECEIVED = CANTIDAD.RECIBIDA ## Devuelve la cantidad recibida al vencimiento de un valor bursátil completamente invertido.
-SLN = SLN ## Devuelve la amortización por método directo de un bien en un período dado.
-SYD = SYD ## Devuelve la amortización por suma de dígitos de los años de un bien durante un período especificado.
-TBILLEQ = LETRA.DE.TES.EQV.A.BONO ## Devuelve el rendimiento de un bono equivalente a una letra del Tesoro (de EE.UU.)
-TBILLPRICE = LETRA.DE.TES.PRECIO ## Devuelve el precio por un valor nominal de 100 $ de una letra del Tesoro (de EE.UU.)
-TBILLYIELD = LETRA.DE.TES.RENDTO ## Devuelve el rendimiento de una letra del Tesoro (de EE.UU.)
-VDB = DVS ## Devuelve la amortización de un bien durante un período específico o parcial a través del método de cálculo del saldo en disminución.
-XIRR = TIR.NO.PER ## Devuelve la tasa interna de retorno para un flujo de efectivo que no es necesariamente periódico.
-XNPV = VNA.NO.PER ## Devuelve el valor neto actual para un flujo de efectivo que no es necesariamente periódico.
-YIELD = RENDTO ## Devuelve el rendimiento de un valor bursátil que paga intereses periódicos.
-YIELDDISC = RENDTO.DESC ## Devuelve el rendimiento anual de un valor bursátil con descuento; por ejemplo, una letra del Tesoro (de EE.UU.)
-YIELDMAT = RENDTO.VENCTO ## Devuelve el rendimiento anual de un valor bursátil que paga intereses al vencimiento.
-
+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
##
-## Information functions Funciones de información
+## Funciones lógicas (Logical Functions)
##
-CELL = CELDA ## Devuelve información acerca del formato, la ubicación o el contenido de una celda.
-ERROR.TYPE = TIPO.DE.ERROR ## Devuelve un número que corresponde a un tipo de error.
-INFO = INFO ## Devuelve información acerca del entorno operativo en uso.
-ISBLANK = ESBLANCO ## Devuelve VERDADERO si el valor está en blanco.
-ISERR = ESERR ## Devuelve VERDADERO si el valor es cualquier valor de error excepto #N/A.
-ISERROR = ESERROR ## Devuelve VERDADERO si el valor es cualquier valor de error.
-ISEVEN = ES.PAR ## Devuelve VERDADERO si el número es par.
-ISLOGICAL = ESLOGICO ## Devuelve VERDADERO si el valor es un valor lógico.
-ISNA = ESNOD ## Devuelve VERDADERO si el valor es el valor de error #N/A.
-ISNONTEXT = ESNOTEXTO ## Devuelve VERDADERO si el valor no es texto.
-ISNUMBER = ESNUMERO ## Devuelve VERDADERO si el valor es un número.
-ISODD = ES.IMPAR ## Devuelve VERDADERO si el número es impar.
-ISREF = ESREF ## Devuelve VERDADERO si el valor es una referencia.
-ISTEXT = ESTEXTO ## Devuelve VERDADERO si el valor es texto.
-N = N ## Devuelve un valor convertido en un número.
-NA = ND ## Devuelve el valor de error #N/A.
-TYPE = TIPO ## Devuelve un número que indica el tipo de datos de un valor.
-
+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
##
-## Logical functions Funciones lógicas
+## Funciones de búsqueda y referencia (Lookup & Reference Functions)
##
-AND = Y ## Devuelve VERDADERO si todos sus argumentos son VERDADERO.
-FALSE = FALSO ## Devuelve el valor lógico FALSO.
-IF = SI ## Especifica una prueba lógica que realizar.
-IFERROR = SI.ERROR ## Devuelve un valor que se especifica si una fórmula lo evalúa como un error; de lo contrario, devuelve el resultado de la fórmula.
-NOT = NO ## Invierte el valor lógico del argumento.
-OR = O ## Devuelve VERDADERO si cualquier argumento es VERDADERO.
-TRUE = VERDADERO ## Devuelve el valor lógico VERDADERO.
-
+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
##
-## Lookup and reference functions Funciones de búsqueda y referencia
+## Funciones matemáticas y trigonométricas (Math & Trig Functions)
##
-ADDRESS = DIRECCION ## Devuelve una referencia como texto a una sola celda de una hoja de cálculo.
-AREAS = AREAS ## Devuelve el número de áreas de una referencia.
-CHOOSE = ELEGIR ## Elige un valor de una lista de valores.
-COLUMN = COLUMNA ## Devuelve el número de columna de una referencia.
-COLUMNS = COLUMNAS ## Devuelve el número de columnas de una referencia.
-HLOOKUP = BUSCARH ## Busca en la fila superior de una matriz y devuelve el valor de la celda indicada.
-HYPERLINK = HIPERVINCULO ## Crea un acceso directo o un salto que abre un documento almacenado en un servidor de red, en una intranet o en Internet.
-INDEX = INDICE ## Usa un índice para elegir un valor de una referencia o matriz.
-INDIRECT = INDIRECTO ## Devuelve una referencia indicada por un valor de texto.
-LOOKUP = BUSCAR ## Busca valores de un vector o una matriz.
-MATCH = COINCIDIR ## Busca valores de una referencia o matriz.
-OFFSET = DESREF ## Devuelve un desplazamiento de referencia respecto a una referencia dada.
-ROW = FILA ## Devuelve el número de fila de una referencia.
-ROWS = FILAS ## Devuelve el número de filas de una referencia.
-RTD = RDTR ## Recupera datos en tiempo real desde un programa compatible con la automatización COM (automatización: modo de trabajar con los objetos de una aplicación desde otra aplicación o herramienta de entorno. La automatización, antes denominada automatización OLE, es un estándar de la industria y una función del Modelo de objetos componentes (COM).).
-TRANSPOSE = TRANSPONER ## Devuelve la transposición de una matriz.
-VLOOKUP = BUSCARV ## Busca en la primera columna de una matriz y se mueve en horizontal por la fila para devolver el valor de una celda.
-
+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
##
-## Math and trigonometry functions Funciones matemáticas y trigonométricas
+## Funciones estadísticas (Statistical Functions)
##
-ABS = ABS ## Devuelve el valor absoluto de un número.
-ACOS = ACOS ## Devuelve el arcocoseno de un número.
-ACOSH = ACOSH ## Devuelve el coseno hiperbólico inverso de un número.
-ASIN = ASENO ## Devuelve el arcoseno de un número.
-ASINH = ASENOH ## Devuelve el seno hiperbólico inverso de un número.
-ATAN = ATAN ## Devuelve la arcotangente de un número.
-ATAN2 = ATAN2 ## Devuelve la arcotangente de las coordenadas "x" e "y".
-ATANH = ATANH ## Devuelve la tangente hiperbólica inversa de un número.
-CEILING = MULTIPLO.SUPERIOR ## Redondea un número al entero más próximo o al múltiplo significativo más cercano.
-COMBIN = COMBINAT ## Devuelve el número de combinaciones para un número determinado de objetos.
-COS = COS ## Devuelve el coseno de un número.
-COSH = COSH ## Devuelve el coseno hiperbólico de un número.
-DEGREES = GRADOS ## Convierte radianes en grados.
-EVEN = REDONDEA.PAR ## Redondea un número hasta el entero par más próximo.
-EXP = EXP ## Devuelve e elevado a la potencia de un número dado.
-FACT = FACT ## Devuelve el factorial de un número.
-FACTDOUBLE = FACT.DOBLE ## Devuelve el factorial doble de un número.
-FLOOR = MULTIPLO.INFERIOR ## Redondea un número hacia abajo, en dirección hacia cero.
-GCD = M.C.D ## Devuelve el máximo común divisor.
-INT = ENTERO ## Redondea un número hacia abajo hasta el entero más próximo.
-LCM = M.C.M ## Devuelve el mínimo común múltiplo.
-LN = LN ## Devuelve el logaritmo natural (neperiano) de un número.
-LOG = LOG ## Devuelve el logaritmo de un número en una base especificada.
-LOG10 = LOG10 ## Devuelve el logaritmo en base 10 de un número.
-MDETERM = MDETERM ## Devuelve la determinante matricial de una matriz.
-MINVERSE = MINVERSA ## Devuelve la matriz inversa de una matriz.
-MMULT = MMULT ## Devuelve el producto de matriz de dos matrices.
-MOD = RESIDUO ## Devuelve el resto de la división.
-MROUND = REDOND.MULT ## Devuelve un número redondeado al múltiplo deseado.
-MULTINOMIAL = MULTINOMIAL ## Devuelve el polinomio de un conjunto de números.
-ODD = REDONDEA.IMPAR ## Redondea un número hacia arriba hasta el entero impar más próximo.
-PI = PI ## Devuelve el valor de pi.
-POWER = POTENCIA ## Devuelve el resultado de elevar un número a una potencia.
-PRODUCT = PRODUCTO ## Multiplica sus argumentos.
-QUOTIENT = COCIENTE ## Devuelve la parte entera de una división.
-RADIANS = RADIANES ## Convierte grados en radianes.
-RAND = ALEATORIO ## Devuelve un número aleatorio entre 0 y 1.
-RANDBETWEEN = ALEATORIO.ENTRE ## Devuelve un número aleatorio entre los números que especifique.
-ROMAN = NUMERO.ROMANO ## Convierte un número arábigo en número romano, con formato de texto.
-ROUND = REDONDEAR ## Redondea un número al número de decimales especificado.
-ROUNDDOWN = REDONDEAR.MENOS ## Redondea un número hacia abajo, en dirección hacia cero.
-ROUNDUP = REDONDEAR.MAS ## Redondea un número hacia arriba, en dirección contraria a cero.
-SERIESSUM = SUMA.SERIES ## Devuelve la suma de una serie de potencias en función de la fórmula.
-SIGN = SIGNO ## Devuelve el signo de un número.
-SIN = SENO ## Devuelve el seno de un ángulo determinado.
-SINH = SENOH ## Devuelve el seno hiperbólico de un número.
-SQRT = RAIZ ## Devuelve la raíz cuadrada positiva de un número.
-SQRTPI = RAIZ2PI ## Devuelve la raíz cuadrada de un número multiplicado por PI (número * pi).
-SUBTOTAL = SUBTOTALES ## Devuelve un subtotal en una lista o base de datos.
-SUM = SUMA ## Suma sus argumentos.
-SUMIF = SUMAR.SI ## Suma las celdas especificadas que cumplen unos criterios determinados.
-SUMIFS = SUMAR.SI.CONJUNTO ## Suma las celdas de un rango que cumplen varios criterios.
-SUMPRODUCT = SUMAPRODUCTO ## Devuelve la suma de los productos de los correspondientes componentes de matriz.
-SUMSQ = SUMA.CUADRADOS ## Devuelve la suma de los cuadrados de los argumentos.
-SUMX2MY2 = SUMAX2MENOSY2 ## Devuelve la suma de la diferencia de los cuadrados de los valores correspondientes de dos matrices.
-SUMX2PY2 = SUMAX2MASY2 ## Devuelve la suma de la suma de los cuadrados de los valores correspondientes de dos matrices.
-SUMXMY2 = SUMAXMENOSY2 ## Devuelve la suma de los cuadrados de las diferencias de los valores correspondientes de dos matrices.
-TAN = TAN ## Devuelve la tangente de un número.
-TANH = TANH ## Devuelve la tangente hiperbólica de un número.
-TRUNC = TRUNCAR ## Trunca un número a un entero.
-
+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
##
-## Statistical functions Funciones estadísticas
+## Funciones de texto (Text Functions)
##
-AVEDEV = DESVPROM ## Devuelve el promedio de las desviaciones absolutas de la media de los puntos de datos.
-AVERAGE = PROMEDIO ## Devuelve el promedio de sus argumentos.
-AVERAGEA = PROMEDIOA ## Devuelve el promedio de sus argumentos, incluidos números, texto y valores lógicos.
-AVERAGEIF = PROMEDIO.SI ## Devuelve el promedio (media aritmética) de todas las celdas de un rango que cumplen unos criterios determinados.
-AVERAGEIFS = PROMEDIO.SI.CONJUNTO ## Devuelve el promedio (media aritmética) de todas las celdas que cumplen múltiples criterios.
-BETADIST = DISTR.BETA ## Devuelve la función de distribución beta acumulativa.
-BETAINV = DISTR.BETA.INV ## Devuelve la función inversa de la función de distribución acumulativa de una distribución beta especificada.
-BINOMDIST = DISTR.BINOM ## Devuelve la probabilidad de una variable aleatoria discreta siguiendo una distribución binomial.
-CHIDIST = DISTR.CHI ## Devuelve la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola.
-CHIINV = PRUEBA.CHI.INV ## Devuelve la función inversa de la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola.
-CHITEST = PRUEBA.CHI ## Devuelve la prueba de independencia.
-CONFIDENCE = INTERVALO.CONFIANZA ## Devuelve el intervalo de confianza de la media de una población.
-CORREL = COEF.DE.CORREL ## Devuelve el coeficiente de correlación entre dos conjuntos de datos.
-COUNT = CONTAR ## Cuenta cuántos números hay en la lista de argumentos.
-COUNTA = CONTARA ## Cuenta cuántos valores hay en la lista de argumentos.
-COUNTBLANK = CONTAR.BLANCO ## Cuenta el número de celdas en blanco de un rango.
-COUNTIF = CONTAR.SI ## Cuenta el número de celdas, dentro del rango, que cumplen el criterio especificado.
-COUNTIFS = CONTAR.SI.CONJUNTO ## Cuenta el número de celdas, dentro del rango, que cumplen varios criterios.
-COVAR = COVAR ## Devuelve la covarianza, que es el promedio de los productos de las desviaciones para cada pareja de puntos de datos.
-CRITBINOM = BINOM.CRIT ## Devuelve el menor valor cuya distribución binomial acumulativa es menor o igual a un valor de criterio.
-DEVSQ = DESVIA2 ## Devuelve la suma de los cuadrados de las desviaciones.
-EXPONDIST = DISTR.EXP ## Devuelve la distribución exponencial.
-FDIST = DISTR.F ## Devuelve la distribución de probabilidad F.
-FINV = DISTR.F.INV ## Devuelve la función inversa de la distribución de probabilidad F.
-FISHER = FISHER ## Devuelve la transformación Fisher.
-FISHERINV = PRUEBA.FISHER.INV ## Devuelve la función inversa de la transformación Fisher.
-FORECAST = PRONOSTICO ## Devuelve un valor en una tendencia lineal.
-FREQUENCY = FRECUENCIA ## Devuelve una distribución de frecuencia como una matriz vertical.
-FTEST = PRUEBA.F ## Devuelve el resultado de una prueba F.
-GAMMADIST = DISTR.GAMMA ## Devuelve la distribución gamma.
-GAMMAINV = DISTR.GAMMA.INV ## Devuelve la función inversa de la distribución gamma acumulativa.
-GAMMALN = GAMMA.LN ## Devuelve el logaritmo natural de la función gamma, G(x).
-GEOMEAN = MEDIA.GEOM ## Devuelve la media geométrica.
-GROWTH = CRECIMIENTO ## Devuelve valores en una tendencia exponencial.
-HARMEAN = MEDIA.ARMO ## Devuelve la media armónica.
-HYPGEOMDIST = DISTR.HIPERGEOM ## Devuelve la distribución hipergeométrica.
-INTERCEPT = INTERSECCION.EJE ## Devuelve la intersección de la línea de regresión lineal.
-KURT = CURTOSIS ## Devuelve la curtosis de un conjunto de datos.
-LARGE = K.ESIMO.MAYOR ## Devuelve el k-ésimo mayor valor de un conjunto de datos.
-LINEST = ESTIMACION.LINEAL ## Devuelve los parámetros de una tendencia lineal.
-LOGEST = ESTIMACION.LOGARITMICA ## Devuelve los parámetros de una tendencia exponencial.
-LOGINV = DISTR.LOG.INV ## Devuelve la función inversa de la distribución logarítmico-normal.
-LOGNORMDIST = DISTR.LOG.NORM ## Devuelve la distribución logarítmico-normal acumulativa.
-MAX = MAX ## Devuelve el valor máximo de una lista de argumentos.
-MAXA = MAXA ## Devuelve el valor máximo de una lista de argumentos, incluidos números, texto y valores lógicos.
-MEDIAN = MEDIANA ## Devuelve la mediana de los números dados.
-MIN = MIN ## Devuelve el valor mínimo de una lista de argumentos.
-MINA = MINA ## Devuelve el valor mínimo de una lista de argumentos, incluidos números, texto y valores lógicos.
-MODE = MODA ## Devuelve el valor más común de un conjunto de datos.
-NEGBINOMDIST = NEGBINOMDIST ## Devuelve la distribución binomial negativa.
-NORMDIST = DISTR.NORM ## Devuelve la distribución normal acumulativa.
-NORMINV = DISTR.NORM.INV ## Devuelve la función inversa de la distribución normal acumulativa.
-NORMSDIST = DISTR.NORM.ESTAND ## Devuelve la distribución normal estándar acumulativa.
-NORMSINV = DISTR.NORM.ESTAND.INV ## Devuelve la función inversa de la distribución normal estándar acumulativa.
-PEARSON = PEARSON ## Devuelve el coeficiente de momento de correlación de producto Pearson.
-PERCENTILE = PERCENTIL ## Devuelve el k-ésimo percentil de los valores de un rango.
-PERCENTRANK = RANGO.PERCENTIL ## Devuelve el rango porcentual de un valor de un conjunto de datos.
-PERMUT = PERMUTACIONES ## Devuelve el número de permutaciones de un número determinado de objetos.
-POISSON = POISSON ## Devuelve la distribución de Poisson.
-PROB = PROBABILIDAD ## Devuelve la probabilidad de que los valores de un rango se encuentren entre dos límites.
-QUARTILE = CUARTIL ## Devuelve el cuartil de un conjunto de datos.
-RANK = JERARQUIA ## Devuelve la jerarquía de un número en una lista de números.
-RSQ = COEFICIENTE.R2 ## Devuelve el cuadrado del coeficiente de momento de correlación de producto Pearson.
-SKEW = COEFICIENTE.ASIMETRIA ## Devuelve la asimetría de una distribución.
-SLOPE = PENDIENTE ## Devuelve la pendiente de la línea de regresión lineal.
-SMALL = K.ESIMO.MENOR ## Devuelve el k-ésimo menor valor de un conjunto de datos.
-STANDARDIZE = NORMALIZACION ## Devuelve un valor normalizado.
-STDEV = DESVEST ## Calcula la desviación estándar a partir de una muestra.
-STDEVA = DESVESTA ## Calcula la desviación estándar a partir de una muestra, incluidos números, texto y valores lógicos.
-STDEVP = DESVESTP ## Calcula la desviación estándar en función de toda la población.
-STDEVPA = DESVESTPA ## Calcula la desviación estándar en función de toda la población, incluidos números, texto y valores lógicos.
-STEYX = ERROR.TIPICO.XY ## Devuelve el error estándar del valor de "y" previsto para cada "x" de la regresión.
-TDIST = DISTR.T ## Devuelve la distribución de t de Student.
-TINV = DISTR.T.INV ## Devuelve la función inversa de la distribución de t de Student.
-TREND = TENDENCIA ## Devuelve valores en una tendencia lineal.
-TRIMMEAN = MEDIA.ACOTADA ## Devuelve la media del interior de un conjunto de datos.
-TTEST = PRUEBA.T ## Devuelve la probabilidad asociada a una prueba t de Student.
-VAR = VAR ## Calcula la varianza en función de una muestra.
-VARA = VARA ## Calcula la varianza en función de una muestra, incluidos números, texto y valores lógicos.
-VARP = VARP ## Calcula la varianza en función de toda la población.
-VARPA = VARPA ## Calcula la varianza en función de toda la población, incluidos números, texto y valores lógicos.
-WEIBULL = DIST.WEIBULL ## Devuelve la distribución de Weibull.
-ZTEST = PRUEBA.Z ## Devuelve el valor de una probabilidad de una cola de una prueba z.
-
+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
##
-## Text functions Funciones de texto
+## Funciones web (Web Functions)
##
-ASC = ASC ## Convierte las letras inglesas o katakana de ancho completo (de dos bytes) dentro de una cadena de caracteres en caracteres de ancho medio (de un byte).
-BAHTTEXT = TEXTOBAHT ## Convierte un número en texto, con el formato de moneda ß (Baht).
-CHAR = CARACTER ## Devuelve el carácter especificado por el número de código.
-CLEAN = LIMPIAR ## Quita del texto todos los caracteres no imprimibles.
-CODE = CODIGO ## Devuelve un código numérico del primer carácter de una cadena de texto.
-CONCATENATE = CONCATENAR ## Concatena varios elementos de texto en uno solo.
-DOLLAR = MONEDA ## Convierte un número en texto, con el formato de moneda $ (dólar).
-EXACT = IGUAL ## Comprueba si dos valores de texto son idénticos.
-FIND = ENCONTRAR ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas).
-FINDB = ENCONTRARB ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas).
-FIXED = DECIMAL ## Da formato a un número como texto con un número fijo de decimales.
-JIS = JIS ## Convierte las letras inglesas o katakana de ancho medio (de un byte) dentro de una cadena de caracteres en caracteres de ancho completo (de dos bytes).
-LEFT = IZQUIERDA ## Devuelve los caracteres del lado izquierdo de un valor de texto.
-LEFTB = IZQUIERDAB ## Devuelve los caracteres del lado izquierdo de un valor de texto.
-LEN = LARGO ## Devuelve el número de caracteres de una cadena de texto.
-LENB = LARGOB ## Devuelve el número de caracteres de una cadena de texto.
-LOWER = MINUSC ## Pone el texto en minúsculas.
-MID = EXTRAE ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique.
-MIDB = EXTRAEB ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique.
-PHONETIC = FONETICO ## Extrae los caracteres fonéticos (furigana) de una cadena de texto.
-PROPER = NOMPROPIO ## Pone en mayúscula la primera letra de cada palabra de un valor de texto.
-REPLACE = REEMPLAZAR ## Reemplaza caracteres de texto.
-REPLACEB = REEMPLAZARB ## Reemplaza caracteres de texto.
-REPT = REPETIR ## Repite el texto un número determinado de veces.
-RIGHT = DERECHA ## Devuelve los caracteres del lado derecho de un valor de texto.
-RIGHTB = DERECHAB ## Devuelve los caracteres del lado derecho de un valor de texto.
-SEARCH = HALLAR ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas).
-SEARCHB = HALLARB ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas).
-SUBSTITUTE = SUSTITUIR ## Sustituye texto nuevo por texto antiguo en una cadena de texto.
-T = T ## Convierte sus argumentos a texto.
-TEXT = TEXTO ## Da formato a un número y lo convierte en texto.
-TRIM = ESPACIOS ## Quita los espacios del texto.
-UPPER = MAYUSC ## Pone el texto en mayúsculas.
-VALUE = VALOR ## Convierte un argumento de texto en un número.
+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
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/config
index 22aaf58b98d..5388f9399c2 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Suomi (Finnish)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = $ # Symbol not known, should it be a € (Euro)?
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #TYHJÄ!
-DIV0 = #JAKO/0!
-VALUE = #ARVO!
-REF = #VIITTAUS!
-NAME = #NIMI?
-NUM = #LUKU!
-NA = #PUUTTUU
+NULL = #TYHJÄ!
+DIV0 = #JAKO/0!
+VALUE = #ARVO!
+REF = #VIITTAUS!
+NAME = #NIMI?
+NUM = #LUKU!
+NA = #PUUTTUU!
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/functions
index 289e0eaca48..33068d93e9f 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/functions
@@ -1,416 +1,537 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
+## PhpSpreadsheet - function name translations
##
+## Suomi (Finnish)
##
+############################################################
##
-## Add-in and Automation functions Apuohjelma- ja automaatiofunktiot
+## Kuutiofunktiot (Cube Functions)
##
-GETPIVOTDATA = NOUDA.PIVOT.TIEDOT ## Palauttaa pivot-taulukkoraporttiin tallennettuja tietoja.
-
+CUBEKPIMEMBER = KUUTIOKPIJÄSEN
+CUBEMEMBER = KUUTIONJÄSEN
+CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS
+CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN
+CUBESET = KUUTIOJOUKKO
+CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ
+CUBEVALUE = KUUTIONARVO
##
-## Cube functions Kuutiofunktiot
+## Tietokantafunktiot (Database Functions)
##
-CUBEKPIMEMBER = KUUTIOKPIJÄSEN ## Palauttaa suorituskykyilmaisimen (KPI) nimen, ominaisuuden sekä mitan ja näyttää nimen sekä ominaisuuden solussa. KPI on mitattavissa oleva suure, kuten kuukauden bruttotuotto tai vuosineljänneksen työntekijäkohtainen liikevaihto, joiden avulla tarkkaillaan organisaation suorituskykyä.
-CUBEMEMBER = KUUTIONJÄSEN ## Palauttaa kuutiohierarkian jäsenen tai monikon. Tällä funktiolla voit tarkistaa, että jäsen tai monikko on olemassa kuutiossa.
-CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS ## Palauttaa kuution jäsenominaisuuden arvon. Tällä funktiolla voit tarkistaa, että nimi on olemassa kuutiossa, ja palauttaa tämän jäsenen määritetyn ominaisuuden.
-CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN ## Palauttaa joukon n:nnen jäsenen. Tällä funktiolla voit palauttaa joukosta elementtejä, kuten parhaan myyjän tai 10 parasta opiskelijaa.
-CUBESET = KUUTIOJOUKKO ## Määrittää lasketun jäsen- tai monikkojoukon lähettämällä joukon lausekkeita palvelimessa olevalle kuutiolle. Palvelin luo joukon ja palauttaa sen Microsoft Office Excelille.
-CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ ## Palauttaa joukon kohteiden määrän.
-CUBEVALUE = KUUTIONARVO ## Palauttaa koostetun arvon kuutiosta.
-
+DAVERAGE = TKESKIARVO
+DCOUNT = TLASKE
+DCOUNTA = TLASKEA
+DGET = TNOUDA
+DMAX = TMAKS
+DMIN = TMIN
+DPRODUCT = TTULO
+DSTDEV = TKESKIHAJONTA
+DSTDEVP = TKESKIHAJONTAP
+DSUM = TSUMMA
+DVAR = TVARIANSSI
+DVARP = TVARIANSSIP
##
-## Database functions Tietokantafunktiot
+## Päivämäärä- ja aikafunktiot (Date & Time Functions)
##
-DAVERAGE = TKESKIARVO ## Palauttaa valittujen tietokantamerkintöjen keskiarvon.
-DCOUNT = TLASKE ## Laskee tietokannan lukuja sisältävien solujen määrän.
-DCOUNTA = TLASKEA ## Laskee tietokannan tietoja sisältävien solujen määrän.
-DGET = TNOUDA ## Hakee määritettyjä ehtoja vastaavan tietueen tietokannasta.
-DMAX = TMAKS ## Palauttaa suurimman arvon tietokannasta valittujen arvojen joukosta.
-DMIN = TMIN ## Palauttaa pienimmän arvon tietokannasta valittujen arvojen joukosta.
-DPRODUCT = TTULO ## Kertoo määritetyn ehdon täyttävien tietokannan tietueiden tietyssä kentässä olevat arvot.
-DSTDEV = TKESKIHAJONTA ## Laskee keskihajonnan tietokannasta valituista arvoista muodostuvan otoksen perusteella.
-DSTDEVP = TKESKIHAJONTAP ## Laskee keskihajonnan tietokannasta valittujen arvojen koko populaation perusteella.
-DSUM = TSUMMA ## Lisää luvut määritetyn ehdon täyttävien tietokannan tietueiden kenttäsarakkeeseen.
-DVAR = TVARIANSSI ## Laskee varianssin tietokannasta valittujen arvojen otoksen perusteella.
-DVARP = TVARIANSSIP ## Laskee varianssin tietokannasta valittujen arvojen koko populaation perusteella.
-
+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
##
-## Date and time functions Päivämäärä- ja aikafunktiot
+## Tekniset funktiot (Engineering Functions)
##
-DATE = PÄIVÄYS ## Palauttaa annetun päivämäärän järjestysluvun.
-DATEVALUE = PÄIVÄYSARVO ## Muuntaa tekstimuodossa olevan päivämäärän järjestysluvuksi.
-DAY = PÄIVÄ ## Muuntaa järjestysluvun kuukauden päiväksi.
-DAYS360 = PÄIVÄT360 ## Laskee kahden päivämäärän välisten päivien määrän käyttäen perustana 360-päiväistä vuotta.
-EDATE = PÄIVÄ.KUUKAUSI ## Palauttaa järjestyslukuna päivämäärän, joka poikkeaa aloituspäivän päivämäärästä annetun kuukausimäärän verran joko eteen- tai taaksepäin.
-EOMONTH = KUUKAUSI.LOPPU ## Palauttaa järjestyslukuna sen kuukauden viimeisen päivämäärän, joka poikkeaa annetun kuukausimäärän verran eteen- tai taaksepäin.
-HOUR = TUNNIT ## Muuntaa järjestysluvun tunneiksi.
-MINUTE = MINUUTIT ## Muuntaa järjestysluvun minuuteiksi.
-MONTH = KUUKAUSI ## Muuntaa järjestysluvun kuukausiksi.
-NETWORKDAYS = TYÖPÄIVÄT ## Palauttaa kahden päivämäärän välissä olevien täysien työpäivien määrän.
-NOW = NYT ## Palauttaa kuluvan päivämäärän ja ajan järjestysnumeron.
-SECOND = SEKUNNIT ## Muuntaa järjestysluvun sekunneiksi.
-TIME = AIKA ## Palauttaa annetun kellonajan järjestysluvun.
-TIMEVALUE = AIKA_ARVO ## Muuntaa tekstimuodossa olevan kellonajan järjestysluvuksi.
-TODAY = TÄMÄ.PÄIVÄ ## Palauttaa kuluvan päivän päivämäärän järjestysluvun.
-WEEKDAY = VIIKONPÄIVÄ ## Muuntaa järjestysluvun viikonpäiväksi.
-WEEKNUM = VIIKKO.NRO ## Muuntaa järjestysluvun luvuksi, joka ilmaisee viikon järjestysluvun vuoden alusta laskettuna.
-WORKDAY = TYÖPÄIVÄ ## Palauttaa järjestysluvun päivämäärälle, joka sijaitsee annettujen työpäivien verran eteen tai taaksepäin.
-YEAR = VUOSI ## Muuntaa järjestysluvun vuosiksi.
-YEARFRAC = VUOSI.OSA ## Palauttaa määritettyjen päivämäärien (aloituspäivä ja lopetuspäivä) välisen osan vuodesta.
-
+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
##
-## Engineering functions Tekniset funktiot
+## Rahoitusfunktiot (Financial Functions)
##
-BESSELI = BESSELI ## Palauttaa muunnetun Bessel-funktion In(x).
-BESSELJ = BESSELJ ## Palauttaa Bessel-funktion Jn(x).
-BESSELK = BESSELK ## Palauttaa muunnetun Bessel-funktion Kn(x).
-BESSELY = BESSELY ## Palauttaa Bessel-funktion Yn(x).
-BIN2DEC = BINDES ## Muuntaa binaariluvun desimaaliluvuksi.
-BIN2HEX = BINHEKSA ## Muuntaa binaariluvun heksadesimaaliluvuksi.
-BIN2OCT = BINOKT ## Muuntaa binaariluvun oktaaliluvuksi.
-COMPLEX = KOMPLEKSI ## Muuntaa reaali- ja imaginaariosien kertoimet kompleksiluvuksi.
-CONVERT = MUUNNA ## Muuntaa luvun toisen mittajärjestelmän mukaiseksi.
-DEC2BIN = DESBIN ## Muuntaa desimaaliluvun binaariluvuksi.
-DEC2HEX = DESHEKSA ## Muuntaa kymmenjärjestelmän luvun heksadesimaaliluvuksi.
-DEC2OCT = DESOKT ## Muuntaa kymmenjärjestelmän luvun oktaaliluvuksi.
-DELTA = SAMA.ARVO ## Tarkistaa, ovatko kaksi arvoa yhtä suuria.
-ERF = VIRHEFUNKTIO ## Palauttaa virhefunktion.
-ERFC = VIRHEFUNKTIO.KOMPLEMENTTI ## Palauttaa komplementtivirhefunktion.
-GESTEP = RAJA ## Testaa, onko luku suurempi kuin kynnysarvo.
-HEX2BIN = HEKSABIN ## Muuntaa heksadesimaaliluvun binaariluvuksi.
-HEX2DEC = HEKSADES ## Muuntaa heksadesimaaliluvun desimaaliluvuksi.
-HEX2OCT = HEKSAOKT ## Muuntaa heksadesimaaliluvun oktaaliluvuksi.
-IMABS = KOMPLEKSI.ITSEISARVO ## Palauttaa kompleksiluvun itseisarvon (moduluksen).
-IMAGINARY = KOMPLEKSI.IMAG ## Palauttaa kompleksiluvun imaginaariosan kertoimen.
-IMARGUMENT = KOMPLEKSI.ARG ## Palauttaa theeta-argumentin, joka on radiaaneina annettu kulma.
-IMCONJUGATE = KOMPLEKSI.KONJ ## Palauttaa kompleksiluvun konjugaattiluvun.
-IMCOS = KOMPLEKSI.COS ## Palauttaa kompleksiluvun kosinin.
-IMDIV = KOMPLEKSI.OSAM ## Palauttaa kahden kompleksiluvun osamäärän.
-IMEXP = KOMPLEKSI.EKSP ## Palauttaa kompleksiluvun eksponentin.
-IMLN = KOMPLEKSI.LN ## Palauttaa kompleksiluvun luonnollisen logaritmin.
-IMLOG10 = KOMPLEKSI.LOG10 ## Palauttaa kompleksiluvun kymmenkantaisen logaritmin.
-IMLOG2 = KOMPLEKSI.LOG2 ## Palauttaa kompleksiluvun kaksikantaisen logaritmin.
-IMPOWER = KOMPLEKSI.POT ## Palauttaa kokonaislukupotenssiin korotetun kompleksiluvun.
-IMPRODUCT = KOMPLEKSI.TULO ## Palauttaa kompleksilukujen tulon.
-IMREAL = KOMPLEKSI.REAALI ## Palauttaa kompleksiluvun reaaliosan kertoimen.
-IMSIN = KOMPLEKSI.SIN ## Palauttaa kompleksiluvun sinin.
-IMSQRT = KOMPLEKSI.NELIÖJ ## Palauttaa kompleksiluvun neliöjuuren.
-IMSUB = KOMPLEKSI.EROTUS ## Palauttaa kahden kompleksiluvun erotuksen.
-IMSUM = KOMPLEKSI.SUM ## Palauttaa kompleksilukujen summan.
-OCT2BIN = OKTBIN ## Muuntaa oktaaliluvun binaariluvuksi.
-OCT2DEC = OKTDES ## Muuntaa oktaaliluvun desimaaliluvuksi.
-OCT2HEX = OKTHEKSA ## Muuntaa oktaaliluvun heksadesimaaliluvuksi.
-
+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
##
-## Financial functions Rahoitusfunktiot
+## Tietofunktiot (Information Functions)
##
-ACCRINT = KERTYNYT.KORKO ## Laskee arvopaperille kertyneen koron, kun korko kertyy säännöllisin väliajoin.
-ACCRINTM = KERTYNYT.KORKO.LOPUSSA ## Laskee arvopaperille kertyneen koron, kun korko maksetaan eräpäivänä.
-AMORDEGRC = AMORDEGRC ## Laskee kunkin laskentakauden poiston poistokerrointa käyttämällä.
-AMORLINC = AMORLINC ## Palauttaa kunkin laskentakauden poiston.
-COUPDAYBS = KORKOPÄIVÄT.ALUSTA ## Palauttaa koronmaksukauden aloituspäivän ja tilityspäivän välisen ajanjakson päivien määrän.
-COUPDAYS = KORKOPÄIVÄT ## Palauttaa päivien määrän koronmaksukaudelta, johon tilityspäivä kuuluu.
-COUPDAYSNC = KORKOPÄIVÄT.SEURAAVA ## Palauttaa tilityspäivän ja seuraavan koronmaksupäivän välisen ajanjakson päivien määrän.
-COUPNCD = KORKOMAKSU.SEURAAVA ## Palauttaa tilityspäivän jälkeisen seuraavan koronmaksupäivän.
-COUPNUM = KORKOPÄIVÄJAKSOT ## Palauttaa arvopaperin ostopäivän ja erääntymispäivän välisten koronmaksupäivien määrän.
-COUPPCD = KORKOPÄIVÄ.EDELLINEN ## Palauttaa tilityspäivää edeltävän koronmaksupäivän.
-CUMIPMT = MAKSETTU.KORKO ## Palauttaa kahden jakson välisenä aikana kertyneen koron.
-CUMPRINC = MAKSETTU.LYHENNYS ## Palauttaa lainalle kahden jakson välisenä aikana kertyneen lyhennyksen.
-DB = DB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan.
-DDB = DDB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DDB-menetelmän (Double-Declining Balance) tai jonkin muun määrittämäsi menetelmän mukaan.
-DISC = DISKONTTOKORKO ## Palauttaa arvopaperin diskonttokoron.
-DOLLARDE = VALUUTTA.DES ## Muuntaa murtolukuna ilmoitetun valuuttamäärän desimaaliluvuksi.
-DOLLARFR = VALUUTTA.MURTO ## Muuntaa desimaalilukuna ilmaistun valuuttamäärän murtoluvuksi.
-DURATION = KESTO ## Palauttaa keston arvopaperille, jonka koronmaksu tapahtuu säännöllisesti.
-EFFECT = KORKO.EFEKT ## Palauttaa todellisen vuosikoron.
-FV = TULEVA.ARVO ## Palauttaa sijoituksen tulevan arvon.
-FVSCHEDULE = TULEVA.ARVO.ERIKORKO ## Palauttaa pääoman tulevan arvon, kun pääomalle on kertynyt korkoa vaihtelevasti.
-INTRATE = KORKO.ARVOPAPERI ## Palauttaa arvopaperin korkokannan täysin sijoitetulle arvopaperille.
-IPMT = IPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona kertyvän koron.
-IRR = SISÄINEN.KORKO ## Laskee sisäisen korkokannan kassavirrasta muodostuvalle sarjalle.
-ISPMT = ONMAKSU ## Laskee sijoituksen maksetun koron tietyllä jaksolla.
-MDURATION = KESTO.MUUNN ## Palauttaa muunnetun Macauley-keston arvopaperille, jonka oletettu nimellisarvo on 100 euroa.
-MIRR = MSISÄINEN ## Palauttaa sisäisen korkokannan, kun positiivisten ja negatiivisten kassavirtojen rahoituskorko on erilainen.
-NOMINAL = KORKO.VUOSI ## Palauttaa vuosittaisen nimelliskoron.
-NPER = NJAKSO ## Palauttaa sijoituksen jaksojen määrän.
-NPV = NNA ## Palauttaa sijoituksen nykyarvon toistuvista kassavirroista muodostuvan sarjan ja diskonttokoron perusteella.
-ODDFPRICE = PARITON.ENS.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa ensimmäinen jakso on pariton.
-ODDFYIELD = PARITON.ENS.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa ensimmäinen jakso on pariton.
-ODDLPRICE = PARITON.VIIM.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa viimeinen jakso on pariton.
-ODDLYIELD = PARITON.VIIM.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa viimeinen jakso on pariton.
-PMT = MAKSU ## Palauttaa annuiteetin kausittaisen maksuerän.
-PPMT = PPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona maksettavan lyhennyksen.
-PRICE = HINTA ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan säännöllisin väliajoin.
-PRICEDISC = HINTA.DISK ## Palauttaa diskontatun arvopaperin hinnan 100 euron nimellisarvoa kohden.
-PRICEMAT = HINTA.LUNASTUS ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan erääntymispäivänä.
-PV = NA ## Palauttaa sijoituksen nykyarvon.
-RATE = KORKO ## Palauttaa annuiteetin kausittaisen korkokannan.
-RECEIVED = SAATU.HINTA ## Palauttaa arvopaperin tuoton erääntymispäivänä kokonaan maksetulle sijoitukselle.
-SLN = STP ## Palauttaa sijoituksen tasapoiston yhdeltä jaksolta.
-SYD = VUOSIPOISTO ## Palauttaa sijoituksen vuosipoiston annettuna kautena amerikkalaisen SYD-menetelmän (Sum-of-Year's Digits) avulla.
-TBILLEQ = OBLIG.TUOTTOPROS ## Palauttaa valtion obligaation tuoton vastaavana joukkovelkakirjan tuottona.
-TBILLPRICE = OBLIG.HINTA ## Palauttaa obligaation hinnan 100 euron nimellisarvoa kohden.
-TBILLYIELD = OBLIG.TUOTTO ## Palauttaa obligaation tuoton.
-VDB = VDB ## Palauttaa annetun kauden tai kauden osan kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan.
-XIRR = SISÄINEN.KORKO.JAKSOTON ## Palauttaa sisäisen korkokannan kassavirtojen sarjoille, jotka eivät välttämättä ole säännöllisiä.
-XNPV = NNA.JAKSOTON ## Palauttaa nettonykyarvon kassavirtasarjalle, joka ei välttämättä ole kausittainen.
-YIELD = TUOTTO ## Palauttaa tuoton arvopaperille, jonka korko maksetaan säännöllisin väliajoin.
-YIELDDISC = TUOTTO.DISK ## Palauttaa diskontatun arvopaperin, kuten obligaation, vuosittaisen tuoton.
-YIELDMAT = TUOTTO.ERÄP ## Palauttaa erääntymispäivänään korkoa tuottavan arvopaperin vuosittaisen tuoton.
-
+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
##
-## Information functions Erikoisfunktiot
+## Loogiset funktiot (Logical Functions)
##
-CELL = SOLU ## Palauttaa tietoja solun muotoilusta, sijainnista ja sisällöstä.
-ERROR.TYPE = VIRHEEN.LAJI ## Palauttaa virhetyyppiä vastaavan luvun.
-INFO = KUVAUS ## Palauttaa tietoja nykyisestä käyttöympäristöstä.
-ISBLANK = ONTYHJÄ ## Palauttaa arvon TOSI, jos arvo on tyhjä.
-ISERR = ONVIRH ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo paitsi arvo #PUUTTUU!.
-ISERROR = ONVIRHE ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo.
-ISEVEN = ONPARILLINEN ## Palauttaa arvon TOSI, jos arvo on parillinen.
-ISLOGICAL = ONTOTUUS ## Palauttaa arvon TOSI, jos arvo on mikä tahansa looginen arvo.
-ISNA = ONPUUTTUU ## Palauttaa arvon TOSI, jos virhearvo on #PUUTTUU!.
-ISNONTEXT = ONEI_TEKSTI ## Palauttaa arvon TOSI, jos arvo ei ole teksti.
-ISNUMBER = ONLUKU ## Palauttaa arvon TOSI, jos arvo on luku.
-ISODD = ONPARITON ## Palauttaa arvon TOSI, jos arvo on pariton.
-ISREF = ONVIITT ## Palauttaa arvon TOSI, jos arvo on viittaus.
-ISTEXT = ONTEKSTI ## Palauttaa arvon TOSI, jos arvo on teksti.
-N = N ## Palauttaa arvon luvuksi muunnettuna.
-NA = PUUTTUU ## Palauttaa virhearvon #PUUTTUU!.
-TYPE = TYYPPI ## Palauttaa luvun, joka ilmaisee arvon tietotyypin.
-
+AND = JA
+FALSE = EPÄTOSI
+IF = JOS
+IFERROR = JOSVIRHE
+IFNA = JOSPUUTTUU
+IFS = JOSS
+NOT = EI
+OR = TAI
+SWITCH = MUUTA
+TRUE = TOSI
+XOR = EHDOTON.TAI
##
-## Logical functions Loogiset funktiot
+## Haku- ja viitefunktiot (Lookup & Reference Functions)
##
-AND = JA ## Palauttaa arvon TOSI, jos kaikkien argumenttien arvo on TOSI.
-FALSE = EPÄTOSI ## Palauttaa totuusarvon EPÄTOSI.
-IF = JOS ## Määrittää suoritettavan loogisen testin.
-IFERROR = JOSVIRHE ## Palauttaa määrittämäsi arvon, jos kaavan tulos on virhe; muussa tapauksessa palauttaa kaavan tuloksen.
-NOT = EI ## Kääntää argumentin loogisen arvon.
-OR = TAI ## Palauttaa arvon TOSI, jos minkä tahansa argumentin arvo on TOSI.
-TRUE = TOSI ## Palauttaa totuusarvon TOSI.
-
+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
##
-## Lookup and reference functions Haku- ja viitefunktiot
+## Matemaattiset ja trigonometriset funktiot (Math & Trig Functions)
##
-ADDRESS = OSOITE ## Palauttaa laskentataulukon soluun osoittavan viittauksen tekstinä.
-AREAS = ALUEET ## Palauttaa viittauksessa olevien alueiden määrän.
-CHOOSE = VALITSE.INDEKSI ## Valitsee arvon arvoluettelosta.
-COLUMN = SARAKE ## Palauttaa viittauksen sarakenumeron.
-COLUMNS = SARAKKEET ## Palauttaa viittauksessa olevien sarakkeiden määrän.
-HLOOKUP = VHAKU ## Suorittaa haun matriisin ylimmältä riviltä ja palauttaa määritetyn solun arvon.
-HYPERLINK = HYPERLINKKI ## Luo pikakuvakkeen tai tekstin, joka avaa verkkopalvelimeen, intranetiin tai Internetiin tallennetun tiedoston.
-INDEX = INDEKSI ## Valitsee arvon viittauksesta tai matriisista indeksin mukaan.
-INDIRECT = EPÄSUORA ## Palauttaa tekstiarvona ilmaistun viittauksen.
-LOOKUP = HAKU ## Etsii arvoja vektorista tai matriisista.
-MATCH = VASTINE ## Etsii arvoja viittauksesta tai matriisista.
-OFFSET = SIIRTYMÄ ## Palauttaa annetun viittauksen siirtymän.
-ROW = RIVI ## Palauttaa viittauksen rivinumeron.
-ROWS = RIVIT ## Palauttaa viittauksessa olevien rivien määrän.
-RTD = RTD ## Noutaa COM-automaatiota (automaatio: Tapa käsitellä sovelluksen objekteja toisesta sovelluksesta tai kehitystyökalusta. Automaatio, jota aiemmin kutsuttiin OLE-automaatioksi, on teollisuusstandardi ja COM-mallin (Component Object Model) ominaisuus.) tukevasta ohjelmasta reaaliaikaisia tietoja.
-TRANSPOSE = TRANSPONOI ## Palauttaa matriisin käänteismatriisin.
-VLOOKUP = PHAKU ## Suorittaa haun matriisin ensimmäisestä sarakkeesta ja palauttaa rivillä olevan solun arvon.
-
+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
##
-## Math and trigonometry functions Matemaattiset ja trigonometriset funktiot
+## Tilastolliset funktiot (Statistical Functions)
##
-ABS = ITSEISARVO ## Palauttaa luvun itseisarvon.
-ACOS = ACOS ## Palauttaa luvun arkuskosinin.
-ACOSH = ACOSH ## Palauttaa luvun käänteisen hyperbolisen kosinin.
-ASIN = ASIN ## Palauttaa luvun arkussinin.
-ASINH = ASINH ## Palauttaa luvun käänteisen hyperbolisen sinin.
-ATAN = ATAN ## Palauttaa luvun arkustangentin.
-ATAN2 = ATAN2 ## Palauttaa arkustangentin x- ja y-koordinaatin perusteella.
-ATANH = ATANH ## Palauttaa luvun käänteisen hyperbolisen tangentin.
-CEILING = PYÖRISTÄ.KERR.YLÖS ## Pyöristää luvun lähimpään kokonaislukuun tai tarkkuusargumentin lähimpään kerrannaiseen.
-COMBIN = KOMBINAATIO ## Palauttaa mahdollisten kombinaatioiden määrän annetulle objektien määrälle.
-COS = COS ## Palauttaa luvun kosinin.
-COSH = COSH ## Palauttaa luvun hyperbolisen kosinin.
-DEGREES = ASTEET ## Muuntaa radiaanit asteiksi.
-EVEN = PARILLINEN ## Pyöristää luvun ylöspäin lähimpään parilliseen kokonaislukuun.
-EXP = EKSPONENTTI ## Palauttaa e:n korotettuna annetun luvun osoittamaan potenssiin.
-FACT = KERTOMA ## Palauttaa luvun kertoman.
-FACTDOUBLE = KERTOMA.OSA ## Palauttaa luvun osakertoman.
-FLOOR = PYÖRISTÄ.KERR.ALAS ## Pyöristää luvun alaspäin (nollaa kohti).
-GCD = SUURIN.YHT.TEKIJÄ ## Palauttaa suurimman yhteisen tekijän.
-INT = KOKONAISLUKU ## Pyöristää luvun alaspäin lähimpään kokonaislukuun.
-LCM = PIENIN.YHT.JAETTAVA ## Palauttaa pienimmän yhteisen tekijän.
-LN = LUONNLOG ## Palauttaa luvun luonnollisen logaritmin.
-LOG = LOG ## Laskee luvun logaritmin käyttämällä annettua kantalukua.
-LOG10 = LOG10 ## Palauttaa luvun kymmenkantaisen logaritmin.
-MDETERM = MDETERM ## Palauttaa matriisin matriisideterminantin.
-MINVERSE = MKÄÄNTEINEN ## Palauttaa matriisin käänteismatriisin.
-MMULT = MKERRO ## Palauttaa kahden matriisin tulon.
-MOD = JAKOJ ## Palauttaa jakolaskun jäännöksen.
-MROUND = PYÖRISTÄ.KERR ## Palauttaa luvun pyöristettynä annetun luvun kerrannaiseen.
-MULTINOMIAL = MULTINOMI ## Palauttaa lukujoukon multinomin.
-ODD = PARITON ## Pyöristää luvun ylöspäin lähimpään parittomaan kokonaislukuun.
-PI = PII ## Palauttaa piin arvon.
-POWER = POTENSSI ## Palauttaa luvun korotettuna haluttuun potenssiin.
-PRODUCT = TULO ## Kertoo annetut argumentit.
-QUOTIENT = OSAMÄÄRÄ ## Palauttaa osamäärän kokonaislukuosan.
-RADIANS = RADIAANIT ## Muuntaa asteet radiaaneiksi.
-RAND = SATUNNAISLUKU ## Palauttaa satunnaisluvun väliltä 0–1.
-RANDBETWEEN = SATUNNAISLUKU.VÄLILTÄ ## Palauttaa satunnaisluvun määritettyjen lukujen väliltä.
-ROMAN = ROMAN ## Muuntaa arabialaisen numeron tekstimuotoiseksi roomalaiseksi numeroksi.
-ROUND = PYÖRISTÄ ## Pyöristää luvun annettuun määrään desimaaleja.
-ROUNDDOWN = PYÖRISTÄ.DES.ALAS ## Pyöristää luvun alaspäin (nollaa kohti).
-ROUNDUP = PYÖRISTÄ.DES.YLÖS ## Pyöristää luvun ylöspäin (poispäin nollasta).
-SERIESSUM = SARJA.SUMMA ## Palauttaa kaavaan perustuvan potenssisarjan arvon.
-SIGN = ETUMERKKI ## Palauttaa luvun etumerkin.
-SIN = SIN ## Palauttaa annetun kulman sinin.
-SINH = SINH ## Palauttaa luvun hyperbolisen sinin.
-SQRT = NELIÖJUURI ## Palauttaa positiivisen neliöjuuren.
-SQRTPI = NELIÖJUURI.PII ## Palauttaa tulon (luku * pii) neliöjuuren.
-SUBTOTAL = VÄLISUMMA ## Palauttaa luettelon tai tietokannan välisumman.
-SUM = SUMMA ## Laskee yhteen annetut argumentit.
-SUMIF = SUMMA.JOS ## Laskee ehdot täyttävien solujen summan.
-SUMIFS = SUMMA.JOS.JOUKKO ## Laskee yhteen solualueen useita ehtoja vastaavat solut.
-SUMPRODUCT = TULOJEN.SUMMA ## Palauttaa matriisin toisiaan vastaavien osien tulojen summan.
-SUMSQ = NELIÖSUMMA ## Palauttaa argumenttien neliöiden summan.
-SUMX2MY2 = NELIÖSUMMIEN.EROTUS ## Palauttaa kahden matriisin toisiaan vastaavien arvojen laskettujen neliösummien erotuksen.
-SUMX2PY2 = NELIÖSUMMIEN.SUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen neliösummien summan.
-SUMXMY2 = EROTUSTEN.NELIÖSUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen erotusten neliösumman.
-TAN = TAN ## Palauttaa luvun tangentin.
-TANH = TANH ## Palauttaa luvun hyperbolisen tangentin.
-TRUNC = KATKAISE ## Katkaisee luvun kokonaisluvuksi.
-
+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
##
-## Statistical functions Tilastolliset funktiot
+## Tekstifunktiot (Text Functions)
##
-AVEDEV = KESKIPOIKKEAMA ## Palauttaa hajontojen itseisarvojen keskiarvon.
-AVERAGE = KESKIARVO ## Palauttaa argumenttien keskiarvon.
-AVERAGEA = KESKIARVOA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, keskiarvon.
-AVERAGEIF = KESKIARVO.JOS ## Palauttaa alueen niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka täyttävät annetut ehdot.
-AVERAGEIFS = KESKIARVO.JOS.JOUKKO ## Palauttaa niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka vastaavat useita ehtoja.
-BETADIST = BEETAJAKAUMA ## Palauttaa kumulatiivisen beetajakaumafunktion arvon.
-BETAINV = BEETAJAKAUMA.KÄÄNT ## Palauttaa määritetyn beetajakauman käänteisen kumulatiivisen jakaumafunktion arvon.
-BINOMDIST = BINOMIJAKAUMA ## Palauttaa yksittäisen termin binomijakaumatodennäköisyyden.
-CHIDIST = CHIJAKAUMA ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden.
-CHIINV = CHIJAKAUMA.KÄÄNT ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden käänteisarvon.
-CHITEST = CHITESTI ## Palauttaa riippumattomuustestin tuloksen.
-CONFIDENCE = LUOTTAMUSVÄLI ## Palauttaa luottamusvälin populaation keskiarvolle.
-CORREL = KORRELAATIO ## Palauttaa kahden arvojoukon korrelaatiokertoimen.
-COUNT = LASKE ## Laskee argumenttiluettelossa olevien lukujen määrän.
-COUNTA = LASKE.A ## Laskee argumenttiluettelossa olevien arvojen määrän.
-COUNTBLANK = LASKE.TYHJÄT ## Laskee alueella olevien tyhjien solujen määrän.
-COUNTIF = LASKE.JOS ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa annettuja ehtoja.
-COUNTIFS = LASKE.JOS.JOUKKO ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa useita ehtoja.
-COVAR = KOVARIANSSI ## Palauttaa kovarianssin, joka on keskiarvo havaintoaineiston kunkin pisteparin poikkeamien tuloista.
-CRITBINOM = BINOMIJAKAUMA.KRIT ## Palauttaa pienimmän arvon, jossa binomijakauman kertymäfunktion arvo on pienempi tai yhtä suuri kuin vertailuarvo.
-DEVSQ = OIKAISTU.NELIÖSUMMA ## Palauttaa keskipoikkeamien neliösumman.
-EXPONDIST = EKSPONENTIAALIJAKAUMA ## Palauttaa eksponentiaalijakauman.
-FDIST = FJAKAUMA ## Palauttaa F-todennäköisyysjakauman.
-FINV = FJAKAUMA.KÄÄNT ## Palauttaa F-todennäköisyysjakauman käänteisfunktion.
-FISHER = FISHER ## Palauttaa Fisher-muunnoksen.
-FISHERINV = FISHER.KÄÄNT ## Palauttaa käänteisen Fisher-muunnoksen.
-FORECAST = ENNUSTE ## Palauttaa lineaarisen trendin arvon.
-FREQUENCY = TAAJUUS ## Palauttaa frekvenssijakautuman pystysuuntaisena matriisina.
-FTEST = FTESTI ## Palauttaa F-testin tuloksen.
-GAMMADIST = GAMMAJAKAUMA ## Palauttaa gammajakauman.
-GAMMAINV = GAMMAJAKAUMA.KÄÄNT ## Palauttaa käänteisen gammajakauman kertymäfunktion.
-GAMMALN = GAMMALN ## Palauttaa gammafunktion luonnollisen logaritmin G(x).
-GEOMEAN = KESKIARVO.GEOM ## Palauttaa geometrisen keskiarvon.
-GROWTH = KASVU ## Palauttaa eksponentiaalisen trendin arvon.
-HARMEAN = KESKIARVO.HARM ## Palauttaa harmonisen keskiarvon.
-HYPGEOMDIST = HYPERGEOM.JAKAUMA ## Palauttaa hypergeometrisen jakauman.
-INTERCEPT = LEIKKAUSPISTE ## Palauttaa lineaarisen regressiosuoran leikkauspisteen.
-KURT = KURT ## Palauttaa tietoalueen vinous-arvon eli huipukkuuden.
-LARGE = SUURI ## Palauttaa tietojoukon k:nneksi suurimman arvon.
-LINEST = LINREGR ## Palauttaa lineaarisen trendin parametrit.
-LOGEST = LOGREGR ## Palauttaa eksponentiaalisen trendin parametrit.
-LOGINV = LOGNORM.JAKAUMA.KÄÄNT ## Palauttaa lognormeeratun jakauman käänteisfunktion.
-LOGNORMDIST = LOGNORM.JAKAUMA ## Palauttaa lognormaalisen jakauman kertymäfunktion.
-MAX = MAKS ## Palauttaa suurimman arvon argumenttiluettelosta.
-MAXA = MAKSA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, suurimman arvon.
-MEDIAN = MEDIAANI ## Palauttaa annettujen lukujen mediaanin.
-MIN = MIN ## Palauttaa pienimmän arvon argumenttiluettelosta.
-MINA = MINA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, pienimmän arvon.
-MODE = MOODI ## Palauttaa tietojoukossa useimmin esiintyvän arvon.
-NEGBINOMDIST = BINOMIJAKAUMA.NEG ## Palauttaa negatiivisen binomijakauman.
-NORMDIST = NORM.JAKAUMA ## Palauttaa normaalijakauman kertymäfunktion.
-NORMINV = NORM.JAKAUMA.KÄÄNT ## Palauttaa käänteisen normaalijakauman kertymäfunktion.
-NORMSDIST = NORM.JAKAUMA.NORMIT ## Palauttaa normitetun normaalijakauman kertymäfunktion.
-NORMSINV = NORM.JAKAUMA.NORMIT.KÄÄNT ## Palauttaa normitetun normaalijakauman kertymäfunktion käänteisarvon.
-PEARSON = PEARSON ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen.
-PERCENTILE = PROSENTTIPISTE ## Palauttaa alueen arvojen k:nnen prosenttipisteen.
-PERCENTRANK = PROSENTTIJÄRJESTYS ## Palauttaa tietojoukon arvon prosentuaalisen järjestysluvun.
-PERMUT = PERMUTAATIO ## Palauttaa mahdollisten permutaatioiden määrän annetulle objektien määrälle.
-POISSON = POISSON ## Palauttaa Poissonin todennäköisyysjakauman.
-PROB = TODENNÄKÖISYYS ## Palauttaa todennäköisyyden sille, että arvot ovat tietyltä väliltä.
-QUARTILE = NELJÄNNES ## Palauttaa tietoalueen neljänneksen.
-RANK = ARVON.MUKAAN ## Palauttaa luvun paikan lukuarvoluettelossa.
-RSQ = PEARSON.NELIÖ ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen neliön.
-SKEW = JAKAUMAN.VINOUS ## Palauttaa jakauman vinouden.
-SLOPE = KULMAKERROIN ## Palauttaa lineaarisen regressiosuoran kulmakertoimen.
-SMALL = PIENI ## Palauttaa tietojoukon k:nneksi pienimmän arvon.
-STANDARDIZE = NORMITA ## Palauttaa normitetun arvon.
-STDEV = KESKIHAJONTA ## Laskee populaation keskihajonnan otoksen perusteella.
-STDEVA = KESKIHAJONTAA ## Laskee populaation keskihajonnan otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot.
-STDEVP = KESKIHAJONTAP ## Laskee normaalijakautuman koko populaation perusteella.
-STDEVPA = KESKIHAJONTAPA ## Laskee populaation keskihajonnan koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot.
-STEYX = KESKIVIRHE ## Palauttaa regression kutakin x-arvoa vastaavan ennustetun y-arvon keskivirheen.
-TDIST = TJAKAUMA ## Palauttaa t-jakautuman.
-TINV = TJAKAUMA.KÄÄNT ## Palauttaa käänteisen t-jakauman.
-TREND = SUUNTAUS ## Palauttaa lineaarisen trendin arvoja.
-TRIMMEAN = KESKIARVO.TASATTU ## Palauttaa tietojoukon tasatun keskiarvon.
-TTEST = TTESTI ## Palauttaa t-testiin liittyvän todennäköisyyden.
-VAR = VAR ## Arvioi populaation varianssia otoksen perusteella.
-VARA = VARA ## Laskee populaation varianssin otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot.
-VARP = VARP ## Laskee varianssin koko populaation perusteella.
-VARPA = VARPA ## Laskee populaation varianssin koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot.
-WEIBULL = WEIBULL ## Palauttaa Weibullin jakauman.
-ZTEST = ZTESTI ## Palauttaa z-testin yksisuuntaisen todennäköisyysarvon.
-
+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
##
-## Text functions Tekstifunktiot
+## Verkkofunktiot (Web Functions)
##
-ASC = ASC ## Muuntaa merkkijonossa olevat englanninkieliset DBCS- tai katakana-merkit SBCS-merkeiksi.
-BAHTTEXT = BAHTTEKSTI ## Muuntaa luvun tekstiksi ß (baht) -valuuttamuotoa käyttämällä.
-CHAR = MERKKI ## Palauttaa koodin lukua vastaavan merkin.
-CLEAN = SIIVOA ## Poistaa tekstistä kaikki tulostumattomat merkit.
-CODE = KOODI ## Palauttaa tekstimerkkijonon ensimmäisen merkin numerokoodin.
-CONCATENATE = KETJUTA ## Yhdistää useat merkkijonot yhdeksi merkkijonoksi.
-DOLLAR = VALUUTTA ## Muuntaa luvun tekstiksi $ (dollari) -valuuttamuotoa käyttämällä.
-EXACT = VERTAA ## Tarkistaa, ovatko kaksi tekstiarvoa samanlaiset.
-FIND = ETSI ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet).
-FINDB = ETSIB ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet).
-FIXED = KIINTEÄ ## Muotoilee luvun tekstiksi, jossa on kiinteä määrä desimaaleja.
-JIS = JIS ## Muuntaa merkkijonossa olevat englanninkieliset SBCS- tai katakana-merkit DBCS-merkeiksi.
-LEFT = VASEN ## Palauttaa tekstiarvon vasemmanpuoliset merkit.
-LEFTB = VASENB ## Palauttaa tekstiarvon vasemmanpuoliset merkit.
-LEN = PITUUS ## Palauttaa tekstimerkkijonon merkkien määrän.
-LENB = PITUUSB ## Palauttaa tekstimerkkijonon merkkien määrän.
-LOWER = PIENET ## Muuntaa tekstin pieniksi kirjaimiksi.
-MID = POIMI.TEKSTI ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta.
-MIDB = POIMI.TEKSTIB ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta.
-PHONETIC = FONEETTINEN ## Hakee foneettiset (furigana) merkit merkkijonosta.
-PROPER = ERISNIMI ## Muuttaa merkkijonon kunkin sanan ensimmäisen kirjaimen isoksi.
-REPLACE = KORVAA ## Korvaa tekstissä olevat merkit.
-REPLACEB = KORVAAB ## Korvaa tekstissä olevat merkit.
-REPT = TOISTA ## Toistaa tekstin annetun määrän kertoja.
-RIGHT = OIKEA ## Palauttaa tekstiarvon oikeanpuoliset merkit.
-RIGHTB = OIKEAB ## Palauttaa tekstiarvon oikeanpuoliset merkit.
-SEARCH = KÄY.LÄPI ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi).
-SEARCHB = KÄY.LÄPIB ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi).
-SUBSTITUTE = VAIHDA ## Korvaa merkkijonossa olevan tekstin toisella.
-T = T ## Muuntaa argumentit tekstiksi.
-TEXT = TEKSTI ## Muotoilee luvun ja muuntaa sen tekstiksi.
-TRIM = POISTA.VÄLIT ## Poistaa välilyönnit tekstistä.
-UPPER = ISOT ## Muuntaa tekstin isoiksi kirjaimiksi.
-VALUE = ARVO ## Muuntaa tekstiargumentin luvuksi.
+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
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/config
index 81895986f49..bdac4121c43 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Français (French)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = €
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #NUL!
-DIV0 = #DIV/0!
-VALUE = #VALEUR!
-REF = #REF!
-NAME = #NOM?
-NUM = #NOMBRE!
-NA = #N/A
+NULL = #NUL!
+DIV0
+VALUE = #VALEUR!
+REF
+NAME = #NOM?
+NUM = #NOMBRE!
+NA
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/functions
index 7f40d5fdeb0..78b603e9cfb 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/functions
@@ -1,416 +1,524 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
+## PhpSpreadsheet - function name translations
##
+## Français (French)
##
+############################################################
##
-## Add-in and Automation functions Fonctions de complément et d’automatisation
+## Fonctions Cube (Cube Functions)
##
-GETPIVOTDATA = LIREDONNEESTABCROISDYNAMIQUE ## Renvoie les données stockées dans un rapport de tableau croisé dynamique.
-
+CUBEKPIMEMBER = MEMBREKPICUBE
+CUBEMEMBER = MEMBRECUBE
+CUBEMEMBERPROPERTY = PROPRIETEMEMBRECUBE
+CUBERANKEDMEMBER = RANGMEMBRECUBE
+CUBESET = JEUCUBE
+CUBESETCOUNT = NBJEUCUBE
+CUBEVALUE = VALEURCUBE
##
-## Cube functions Fonctions Cube
+## Fonctions de base de données (Database Functions)
##
-CUBEKPIMEMBER = MEMBREKPICUBE ## Renvoie un nom, une propriété et une mesure d’indicateur de performance clé et affiche le nom et la propriété dans la cellule. Un indicateur de performance clé est une mesure quantifiable, telle que la marge bénéficiaire brute mensuelle ou la rotation trimestrielle du personnel, utilisée pour évaluer les performances d’une entreprise.
-CUBEMEMBER = MEMBRECUBE ## Renvoie un membre ou un uplet dans une hiérarchie de cubes. Utilisez cette fonction pour valider l’existence du membre ou de l’uplet dans le cube.
-CUBEMEMBERPROPERTY = PROPRIETEMEMBRECUBE ## Renvoie la valeur d’une propriété de membre du cube. Utilisez cette fonction pour valider l’existence d’un nom de membre dans le cube et pour renvoyer la propriété spécifiée pour ce membre.
-CUBERANKEDMEMBER = RANGMEMBRECUBE ## Renvoie le nième membre ou le membre placé à un certain rang dans un ensemble. Utilisez cette fonction pour renvoyer un ou plusieurs éléments d’un ensemble, tels que les meilleurs vendeurs ou les 10 meilleurs étudiants.
-CUBESET = JEUCUBE ## Définit un ensemble calculé de membres ou d’uplets en envoyant une expression définie au cube sur le serveur qui crée l’ensemble et le renvoie à Microsoft Office Excel.
-CUBESETCOUNT = NBJEUCUBE ## Renvoie le nombre d’éléments dans un jeu.
-CUBEVALUE = VALEURCUBE ## Renvoie une valeur d’agrégation issue d’un cube.
-
+DAVERAGE = BDMOYENNE
+DCOUNT = BDNB
+DCOUNTA = BDNBVAL
+DGET = BDLIRE
+DMAX = BDMAX
+DMIN = BDMIN
+DPRODUCT = BDPRODUIT
+DSTDEV = BDECARTYPE
+DSTDEVP = BDECARTYPEP
+DSUM = BDSOMME
+DVAR = BDVAR
+DVARP = BDVARP
##
-## Database functions Fonctions de base de données
+## Fonctions de date et d’heure (Date & Time Functions)
##
-DAVERAGE = BDMOYENNE ## Renvoie la moyenne des entrées de base de données sélectionnées.
-DCOUNT = BCOMPTE ## Compte le nombre de cellules d’une base de données qui contiennent des nombres.
-DCOUNTA = BDNBVAL ## Compte les cellules non vides d’une base de données.
-DGET = BDLIRE ## Extrait d’une base de données un enregistrement unique répondant aux critères spécifiés.
-DMAX = BDMAX ## Renvoie la valeur maximale des entrées de base de données sélectionnées.
-DMIN = BDMIN ## Renvoie la valeur minimale des entrées de base de données sélectionnées.
-DPRODUCT = BDPRODUIT ## Multiplie les valeurs d’un champ particulier des enregistrements d’une base de données, qui répondent aux critères spécifiés.
-DSTDEV = BDECARTYPE ## Calcule l’écart type pour un échantillon d’entrées de base de données sélectionnées.
-DSTDEVP = BDECARTYPEP ## Calcule l’écart type pour l’ensemble d’une population d’entrées de base de données sélectionnées.
-DSUM = BDSOMME ## Ajoute les nombres dans la colonne de champ des enregistrements de la base de données, qui répondent aux critères.
-DVAR = BDVAR ## Calcule la variance pour un échantillon d’entrées de base de données sélectionnées.
-DVARP = BDVARP ## Calcule la variance pour l’ensemble d’une population d’entrées de base de données sélectionnées.
-
+DATE = DATE
+DATEVALUE = DATEVAL
+DAY = JOUR
+DAYS = JOURS
+DAYS360 = JOURS360
+EDATE = MOIS.DECALER
+EOMONTH = FIN.MOIS
+HOUR = HEURE
+ISOWEEKNUM = NO.SEMAINE.ISO
+MINUTE = MINUTE
+MONTH = MOIS
+NETWORKDAYS = NB.JOURS.OUVRES
+NETWORKDAYS.INTL = NB.JOURS.OUVRES.INTL
+NOW = MAINTENANT
+SECOND = SECONDE
+TIME = TEMPS
+TIMEVALUE = TEMPSVAL
+TODAY = AUJOURDHUI
+WEEKDAY = JOURSEM
+WEEKNUM = NO.SEMAINE
+WORKDAY = SERIE.JOUR.OUVRE
+WORKDAY.INTL = SERIE.JOUR.OUVRE.INTL
+YEAR = ANNEE
+YEARFRAC = FRACTION.ANNEE
##
-## Date and time functions Fonctions de date et d’heure
+## Fonctions d’ingénierie (Engineering Functions)
##
-DATE = DATE ## Renvoie le numéro de série d’une date précise.
-DATEVALUE = DATEVAL ## Convertit une date représentée sous forme de texte en numéro de série.
-DAY = JOUR ## Convertit un numéro de série en jour du mois.
-DAYS360 = JOURS360 ## Calcule le nombre de jours qui séparent deux dates sur la base d’une année de 360 jours.
-EDATE = MOIS.DECALER ## Renvoie le numéro séquentiel de la date qui représente une date spécifiée (l’argument date_départ), corrigée en plus ou en moins du nombre de mois indiqué.
-EOMONTH = FIN.MOIS ## Renvoie le numéro séquentiel de la date du dernier jour du mois précédant ou suivant la date_départ du nombre de mois indiqué.
-HOUR = HEURE ## Convertit un numéro de série en heure.
-MINUTE = MINUTE ## Convertit un numéro de série en minute.
-MONTH = MOIS ## Convertit un numéro de série en mois.
-NETWORKDAYS = NB.JOURS.OUVRES ## Renvoie le nombre de jours ouvrés entiers compris entre deux dates.
-NOW = MAINTENANT ## Renvoie le numéro de série de la date et de l’heure du jour.
-SECOND = SECONDE ## Convertit un numéro de série en seconde.
-TIME = TEMPS ## Renvoie le numéro de série d’une heure précise.
-TIMEVALUE = TEMPSVAL ## Convertit une date représentée sous forme de texte en numéro de série.
-TODAY = AUJOURDHUI ## Renvoie le numéro de série de la date du jour.
-WEEKDAY = JOURSEM ## Convertit un numéro de série en jour de la semaine.
-WEEKNUM = NO.SEMAINE ## Convertit un numéro de série en un numéro représentant l’ordre de la semaine dans l’année.
-WORKDAY = SERIE.JOUR.OUVRE ## Renvoie le numéro de série de la date avant ou après le nombre de jours ouvrés spécifiés.
-YEAR = ANNEE ## Convertit un numéro de série en année.
-YEARFRAC = FRACTION.ANNEE ## Renvoie la fraction de l’année représentant le nombre de jours entre la date de début et la date de fin.
-
+BESSELI = BESSELI
+BESSELJ = BESSELJ
+BESSELK = BESSELK
+BESSELY = BESSELY
+BIN2DEC = BINDEC
+BIN2HEX = BINHEX
+BIN2OCT = BINOCT
+BITAND = BITET
+BITLSHIFT = BITDECALG
+BITOR = BITOU
+BITRSHIFT = BITDECALD
+BITXOR = BITOUEXCLUSIF
+COMPLEX = COMPLEXE
+CONVERT = CONVERT
+DEC2BIN = DECBIN
+DEC2HEX = DECHEX
+DEC2OCT = DECOCT
+DELTA = DELTA
+ERF = ERF
+ERF.PRECISE = ERF.PRECIS
+ERFC = ERFC
+ERFC.PRECISE = ERFC.PRECIS
+GESTEP = SUP.SEUIL
+HEX2BIN = HEXBIN
+HEX2DEC = HEXDEC
+HEX2OCT = HEXOCT
+IMABS = COMPLEXE.MODULE
+IMAGINARY = COMPLEXE.IMAGINAIRE
+IMARGUMENT = COMPLEXE.ARGUMENT
+IMCONJUGATE = COMPLEXE.CONJUGUE
+IMCOS = COMPLEXE.COS
+IMCOSH = COMPLEXE.COSH
+IMCOT = COMPLEXE.COT
+IMCSC = COMPLEXE.CSC
+IMCSCH = COMPLEXE.CSCH
+IMDIV = COMPLEXE.DIV
+IMEXP = COMPLEXE.EXP
+IMLN = COMPLEXE.LN
+IMLOG10 = COMPLEXE.LOG10
+IMLOG2 = COMPLEXE.LOG2
+IMPOWER = COMPLEXE.PUISSANCE
+IMPRODUCT = COMPLEXE.PRODUIT
+IMREAL = COMPLEXE.REEL
+IMSEC = COMPLEXE.SEC
+IMSECH = COMPLEXE.SECH
+IMSIN = COMPLEXE.SIN
+IMSINH = COMPLEXE.SINH
+IMSQRT = COMPLEXE.RACINE
+IMSUB = COMPLEXE.DIFFERENCE
+IMSUM = COMPLEXE.SOMME
+IMTAN = COMPLEXE.TAN
+OCT2BIN = OCTBIN
+OCT2DEC = OCTDEC
+OCT2HEX = OCTHEX
##
-## Engineering functions Fonctions d’ingénierie
+## Fonctions financières (Financial Functions)
##
-BESSELI = BESSELI ## Renvoie la fonction Bessel modifiée In(x).
-BESSELJ = BESSELJ ## Renvoie la fonction Bessel Jn(x).
-BESSELK = BESSELK ## Renvoie la fonction Bessel modifiée Kn(x).
-BESSELY = BESSELY ## Renvoie la fonction Bessel Yn(x).
-BIN2DEC = BINDEC ## Convertit un nombre binaire en nombre décimal.
-BIN2HEX = BINHEX ## Convertit un nombre binaire en nombre hexadécimal.
-BIN2OCT = BINOCT ## Convertit un nombre binaire en nombre octal.
-COMPLEX = COMPLEXE ## Convertit des coefficients réel et imaginaire en un nombre complexe.
-CONVERT = CONVERT ## Convertit un nombre d’une unité de mesure à une autre.
-DEC2BIN = DECBIN ## Convertit un nombre décimal en nombre binaire.
-DEC2HEX = DECHEX ## Convertit un nombre décimal en nombre hexadécimal.
-DEC2OCT = DECOCT ## Convertit un nombre décimal en nombre octal.
-DELTA = DELTA ## Teste l’égalité de deux nombres.
-ERF = ERF ## Renvoie la valeur de la fonction d’erreur.
-ERFC = ERFC ## Renvoie la valeur de la fonction d’erreur complémentaire.
-GESTEP = SUP.SEUIL ## Teste si un nombre est supérieur à une valeur de seuil.
-HEX2BIN = HEXBIN ## Convertit un nombre hexadécimal en nombre binaire.
-HEX2DEC = HEXDEC ## Convertit un nombre hexadécimal en nombre décimal.
-HEX2OCT = HEXOCT ## Convertit un nombre hexadécimal en nombre octal.
-IMABS = COMPLEXE.MODULE ## Renvoie la valeur absolue (module) d’un nombre complexe.
-IMAGINARY = COMPLEXE.IMAGINAIRE ## Renvoie le coefficient imaginaire d’un nombre complexe.
-IMARGUMENT = COMPLEXE.ARGUMENT ## Renvoie l’argument thêta, un angle exprimé en radians.
-IMCONJUGATE = COMPLEXE.CONJUGUE ## Renvoie le nombre complexe conjugué d’un nombre complexe.
-IMCOS = IMCOS ## Renvoie le cosinus d’un nombre complexe.
-IMDIV = COMPLEXE.DIV ## Renvoie le quotient de deux nombres complexes.
-IMEXP = COMPLEXE.EXP ## Renvoie la fonction exponentielle d’un nombre complexe.
-IMLN = COMPLEXE.LN ## Renvoie le logarithme népérien d’un nombre complexe.
-IMLOG10 = COMPLEXE.LOG10 ## Calcule le logarithme en base 10 d’un nombre complexe.
-IMLOG2 = COMPLEXE.LOG2 ## Calcule le logarithme en base 2 d’un nombre complexe.
-IMPOWER = COMPLEXE.PUISSANCE ## Renvoie un nombre complexe élevé à une puissance entière.
-IMPRODUCT = COMPLEXE.PRODUIT ## Renvoie le produit de plusieurs nombres complexes.
-IMREAL = COMPLEXE.REEL ## Renvoie le coefficient réel d’un nombre complexe.
-IMSIN = COMPLEXE.SIN ## Renvoie le sinus d’un nombre complexe.
-IMSQRT = COMPLEXE.RACINE ## Renvoie la racine carrée d’un nombre complexe.
-IMSUB = COMPLEXE.DIFFERENCE ## Renvoie la différence entre deux nombres complexes.
-IMSUM = COMPLEXE.SOMME ## Renvoie la somme de plusieurs nombres complexes.
-OCT2BIN = OCTBIN ## Convertit un nombre octal en nombre binaire.
-OCT2DEC = OCTDEC ## Convertit un nombre octal en nombre décimal.
-OCT2HEX = OCTHEX ## Convertit un nombre octal en nombre hexadécimal.
-
+ACCRINT = INTERET.ACC
+ACCRINTM = INTERET.ACC.MAT
+AMORDEGRC = AMORDEGRC
+AMORLINC = AMORLINC
+COUPDAYBS = NB.JOURS.COUPON.PREC
+COUPDAYS = NB.JOURS.COUPONS
+COUPDAYSNC = NB.JOURS.COUPON.SUIV
+COUPNCD = DATE.COUPON.SUIV
+COUPNUM = NB.COUPONS
+COUPPCD = DATE.COUPON.PREC
+CUMIPMT = CUMUL.INTER
+CUMPRINC = CUMUL.PRINCPER
+DB = DB
+DDB = DDB
+DISC = TAUX.ESCOMPTE
+DOLLARDE = PRIX.DEC
+DOLLARFR = PRIX.FRAC
+DURATION = DUREE
+EFFECT = TAUX.EFFECTIF
+FV = VC
+FVSCHEDULE = VC.PAIEMENTS
+INTRATE = TAUX.INTERET
+IPMT = INTPER
+IRR = TRI
+ISPMT = ISPMT
+MDURATION = DUREE.MODIFIEE
+MIRR = TRIM
+NOMINAL = TAUX.NOMINAL
+NPER = NPM
+NPV = VAN
+ODDFPRICE = PRIX.PCOUPON.IRREG
+ODDFYIELD = REND.PCOUPON.IRREG
+ODDLPRICE = PRIX.DCOUPON.IRREG
+ODDLYIELD = REND.DCOUPON.IRREG
+PDURATION = PDUREE
+PMT = VPM
+PPMT = PRINCPER
+PRICE = PRIX.TITRE
+PRICEDISC = VALEUR.ENCAISSEMENT
+PRICEMAT = PRIX.TITRE.ECHEANCE
+PV = VA
+RATE = TAUX
+RECEIVED = VALEUR.NOMINALE
+RRI = TAUX.INT.EQUIV
+SLN = AMORLIN
+SYD = SYD
+TBILLEQ = TAUX.ESCOMPTE.R
+TBILLPRICE = PRIX.BON.TRESOR
+TBILLYIELD = RENDEMENT.BON.TRESOR
+VDB = VDB
+XIRR = TRI.PAIEMENTS
+XNPV = VAN.PAIEMENTS
+YIELD = RENDEMENT.TITRE
+YIELDDISC = RENDEMENT.SIMPLE
+YIELDMAT = RENDEMENT.TITRE.ECHEANCE
##
-## Financial functions Fonctions financières
+## Fonctions d’information (Information Functions)
##
-ACCRINT = INTERET.ACC ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu périodiquement.
-ACCRINTM = INTERET.ACC.MAT ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu à l’échéance.
-AMORDEGRC = AMORDEGRC ## Renvoie l’amortissement correspondant à chaque période comptable en utilisant un coefficient d’amortissement.
-AMORLINC = AMORLINC ## Renvoie l’amortissement d’un bien à la fin d’une période fiscale donnée.
-COUPDAYBS = NB.JOURS.COUPON.PREC ## Renvoie le nombre de jours entre le début de la période de coupon et la date de liquidation.
-COUPDAYS = NB.JOURS.COUPONS ## Renvoie le nombre de jours pour la période du coupon contenant la date de liquidation.
-COUPDAYSNC = NB.JOURS.COUPON.SUIV ## Renvoie le nombre de jours entre la date de liquidation et la date du coupon suivant la date de liquidation.
-COUPNCD = DATE.COUPON.SUIV ## Renvoie la première date de coupon ultérieure à la date de règlement.
-COUPNUM = NB.COUPONS ## Renvoie le nombre de coupons dus entre la date de règlement et la date d’échéance.
-COUPPCD = DATE.COUPON.PREC ## Renvoie la date de coupon précédant la date de règlement.
-CUMIPMT = CUMUL.INTER ## Renvoie l’intérêt cumulé payé sur un emprunt entre deux périodes.
-CUMPRINC = CUMUL.PRINCPER ## Renvoie le montant cumulé des remboursements du capital d’un emprunt effectués entre deux périodes.
-DB = DB ## Renvoie l’amortissement d’un bien pour une période spécifiée en utilisant la méthode de l’amortissement dégressif à taux fixe.
-DDB = DDB ## Renvoie l’amortissement d’un bien pour toute période spécifiée, en utilisant la méthode de l’amortissement dégressif à taux double ou selon un coefficient à spécifier.
-DISC = TAUX.ESCOMPTE ## Calcule le taux d’escompte d’une transaction.
-DOLLARDE = PRIX.DEC ## Convertit un prix en euros, exprimé sous forme de fraction, en un prix en euros exprimé sous forme de nombre décimal.
-DOLLARFR = PRIX.FRAC ## Convertit un prix en euros, exprimé sous forme de nombre décimal, en un prix en euros exprimé sous forme de fraction.
-DURATION = DUREE ## Renvoie la durée, en années, d’un titre dont l’intérêt est perçu périodiquement.
-EFFECT = TAUX.EFFECTIF ## Renvoie le taux d’intérêt annuel effectif.
-FV = VC ## Renvoie la valeur future d’un investissement.
-FVSCHEDULE = VC.PAIEMENTS ## Calcule la valeur future d’un investissement en appliquant une série de taux d’intérêt composites.
-INTRATE = TAUX.INTERET ## Affiche le taux d’intérêt d’un titre totalement investi.
-IPMT = INTPER ## Calcule le montant des intérêts d’un investissement pour une période donnée.
-IRR = TRI ## Calcule le taux de rentabilité interne d’un investissement pour une succession de trésoreries.
-ISPMT = ISPMT ## Calcule le montant des intérêts d’un investissement pour une période donnée.
-MDURATION = DUREE.MODIFIEE ## Renvoie la durée de Macauley modifiée pour un titre ayant une valeur nominale hypothétique de 100_euros.
-MIRR = TRIM ## Calcule le taux de rentabilité interne lorsque les paiements positifs et négatifs sont financés à des taux différents.
-NOMINAL = TAUX.NOMINAL ## Calcule le taux d’intérêt nominal annuel.
-NPER = NPM ## Renvoie le nombre de versements nécessaires pour rembourser un emprunt.
-NPV = VAN ## Calcule la valeur actuelle nette d’un investissement basé sur une série de décaissements et un taux d’escompte.
-ODDFPRICE = PRIX.PCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière.
-ODDFYIELD = REND.PCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la première période de coupon est irrégulière.
-ODDLPRICE = PRIX.DCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière.
-ODDLYIELD = REND.DCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la dernière période de coupon est irrégulière.
-PMT = VPM ## Calcule le paiement périodique d’un investissement donné.
-PPMT = PRINCPER ## Calcule, pour une période donnée, la part de remboursement du principal d’un investissement.
-PRICE = PRIX.TITRE ## Renvoie le prix d’un titre rapportant des intérêts périodiques, pour une valeur nominale de 100 euros.
-PRICEDISC = VALEUR.ENCAISSEMENT ## Renvoie la valeur d’encaissement d’un escompte commercial, pour une valeur nominale de 100 euros.
-PRICEMAT = PRIX.TITRE.ECHEANCE ## Renvoie le prix d’un titre dont la valeur nominale est 100 euros et qui rapporte des intérêts à l’échéance.
-PV = PV ## Calcule la valeur actuelle d’un investissement.
-RATE = TAUX ## Calcule le taux d’intérêt par période pour une annuité.
-RECEIVED = VALEUR.NOMINALE ## Renvoie la valeur nominale à échéance d’un effet de commerce.
-SLN = AMORLIN ## Calcule l’amortissement linéaire d’un bien pour une période donnée.
-SYD = SYD ## Calcule l’amortissement d’un bien pour une période donnée sur la base de la méthode américaine Sum-of-Years Digits (amortissement dégressif à taux décroissant appliqué à une valeur constante).
-TBILLEQ = TAUX.ESCOMPTE.R ## Renvoie le taux d’escompte rationnel d’un bon du Trésor.
-TBILLPRICE = PRIX.BON.TRESOR ## Renvoie le prix d’un bon du Trésor d’une valeur nominale de 100 euros.
-TBILLYIELD = RENDEMENT.BON.TRESOR ## Calcule le taux de rendement d’un bon du Trésor.
-VDB = VDB ## Renvoie l’amortissement d’un bien pour une période spécifiée ou partielle en utilisant une méthode de l’amortissement dégressif à taux fixe.
-XIRR = TRI.PAIEMENTS ## Calcule le taux de rentabilité interne d’un ensemble de paiements non périodiques.
-XNPV = VAN.PAIEMENTS ## Renvoie la valeur actuelle nette d’un ensemble de paiements non périodiques.
-YIELD = RENDEMENT.TITRE ## Calcule le rendement d’un titre rapportant des intérêts périodiquement.
-YIELDDISC = RENDEMENT.SIMPLE ## Calcule le taux de rendement d’un emprunt à intérêt simple (par exemple, un bon du Trésor).
-YIELDMAT = RENDEMENT.TITRE.ECHEANCE ## Renvoie le rendement annuel d’un titre qui rapporte des intérêts à l’échéance.
-
+CELL = CELLULE
+ERROR.TYPE = TYPE.ERREUR
+INFO = INFORMATIONS
+ISBLANK = ESTVIDE
+ISERR = ESTERR
+ISERROR = ESTERREUR
+ISEVEN = EST.PAIR
+ISFORMULA = ESTFORMULE
+ISLOGICAL = ESTLOGIQUE
+ISNA = ESTNA
+ISNONTEXT = ESTNONTEXTE
+ISNUMBER = ESTNUM
+ISODD = EST.IMPAIR
+ISREF = ESTREF
+ISTEXT = ESTTEXTE
+N = N
+NA = NA
+SHEET = FEUILLE
+SHEETS = FEUILLES
+TYPE = TYPE
##
-## Information functions Fonctions d’information
+## Fonctions logiques (Logical Functions)
##
-CELL = CELLULE ## Renvoie des informations sur la mise en forme, l’emplacement et le contenu d’une cellule.
-ERROR.TYPE = TYPE.ERREUR ## Renvoie un nombre correspondant à un type d’erreur.
-INFO = INFORMATIONS ## Renvoie des informations sur l’environnement d’exploitation actuel.
-ISBLANK = ESTVIDE ## Renvoie VRAI si l’argument valeur est vide.
-ISERR = ESTERR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur, sauf #N/A.
-ISERROR = ESTERREUR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur.
-ISEVEN = EST.PAIR ## Renvoie VRAI si le chiffre est pair.
-ISLOGICAL = ESTLOGIQUE ## Renvoie VRAI si l’argument valeur fait référence à une valeur logique.
-ISNA = ESTNA ## Renvoie VRAI si l’argument valeur fait référence à la valeur d’erreur #N/A.
-ISNONTEXT = ESTNONTEXTE ## Renvoie VRAI si l’argument valeur ne se présente pas sous forme de texte.
-ISNUMBER = ESTNUM ## Renvoie VRAI si l’argument valeur représente un nombre.
-ISODD = EST.IMPAIR ## Renvoie VRAI si le chiffre est impair.
-ISREF = ESTREF ## Renvoie VRAI si l’argument valeur est une référence.
-ISTEXT = ESTTEXTE ## Renvoie VRAI si l’argument valeur se présente sous forme de texte.
-N = N ## Renvoie une valeur convertie en nombre.
-NA = NA ## Renvoie la valeur d’erreur #N/A.
-TYPE = TYPE ## Renvoie un nombre indiquant le type de données d’une valeur.
-
+AND = ET
+FALSE = FAUX
+IF = SI
+IFERROR = SIERREUR
+IFNA = SI.NON.DISP
+IFS = SI.CONDITIONS
+NOT = NON
+OR = OU
+SWITCH = SI.MULTIPLE
+TRUE = VRAI
+XOR = OUX
##
-## Logical functions Fonctions logiques
+## Fonctions de recherche et de référence (Lookup & Reference Functions)
##
-AND = ET ## Renvoie VRAI si tous ses arguments sont VRAI.
-FALSE = FAUX ## Renvoie la valeur logique FAUX.
-IF = SI ## Spécifie un test logique à effectuer.
-IFERROR = SIERREUR ## Renvoie une valeur que vous spécifiez si une formule génère une erreur ; sinon, elle renvoie le résultat de la formule.
-NOT = NON ## Inverse la logique de cet argument.
-OR = OU ## Renvoie VRAI si un des arguments est VRAI.
-TRUE = VRAI ## Renvoie la valeur logique VRAI.
-
+ADDRESS = ADRESSE
+AREAS = ZONES
+CHOOSE = CHOISIR
+COLUMN = COLONNE
+COLUMNS = COLONNES
+FORMULATEXT = FORMULETEXTE
+GETPIVOTDATA = LIREDONNEESTABCROISDYNAMIQUE
+HLOOKUP = RECHERCHEH
+HYPERLINK = LIEN_HYPERTEXTE
+INDEX = INDEX
+INDIRECT = INDIRECT
+LOOKUP = RECHERCHE
+MATCH = EQUIV
+OFFSET = DECALER
+ROW = LIGNE
+ROWS = LIGNES
+RTD = RTD
+TRANSPOSE = TRANSPOSE
+VLOOKUP = RECHERCHEV
##
-## Lookup and reference functions Fonctions de recherche et de référence
+## Fonctions mathématiques et trigonométriques (Math & Trig Functions)
##
-ADDRESS = ADRESSE ## Renvoie une référence sous forme de texte à une seule cellule d’une feuille de calcul.
-AREAS = ZONES ## Renvoie le nombre de zones dans une référence.
-CHOOSE = CHOISIR ## Choisit une valeur dans une liste.
-COLUMN = COLONNE ## Renvoie le numéro de colonne d’une référence.
-COLUMNS = COLONNES ## Renvoie le nombre de colonnes dans une référence.
-HLOOKUP = RECHERCHEH ## Effectue une recherche dans la première ligne d’une matrice et renvoie la valeur de la cellule indiquée.
-HYPERLINK = LIEN_HYPERTEXTE ## Crée un raccourci ou un renvoi qui ouvre un document stocké sur un serveur réseau, sur un réseau Intranet ou sur Internet.
-INDEX = INDEX ## Utilise un index pour choisir une valeur provenant d’une référence ou d’une matrice.
-INDIRECT = INDIRECT ## Renvoie une référence indiquée par une valeur de texte.
-LOOKUP = RECHERCHE ## Recherche des valeurs dans un vecteur ou une matrice.
-MATCH = EQUIV ## Recherche des valeurs dans une référence ou une matrice.
-OFFSET = DECALER ## Renvoie une référence décalée par rapport à une référence donnée.
-ROW = LIGNE ## Renvoie le numéro de ligne d’une référence.
-ROWS = LIGNES ## Renvoie le nombre de lignes dans une référence.
-RTD = RTD ## Extrait les données en temps réel à partir d’un programme prenant en charge l’automation COM (Automation : utilisation des objets d'une application à partir d'une autre application ou d'un autre outil de développement. Autrefois appelée OLE Automation, Automation est une norme industrielle et une fonctionnalité du modèle d'objet COM (Component Object Model).).
-TRANSPOSE = TRANSPOSE ## Renvoie la transposition d’une matrice.
-VLOOKUP = RECHERCHEV ## Effectue une recherche dans la première colonne d’une matrice et se déplace sur la ligne pour renvoyer la valeur d’une cellule.
-
+ABS = ABS
+ACOS = ACOS
+ACOSH = ACOSH
+ACOT = ACOT
+ACOTH = ACOTH
+AGGREGATE = AGREGAT
+ARABIC = CHIFFRE.ARABE
+ASIN = ASIN
+ASINH = ASINH
+ATAN = ATAN
+ATAN2 = ATAN2
+ATANH = ATANH
+BASE = BASE
+CEILING.MATH = PLAFOND.MATH
+CEILING.PRECISE = PLAFOND.PRECIS
+COMBIN = COMBIN
+COMBINA = COMBINA
+COS = COS
+COSH = COSH
+COT = COT
+COTH = COTH
+CSC = CSC
+CSCH = CSCH
+DECIMAL = DECIMAL
+DEGREES = DEGRES
+ECMA.CEILING = ECMA.PLAFOND
+EVEN = PAIR
+EXP = EXP
+FACT = FACT
+FACTDOUBLE = FACTDOUBLE
+FLOOR.MATH = PLANCHER.MATH
+FLOOR.PRECISE = PLANCHER.PRECIS
+GCD = PGCD
+INT = ENT
+ISO.CEILING = ISO.PLAFOND
+LCM = PPCM
+LN = LN
+LOG = LOG
+LOG10 = LOG10
+MDETERM = DETERMAT
+MINVERSE = INVERSEMAT
+MMULT = PRODUITMAT
+MOD = MOD
+MROUND = ARRONDI.AU.MULTIPLE
+MULTINOMIAL = MULTINOMIALE
+MUNIT = MATRICE.UNITAIRE
+ODD = IMPAIR
+PI = PI
+POWER = PUISSANCE
+PRODUCT = PRODUIT
+QUOTIENT = QUOTIENT
+RADIANS = RADIANS
+RAND = ALEA
+RANDBETWEEN = ALEA.ENTRE.BORNES
+ROMAN = ROMAIN
+ROUND = ARRONDI
+ROUNDDOWN = ARRONDI.INF
+ROUNDUP = ARRONDI.SUP
+SEC = SEC
+SECH = SECH
+SERIESSUM = SOMME.SERIES
+SIGN = SIGNE
+SIN = SIN
+SINH = SINH
+SQRT = RACINE
+SQRTPI = RACINE.PI
+SUBTOTAL = SOUS.TOTAL
+SUM = SOMME
+SUMIF = SOMME.SI
+SUMIFS = SOMME.SI.ENS
+SUMPRODUCT = SOMMEPROD
+SUMSQ = SOMME.CARRES
+SUMX2MY2 = SOMME.X2MY2
+SUMX2PY2 = SOMME.X2PY2
+SUMXMY2 = SOMME.XMY2
+TAN = TAN
+TANH = TANH
+TRUNC = TRONQUE
##
-## Math and trigonometry functions Fonctions mathématiques et trigonométriques
+## Fonctions statistiques (Statistical Functions)
##
-ABS = ABS ## Renvoie la valeur absolue d’un nombre.
-ACOS = ACOS ## Renvoie l’arccosinus d’un nombre.
-ACOSH = ACOSH ## Renvoie le cosinus hyperbolique inverse d’un nombre.
-ASIN = ASIN ## Renvoie l’arcsinus d’un nombre.
-ASINH = ASINH ## Renvoie le sinus hyperbolique inverse d’un nombre.
-ATAN = ATAN ## Renvoie l’arctangente d’un nombre.
-ATAN2 = ATAN2 ## Renvoie l’arctangente des coordonnées x et y.
-ATANH = ATANH ## Renvoie la tangente hyperbolique inverse d’un nombre.
-CEILING = PLAFOND ## Arrondit un nombre au nombre entier le plus proche ou au multiple le plus proche de l’argument précision en s’éloignant de zéro.
-COMBIN = COMBIN ## Renvoie le nombre de combinaisons que l’on peut former avec un nombre donné d’objets.
-COS = COS ## Renvoie le cosinus d’un nombre.
-COSH = COSH ## Renvoie le cosinus hyperbolique d’un nombre.
-DEGREES = DEGRES ## Convertit des radians en degrés.
-EVEN = PAIR ## Arrondit un nombre au nombre entier pair le plus proche en s’éloignant de zéro.
-EXP = EXP ## Renvoie e élevé à la puissance d’un nombre donné.
-FACT = FACT ## Renvoie la factorielle d’un nombre.
-FACTDOUBLE = FACTDOUBLE ## Renvoie la factorielle double d’un nombre.
-FLOOR = PLANCHER ## Arrondit un nombre en tendant vers 0 (zéro).
-GCD = PGCD ## Renvoie le plus grand commun diviseur.
-INT = ENT ## Arrondit un nombre à l’entier immédiatement inférieur.
-LCM = PPCM ## Renvoie le plus petit commun multiple.
-LN = LN ## Renvoie le logarithme népérien d’un nombre.
-LOG = LOG ## Renvoie le logarithme d’un nombre dans la base spécifiée.
-LOG10 = LOG10 ## Calcule le logarithme en base 10 d’un nombre.
-MDETERM = DETERMAT ## Renvoie le déterminant d’une matrice.
-MINVERSE = INVERSEMAT ## Renvoie la matrice inverse d’une matrice.
-MMULT = PRODUITMAT ## Renvoie le produit de deux matrices.
-MOD = MOD ## Renvoie le reste d’une division.
-MROUND = ARRONDI.AU.MULTIPLE ## Donne l’arrondi d’un nombre au multiple spécifié.
-MULTINOMIAL = MULTINOMIALE ## Calcule la multinomiale d’un ensemble de nombres.
-ODD = IMPAIR ## Renvoie le nombre, arrondi à la valeur du nombre entier impair le plus proche en s’éloignant de zéro.
-PI = PI ## Renvoie la valeur de pi.
-POWER = PUISSANCE ## Renvoie la valeur du nombre élevé à une puissance.
-PRODUCT = PRODUIT ## Multiplie ses arguments.
-QUOTIENT = QUOTIENT ## Renvoie la partie entière du résultat d’une division.
-RADIANS = RADIANS ## Convertit des degrés en radians.
-RAND = ALEA ## Renvoie un nombre aléatoire compris entre 0 et 1.
-RANDBETWEEN = ALEA.ENTRE.BORNES ## Renvoie un nombre aléatoire entre les nombres que vous spécifiez.
-ROMAN = ROMAIN ## Convertit des chiffres arabes en chiffres romains, sous forme de texte.
-ROUND = ARRONDI ## Arrondit un nombre au nombre de chiffres indiqué.
-ROUNDDOWN = ARRONDI.INF ## Arrondit un nombre en tendant vers 0 (zéro).
-ROUNDUP = ARRONDI.SUP ## Arrondit un nombre à l’entier supérieur, en s’éloignant de zéro.
-SERIESSUM = SOMME.SERIES ## Renvoie la somme d’une série géométrique en s’appuyant sur la formule suivante :
-SIGN = SIGNE ## Renvoie le signe d’un nombre.
-SIN = SIN ## Renvoie le sinus d’un angle donné.
-SINH = SINH ## Renvoie le sinus hyperbolique d’un nombre.
-SQRT = RACINE ## Renvoie la racine carrée d’un nombre.
-SQRTPI = RACINE.PI ## Renvoie la racine carrée de (nombre * pi).
-SUBTOTAL = SOUS.TOTAL ## Renvoie un sous-total dans une liste ou une base de données.
-SUM = SOMME ## Calcule la somme de ses arguments.
-SUMIF = SOMME.SI ## Additionne les cellules spécifiées si elles répondent à un critère donné.
-SUMIFS = SOMME.SI.ENS ## Ajoute les cellules d’une plage qui répondent à plusieurs critères.
-SUMPRODUCT = SOMMEPROD ## Multiplie les valeurs correspondantes des matrices spécifiées et calcule la somme de ces produits.
-SUMSQ = SOMME.CARRES ## Renvoie la somme des carrés des arguments.
-SUMX2MY2 = SOMME.X2MY2 ## Renvoie la somme de la différence des carrés des valeurs correspondantes de deux matrices.
-SUMX2PY2 = SOMME.X2PY2 ## Renvoie la somme de la somme des carrés des valeurs correspondantes de deux matrices.
-SUMXMY2 = SOMME.XMY2 ## Renvoie la somme des carrés des différences entre les valeurs correspondantes de deux matrices.
-TAN = TAN ## Renvoie la tangente d’un nombre.
-TANH = TANH ## Renvoie la tangente hyperbolique d’un nombre.
-TRUNC = TRONQUE ## Renvoie la partie entière d’un nombre.
-
+AVEDEV = ECART.MOYEN
+AVERAGE = MOYENNE
+AVERAGEA = AVERAGEA
+AVERAGEIF = MOYENNE.SI
+AVERAGEIFS = MOYENNE.SI.ENS
+BETA.DIST = LOI.BETA.N
+BETA.INV = BETA.INVERSE.N
+BINOM.DIST = LOI.BINOMIALE.N
+BINOM.DIST.RANGE = LOI.BINOMIALE.SERIE
+BINOM.INV = LOI.BINOMIALE.INVERSE
+CHISQ.DIST = LOI.KHIDEUX.N
+CHISQ.DIST.RT = LOI.KHIDEUX.DROITE
+CHISQ.INV = LOI.KHIDEUX.INVERSE
+CHISQ.INV.RT = LOI.KHIDEUX.INVERSE.DROITE
+CHISQ.TEST = CHISQ.TEST
+CONFIDENCE.NORM = INTERVALLE.CONFIANCE.NORMAL
+CONFIDENCE.T = INTERVALLE.CONFIANCE.STUDENT
+CORREL = COEFFICIENT.CORRELATION
+COUNT = NB
+COUNTA = NBVAL
+COUNTBLANK = NB.VIDE
+COUNTIF = NB.SI
+COUNTIFS = NB.SI.ENS
+COVARIANCE.P = COVARIANCE.PEARSON
+COVARIANCE.S = COVARIANCE.STANDARD
+DEVSQ = SOMME.CARRES.ECARTS
+EXPON.DIST = LOI.EXPONENTIELLE.N
+F.DIST = LOI.F.N
+F.DIST.RT = LOI.F.DROITE
+F.INV = INVERSE.LOI.F.N
+F.INV.RT = INVERSE.LOI.F.DROITE
+F.TEST = F.TEST
+FISHER = FISHER
+FISHERINV = FISHER.INVERSE
+FORECAST.ETS = PREVISION.ETS
+FORECAST.ETS.CONFINT = PREVISION.ETS.CONFINT
+FORECAST.ETS.SEASONALITY = PREVISION.ETS.CARACTERESAISONNIER
+FORECAST.ETS.STAT = PREVISION.ETS.STAT
+FORECAST.LINEAR = PREVISION.LINEAIRE
+FREQUENCY = FREQUENCE
+GAMMA = GAMMA
+GAMMA.DIST = LOI.GAMMA.N
+GAMMA.INV = LOI.GAMMA.INVERSE.N
+GAMMALN = LNGAMMA
+GAMMALN.PRECISE = LNGAMMA.PRECIS
+GAUSS = GAUSS
+GEOMEAN = MOYENNE.GEOMETRIQUE
+GROWTH = CROISSANCE
+HARMEAN = MOYENNE.HARMONIQUE
+HYPGEOM.DIST = LOI.HYPERGEOMETRIQUE.N
+INTERCEPT = ORDONNEE.ORIGINE
+KURT = KURTOSIS
+LARGE = GRANDE.VALEUR
+LINEST = DROITEREG
+LOGEST = LOGREG
+LOGNORM.DIST = LOI.LOGNORMALE.N
+LOGNORM.INV = LOI.LOGNORMALE.INVERSE.N
+MAX = MAX
+MAXA = MAXA
+MAXIFS = MAX.SI
+MEDIAN = MEDIANE
+MIN = MIN
+MINA = MINA
+MINIFS = MIN.SI
+MODE.MULT = MODE.MULTIPLE
+MODE.SNGL = MODE.SIMPLE
+NEGBINOM.DIST = LOI.BINOMIALE.NEG.N
+NORM.DIST = LOI.NORMALE.N
+NORM.INV = LOI.NORMALE.INVERSE.N
+NORM.S.DIST = LOI.NORMALE.STANDARD.N
+NORM.S.INV = LOI.NORMALE.STANDARD.INVERSE.N
+PEARSON = PEARSON
+PERCENTILE.EXC = CENTILE.EXCLURE
+PERCENTILE.INC = CENTILE.INCLURE
+PERCENTRANK.EXC = RANG.POURCENTAGE.EXCLURE
+PERCENTRANK.INC = RANG.POURCENTAGE.INCLURE
+PERMUT = PERMUTATION
+PERMUTATIONA = PERMUTATIONA
+PHI = PHI
+POISSON.DIST = LOI.POISSON.N
+PROB = PROBABILITE
+QUARTILE.EXC = QUARTILE.EXCLURE
+QUARTILE.INC = QUARTILE.INCLURE
+RANK.AVG = MOYENNE.RANG
+RANK.EQ = EQUATION.RANG
+RSQ = COEFFICIENT.DETERMINATION
+SKEW = COEFFICIENT.ASYMETRIE
+SKEW.P = COEFFICIENT.ASYMETRIE.P
+SLOPE = PENTE
+SMALL = PETITE.VALEUR
+STANDARDIZE = CENTREE.REDUITE
+STDEV.P = ECARTYPE.PEARSON
+STDEV.S = ECARTYPE.STANDARD
+STDEVA = STDEVA
+STDEVPA = STDEVPA
+STEYX = ERREUR.TYPE.XY
+T.DIST = LOI.STUDENT.N
+T.DIST.2T = LOI.STUDENT.BILATERALE
+T.DIST.RT = LOI.STUDENT.DROITE
+T.INV = LOI.STUDENT.INVERSE.N
+T.INV.2T = LOI.STUDENT.INVERSE.BILATERALE
+T.TEST = T.TEST
+TREND = TENDANCE
+TRIMMEAN = MOYENNE.REDUITE
+VAR.P = VAR.P.N
+VAR.S = VAR.S
+VARA = VARA
+VARPA = VARPA
+WEIBULL.DIST = LOI.WEIBULL.N
+Z.TEST = Z.TEST
##
-## Statistical functions Fonctions statistiques
+## Fonctions de texte (Text Functions)
##
-AVEDEV = ECART.MOYEN ## Renvoie la moyenne des écarts absolus observés dans la moyenne des points de données.
-AVERAGE = MOYENNE ## Renvoie la moyenne de ses arguments.
-AVERAGEA = AVERAGEA ## Renvoie la moyenne de ses arguments, nombres, texte et valeurs logiques inclus.
-AVERAGEIF = MOYENNE.SI ## Renvoie la moyenne (arithmétique) de toutes les cellules d’une plage qui répondent à des critères donnés.
-AVERAGEIFS = MOYENNE.SI.ENS ## Renvoie la moyenne (arithmétique) de toutes les cellules qui répondent à plusieurs critères.
-BETADIST = LOI.BETA ## Renvoie la fonction de distribution cumulée.
-BETAINV = BETA.INVERSE ## Renvoie l’inverse de la fonction de distribution cumulée pour une distribution bêta spécifiée.
-BINOMDIST = LOI.BINOMIALE ## Renvoie la probabilité d’une variable aléatoire discrète suivant la loi binomiale.
-CHIDIST = LOI.KHIDEUX ## Renvoie la probabilité unilatérale de la distribution khi-deux.
-CHIINV = KHIDEUX.INVERSE ## Renvoie l’inverse de la probabilité unilatérale de la distribution khi-deux.
-CHITEST = TEST.KHIDEUX ## Renvoie le test d’indépendance.
-CONFIDENCE = INTERVALLE.CONFIANCE ## Renvoie l’intervalle de confiance pour une moyenne de population.
-CORREL = COEFFICIENT.CORRELATION ## Renvoie le coefficient de corrélation entre deux séries de données.
-COUNT = NB ## Détermine les nombres compris dans la liste des arguments.
-COUNTA = NBVAL ## Détermine le nombre de valeurs comprises dans la liste des arguments.
-COUNTBLANK = NB.VIDE ## Compte le nombre de cellules vides dans une plage.
-COUNTIF = NB.SI ## Compte le nombre de cellules qui répondent à un critère donné dans une plage.
-COUNTIFS = NB.SI.ENS ## Compte le nombre de cellules à l’intérieur d’une plage qui répondent à plusieurs critères.
-COVAR = COVARIANCE ## Renvoie la covariance, moyenne des produits des écarts pour chaque série d’observations.
-CRITBINOM = CRITERE.LOI.BINOMIALE ## Renvoie la plus petite valeur pour laquelle la distribution binomiale cumulée est inférieure ou égale à une valeur de critère.
-DEVSQ = SOMME.CARRES.ECARTS ## Renvoie la somme des carrés des écarts.
-EXPONDIST = LOI.EXPONENTIELLE ## Renvoie la distribution exponentielle.
-FDIST = LOI.F ## Renvoie la distribution de probabilité F.
-FINV = INVERSE.LOI.F ## Renvoie l’inverse de la distribution de probabilité F.
-FISHER = FISHER ## Renvoie la transformation de Fisher.
-FISHERINV = FISHER.INVERSE ## Renvoie l’inverse de la transformation de Fisher.
-FORECAST = PREVISION ## Calcule une valeur par rapport à une tendance linéaire.
-FREQUENCY = FREQUENCE ## Calcule la fréquence d’apparition des valeurs dans une plage de valeurs, puis renvoie des nombres sous forme de matrice verticale.
-FTEST = TEST.F ## Renvoie le résultat d’un test F.
-GAMMADIST = LOI.GAMMA ## Renvoie la probabilité d’une variable aléatoire suivant une loi Gamma.
-GAMMAINV = LOI.GAMMA.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi Gamma.
-GAMMALN = LNGAMMA ## Renvoie le logarithme népérien de la fonction Gamma, G(x)
-GEOMEAN = MOYENNE.GEOMETRIQUE ## Renvoie la moyenne géométrique.
-GROWTH = CROISSANCE ## Calcule des valeurs par rapport à une tendance exponentielle.
-HARMEAN = MOYENNE.HARMONIQUE ## Renvoie la moyenne harmonique.
-HYPGEOMDIST = LOI.HYPERGEOMETRIQUE ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi hypergéométrique.
-INTERCEPT = ORDONNEE.ORIGINE ## Renvoie l’ordonnée à l’origine d’une droite de régression linéaire.
-KURT = KURTOSIS ## Renvoie le kurtosis d’une série de données.
-LARGE = GRANDE.VALEUR ## Renvoie la k-ième plus grande valeur d’une série de données.
-LINEST = DROITEREG ## Renvoie les paramètres d’une tendance linéaire.
-LOGEST = LOGREG ## Renvoie les paramètres d’une tendance exponentielle.
-LOGINV = LOI.LOGNORMALE.INVERSE ## Renvoie l’inverse de la probabilité pour une variable aléatoire suivant la loi lognormale.
-LOGNORMDIST = LOI.LOGNORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi lognormale.
-MAX = MAX ## Renvoie la valeur maximale contenue dans une liste d’arguments.
-MAXA = MAXA ## Renvoie la valeur maximale d’une liste d’arguments, nombres, texte et valeurs logiques inclus.
-MEDIAN = MEDIANE ## Renvoie la valeur médiane des nombres donnés.
-MIN = MIN ## Renvoie la valeur minimale contenue dans une liste d’arguments.
-MINA = MINA ## Renvoie la plus petite valeur d’une liste d’arguments, nombres, texte et valeurs logiques inclus.
-MODE = MODE ## Renvoie la valeur la plus courante d’une série de données.
-NEGBINOMDIST = LOI.BINOMIALE.NEG ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi binomiale négative.
-NORMDIST = LOI.NORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale.
-NORMINV = LOI.NORMALE.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi normale standard.
-NORMSDIST = LOI.NORMALE.STANDARD ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale standard.
-NORMSINV = LOI.NORMALE.STANDARD.INVERSE ## Renvoie l’inverse de la distribution cumulée normale standard.
-PEARSON = PEARSON ## Renvoie le coefficient de corrélation d’échantillonnage de Pearson.
-PERCENTILE = CENTILE ## Renvoie le k-ième centile des valeurs d’une plage.
-PERCENTRANK = RANG.POURCENTAGE ## Renvoie le rang en pourcentage d’une valeur d’une série de données.
-PERMUT = PERMUTATION ## Renvoie le nombre de permutations pour un nombre donné d’objets.
-POISSON = LOI.POISSON ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Poisson.
-PROB = PROBABILITE ## Renvoie la probabilité que des valeurs d’une plage soient comprises entre deux limites.
-QUARTILE = QUARTILE ## Renvoie le quartile d’une série de données.
-RANK = RANG ## Renvoie le rang d’un nombre contenu dans une liste.
-RSQ = COEFFICIENT.DETERMINATION ## Renvoie la valeur du coefficient de détermination R^2 d’une régression linéaire.
-SKEW = COEFFICIENT.ASYMETRIE ## Renvoie l’asymétrie d’une distribution.
-SLOPE = PENTE ## Renvoie la pente d’une droite de régression linéaire.
-SMALL = PETITE.VALEUR ## Renvoie la k-ième plus petite valeur d’une série de données.
-STANDARDIZE = CENTREE.REDUITE ## Renvoie une valeur centrée réduite.
-STDEV = ECARTYPE ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population.
-STDEVA = STDEVA ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques inclus.
-STDEVP = ECARTYPEP ## Calcule l’écart type d’une population à partir de la population entière.
-STDEVPA = STDEVPA ## Calcule l’écart type d’une population à partir de l’ensemble de la population, nombres, texte et valeurs logiques inclus.
-STEYX = ERREUR.TYPE.XY ## Renvoie l’erreur type de la valeur y prévue pour chaque x de la régression.
-TDIST = LOI.STUDENT ## Renvoie la probabilité d’une variable aléatoire suivant une loi T de Student.
-TINV = LOI.STUDENT.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi T de Student.
-TREND = TENDANCE ## Renvoie des valeurs par rapport à une tendance linéaire.
-TRIMMEAN = MOYENNE.REDUITE ## Renvoie la moyenne de l’intérieur d’une série de données.
-TTEST = TEST.STUDENT ## Renvoie la probabilité associée à un test T de Student.
-VAR = VAR ## Calcule la variance sur la base d’un échantillon.
-VARA = VARA ## Estime la variance d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques incluses.
-VARP = VAR.P ## Calcule la variance sur la base de l’ensemble de la population.
-VARPA = VARPA ## Calcule la variance d’une population en se basant sur la population entière, nombres, texte et valeurs logiques inclus.
-WEIBULL = LOI.WEIBULL ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Weibull.
-ZTEST = TEST.Z ## Renvoie la valeur de probabilité unilatérale d’un test z.
-
+BAHTTEXT = BAHTTEXT
+CHAR = CAR
+CLEAN = EPURAGE
+CODE = CODE
+CONCAT = CONCAT
+DOLLAR = DEVISE
+EXACT = EXACT
+FIND = TROUVE
+FIXED = CTXT
+LEFT = GAUCHE
+LEN = NBCAR
+LOWER = MINUSCULE
+MID = STXT
+NUMBERVALUE = VALEURNOMBRE
+PHONETIC = PHONETIQUE
+PROPER = NOMPROPRE
+REPLACE = REMPLACER
+REPT = REPT
+RIGHT = DROITE
+SEARCH = CHERCHE
+SUBSTITUTE = SUBSTITUE
+T = T
+TEXT = TEXTE
+TEXTJOIN = JOINDRE.TEXTE
+TRIM = SUPPRESPACE
+UNICHAR = UNICAR
+UNICODE = UNICODE
+UPPER = MAJUSCULE
+VALUE = CNUM
##
-## Text functions Fonctions de texte
+## Fonctions web (Web Functions)
##
-ASC = ASC ## Change les caractères anglais ou katakana à pleine chasse (codés sur deux octets) à l’intérieur d’une chaîne de caractères en caractères à demi-chasse (codés sur un octet).
-BAHTTEXT = BAHTTEXT ## Convertit un nombre en texte en utilisant le format monétaire ß (baht).
-CHAR = CAR ## Renvoie le caractère spécifié par le code numérique.
-CLEAN = EPURAGE ## Supprime tous les caractères de contrôle du texte.
-CODE = CODE ## Renvoie le numéro de code du premier caractère du texte.
-CONCATENATE = CONCATENER ## Assemble plusieurs éléments textuels de façon à n’en former qu’un seul.
-DOLLAR = EURO ## Convertit un nombre en texte en utilisant le format monétaire € (euro).
-EXACT = EXACT ## Vérifie si deux valeurs de texte sont identiques.
-FIND = TROUVE ## Trouve un valeur textuelle dans une autre, en respectant la casse.
-FINDB = TROUVERB ## Trouve un valeur textuelle dans une autre, en respectant la casse.
-FIXED = CTXT ## Convertit un nombre au format texte avec un nombre de décimales spécifié.
-JIS = JIS ## Change les caractères anglais ou katakana à demi-chasse (codés sur un octet) à l’intérieur d’une chaîne de caractères en caractères à à pleine chasse (codés sur deux octets).
-LEFT = GAUCHE ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères.
-LEFTB = GAUCHEB ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères.
-LEN = NBCAR ## Renvoie le nombre de caractères contenus dans une chaîne de texte.
-LENB = LENB ## Renvoie le nombre de caractères contenus dans une chaîne de texte.
-LOWER = MINUSCULE ## Convertit le texte en minuscules.
-MID = STXT ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez.
-MIDB = STXTB ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez.
-PHONETIC = PHONETIQUE ## Extrait les caractères phonétiques (furigana) d’une chaîne de texte.
-PROPER = NOMPROPRE ## Met en majuscules la première lettre de chaque mot dans une chaîne textuelle.
-REPLACE = REMPLACER ## Remplace des caractères dans un texte.
-REPLACEB = REMPLACERB ## Remplace des caractères dans un texte.
-REPT = REPT ## Répète un texte un certain nombre de fois.
-RIGHT = DROITE ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères.
-RIGHTB = DROITEB ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères.
-SEARCH = CHERCHE ## Trouve un texte dans un autre texte (sans respecter la casse).
-SEARCHB = CHERCHERB ## Trouve un texte dans un autre texte (sans respecter la casse).
-SUBSTITUTE = SUBSTITUE ## Remplace l’ancien texte d’une chaîne de caractères par un nouveau.
-T = T ## Convertit ses arguments en texte.
-TEXT = TEXTE ## Convertit un nombre au format texte.
-TRIM = SUPPRESPACE ## Supprime les espaces du texte.
-UPPER = MAJUSCULE ## Convertit le texte en majuscules.
-VALUE = CNUM ## Convertit un argument textuel en nombre
+ENCODEURL = URLENCODAGE
+FILTERXML = FILTRE.XML
+WEBSERVICE = SERVICEWEB
+
+##
+## Fonctions de compatibilité (Compatibility Functions)
+##
+BETADIST = LOI.BETA
+BETAINV = BETA.INVERSE
+BINOMDIST = LOI.BINOMIALE
+CEILING = PLAFOND
+CHIDIST = LOI.KHIDEUX
+CHIINV = KHIDEUX.INVERSE
+CHITEST = TEST.KHIDEUX
+CONCATENATE = CONCATENER
+CONFIDENCE = INTERVALLE.CONFIANCE
+COVAR = COVARIANCE
+CRITBINOM = CRITERE.LOI.BINOMIALE
+EXPONDIST = LOI.EXPONENTIELLE
+FDIST = LOI.F
+FINV = INVERSE.LOI.F
+FLOOR = PLANCHER
+FORECAST = PREVISION
+FTEST = TEST.F
+GAMMADIST = LOI.GAMMA
+GAMMAINV = LOI.GAMMA.INVERSE
+HYPGEOMDIST = LOI.HYPERGEOMETRIQUE
+LOGINV = LOI.LOGNORMALE.INVERSE
+LOGNORMDIST = LOI.LOGNORMALE
+MODE = MODE
+NEGBINOMDIST = LOI.BINOMIALE.NEG
+NORMDIST = LOI.NORMALE
+NORMINV = LOI.NORMALE.INVERSE
+NORMSDIST = LOI.NORMALE.STANDARD
+NORMSINV = LOI.NORMALE.STANDARD.INVERSE
+PERCENTILE = CENTILE
+PERCENTRANK = RANG.POURCENTAGE
+POISSON = LOI.POISSON
+QUARTILE = QUARTILE
+RANK = RANG
+STDEV = ECARTYPE
+STDEVP = ECARTYPEP
+TDIST = LOI.STUDENT
+TINV = LOI.STUDENT.INVERSE
+TTEST = TEST.STUDENT
+VAR = VAR
+VARP = VAR.P
+WEIBULL = LOI.WEIBULL
+ZTEST = TEST.Z
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/config
index db61436c1ed..dc585d71f88 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/config
@@ -1,23 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Magyar (Hungarian)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = Ft
-
-
-##
-## Excel Error Codes (For future use)
-##
-NULL = #NULLA!
-DIV0 = #ZÉRÓOSZTÓ!
-VALUE = #ÉRTÉK!
-REF = #HIV!
-NAME = #NÉV?
-NUM = #SZÁM!
-NA = #HIÁNYZIK
+NULL = #NULLA!
+DIV0 = #ZÉRÓOSZTÓ!
+VALUE = #ÉRTÉK!
+REF = #HIV!
+NAME = #NÉV?
+NUM = #SZÁM!
+NA = #HIÁNYZIK
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/functions
index 3adffeb148d..46b30127146 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/functions
@@ -1,416 +1,537 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
+## PhpSpreadsheet - function name translations
##
+## Magyar (Hungarian)
##
+############################################################
##
-## Add-in and Automation functions Bővítmények és automatizálási függvények
+## Kockafüggvények (Cube Functions)
##
-GETPIVOTDATA = KIMUTATÁSADATOT.VESZ ## A kimutatásokban tárolt adatok visszaadására használható.
-
+CUBEKPIMEMBER = KOCKA.FŐTELJMUT
+CUBEMEMBER = KOCKA.TAG
+CUBEMEMBERPROPERTY = KOCKA.TAG.TUL
+CUBERANKEDMEMBER = KOCKA.HALM.ELEM
+CUBESET = KOCKA.HALM
+CUBESETCOUNT = KOCKA.HALM.DB
+CUBEVALUE = KOCKA.ÉRTÉK
##
-## Cube functions Kockafüggvények
+## Adatbázis-kezelő függvények (Database Functions)
##
-CUBEKPIMEMBER = KOCKA.FŐTELJMUT ## Egy fő teljesítménymutató (KPI) nevét, tulajdonságát és mértékegységét adja eredményül, a nevet és a tulajdonságot megjeleníti a cellában. A KPI-k számszerűsíthető mérési lehetőséget jelentenek – ilyen mutató például a havi bruttó nyereség vagy az egy alkalmazottra jutó negyedéves forgalom –, egy szervezet teljesítményének nyomonkövetésére használhatók.
-CUBEMEMBER = KOCKA.TAG ## Kockahierachia tagját vagy rekordját adja eredményül. Ellenőrizhető vele, hogy szerepel-e a kockában az adott tag vagy rekord.
-CUBEMEMBERPROPERTY = KOCKA.TAG.TUL ## A kocka egyik tagtulajdonságának értékét adja eredményül. Használatával ellenőrizhető, hogy szerepel-e egy tagnév a kockában, eredménye pedig az erre a tagra vonatkozó, megadott tulajdonság.
-CUBERANKEDMEMBER = KOCKA.HALM.ELEM ## Egy halmaz rangsor szerinti n-edik tagját adja eredményül. Használatával egy halmaz egy vagy több elemét kaphatja meg, például a legnagyobb teljesítményű üzletkötőt vagy a 10 legjobb tanulót.
-CUBESET = KOCKA.HALM ## Számított tagok vagy rekordok halmazát adja eredményül, ehhez egy beállított kifejezést elküld a kiszolgálón található kockának, majd ezt a halmazt adja vissza a Microsoft Office Excel alkalmazásnak.
-CUBESETCOUNT = KOCKA.HALM.DB ## Egy halmaz elemszámát adja eredményül.
-CUBEVALUE = KOCKA.ÉRTÉK ## Kockából összesített értéket ad eredményül.
-
+DAVERAGE = AB.ÁTLAG
+DCOUNT = AB.DARAB
+DCOUNTA = AB.DARAB2
+DGET = AB.MEZŐ
+DMAX = AB.MAX
+DMIN = AB.MIN
+DPRODUCT = AB.SZORZAT
+DSTDEV = AB.SZÓRÁS
+DSTDEVP = AB.SZÓRÁS2
+DSUM = AB.SZUM
+DVAR = AB.VAR
+DVARP = AB.VAR2
##
-## Database functions Adatbázis-kezelő függvények
+## Dátumfüggvények (Date & Time Functions)
##
-DAVERAGE = AB.ÁTLAG ## A kijelölt adatbáziselemek átlagát számítja ki.
-DCOUNT = AB.DARAB ## Megszámolja, hogy az adatbázisban hány cella tartalmaz számokat.
-DCOUNTA = AB.DARAB2 ## Megszámolja az adatbázisban lévő nem üres cellákat.
-DGET = AB.MEZŐ ## Egy adatbázisból egyetlen olyan rekordot ad vissza, amely megfelel a megadott feltételeknek.
-DMAX = AB.MAX ## A kiválasztott adatbáziselemek közül a legnagyobb értéket adja eredményül.
-DMIN = AB.MIN ## A kijelölt adatbáziselemek közül a legkisebb értéket adja eredményül.
-DPRODUCT = AB.SZORZAT ## Az adatbázis megadott feltételeknek eleget tevő rekordjaira összeszorozza a megadott mezőben található számértékeket, és eredményül ezt a szorzatot adja.
-DSTDEV = AB.SZÓRÁS ## A kijelölt adatbáziselemek egy mintája alapján megbecsüli a szórást.
-DSTDEVP = AB.SZÓRÁS2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórást.
-DSUM = AB.SZUM ## Összeadja a feltételnek megfelelő adatbázisrekordok mezőoszlopában a számokat.
-DVAR = AB.VAR ## A kijelölt adatbáziselemek mintája alapján becslést ad a szórásnégyzetre.
-DVARP = AB.VAR2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórásnégyzetet.
-
+DATE = DÁTUM
+DATEDIF = DÁTUMTÓLIG
+DATESTRING = DÁTUMSZÖVEG
+DATEVALUE = DÁTUMÉRTÉK
+DAY = NAP
+DAYS = NAPOK
+DAYS360 = NAP360
+EDATE = KALK.DÁTUM
+EOMONTH = HÓNAP.UTOLSÓ.NAP
+HOUR = ÓRA
+ISOWEEKNUM = ISO.HÉT.SZÁMA
+MINUTE = PERCEK
+MONTH = HÓNAP
+NETWORKDAYS = ÖSSZ.MUNKANAP
+NETWORKDAYS.INTL = ÖSSZ.MUNKANAP.INTL
+NOW = MOST
+SECOND = MPERC
+THAIDAYOFWEEK = THAIHÉTNAPJA
+THAIMONTHOFYEAR = THAIHÓNAP
+THAIYEAR = THAIÉV
+TIME = IDŐ
+TIMEVALUE = IDŐÉRTÉK
+TODAY = MA
+WEEKDAY = HÉT.NAPJA
+WEEKNUM = HÉT.SZÁMA
+WORKDAY = KALK.MUNKANAP
+WORKDAY.INTL = KALK.MUNKANAP.INTL
+YEAR = ÉV
+YEARFRAC = TÖRTÉV
##
-## Date and time functions Dátumfüggvények
+## Mérnöki függvények (Engineering Functions)
##
-DATE = DÁTUM ## Adott dátum dátumértékét adja eredményül.
-DATEVALUE = DÁTUMÉRTÉK ## Szövegként megadott dátumot dátumértékké alakít át.
-DAY = NAP ## Dátumértéket a hónap egy napjává (0-31) alakít.
-DAYS360 = NAP360 ## Két dátum közé eső napok számát számítja ki a 360 napos év alapján.
-EDATE = EDATE ## Adott dátumnál adott számú hónappal korábbi vagy későbbi dátum dátumértékét adja eredményül.
-EOMONTH = EOMONTH ## Adott dátumnál adott számú hónappal korábbi vagy későbbi hónap utolsó napjának dátumértékét adja eredményül.
-HOUR = ÓRA ## Időértéket órákká alakít.
-MINUTE = PERC ## Időértéket percekké alakít.
-MONTH = HÓNAP ## Időértéket hónapokká alakít.
-NETWORKDAYS = NETWORKDAYS ## Két dátum között a teljes munkanapok számát adja meg.
-NOW = MOST ## A napi dátum dátumértékét és a pontos idő időértékét adja eredményül.
-SECOND = MPERC ## Időértéket másodpercekké alakít át.
-TIME = IDŐ ## Adott időpont időértékét adja meg.
-TIMEVALUE = IDŐÉRTÉK ## Szövegként megadott időpontot időértékké alakít át.
-TODAY = MA ## A napi dátum dátumértékét adja eredményül.
-WEEKDAY = HÉT.NAPJA ## Dátumértéket a hét napjává alakítja át.
-WEEKNUM = WEEKNUM ## Visszatérési értéke egy szám, amely azt mutatja meg, hogy a megadott dátum az év hányadik hetére esik.
-WORKDAY = WORKDAY ## Adott dátumnál adott munkanappal korábbi vagy későbbi dátum dátumértékét adja eredményül.
-YEAR = ÉV ## Sorszámot évvé alakít át.
-YEARFRAC = YEARFRAC ## Az adott dátumok közötti teljes napok számát törtévként adja meg.
-
+BESSELI = BESSELI
+BESSELJ = BESSELJ
+BESSELK = BESSELK
+BESSELY = BESSELY
+BIN2DEC = BIN.DEC
+BIN2HEX = BIN.HEX
+BIN2OCT = BIN.OKT
+BITAND = BIT.ÉS
+BITLSHIFT = BIT.BAL.ELTOL
+BITOR = BIT.VAGY
+BITRSHIFT = BIT.JOBB.ELTOL
+BITXOR = BIT.XVAGY
+COMPLEX = KOMPLEX
+CONVERT = KONVERTÁLÁS
+DEC2BIN = DEC.BIN
+DEC2HEX = DEC.HEX
+DEC2OCT = DEC.OKT
+DELTA = DELTA
+ERF = HIBAF
+ERF.PRECISE = HIBAF.PONTOS
+ERFC = HIBAF.KOMPLEMENTER
+ERFC.PRECISE = HIBAFKOMPLEMENTER.PONTOS
+GESTEP = KÜSZÖBNÉL.NAGYOBB
+HEX2BIN = HEX.BIN
+HEX2DEC = HEX.DEC
+HEX2OCT = HEX.OKT
+IMABS = KÉPZ.ABSZ
+IMAGINARY = KÉPZETES
+IMARGUMENT = KÉPZ.ARGUMENT
+IMCONJUGATE = KÉPZ.KONJUGÁLT
+IMCOS = KÉPZ.COS
+IMCOSH = KÉPZ.COSH
+IMCOT = KÉPZ.COT
+IMCSC = KÉPZ.CSC
+IMCSCH = KÉPZ.CSCH
+IMDIV = KÉPZ.HÁNYAD
+IMEXP = KÉPZ.EXP
+IMLN = KÉPZ.LN
+IMLOG10 = KÉPZ.LOG10
+IMLOG2 = KÉPZ.LOG2
+IMPOWER = KÉPZ.HATV
+IMPRODUCT = KÉPZ.SZORZAT
+IMREAL = KÉPZ.VALÓS
+IMSEC = KÉPZ.SEC
+IMSECH = KÉPZ.SECH
+IMSIN = KÉPZ.SIN
+IMSINH = KÉPZ.SINH
+IMSQRT = KÉPZ.GYÖK
+IMSUB = KÉPZ.KÜL
+IMSUM = KÉPZ.ÖSSZEG
+IMTAN = KÉPZ.TAN
+OCT2BIN = OKT.BIN
+OCT2DEC = OKT.DEC
+OCT2HEX = OKT.HEX
##
-## Engineering functions Mérnöki függvények
+## Pénzügyi függvények (Financial Functions)
##
-BESSELI = BESSELI ## Az In(x) módosított Bessel-függvény értékét adja eredményül.
-BESSELJ = BESSELJ ## A Jn(x) Bessel-függvény értékét adja eredményül.
-BESSELK = BESSELK ## A Kn(x) módosított Bessel-függvény értékét adja eredményül.
-BESSELY = BESSELY ## Az Yn(x) módosított Bessel-függvény értékét adja eredményül.
-BIN2DEC = BIN2DEC ## Bináris számot decimálissá alakít át.
-BIN2HEX = BIN2HEX ## Bináris számot hexadecimálissá alakít át.
-BIN2OCT = BIN2OCT ## Bináris számot oktálissá alakít át.
-COMPLEX = COMPLEX ## Valós és képzetes részből komplex számot képez.
-CONVERT = CONVERT ## Mértékegységeket vált át.
-DEC2BIN = DEC2BIN ## Decimális számot binárissá alakít át.
-DEC2HEX = DEC2HEX ## Decimális számot hexadecimálissá alakít át.
-DEC2OCT = DEC2OCT ## Decimális számot oktálissá alakít át.
-DELTA = DELTA ## Azt vizsgálja, hogy két érték egyenlő-e.
-ERF = ERF ## A hibafüggvény értékét adja eredményül.
-ERFC = ERFC ## A kiegészített hibafüggvény értékét adja eredményül.
-GESTEP = GESTEP ## Azt vizsgálja, hogy egy szám nagyobb-e adott küszöbértéknél.
-HEX2BIN = HEX2BIN ## Hexadecimális számot binárissá alakít át.
-HEX2DEC = HEX2DEC ## Hexadecimális számot decimálissá alakít át.
-HEX2OCT = HEX2OCT ## Hexadecimális számot oktálissá alakít át.
-IMABS = IMABS ## Komplex szám abszolút értékét (modulusát) adja eredményül.
-IMAGINARY = IMAGINARY ## Komplex szám képzetes részét adja eredményül.
-IMARGUMENT = IMARGUMENT ## A komplex szám radiánban kifejezett théta argumentumát adja eredményül.
-IMCONJUGATE = IMCONJUGATE ## Komplex szám komplex konjugáltját adja eredményül.
-IMCOS = IMCOS ## Komplex szám koszinuszát adja eredményül.
-IMDIV = IMDIV ## Két komplex szám hányadosát adja eredményül.
-IMEXP = IMEXP ## Az e szám komplex kitevőjű hatványát adja eredményül.
-IMLN = IMLN ## Komplex szám természetes logaritmusát adja eredményül.
-IMLOG10 = IMLOG10 ## Komplex szám tízes alapú logaritmusát adja eredményül.
-IMLOG2 = IMLOG2 ## Komplex szám kettes alapú logaritmusát adja eredményül.
-IMPOWER = IMPOWER ## Komplex szám hatványát adja eredményül.
-IMPRODUCT = IMPRODUCT ## Komplex számok szorzatát adja eredményül.
-IMREAL = IMREAL ## Komplex szám valós részét adja eredményül.
-IMSIN = IMSIN ## Komplex szám szinuszát adja eredményül.
-IMSQRT = IMSQRT ## Komplex szám négyzetgyökét adja eredményül.
-IMSUB = IMSUB ## Két komplex szám különbségét adja eredményül.
-IMSUM = IMSUM ## Komplex számok összegét adja eredményül.
-OCT2BIN = OCT2BIN ## Oktális számot binárissá alakít át.
-OCT2DEC = OCT2DEC ## Oktális számot decimálissá alakít át.
-OCT2HEX = OCT2HEX ## Oktális számot hexadecimálissá alakít át.
-
+ACCRINT = IDŐSZAKI.KAMAT
+ACCRINTM = LEJÁRATI.KAMAT
+AMORDEGRC = ÉRTÉKCSÖKK.TÉNYEZŐVEL
+AMORLINC = ÉRTÉKCSÖKK
+COUPDAYBS = SZELVÉNYIDŐ.KEZDETTŐL
+COUPDAYS = SZELVÉNYIDŐ
+COUPDAYSNC = SZELVÉNYIDŐ.KIFIZETÉSTŐL
+COUPNCD = ELSŐ.SZELVÉNYDÁTUM
+COUPNUM = SZELVÉNYSZÁM
+COUPPCD = UTOLSÓ.SZELVÉNYDÁTUM
+CUMIPMT = ÖSSZES.KAMAT
+CUMPRINC = ÖSSZES.TŐKERÉSZ
+DB = KCS2
+DDB = KCSA
+DISC = LESZÁM
+DOLLARDE = FORINT.DEC
+DOLLARFR = FORINT.TÖRT
+DURATION = KAMATÉRZ
+EFFECT = TÉNYLEGES
+FV = JBÉ
+FVSCHEDULE = KJÉ
+INTRATE = KAMATRÁTA
+IPMT = RRÉSZLET
+IRR = BMR
+ISPMT = LRÉSZLETKAMAT
+MDURATION = MKAMATÉRZ
+MIRR = MEGTÉRÜLÉS
+NOMINAL = NÉVLEGES
+NPER = PER.SZÁM
+NPV = NMÉ
+ODDFPRICE = ELTÉRŐ.EÁR
+ODDFYIELD = ELTÉRŐ.EHOZAM
+ODDLPRICE = ELTÉRŐ.UÁR
+ODDLYIELD = ELTÉRŐ.UHOZAM
+PDURATION = KAMATÉRZ.PER
+PMT = RÉSZLET
+PPMT = PRÉSZLET
+PRICE = ÁR
+PRICEDISC = ÁR.LESZÁM
+PRICEMAT = ÁR.LEJÁRAT
+PV = MÉ
+RATE = RÁTA
+RECEIVED = KAPOTT
+RRI = MR
+SLN = LCSA
+SYD = ÉSZÖ
+TBILLEQ = KJEGY.EGYENÉRT
+TBILLPRICE = KJEGY.ÁR
+TBILLYIELD = KJEGY.HOZAM
+VDB = ÉCSRI
+XIRR = XBMR
+XNPV = XNJÉ
+YIELD = HOZAM
+YIELDDISC = HOZAM.LESZÁM
+YIELDMAT = HOZAM.LEJÁRAT
##
-## Financial functions Pénzügyi függvények
+## Információs függvények (Information Functions)
##
-ACCRINT = ACCRINT ## Periodikusan kamatozó értékpapír felszaporodott kamatát adja eredményül.
-ACCRINTM = ACCRINTM ## Lejáratkor kamatozó értékpapír felszaporodott kamatát adja eredményül.
-AMORDEGRC = AMORDEGRC ## Állóeszköz lineáris értékcsökkenését adja meg az egyes könyvelési időszakokra vonatkozóan.
-AMORLINC = AMORLINC ## Az egyes könyvelési időszakokban az értékcsökkenést adja meg.
-COUPDAYBS = COUPDAYBS ## A szelvényidőszak kezdetétől a kifizetés időpontjáig eltelt napokat adja vissza.
-COUPDAYS = COUPDAYS ## A kifizetés időpontját magában foglaló szelvényperiódus hosszát adja meg napokban.
-COUPDAYSNC = COUPDAYSNC ## A kifizetés időpontja és a legközelebbi szelvénydátum közötti napok számát adja meg.
-COUPNCD = COUPNCD ## A kifizetést követő legelső szelvénydátumot adja eredményül.
-COUPNUM = COUPNUM ## A kifizetés és a lejárat időpontja között kifizetendő szelvények számát adja eredményül.
-COUPPCD = COUPPCD ## A kifizetés előtti utolsó szelvénydátumot adja eredményül.
-CUMIPMT = CUMIPMT ## Két fizetési időszak között kifizetett kamat halmozott értékét adja eredményül.
-CUMPRINC = CUMPRINC ## Két fizetési időszak között kifizetett részletek halmozott (kamatot nem tartalmazó) értékét adja eredményül.
-DB = KCS2 ## Eszköz adott időszak alatti értékcsökkenését számítja ki a lineáris leírási modell alkalmazásával.
-DDB = KCSA ## Eszköz értékcsökkenését számítja ki adott időszakra vonatkozóan a progresszív vagy egyéb megadott leírási modell alkalmazásával.
-DISC = DISC ## Értékpapír leszámítolási kamatlábát adja eredményül.
-DOLLARDE = DOLLARDE ## Egy közönséges törtként megadott számot tizedes törtté alakít át.
-DOLLARFR = DOLLARFR ## Tizedes törtként megadott számot közönséges törtté alakít át.
-DURATION = DURATION ## Periodikus kamatfizetésű értékpapír éves kamatérzékenységét adja eredményül.
-EFFECT = EFFECT ## Az éves tényleges kamatláb értékét adja eredményül.
-FV = JBÉ ## Befektetés jövőbeli értékét számítja ki.
-FVSCHEDULE = FVSCHEDULE ## A kezdőtőke adott kamatlábak szerint megnövelt jövőbeli értékét adja eredményül.
-INTRATE = INTRATE ## A lejáratig teljesen lekötött értékpapír kamatrátáját adja eredményül.
-IPMT = RRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra.
-IRR = BMR ## A befektetés belső megtérülési rátáját számítja ki pénzáramláshoz.
-ISPMT = LRÉSZLETKAMAT ## A befektetés adott időszakára fizetett kamatot számítja ki.
-MDURATION = MDURATION ## Egy 100 Ft névértékű értékpapír Macauley-féle módosított kamatérzékenységét adja eredményül.
-MIRR = MEGTÉRÜLÉS ## A befektetés belső megtérülési rátáját számítja ki a költségek és a bevételek különböző kamatlába mellett.
-NOMINAL = NOMINAL ## Az éves névleges kamatláb értékét adja eredményül.
-NPER = PER.SZÁM ## A törlesztési időszakok számát adja meg.
-NPV = NMÉ ## Befektetéshez kapcsolódó pénzáramlás nettó jelenértékét számítja ki ismert pénzáramlás és kamatláb mellett.
-ODDFPRICE = ODDFPRICE ## Egy 100 Ft névértékű, a futamidő elején töredék-időszakos értékpapír árát adja eredményül.
-ODDFYIELD = ODDFYIELD ## A futamidő elején töredék-időszakos értékpapír hozamát adja eredményül.
-ODDLPRICE = ODDLPRICE ## Egy 100 Ft névértékű, a futamidő végén töredék-időszakos értékpapír árát adja eredményül.
-ODDLYIELD = ODDLYIELD ## A futamidő végén töredék-időszakos értékpapír hozamát adja eredményül.
-PMT = RÉSZLET ## A törlesztési időszakra vonatkozó törlesztési összeget számítja ki.
-PPMT = PRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra.
-PRICE = PRICE ## Egy 100 Ft névértékű, periodikusan kamatozó értékpapír árát adja eredményül.
-PRICEDISC = PRICEDISC ## Egy 100 Ft névértékű leszámítolt értékpapír árát adja eredményül.
-PRICEMAT = PRICEMAT ## Egy 100 Ft névértékű, a lejáratkor kamatozó értékpapír árát adja eredményül.
-PV = MÉ ## Befektetés jelenlegi értékét számítja ki.
-RATE = RÁTA ## Egy törlesztési időszakban az egy időszakra eső kamatláb nagyságát számítja ki.
-RECEIVED = RECEIVED ## A lejáratig teljesen lekötött értékpapír lejáratakor kapott összegét adja eredményül.
-SLN = LCSA ## Tárgyi eszköz egy időszakra eső amortizációját adja meg bruttó érték szerinti lineáris leírási kulcsot alkalmazva.
-SYD = SYD ## Tárgyi eszköz értékcsökkenését számítja ki adott időszakra az évek számjegyösszegével dolgozó módszer alapján.
-TBILLEQ = TBILLEQ ## Kincstárjegy kötvény-egyenértékű hozamát adja eredményül.
-TBILLPRICE = TBILLPRICE ## Egy 100 Ft névértékű kincstárjegy árát adja eredményül.
-TBILLYIELD = TBILLYIELD ## Kincstárjegy hozamát adja eredményül.
-VDB = ÉCSRI ## Tárgyi eszköz amortizációját számítja ki megadott vagy részidőszakra a csökkenő egyenleg módszerének alkalmazásával.
-XIRR = XIRR ## Ütemezett készpénzforgalom (cash flow) belső megtérülési kamatrátáját adja eredményül.
-XNPV = XNPV ## Ütemezett készpénzforgalom (cash flow) nettó jelenlegi értékét adja eredményül.
-YIELD = YIELD ## Periodikusan kamatozó értékpapír hozamát adja eredményül.
-YIELDDISC = YIELDDISC ## Leszámítolt értékpapír (például kincstárjegy) éves hozamát adja eredményül.
-YIELDMAT = YIELDMAT ## Lejáratkor kamatozó értékpapír éves hozamát adja eredményül.
-
+CELL = CELLA
+ERROR.TYPE = HIBA.TÍPUS
+INFO = INFÓ
+ISBLANK = ÜRES
+ISERR = HIBA.E
+ISERROR = HIBÁS
+ISEVEN = PÁROSE
+ISFORMULA = KÉPLET
+ISLOGICAL = LOGIKAI
+ISNA = NINCS
+ISNONTEXT = NEM.SZÖVEG
+ISNUMBER = SZÁM
+ISODD = PÁRATLANE
+ISREF = HIVATKOZÁS
+ISTEXT = SZÖVEG.E
+N = S
+NA = HIÁNYZIK
+SHEET = LAP
+SHEETS = LAPOK
+TYPE = TÍPUS
##
-## Information functions Információs függvények
+## Logikai függvények (Logical Functions)
##
-CELL = CELLA ## Egy cella formátumára, elhelyezkedésére vagy tartalmára vonatkozó adatokat ad eredményül.
-ERROR.TYPE = HIBA.TÍPUS ## Egy hibatípushoz tartozó számot ad eredményül.
-INFO = INFÓ ## A rendszer- és munkakörnyezet pillanatnyi állapotáról ad felvilágosítást.
-ISBLANK = ÜRES ## Eredménye IGAZ, ha az érték üres.
-ISERR = HIBA ## Eredménye IGAZ, ha az érték valamelyik hibaérték a #HIÁNYZIK kivételével.
-ISERROR = HIBÁS ## Eredménye IGAZ, ha az érték valamelyik hibaérték.
-ISEVEN = ISEVEN ## Eredménye IGAZ, ha argumentuma páros szám.
-ISLOGICAL = LOGIKAI ## Eredménye IGAZ, ha az érték logikai érték.
-ISNA = NINCS ## Eredménye IGAZ, ha az érték a #HIÁNYZIK hibaérték.
-ISNONTEXT = NEM.SZÖVEG ## Eredménye IGAZ, ha az érték nem szöveg.
-ISNUMBER = SZÁM ## Eredménye IGAZ, ha az érték szám.
-ISODD = ISODD ## Eredménye IGAZ, ha argumentuma páratlan szám.
-ISREF = HIVATKOZÁS ## Eredménye IGAZ, ha az érték hivatkozás.
-ISTEXT = SZÖVEG.E ## Eredménye IGAZ, ha az érték szöveg.
-N = N ## Argumentumának értékét számmá alakítja.
-NA = HIÁNYZIK ## Eredménye a #HIÁNYZIK hibaérték.
-TYPE = TÍPUS ## Érték adattípusának azonosítószámát adja eredményül.
-
+AND = ÉS
+FALSE = HAMIS
+IF = HA
+IFERROR = HAHIBA
+IFNA = HAHIÁNYZIK
+IFS = HAELSŐIGAZ
+NOT = NEM
+OR = VAGY
+SWITCH = ÁTVÁLT
+TRUE = IGAZ
+XOR = XVAGY
##
-## Logical functions Logikai függvények
+## Keresési és hivatkozási függvények (Lookup & Reference Functions)
##
-AND = ÉS ## Eredménye IGAZ, ha minden argumentuma IGAZ.
-FALSE = HAMIS ## A HAMIS logikai értéket adja eredményül.
-IF = HA ## Logikai vizsgálatot hajt végre.
-IFERROR = HAHIBA ## A megadott értéket adja vissza, ha egy képlet hibához vezet; más esetben a képlet értékét adja eredményül.
-NOT = NEM ## Argumentuma értékének ellentettjét adja eredményül.
-OR = VAGY ## Eredménye IGAZ, ha bármely argumentuma IGAZ.
-TRUE = IGAZ ## Az IGAZ logikai értéket adja eredményül.
-
+ADDRESS = CÍM
+AREAS = TERÜLET
+CHOOSE = VÁLASZT
+COLUMN = OSZLOP
+COLUMNS = OSZLOPOK
+FORMULATEXT = KÉPLETSZÖVEG
+GETPIVOTDATA = KIMUTATÁSADATOT.VESZ
+HLOOKUP = VKERES
+HYPERLINK = HIPERHIVATKOZÁS
+INDEX = INDEX
+INDIRECT = INDIREKT
+LOOKUP = KERES
+MATCH = HOL.VAN
+OFFSET = ELTOLÁS
+ROW = SOR
+ROWS = SOROK
+RTD = VIA
+TRANSPOSE = TRANSZPONÁLÁS
+VLOOKUP = FKERES
##
-## Lookup and reference functions Keresési és hivatkozási függvények
+## Matematikai és trigonometrikus függvények (Math & Trig Functions)
##
-ADDRESS = CÍM ## A munkalap egy cellájára való hivatkozást adja szövegként eredményül.
-AREAS = TERÜLET ## Hivatkozásban a területek számát adja eredményül.
-CHOOSE = VÁLASZT ## Értékek listájából választ ki egy elemet.
-COLUMN = OSZLOP ## Egy hivatkozás oszlopszámát adja eredményül.
-COLUMNS = OSZLOPOK ## A hivatkozásban található oszlopok számát adja eredményül.
-HLOOKUP = VKERES ## A megadott tömb felső sorában adott értékű elemet keres, és a megtalált elem oszlopából adott sorban elhelyezkedő értékkel tér vissza.
-HYPERLINK = HIPERHIVATKOZÁS ## Hálózati kiszolgálón, intraneten vagy az interneten tárolt dokumentumot megnyitó parancsikont vagy hivatkozást hoz létre.
-INDEX = INDEX ## Tömb- vagy hivatkozás indexszel megadott értékét adja vissza.
-INDIRECT = INDIREKT ## Szöveg megadott hivatkozást ad eredményül.
-LOOKUP = KERES ## Vektorban vagy tömbben keres meg értékeket.
-MATCH = HOL.VAN ## Hivatkozásban vagy tömbben értékeket keres.
-OFFSET = OFSZET ## Hivatkozás egy másik hivatkozástól számított távolságát adja meg.
-ROW = SOR ## Egy hivatkozás sorának számát adja meg.
-ROWS = SOROK ## Egy hivatkozás sorainak számát adja meg.
-RTD = RTD ## Valós idejű adatokat keres vissza a COM automatizmust (automatizálás: Egy alkalmazás objektumaival való munka másik alkalmazásból vagy fejlesztőeszközből. A korábban OLE automatizmusnak nevezett automatizálás iparági szabvány, a Component Object Model (COM) szolgáltatása.) támogató programból.
-TRANSPOSE = TRANSZPONÁLÁS ## Egy tömb transzponáltját adja eredményül.
-VLOOKUP = FKERES ## A megadott tömb bal szélső oszlopában megkeres egy értéket, majd annak sora és a megadott oszlop metszéspontjában levő értéked adja eredményül.
-
+ABS = ABS
+ACOS = ARCCOS
+ACOSH = ACOSH
+ACOT = ARCCOT
+ACOTH = ARCCOTH
+AGGREGATE = ÖSSZESÍT
+ARABIC = ARAB
+ASIN = ARCSIN
+ASINH = ASINH
+ATAN = ARCTAN
+ATAN2 = ARCTAN2
+ATANH = ATANH
+BASE = ALAP
+CEILING.MATH = PLAFON.MAT
+CEILING.PRECISE = PLAFON.PONTOS
+COMBIN = KOMBINÁCIÓK
+COMBINA = KOMBINÁCIÓK.ISM
+COS = COS
+COSH = COSH
+COT = COT
+COTH = COTH
+CSC = CSC
+CSCH = CSCH
+DECIMAL = TIZEDES
+DEGREES = FOK
+ECMA.CEILING = ECMA.PLAFON
+EVEN = PÁROS
+EXP = KITEVŐ
+FACT = FAKT
+FACTDOUBLE = FAKTDUPLA
+FLOOR.MATH = PADLÓ.MAT
+FLOOR.PRECISE = PADLÓ.PONTOS
+GCD = LKO
+INT = INT
+ISO.CEILING = ISO.PLAFON
+LCM = LKT
+LN = LN
+LOG = LOG
+LOG10 = LOG10
+MDETERM = MDETERM
+MINVERSE = INVERZ.MÁTRIX
+MMULT = MSZORZAT
+MOD = MARADÉK
+MROUND = TÖBBSZ.KEREKÍT
+MULTINOMIAL = SZORHÁNYFAKT
+MUNIT = MMÁTRIX
+ODD = PÁRATLAN
+PI = PI
+POWER = HATVÁNY
+PRODUCT = SZORZAT
+QUOTIENT = KVÓCIENS
+RADIANS = RADIÁN
+RAND = VÉL
+RANDBETWEEN = VÉLETLEN.KÖZÖTT
+ROMAN = RÓMAI
+ROUND = KEREKÍTÉS
+ROUNDBAHTDOWN = BAHTKEREK.LE
+ROUNDBAHTUP = BAHTKEREK.FEL
+ROUNDDOWN = KEREK.LE
+ROUNDUP = KEREK.FEL
+SEC = SEC
+SECH = SECH
+SERIESSUM = SORÖSSZEG
+SIGN = ELŐJEL
+SIN = SIN
+SINH = SINH
+SQRT = GYÖK
+SQRTPI = GYÖKPI
+SUBTOTAL = RÉSZÖSSZEG
+SUM = SZUM
+SUMIF = SZUMHA
+SUMIFS = SZUMHATÖBB
+SUMPRODUCT = SZORZATÖSSZEG
+SUMSQ = NÉGYZETÖSSZEG
+SUMX2MY2 = SZUMX2BŐLY2
+SUMX2PY2 = SZUMX2MEGY2
+SUMXMY2 = SZUMXBŐLY2
+TAN = TAN
+TANH = TANH
+TRUNC = CSONK
##
-## Math and trigonometry functions Matematikai és trigonometrikus függvények
+## Statisztikai függvények (Statistical Functions)
##
-ABS = ABS ## Egy szám abszolút értékét adja eredményül.
-ACOS = ARCCOS ## Egy szám arkusz koszinuszát számítja ki.
-ACOSH = ACOSH ## Egy szám inverz koszinusz hiperbolikuszát számítja ki.
-ASIN = ARCSIN ## Egy szám arkusz szinuszát számítja ki.
-ASINH = ASINH ## Egy szám inverz szinusz hiperbolikuszát számítja ki.
-ATAN = ARCTAN ## Egy szám arkusz tangensét számítja ki.
-ATAN2 = ARCTAN2 ## X és y koordináták alapján számítja ki az arkusz tangens értéket.
-ATANH = ATANH ## A szám inverz tangens hiperbolikuszát számítja ki.
-CEILING = PLAFON ## Egy számot a legközelebbi egészre vagy a pontosságként megadott érték legközelebb eső többszörösére kerekít.
-COMBIN = KOMBINÁCIÓK ## Adott számú objektum összes lehetséges kombinációinak számát számítja ki.
-COS = COS ## Egy szám koszinuszát számítja ki.
-COSH = COSH ## Egy szám koszinusz hiperbolikuszát számítja ki.
-DEGREES = FOK ## Radiánt fokká alakít át.
-EVEN = PÁROS ## Egy számot a legközelebbi páros egész számra kerekít.
-EXP = KITEVŐ ## Az e adott kitevőjű hatványát adja eredményül.
-FACT = FAKT ## Egy szám faktoriálisát számítja ki.
-FACTDOUBLE = FACTDOUBLE ## Egy szám dupla faktoriálisát adja eredményül.
-FLOOR = PADLÓ ## Egy számot lefelé, a nulla felé kerekít.
-GCD = GCD ## A legnagyobb közös osztót adja eredményül.
-INT = INT ## Egy számot lefelé kerekít a legközelebbi egészre.
-LCM = LCM ## A legkisebb közös többszöröst adja eredményül.
-LN = LN ## Egy szám természetes logaritmusát számítja ki.
-LOG = LOG ## Egy szám adott alapú logaritmusát számítja ki.
-LOG10 = LOG10 ## Egy szám 10-es alapú logaritmusát számítja ki.
-MDETERM = MDETERM ## Egy tömb mátrix-determinánsát számítja ki.
-MINVERSE = INVERZ.MÁTRIX ## Egy tömb mátrix inverzét adja eredményül.
-MMULT = MSZORZAT ## Két tömb mátrix-szorzatát adja meg.
-MOD = MARADÉK ## Egy szám osztási maradékát adja eredményül.
-MROUND = MROUND ## A kívánt többszörösére kerekített értéket ad eredményül.
-MULTINOMIAL = MULTINOMIAL ## Számhalmaz multinomiálisát adja eredményül.
-ODD = PÁRATLAN ## Egy számot a legközelebbi páratlan számra kerekít.
-PI = PI ## A pi matematikai állandót adja vissza.
-POWER = HATVÁNY ## Egy szám adott kitevőjű hatványát számítja ki.
-PRODUCT = SZORZAT ## Argumentumai szorzatát számítja ki.
-QUOTIENT = QUOTIENT ## Egy hányados egész részét adja eredményül.
-RADIANS = RADIÁN ## Fokot radiánná alakít át.
-RAND = VÉL ## Egy 0 és 1 közötti véletlen számot ad eredményül.
-RANDBETWEEN = RANDBETWEEN ## Megadott számok közé eső véletlen számot állít elő.
-ROMAN = RÓMAI ## Egy számot római számokkal kifejezve szövegként ad eredményül.
-ROUND = KEREKÍTÉS ## Egy számot adott számú számjegyre kerekít.
-ROUNDDOWN = KEREKÍTÉS.LE ## Egy számot lefelé, a nulla felé kerekít.
-ROUNDUP = KEREKÍTÉS.FEL ## Egy számot felfelé, a nullától távolabbra kerekít.
-SERIESSUM = SERIESSUM ## Hatványsor összegét adja eredményül.
-SIGN = ELŐJEL ## Egy szám előjelét adja meg.
-SIN = SIN ## Egy szög szinuszát számítja ki.
-SINH = SINH ## Egy szám szinusz hiperbolikuszát számítja ki.
-SQRT = GYÖK ## Egy szám pozitív négyzetgyökét számítja ki.
-SQRTPI = SQRTPI ## A (szám*pi) négyzetgyökét adja eredményül.
-SUBTOTAL = RÉSZÖSSZEG ## Lista vagy adatbázis részösszegét adja eredményül.
-SUM = SZUM ## Összeadja az argumentumlistájában lévő számokat.
-SUMIF = SZUMHA ## A megadott feltételeknek eleget tevő cellákban található értékeket adja össze.
-SUMIFS = SZUMHATÖBB ## Több megadott feltételnek eleget tévő tartománycellák összegét adja eredményül.
-SUMPRODUCT = SZORZATÖSSZEG ## A megfelelő tömbelemek szorzatának összegét számítja ki.
-SUMSQ = NÉGYZETÖSSZEG ## Argumentumai négyzetének összegét számítja ki.
-SUMX2MY2 = SZUMX2BŐLY2 ## Két tömb megfelelő elemei négyzetének különbségét összegzi.
-SUMX2PY2 = SZUMX2MEGY2 ## Két tömb megfelelő elemei négyzetének összegét összegzi.
-SUMXMY2 = SZUMXBŐLY2 ## Két tömb megfelelő elemei különbségének négyzetösszegét számítja ki.
-TAN = TAN ## Egy szám tangensét számítja ki.
-TANH = TANH ## Egy szám tangens hiperbolikuszát számítja ki.
-TRUNC = CSONK ## Egy számot egésszé csonkít.
-
+AVEDEV = ÁTL.ELTÉRÉS
+AVERAGE = ÁTLAG
+AVERAGEA = ÁTLAGA
+AVERAGEIF = ÁTLAGHA
+AVERAGEIFS = ÁTLAGHATÖBB
+BETA.DIST = BÉTA.ELOSZL
+BETA.INV = BÉTA.INVERZ
+BINOM.DIST = BINOM.ELOSZL
+BINOM.DIST.RANGE = BINOM.ELOSZL.TART
+BINOM.INV = BINOM.INVERZ
+CHISQ.DIST = KHINÉGYZET.ELOSZLÁS
+CHISQ.DIST.RT = KHINÉGYZET.ELOSZLÁS.JOBB
+CHISQ.INV = KHINÉGYZET.INVERZ
+CHISQ.INV.RT = KHINÉGYZET.INVERZ.JOBB
+CHISQ.TEST = KHINÉGYZET.PRÓBA
+CONFIDENCE.NORM = MEGBÍZHATÓSÁG.NORM
+CONFIDENCE.T = MEGBÍZHATÓSÁG.T
+CORREL = KORREL
+COUNT = DARAB
+COUNTA = DARAB2
+COUNTBLANK = DARABÜRES
+COUNTIF = DARABTELI
+COUNTIFS = DARABHATÖBB
+COVARIANCE.P = KOVARIANCIA.S
+COVARIANCE.S = KOVARIANCIA.M
+DEVSQ = SQ
+EXPON.DIST = EXP.ELOSZL
+F.DIST = F.ELOSZL
+F.DIST.RT = F.ELOSZLÁS.JOBB
+F.INV = F.INVERZ
+F.INV.RT = F.INVERZ.JOBB
+F.TEST = F.PRÓB
+FISHER = FISHER
+FISHERINV = INVERZ.FISHER
+FORECAST.ETS = ELŐREJELZÉS.ESIM
+FORECAST.ETS.CONFINT = ELŐREJELZÉS.ESIM.KONFINT
+FORECAST.ETS.SEASONALITY = ELŐREJELZÉS.ESIM.SZEZONALITÁS
+FORECAST.ETS.STAT = ELŐREJELZÉS.ESIM.STAT
+FORECAST.LINEAR = ELŐREJELZÉS.LINEÁRIS
+FREQUENCY = GYAKORISÁG
+GAMMA = GAMMA
+GAMMA.DIST = GAMMA.ELOSZL
+GAMMA.INV = GAMMA.INVERZ
+GAMMALN = GAMMALN
+GAMMALN.PRECISE = GAMMALN.PONTOS
+GAUSS = GAUSS
+GEOMEAN = MÉRTANI.KÖZÉP
+GROWTH = NÖV
+HARMEAN = HARM.KÖZÉP
+HYPGEOM.DIST = HIPGEOM.ELOSZLÁS
+INTERCEPT = METSZ
+KURT = CSÚCSOSSÁG
+LARGE = NAGY
+LINEST = LIN.ILL
+LOGEST = LOG.ILL
+LOGNORM.DIST = LOGNORM.ELOSZLÁS
+LOGNORM.INV = LOGNORM.INVERZ
+MAX = MAX
+MAXA = MAXA
+MAXIFS = MAXHA
+MEDIAN = MEDIÁN
+MIN = MIN
+MINA = MIN2
+MINIFS = MINHA
+MODE.MULT = MÓDUSZ.TÖBB
+MODE.SNGL = MÓDUSZ.EGY
+NEGBINOM.DIST = NEGBINOM.ELOSZLÁS
+NORM.DIST = NORM.ELOSZLÁS
+NORM.INV = NORM.INVERZ
+NORM.S.DIST = NORM.S.ELOSZLÁS
+NORM.S.INV = NORM.S.INVERZ
+PEARSON = PEARSON
+PERCENTILE.EXC = PERCENTILIS.KIZÁR
+PERCENTILE.INC = PERCENTILIS.TARTALMAZ
+PERCENTRANK.EXC = SZÁZALÉKRANG.KIZÁR
+PERCENTRANK.INC = SZÁZALÉKRANG.TARTALMAZ
+PERMUT = VARIÁCIÓK
+PERMUTATIONA = VARIÁCIÓK.ISM
+PHI = FI
+POISSON.DIST = POISSON.ELOSZLÁS
+PROB = VALÓSZÍNŰSÉG
+QUARTILE.EXC = KVARTILIS.KIZÁR
+QUARTILE.INC = KVARTILIS.TARTALMAZ
+RANK.AVG = RANG.ÁTL
+RANK.EQ = RANG.EGY
+RSQ = RNÉGYZET
+SKEW = FERDESÉG
+SKEW.P = FERDESÉG.P
+SLOPE = MEREDEKSÉG
+SMALL = KICSI
+STANDARDIZE = NORMALIZÁLÁS
+STDEV.P = SZÓR.S
+STDEV.S = SZÓR.M
+STDEVA = SZÓRÁSA
+STDEVPA = SZÓRÁSPA
+STEYX = STHIBAYX
+T.DIST = T.ELOSZL
+T.DIST.2T = T.ELOSZLÁS.2SZ
+T.DIST.RT = T.ELOSZLÁS.JOBB
+T.INV = T.INVERZ
+T.INV.2T = T.INVERZ.2SZ
+T.TEST = T.PRÓB
+TREND = TREND
+TRIMMEAN = RÉSZÁTLAG
+VAR.P = VAR.S
+VAR.S = VAR.M
+VARA = VARA
+VARPA = VARPA
+WEIBULL.DIST = WEIBULL.ELOSZLÁS
+Z.TEST = Z.PRÓB
##
-## Statistical functions Statisztikai függvények
+## Szövegműveletekhez használható függvények (Text Functions)
##
-AVEDEV = ÁTL.ELTÉRÉS ## Az adatpontoknak átlaguktól való átlagos abszolút eltérését számítja ki.
-AVERAGE = ÁTLAG ## Argumentumai átlagát számítja ki.
-AVERAGEA = ÁTLAGA ## Argumentumai átlagát számítja ki (beleértve a számokat, szöveget és logikai értékeket).
-AVERAGEIF = ÁTLAGHA ## A megadott feltételnek eleget tévő tartomány celláinak átlagát (számtani közepét) adja eredményül.
-AVERAGEIFS = ÁTLAGHATÖBB ## A megadott feltételeknek eleget tévő cellák átlagát (számtani közepét) adja eredményül.
-BETADIST = BÉTA.ELOSZLÁS ## A béta-eloszlás függvényt számítja ki.
-BETAINV = INVERZ.BÉTA ## Adott béta-eloszláshoz kiszámítja a béta eloszlásfüggvény inverzét.
-BINOMDIST = BINOM.ELOSZLÁS ## A diszkrét binomiális eloszlás valószínűségértékét számítja ki.
-CHIDIST = KHI.ELOSZLÁS ## A khi-négyzet-eloszlás egyszélű valószínűségértékét számítja ki.
-CHIINV = INVERZ.KHI ## A khi-négyzet-eloszlás egyszélű valószínűségértékének inverzét számítja ki.
-CHITEST = KHI.PRÓBA ## Függetlenségvizsgálatot hajt végre.
-CONFIDENCE = MEGBÍZHATÓSÁG ## Egy statisztikai sokaság várható értékének megbízhatósági intervallumát adja eredményül.
-CORREL = KORREL ## Két adathalmaz korrelációs együtthatóját számítja ki.
-COUNT = DARAB ## Megszámolja, hogy argumentumlistájában hány szám található.
-COUNTA = DARAB2 ## Megszámolja, hogy argumentumlistájában hány érték található.
-COUNTBLANK = DARABÜRES ## Egy tartományban összeszámolja az üres cellákat.
-COUNTIF = DARABTELI ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek a megadott feltételnek.
-COUNTIFS = DARABHATÖBB ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek több feltételnek.
-COVAR = KOVAR ## A kovarianciát, azaz a páronkénti eltérések szorzatának átlagát számítja ki.
-CRITBINOM = KRITBINOM ## Azt a legkisebb számot adja eredményül, amelyre a binomiális eloszlásfüggvény értéke nem kisebb egy adott határértéknél.
-DEVSQ = SQ ## Az átlagtól való eltérések négyzetének összegét számítja ki.
-EXPONDIST = EXP.ELOSZLÁS ## Az exponenciális eloszlás értékét számítja ki.
-FDIST = F.ELOSZLÁS ## Az F-eloszlás értékét számítja ki.
-FINV = INVERZ.F ## Az F-eloszlás inverzének értékét számítja ki.
-FISHER = FISHER ## Fisher-transzformációt hajt végre.
-FISHERINV = INVERZ.FISHER ## A Fisher-transzformáció inverzét hajtja végre.
-FORECAST = ELŐREJELZÉS ## Az ismert értékek alapján lineáris regresszióval becsült értéket ad eredményül.
-FREQUENCY = GYAKORISÁG ## A gyakorisági vagy empirikus eloszlás értékét függőleges tömbként adja eredményül.
-FTEST = F.PRÓBA ## Az F-próba értékét adja eredményül.
-GAMMADIST = GAMMA.ELOSZLÁS ## A gamma-eloszlás értékét számítja ki.
-GAMMAINV = INVERZ.GAMMA ## A gamma-eloszlás eloszlásfüggvénye inverzének értékét számítja ki.
-GAMMALN = GAMMALN ## A gamma-függvény természetes logaritmusát számítja ki.
-GEOMEAN = MÉRTANI.KÖZÉP ## Argumentumai mértani középértékét számítja ki.
-GROWTH = NÖV ## Exponenciális regresszió alapján ad becslést.
-HARMEAN = HARM.KÖZÉP ## Argumentumai harmonikus átlagát számítja ki.
-HYPGEOMDIST = HIPERGEOM.ELOSZLÁS ## A hipergeometriai eloszlás értékét számítja ki.
-INTERCEPT = METSZ ## A regressziós egyenes y tengellyel való metszéspontját határozza meg.
-KURT = CSÚCSOSSÁG ## Egy adathalmaz csúcsosságát számítja ki.
-LARGE = NAGY ## Egy adathalmaz k-adik legnagyobb elemét adja eredményül.
-LINEST = LIN.ILL ## A legkisebb négyzetek módszerével az adatokra illesztett egyenes paramétereit határozza meg.
-LOGEST = LOG.ILL ## Az adatokra illesztett exponenciális görbe paramétereit határozza meg.
-LOGINV = INVERZ.LOG.ELOSZLÁS ## A lognormális eloszlás inverzét számítja ki.
-LOGNORMDIST = LOG.ELOSZLÁS ## A lognormális eloszlásfüggvény értékét számítja ki.
-MAX = MAX ## Az argumentumai között szereplő legnagyobb számot adja meg.
-MAXA = MAX2 ## Az argumentumai között szereplő legnagyobb számot adja meg (beleértve a számokat, szöveget és logikai értékeket).
-MEDIAN = MEDIÁN ## Adott számhalmaz mediánját számítja ki.
-MIN = MIN ## Az argumentumai között szereplő legkisebb számot adja meg.
-MINA = MIN2 ## Az argumentumai között szereplő legkisebb számot adja meg, beleértve a számokat, szöveget és logikai értékeket.
-MODE = MÓDUSZ ## Egy adathalmazból kiválasztja a leggyakrabban előforduló számot.
-NEGBINOMDIST = NEGBINOM.ELOSZL ## A negatív binomiális eloszlás értékét számítja ki.
-NORMDIST = NORM.ELOSZL ## A normális eloszlás értékét számítja ki.
-NORMINV = INVERZ.NORM ## A normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki.
-NORMSDIST = STNORMELOSZL ## A standard normális eloszlás eloszlásfüggvényének értékét számítja ki.
-NORMSINV = INVERZ.STNORM ## A standard normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki.
-PEARSON = PEARSON ## A Pearson-féle korrelációs együtthatót számítja ki.
-PERCENTILE = PERCENTILIS ## Egy tartományban található értékek k-adik percentilisét, azaz százalékosztályát adja eredményül.
-PERCENTRANK = SZÁZALÉKRANG ## Egy értéknek egy adathalmazon belül vett százalékos rangját (elhelyezkedését) számítja ki.
-PERMUT = VARIÁCIÓK ## Adott számú objektum k-ad osztályú ismétlés nélküli variációinak számát számítja ki.
-POISSON = POISSON ## A Poisson-eloszlás értékét számítja ki.
-PROB = VALÓSZÍNŰSÉG ## Annak valószínűségét számítja ki, hogy adott értékek két határérték közé esnek.
-QUARTILE = KVARTILIS ## Egy adathalmaz kvartilisét (negyedszintjét) számítja ki.
-RANK = SORSZÁM ## Kiszámítja, hogy egy szám hányadik egy számsorozatban.
-RSQ = RNÉGYZET ## Kiszámítja a Pearson-féle szorzatmomentum korrelációs együtthatójának négyzetét.
-SKEW = FERDESÉG ## Egy eloszlás ferdeségét határozza meg.
-SLOPE = MEREDEKSÉG ## Egy lineáris regressziós egyenes meredekségét számítja ki.
-SMALL = KICSI ## Egy adathalmaz k-adik legkisebb elemét adja meg.
-STANDARDIZE = NORMALIZÁLÁS ## Normalizált értéket ad eredményül.
-STDEV = SZÓRÁS ## Egy statisztikai sokaság mintájából kiszámítja annak szórását.
-STDEVA = SZÓRÁSA ## Egy statisztikai sokaság mintájából kiszámítja annak szórását (beleértve a számokat, szöveget és logikai értékeket).
-STDEVP = SZÓRÁSP ## Egy statisztikai sokaság egészéből kiszámítja annak szórását.
-STDEVPA = SZÓRÁSPA ## Egy statisztikai sokaság egészéből kiszámítja annak szórását (beleértve számokat, szöveget és logikai értékeket).
-STEYX = STHIBAYX ## Egy regresszió esetén az egyes x-értékek alapján meghatározott y-értékek standard hibáját számítja ki.
-TDIST = T.ELOSZLÁS ## A Student-féle t-eloszlás értékét számítja ki.
-TINV = INVERZ.T ## A Student-féle t-eloszlás inverzét számítja ki.
-TREND = TREND ## Lineáris trend értékeit számítja ki.
-TRIMMEAN = RÉSZÁTLAG ## Egy adathalmaz középső részének átlagát számítja ki.
-TTEST = T.PRÓBA ## A Student-féle t-próbához tartozó valószínűséget számítja ki.
-VAR = VAR ## Minta alapján becslést ad a varianciára.
-VARA = VARA ## Minta alapján becslést ad a varianciára (beleértve számokat, szöveget és logikai értékeket).
-VARP = VARP ## Egy statisztikai sokaság varianciáját számítja ki.
-VARPA = VARPA ## Egy statisztikai sokaság varianciáját számítja ki (beleértve számokat, szöveget és logikai értékeket).
-WEIBULL = WEIBULL ## A Weibull-féle eloszlás értékét számítja ki.
-ZTEST = Z.PRÓBA ## Az egyszélű z-próbával kapott valószínűségértéket számítja ki.
-
+BAHTTEXT = BAHTSZÖVEG
+CHAR = KARAKTER
+CLEAN = TISZTÍT
+CODE = KÓD
+CONCAT = FŰZ
+DOLLAR = FORINT
+EXACT = AZONOS
+FIND = SZÖVEG.TALÁL
+FIXED = FIX
+ISTHAIDIGIT = ON.THAI.NUMERO
+LEFT = BAL
+LEN = HOSSZ
+LOWER = KISBETŰ
+MID = KÖZÉP
+NUMBERSTRING = SZÁM.BETŰVEL
+NUMBERVALUE = SZÁMÉRTÉK
+PHONETIC = FONETIKUS
+PROPER = TNÉV
+REPLACE = CSERE
+REPT = SOKSZOR
+RIGHT = JOBB
+SEARCH = SZÖVEG.KERES
+SUBSTITUTE = HELYETTE
+T = T
+TEXT = SZÖVEG
+TEXTJOIN = SZÖVEGÖSSZEFŰZÉS
+THAIDIGIT = THAISZÁM
+THAINUMSOUND = THAISZÁMHANG
+THAINUMSTRING = THAISZÁMKAR
+THAISTRINGLENGTH = THAIKARHOSSZ
+TRIM = KIMETSZ
+UNICHAR = UNIKARAKTER
+UNICODE = UNICODE
+UPPER = NAGYBETŰS
+VALUE = ÉRTÉK
##
-## Text functions Szövegműveletekhez használható függvények
+## Webes függvények (Web Functions)
##
-ASC = ASC ## Szöveg teljes szélességű (kétbájtos) latin és katakana karaktereit félszélességű (egybájtos) karakterekké alakítja.
-BAHTTEXT = BAHTSZÖVEG ## Számot szöveggé alakít a ß (baht) pénznemformátum használatával.
-CHAR = KARAKTER ## A kódszámmal meghatározott karaktert adja eredményül.
-CLEAN = TISZTÍT ## A szövegből eltávolítja az összes nem nyomtatható karaktert.
-CODE = KÓD ## Karaktersorozat első karakterének numerikus kódját adja eredményül.
-CONCATENATE = ÖSSZEFŰZ ## Több szövegelemet egyetlen szöveges elemmé fűz össze.
-DOLLAR = FORINT ## Számot pénznem formátumú szöveggé alakít át.
-EXACT = AZONOS ## Megvizsgálja, hogy két érték azonos-e.
-FIND = SZÖVEG.TALÁL ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével).
-FINDB = SZÖVEG.TALÁL2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével).
-FIXED = FIX ## Számot szöveges formátumúra alakít adott számú tizedesjegyre kerekítve.
-JIS = JIS ## A félszélességű (egybájtos) latin és a katakana karaktereket teljes szélességű (kétbájtos) karakterekké alakítja.
-LEFT = BAL ## Szöveg bal szélső karaktereit adja eredményül.
-LEFTB = BAL2 ## Szöveg bal szélső karaktereit adja eredményül.
-LEN = HOSSZ ## Szöveg karakterekben mért hosszát adja eredményül.
-LENB = HOSSZ2 ## Szöveg karakterekben mért hosszát adja eredményül.
-LOWER = KISBETŰ ## Szöveget kisbetűssé alakít át.
-MID = KÖZÉP ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként.
-MIDB = KÖZÉP2 ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként.
-PHONETIC = PHONETIC ## Szöveg furigana (fonetikus) karaktereit adja vissza.
-PROPER = TNÉV ## Szöveg minden szavának kezdőbetűjét nagybetűsre cseréli.
-REPLACE = CSERE ## A szövegen belül karaktereket cserél.
-REPLACEB = CSERE2 ## A szövegen belül karaktereket cserél.
-REPT = SOKSZOR ## Megadott számú alkalommal megismétel egy szövegrészt.
-RIGHT = JOBB ## Szövegrész jobb szélső karaktereit adja eredményül.
-RIGHTB = JOBB2 ## Szövegrész jobb szélső karaktereit adja eredményül.
-SEARCH = SZÖVEG.KERES ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget).
-SEARCHB = SZÖVEG.KERES2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget).
-SUBSTITUTE = HELYETTE ## Szövegben adott karaktereket másikra cserél.
-T = T ## Argumentumát szöveggé alakítja át.
-TEXT = SZÖVEG ## Számértéket alakít át adott számformátumú szöveggé.
-TRIM = TRIM ## A szövegből eltávolítja a szóközöket.
-UPPER = NAGYBETŰS ## Szöveget nagybetűssé alakít át.
-VALUE = ÉRTÉK ## Szöveget számmá alakít át.
+ENCODEURL = URL.KÓDOL
+FILTERXML = XMLSZŰRÉS
+WEBSERVICE = WEBSZOLGÁLTATÁS
+
+##
+## Kompatibilitási függvények (Compatibility Functions)
+##
+BETADIST = BÉTA.ELOSZLÁS
+BETAINV = INVERZ.BÉTA
+BINOMDIST = BINOM.ELOSZLÁS
+CEILING = PLAFON
+CHIDIST = KHI.ELOSZLÁS
+CHIINV = INVERZ.KHI
+CHITEST = KHI.PRÓBA
+CONCATENATE = ÖSSZEFŰZ
+CONFIDENCE = MEGBÍZHATÓSÁG
+COVAR = KOVAR
+CRITBINOM = KRITBINOM
+EXPONDIST = EXP.ELOSZLÁS
+FDIST = F.ELOSZLÁS
+FINV = INVERZ.F
+FLOOR = PADLÓ
+FORECAST = ELŐREJELZÉS
+FTEST = F.PRÓBA
+GAMMADIST = GAMMA.ELOSZLÁS
+GAMMAINV = INVERZ.GAMMA
+HYPGEOMDIST = HIPERGEOM.ELOSZLÁS
+LOGINV = INVERZ.LOG.ELOSZLÁS
+LOGNORMDIST = LOG.ELOSZLÁS
+MODE = MÓDUSZ
+NEGBINOMDIST = NEGBINOM.ELOSZL
+NORMDIST = NORM.ELOSZL
+NORMINV = INVERZ.NORM
+NORMSDIST = STNORMELOSZL
+NORMSINV = INVERZ.STNORM
+PERCENTILE = PERCENTILIS
+PERCENTRANK = SZÁZALÉKRANG
+POISSON = POISSON
+QUARTILE = KVARTILIS
+RANK = SORSZÁM
+STDEV = SZÓRÁS
+STDEVP = SZÓRÁSP
+TDIST = T.ELOSZLÁS
+TINV = INVERZ.T
+TTEST = T.PRÓBA
+VAR = VAR
+VARP = VARP
+WEIBULL = WEIBULL
+ZTEST = Z.PRÓBA
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/config
index 6cc013aec23..5c1e49556a0 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Italiano (Italian)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = €
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #NULLO!
-DIV0 = #DIV/0!
-VALUE = #VALORE!
-REF = #RIF!
-NAME = #NOME?
-NUM = #NUM!
-NA = #N/D
+NULL
+DIV0
+VALUE = #VALORE!
+REF = #RIF!
+NAME = #NOME?
+NUM
+NA = #N/D
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/functions
index 1901bafa7a1..c14ed85f07b 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/functions
@@ -1,416 +1,537 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
+## PhpSpreadsheet - function name translations
##
+## Italiano (Italian)
##
+############################################################
##
-## Add-in and Automation functions Funzioni di automazione e dei componenti aggiuntivi
+## Funzioni cubo (Cube Functions)
##
-GETPIVOTDATA = INFO.DATI.TAB.PIVOT ## Restituisce i dati memorizzati in un rapporto di tabella pivot
-
+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
##
-## Cube functions Funzioni cubo
+## Funzioni di database (Database Functions)
##
-CUBEKPIMEMBER = MEMBRO.KPI.CUBO ## Restituisce il nome, la proprietà e la misura di un indicatore di prestazioni chiave (KPI) e visualizza il nome e la proprietà nella cella. Un KPI è una misura quantificabile, ad esempio l'utile lordo mensile o il fatturato trimestrale dei dipendenti, utilizzata per il monitoraggio delle prestazioni di un'organizzazione.
-CUBEMEMBER = MEMBRO.CUBO ## Restituisce un membro o una tupla in una gerarchia di cubi. Consente di verificare l'esistenza del membro o della tupla nel cubo.
-CUBEMEMBERPROPERTY = PROPRIETÀ.MEMBRO.CUBO ## Restituisce il valore di una proprietà di un membro del cubo. Consente di verificare l'esistenza di un nome di membro all'interno del cubo e di restituire la proprietà specificata per tale membro.
-CUBERANKEDMEMBER = MEMBRO.CUBO.CON.RANGO ## Restituisce l'n-esimo membro o il membro ordinato di un insieme. Consente di restituire uno o più elementi in un insieme, ad esempio l'agente di vendita migliore o i primi 10 studenti.
-CUBESET = SET.CUBO ## Definisce un insieme di tuple o membri calcolati mediante l'invio di un'espressione di insieme al cubo sul server. In questo modo l'insieme viene creato e restituito a Microsoft Office Excel.
-CUBESETCOUNT = CONTA.SET.CUBO ## Restituisce il numero di elementi di un insieme.
-CUBEVALUE = VALORE.CUBO ## Restituisce un valore aggregato da un cubo.
-
+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
##
-## Database functions Funzioni di database
+## Funzioni data e ora (Date & Time Functions)
##
-DAVERAGE = DB.MEDIA ## Restituisce la media di voci del database selezionate
-DCOUNT = DB.CONTA.NUMERI ## Conta le celle di un database contenenti numeri
-DCOUNTA = DB.CONTA.VALORI ## Conta le celle non vuote in un database
-DGET = DB.VALORI ## Estrae da un database un singolo record che soddisfa i criteri specificati
-DMAX = DB.MAX ## Restituisce il valore massimo dalle voci selezionate in un database
-DMIN = DB.MIN ## Restituisce il valore minimo dalle voci di un database selezionate
-DPRODUCT = DB.PRODOTTO ## Moltiplica i valori in un determinato campo di record che soddisfano i criteri del database
-DSTDEV = DB.DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione di voci di un database selezionate
-DSTDEVP = DB.DEV.ST.POP ## Calcola la deviazione standard sulla base di tutte le voci di un database selezionate
-DSUM = DB.SOMMA ## Aggiunge i numeri nel campo colonna di record del database che soddisfa determinati criteri
-DVAR = DB.VAR ## Restituisce una stima della varianza sulla base di un campione da voci di un database selezionate
-DVARP = DB.VAR.POP ## Calcola la varianza sulla base di tutte le voci di un database selezionate
-
+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
##
-## Date and time functions Funzioni data e ora
+## Funzioni ingegneristiche (Engineering Functions)
##
-DATE = DATA ## Restituisce il numero seriale di una determinata data
-DATEVALUE = DATA.VALORE ## Converte una data sotto forma di testo in un numero seriale
-DAY = GIORNO ## Converte un numero seriale in un giorno del mese
-DAYS360 = GIORNO360 ## Calcola il numero di giorni compreso tra due date basandosi su un anno di 360 giorni
-EDATE = DATA.MESE ## Restituisce il numero seriale della data che rappresenta il numero di mesi prima o dopo la data di inizio
-EOMONTH = FINE.MESE ## Restituisce il numero seriale dell'ultimo giorno del mese, prima o dopo un determinato numero di mesi
-HOUR = ORA ## Converte un numero seriale in un'ora
-MINUTE = MINUTO ## Converte un numero seriale in un minuto
-MONTH = MESE ## Converte un numero seriale in un mese
-NETWORKDAYS = GIORNI.LAVORATIVI.TOT ## Restituisce il numero di tutti i giorni lavorativi compresi fra due date
-NOW = ADESSO ## Restituisce il numero seriale della data e dell'ora corrente
-SECOND = SECONDO ## Converte un numero seriale in un secondo
-TIME = ORARIO ## Restituisce il numero seriale di una determinata ora
-TIMEVALUE = ORARIO.VALORE ## Converte un orario in forma di testo in un numero seriale
-TODAY = OGGI ## Restituisce il numero seriale relativo alla data odierna
-WEEKDAY = GIORNO.SETTIMANA ## Converte un numero seriale in un giorno della settimana
-WEEKNUM = NUM.SETTIMANA ## Converte un numero seriale in un numero che rappresenta la posizione numerica di una settimana nell'anno
-WORKDAY = GIORNO.LAVORATIVO ## Restituisce il numero della data prima o dopo un determinato numero di giorni lavorativi
-YEAR = ANNO ## Converte un numero seriale in un anno
-YEARFRAC = FRAZIONE.ANNO ## Restituisce la frazione dell'anno che rappresenta il numero dei giorni compresi tra una data_ iniziale e una data_finale
-
+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
##
-## Engineering functions Funzioni ingegneristiche
+## Funzioni finanziarie (Financial Functions)
##
-BESSELI = BESSEL.I ## Restituisce la funzione di Bessel modificata In(x)
-BESSELJ = BESSEL.J ## Restituisce la funzione di Bessel Jn(x)
-BESSELK = BESSEL.K ## Restituisce la funzione di Bessel modificata Kn(x)
-BESSELY = BESSEL.Y ## Restituisce la funzione di Bessel Yn(x)
-BIN2DEC = BINARIO.DECIMALE ## Converte un numero binario in decimale
-BIN2HEX = BINARIO.HEX ## Converte un numero binario in esadecimale
-BIN2OCT = BINARIO.OCT ## Converte un numero binario in ottale
-COMPLEX = COMPLESSO ## Converte i coefficienti reali e immaginari in numeri complessi
-CONVERT = CONVERTI ## Converte un numero da un sistema di misura in un altro
-DEC2BIN = DECIMALE.BINARIO ## Converte un numero decimale in binario
-DEC2HEX = DECIMALE.HEX ## Converte un numero decimale in esadecimale
-DEC2OCT = DECIMALE.OCT ## Converte un numero decimale in ottale
-DELTA = DELTA ## Verifica se due valori sono uguali
-ERF = FUNZ.ERRORE ## Restituisce la funzione di errore
-ERFC = FUNZ.ERRORE.COMP ## Restituisce la funzione di errore complementare
-GESTEP = SOGLIA ## Verifica se un numero è maggiore del valore di soglia
-HEX2BIN = HEX.BINARIO ## Converte un numero esadecimale in binario
-HEX2DEC = HEX.DECIMALE ## Converte un numero esadecimale in decimale
-HEX2OCT = HEX.OCT ## Converte un numero esadecimale in ottale
-IMABS = COMP.MODULO ## Restituisce il valore assoluto (modulo) di un numero complesso
-IMAGINARY = COMP.IMMAGINARIO ## Restituisce il coefficiente immaginario di un numero complesso
-IMARGUMENT = COMP.ARGOMENTO ## Restituisce l'argomento theta, un angolo espresso in radianti
-IMCONJUGATE = COMP.CONIUGATO ## Restituisce il complesso coniugato del numero complesso
-IMCOS = COMP.COS ## Restituisce il coseno di un numero complesso
-IMDIV = COMP.DIV ## Restituisce il quoziente di due numeri complessi
-IMEXP = COMP.EXP ## Restituisce il valore esponenziale di un numero complesso
-IMLN = COMP.LN ## Restituisce il logaritmo naturale di un numero complesso
-IMLOG10 = COMP.LOG10 ## Restituisce il logaritmo in base 10 di un numero complesso
-IMLOG2 = COMP.LOG2 ## Restituisce un logaritmo in base 2 di un numero complesso
-IMPOWER = COMP.POTENZA ## Restituisce il numero complesso elevato a una potenza intera
-IMPRODUCT = COMP.PRODOTTO ## Restituisce il prodotto di numeri complessi compresi tra 2 e 29
-IMREAL = COMP.PARTE.REALE ## Restituisce il coefficiente reale di un numero complesso
-IMSIN = COMP.SEN ## Restituisce il seno di un numero complesso
-IMSQRT = COMP.RADQ ## Restituisce la radice quadrata di un numero complesso
-IMSUB = COMP.DIFF ## Restituisce la differenza fra due numeri complessi
-IMSUM = COMP.SOMMA ## Restituisce la somma di numeri complessi
-OCT2BIN = OCT.BINARIO ## Converte un numero ottale in binario
-OCT2DEC = OCT.DECIMALE ## Converte un numero ottale in decimale
-OCT2HEX = OCT.HEX ## Converte un numero ottale in esadecimale
-
+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
##
-## Financial functions Funzioni finanziarie
+## Funzioni relative alle informazioni (Information Functions)
##
-ACCRINT = INT.MATURATO.PER ## Restituisce l'interesse maturato di un titolo che paga interessi periodici
-ACCRINTM = INT.MATURATO.SCAD ## Restituisce l'interesse maturato di un titolo che paga interessi alla scadenza
-AMORDEGRC = AMMORT.DEGR ## Restituisce l'ammortamento per ogni periodo contabile utilizzando un coefficiente di ammortamento
-AMORLINC = AMMORT.PER ## Restituisce l'ammortamento per ogni periodo contabile
-COUPDAYBS = GIORNI.CED.INIZ.LIQ ## Restituisce il numero dei giorni che vanno dall'inizio del periodo di durata della cedola alla data di liquidazione
-COUPDAYS = GIORNI.CED ## Restituisce il numero dei giorni relativi al periodo della cedola che contiene la data di liquidazione
-COUPDAYSNC = GIORNI.CED.NUOVA ## Restituisce il numero di giorni che vanno dalla data di liquidazione alla data della cedola successiva
-COUPNCD = DATA.CED.SUCC ## Restituisce un numero che rappresenta la data della cedola successiva alla data di liquidazione
-COUPNUM = NUM.CED ## Restituisce il numero di cedole pagabili fra la data di liquidazione e la data di scadenza
-COUPPCD = DATA.CED.PREC ## Restituisce un numero che rappresenta la data della cedola precedente alla data di liquidazione
-CUMIPMT = INT.CUMUL ## Restituisce l'interesse cumulativo pagato fra due periodi
-CUMPRINC = CAP.CUM ## Restituisce il capitale cumulativo pagato per estinguere un debito fra due periodi
-DB = DB ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a quote fisse decrescenti
-DDB = AMMORT ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a doppie quote decrescenti o altri metodi specificati
-DISC = TASSO.SCONTO ## Restituisce il tasso di sconto per un titolo
-DOLLARDE = VALUTA.DEC ## Converte un prezzo valuta, espresso come frazione, in prezzo valuta, espresso come numero decimale
-DOLLARFR = VALUTA.FRAZ ## Converte un prezzo valuta, espresso come numero decimale, in prezzo valuta, espresso come frazione
-DURATION = DURATA ## Restituisce la durata annuale di un titolo con i pagamenti di interesse periodico
-EFFECT = EFFETTIVO ## Restituisce l'effettivo tasso di interesse annuo
-FV = VAL.FUT ## Restituisce il valore futuro di un investimento
-FVSCHEDULE = VAL.FUT.CAPITALE ## Restituisce il valore futuro di un capitale iniziale dopo aver applicato una serie di tassi di interesse composti
-INTRATE = TASSO.INT ## Restituisce il tasso di interesse per un titolo interamente investito
-IPMT = INTERESSI ## Restituisce il valore degli interessi per un investimento relativo a un periodo specifico
-IRR = TIR.COST ## Restituisce il tasso di rendimento interno per una serie di flussi di cassa
-ISPMT = INTERESSE.RATA ## Calcola l'interesse di un investimento pagato durante un periodo specifico
-MDURATION = DURATA.M ## Restituisce la durata Macauley modificata per un titolo con un valore presunto di € 100
-MIRR = TIR.VAR ## Restituisce il tasso di rendimento interno in cui i flussi di cassa positivi e negativi sono finanziati a tassi differenti
-NOMINAL = NOMINALE ## Restituisce il tasso di interesse nominale annuale
-NPER = NUM.RATE ## Restituisce un numero di periodi relativi a un investimento
-NPV = VAN ## Restituisce il valore attuale netto di un investimento basato su una serie di flussi di cassa periodici e sul tasso di sconto
-ODDFPRICE = PREZZO.PRIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente il primo periodo di durata irregolare
-ODDFYIELD = REND.PRIMO.IRR ## Restituisce il rendimento di un titolo avente il primo periodo di durata irregolare
-ODDLPRICE = PREZZO.ULTIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente l'ultimo periodo di durata irregolare
-ODDLYIELD = REND.ULTIMO.IRR ## Restituisce il rendimento di un titolo avente l'ultimo periodo di durata irregolare
-PMT = RATA ## Restituisce il pagamento periodico di una rendita annua
-PPMT = P.RATA ## Restituisce il pagamento sul capitale di un investimento per un dato periodo
-PRICE = PREZZO ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga interessi periodici
-PRICEDISC = PREZZO.SCONT ## Restituisce il prezzo di un titolo scontato dal valore nominale di € 100
-PRICEMAT = PREZZO.SCAD ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga gli interessi alla scadenza
-PV = VA ## Restituisce il valore attuale di un investimento
-RATE = TASSO ## Restituisce il tasso di interesse per un periodo di un'annualità
-RECEIVED = RICEV.SCAD ## Restituisce l'ammontare ricevuto alla scadenza di un titolo interamente investito
-SLN = AMMORT.COST ## Restituisce l'ammortamento a quote costanti di un bene per un singolo periodo
-SYD = AMMORT.ANNUO ## Restituisce l'ammortamento a somma degli anni di un bene per un periodo specificato
-TBILLEQ = BOT.EQUIV ## Restituisce il rendimento equivalente ad un'obbligazione per un Buono ordinario del Tesoro
-TBILLPRICE = BOT.PREZZO ## Restituisce il prezzo di un Buono del Tesoro dal valore nominale di € 100
-TBILLYIELD = BOT.REND ## Restituisce il rendimento di un Buono del Tesoro
-VDB = AMMORT.VAR ## Restituisce l'ammortamento di un bene per un periodo specificato o parziale utilizzando il metodo a doppie quote proporzionali ai valori residui
-XIRR = TIR.X ## Restituisce il tasso di rendimento interno di un impiego di flussi di cassa
-XNPV = VAN.X ## Restituisce il valore attuale netto di un impiego di flussi di cassa non necessariamente periodici
-YIELD = REND ## Restituisce il rendimento di un titolo che frutta interessi periodici
-YIELDDISC = REND.TITOLI.SCONT ## Restituisce il rendimento annuale di un titolo scontato, ad esempio un Buono del Tesoro
-YIELDMAT = REND.SCAD ## Restituisce il rendimento annuo di un titolo che paga interessi alla scadenza
-
+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
##
-## Information functions Funzioni relative alle informazioni
+## Funzioni logiche (Logical Functions)
##
-CELL = CELLA ## Restituisce le informazioni sulla formattazione, la posizione o i contenuti di una cella
-ERROR.TYPE = ERRORE.TIPO ## Restituisce un numero che corrisponde a un tipo di errore
-INFO = INFO ## Restituisce le informazioni sull'ambiente operativo corrente
-ISBLANK = VAL.VUOTO ## Restituisce VERO se il valore è vuoto
-ISERR = VAL.ERR ## Restituisce VERO se il valore è un valore di errore qualsiasi tranne #N/D
-ISERROR = VAL.ERRORE ## Restituisce VERO se il valore è un valore di errore qualsiasi
-ISEVEN = VAL.PARI ## Restituisce VERO se il numero è pari
-ISLOGICAL = VAL.LOGICO ## Restituisce VERO se il valore è un valore logico
-ISNA = VAL.NON.DISP ## Restituisce VERO se il valore è un valore di errore #N/D
-ISNONTEXT = VAL.NON.TESTO ## Restituisce VERO se il valore non è in formato testo
-ISNUMBER = VAL.NUMERO ## Restituisce VERO se il valore è un numero
-ISODD = VAL.DISPARI ## Restituisce VERO se il numero è dispari
-ISREF = VAL.RIF ## Restituisce VERO se il valore è un riferimento
-ISTEXT = VAL.TESTO ## Restituisce VERO se il valore è in formato testo
-N = NUM ## Restituisce un valore convertito in numero
-NA = NON.DISP ## Restituisce il valore di errore #N/D
-TYPE = TIPO ## Restituisce un numero che indica il tipo di dati relativi a un valore
-
+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
##
-## Logical functions Funzioni logiche
+## Funzioni di ricerca e di riferimento (Lookup & Reference Functions)
##
-AND = E ## Restituisce VERO se tutti gli argomenti sono VERO
-FALSE = FALSO ## Restituisce il valore logico FALSO
-IF = SE ## Specifica un test logico da eseguire
-IFERROR = SE.ERRORE ## Restituisce un valore specificato se una formula fornisce un errore come risultato; in caso contrario, restituisce il risultato della formula
-NOT = NON ## Inverte la logica degli argomenti
-OR = O ## Restituisce VERO se un argomento qualsiasi è VERO
-TRUE = VERO ## Restituisce il valore logico VERO
-
+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
##
-## Lookup and reference functions Funzioni di ricerca e di riferimento
+## Funzioni matematiche e trigonometriche (Math & Trig Functions)
##
-ADDRESS = INDIRIZZO ## Restituisce un riferimento come testo in una singola cella di un foglio di lavoro
-AREAS = AREE ## Restituisce il numero di aree in un riferimento
-CHOOSE = SCEGLI ## Sceglie un valore da un elenco di valori
-COLUMN = RIF.COLONNA ## Restituisce il numero di colonna di un riferimento
-COLUMNS = COLONNE ## Restituisce il numero di colonne in un riferimento
-HLOOKUP = CERCA.ORIZZ ## Effettua una ricerca nella riga superiore di una matrice e restituisce il valore della cella specificata
-HYPERLINK = COLLEG.IPERTESTUALE ## Crea un collegamento che apre un documento memorizzato in un server di rete, una rete Intranet o Internet
-INDEX = INDICE ## Utilizza un indice per scegliere un valore da un riferimento o da una matrice
-INDIRECT = INDIRETTO ## Restituisce un riferimento specificato da un valore testo
-LOOKUP = CERCA ## Ricerca i valori in un vettore o in una matrice
-MATCH = CONFRONTA ## Ricerca i valori in un riferimento o in una matrice
-OFFSET = SCARTO ## Restituisce uno scarto di riferimento da un riferimento dato
-ROW = RIF.RIGA ## Restituisce il numero di riga di un riferimento
-ROWS = RIGHE ## Restituisce il numero delle righe in un riferimento
-RTD = DATITEMPOREALE ## Recupera dati in tempo reale da un programma che supporta l'automazione COM (automazione: Metodo per utilizzare gli oggetti di un'applicazione da un'altra applicazione o da un altro strumento di sviluppo. Precedentemente nota come automazione OLE, l'automazione è uno standard del settore e una caratteristica del modello COM (Component Object Model).)
-TRANSPOSE = MATR.TRASPOSTA ## Restituisce la trasposizione di una matrice
-VLOOKUP = CERCA.VERT ## Effettua una ricerca nella prima colonna di una matrice e si sposta attraverso la riga per restituire il valore di una cella
-
+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
##
-## Math and trigonometry functions Funzioni matematiche e trigonometriche
+## Funzioni statistiche (Statistical Functions)
##
-ABS = ASS ## Restituisce il valore assoluto di un numero.
-ACOS = ARCCOS ## Restituisce l'arcocoseno di un numero
-ACOSH = ARCCOSH ## Restituisce l'inverso del coseno iperbolico di un numero
-ASIN = ARCSEN ## Restituisce l'arcoseno di un numero
-ASINH = ARCSENH ## Restituisce l'inverso del seno iperbolico di un numero
-ATAN = ARCTAN ## Restituisce l'arcotangente di un numero
-ATAN2 = ARCTAN.2 ## Restituisce l'arcotangente delle coordinate x e y specificate
-ATANH = ARCTANH ## Restituisce l'inverso della tangente iperbolica di un numero
-CEILING = ARROTONDA.ECCESSO ## Arrotonda un numero per eccesso all'intero più vicino o al multiplo più vicino a peso
-COMBIN = COMBINAZIONE ## Restituisce il numero di combinazioni possibili per un numero assegnato di elementi
-COS = COS ## Restituisce il coseno dell'angolo specificato
-COSH = COSH ## Restituisce il coseno iperbolico di un numero
-DEGREES = GRADI ## Converte i radianti in gradi
-EVEN = PARI ## Arrotonda il valore assoluto di un numero per eccesso al più vicino intero pari
-EXP = ESP ## Restituisce il numero e elevato alla potenza di num
-FACT = FATTORIALE ## Restituisce il fattoriale di un numero
-FACTDOUBLE = FATT.DOPPIO ## Restituisce il fattoriale doppio di un numero
-FLOOR = ARROTONDA.DIFETTO ## Arrotonda un numero per difetto al multiplo più vicino a zero
-GCD = MCD ## Restituisce il massimo comune divisore
-INT = INT ## Arrotonda un numero per difetto al numero intero più vicino
-LCM = MCM ## Restituisce il minimo comune multiplo
-LN = LN ## Restituisce il logaritmo naturale di un numero
-LOG = LOG ## Restituisce il logaritmo di un numero in una specificata base
-LOG10 = LOG10 ## Restituisce il logaritmo in base 10 di un numero
-MDETERM = MATR.DETERM ## Restituisce il determinante di una matrice
-MINVERSE = MATR.INVERSA ## Restituisce l'inverso di una matrice
-MMULT = MATR.PRODOTTO ## Restituisce il prodotto di due matrici
-MOD = RESTO ## Restituisce il resto della divisione
-MROUND = ARROTONDA.MULTIPLO ## Restituisce un numero arrotondato al multiplo desiderato
-MULTINOMIAL = MULTINOMIALE ## Restituisce il multinomiale di un insieme di numeri
-ODD = DISPARI ## Arrotonda un numero per eccesso al più vicino intero dispari
-PI = PI.GRECO ## Restituisce il valore di pi greco
-POWER = POTENZA ## Restituisce il risultato di un numero elevato a potenza
-PRODUCT = PRODOTTO ## Moltiplica i suoi argomenti
-QUOTIENT = QUOZIENTE ## Restituisce la parte intera di una divisione
-RADIANS = RADIANTI ## Converte i gradi in radianti
-RAND = CASUALE ## Restituisce un numero casuale compreso tra 0 e 1
-RANDBETWEEN = CASUALE.TRA ## Restituisce un numero casuale compreso tra i numeri specificati
-ROMAN = ROMANO ## Restituisce il numero come numero romano sotto forma di testo
-ROUND = ARROTONDA ## Arrotonda il numero al numero di cifre specificato
-ROUNDDOWN = ARROTONDA.PER.DIF ## Arrotonda il valore assoluto di un numero per difetto
-ROUNDUP = ARROTONDA.PER.ECC ## Arrotonda il valore assoluto di un numero per eccesso
-SERIESSUM = SOMMA.SERIE ## Restituisce la somma di una serie di potenze in base alla formula
-SIGN = SEGNO ## Restituisce il segno di un numero
-SIN = SEN ## Restituisce il seno di un dato angolo
-SINH = SENH ## Restituisce il seno iperbolico di un numero
-SQRT = RADQ ## Restituisce una radice quadrata
-SQRTPI = RADQ.PI.GRECO ## Restituisce la radice quadrata di un numero (numero * pi greco)
-SUBTOTAL = SUBTOTALE ## Restituisce un subtotale in un elenco o in un database
-SUM = SOMMA ## Somma i suoi argomenti
-SUMIF = SOMMA.SE ## Somma le celle specificate da un dato criterio
-SUMIFS = SOMMA.PIÙ.SE ## Somma le celle in un intervallo che soddisfano più criteri
-SUMPRODUCT = MATR.SOMMA.PRODOTTO ## Restituisce la somma dei prodotti dei componenti corrispondenti della matrice
-SUMSQ = SOMMA.Q ## Restituisce la somma dei quadrati degli argomenti
-SUMX2MY2 = SOMMA.DIFF.Q ## Restituisce la somma della differenza dei quadrati dei corrispondenti elementi in due matrici
-SUMX2PY2 = SOMMA.SOMMA.Q ## Restituisce la somma della somma dei quadrati dei corrispondenti elementi in due matrici
-SUMXMY2 = SOMMA.Q.DIFF ## Restituisce la somma dei quadrati delle differenze dei corrispondenti elementi in due matrici
-TAN = TAN ## Restituisce la tangente di un numero
-TANH = TANH ## Restituisce la tangente iperbolica di un numero
-TRUNC = TRONCA ## Tronca la parte decimale di un numero
-
+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
##
-## Statistical functions Funzioni statistiche
+## Funzioni di testo (Text Functions)
##
-AVEDEV = MEDIA.DEV ## Restituisce la media delle deviazioni assolute delle coordinate rispetto alla loro media
-AVERAGE = MEDIA ## Restituisce la media degli argomenti
-AVERAGEA = MEDIA.VALORI ## Restituisce la media degli argomenti, inclusi i numeri, il testo e i valori logici
-AVERAGEIF = MEDIA.SE ## Restituisce la media aritmetica di tutte le celle in un intervallo che soddisfano un determinato criterio
-AVERAGEIFS = MEDIA.PIÙ.SE ## Restituisce la media aritmetica di tutte le celle che soddisfano più criteri
-BETADIST = DISTRIB.BETA ## Restituisce la funzione di distribuzione cumulativa beta
-BETAINV = INV.BETA ## Restituisce l'inverso della funzione di distribuzione cumulativa per una distribuzione beta specificata
-BINOMDIST = DISTRIB.BINOM ## Restituisce la distribuzione binomiale per il termine individuale
-CHIDIST = DISTRIB.CHI ## Restituisce la probabilità a una coda per la distribuzione del chi quadrato
-CHIINV = INV.CHI ## Restituisce l'inverso della probabilità ad una coda per la distribuzione del chi quadrato
-CHITEST = TEST.CHI ## Restituisce il test per l'indipendenza
-CONFIDENCE = CONFIDENZA ## Restituisce l'intervallo di confidenza per una popolazione
-CORREL = CORRELAZIONE ## Restituisce il coefficiente di correlazione tra due insiemi di dati
-COUNT = CONTA.NUMERI ## Conta la quantità di numeri nell'elenco di argomenti
-COUNTA = CONTA.VALORI ## Conta il numero di valori nell'elenco di argomenti
-COUNTBLANK = CONTA.VUOTE ## Conta il numero di celle vuote all'interno di un intervallo
-COUNTIF = CONTA.SE ## Conta il numero di celle all'interno di un intervallo che soddisfa i criteri specificati
-COUNTIFS = CONTA.PIÙ.SE ## Conta il numero di celle in un intervallo che soddisfano più criteri.
-COVAR = COVARIANZA ## Calcola la covarianza, la media dei prodotti delle deviazioni accoppiate
-CRITBINOM = CRIT.BINOM ## Restituisce il più piccolo valore per il quale la distribuzione cumulativa binomiale risulta maggiore o uguale ad un valore di criterio
-DEVSQ = DEV.Q ## Restituisce la somma dei quadrati delle deviazioni
-EXPONDIST = DISTRIB.EXP ## Restituisce la distribuzione esponenziale
-FDIST = DISTRIB.F ## Restituisce la distribuzione di probabilità F
-FINV = INV.F ## Restituisce l'inverso della distribuzione della probabilità F
-FISHER = FISHER ## Restituisce la trasformazione di Fisher
-FISHERINV = INV.FISHER ## Restituisce l'inverso della trasformazione di Fisher
-FORECAST = PREVISIONE ## Restituisce i valori lungo una tendenza lineare
-FREQUENCY = FREQUENZA ## Restituisce la distribuzione di frequenza come matrice verticale
-FTEST = TEST.F ## Restituisce il risultato di un test F
-GAMMADIST = DISTRIB.GAMMA ## Restituisce la distribuzione gamma
-GAMMAINV = INV.GAMMA ## Restituisce l'inverso della distribuzione cumulativa gamma
-GAMMALN = LN.GAMMA ## Restituisce il logaritmo naturale della funzione gamma, G(x)
-GEOMEAN = MEDIA.GEOMETRICA ## Restituisce la media geometrica
-GROWTH = CRESCITA ## Restituisce i valori lungo una linea di tendenza esponenziale
-HARMEAN = MEDIA.ARMONICA ## Restituisce la media armonica
-HYPGEOMDIST = DISTRIB.IPERGEOM ## Restituisce la distribuzione ipergeometrica
-INTERCEPT = INTERCETTA ## Restituisce l'intercetta della retta di regressione lineare
-KURT = CURTOSI ## Restituisce la curtosi di un insieme di dati
-LARGE = GRANDE ## Restituisce il k-esimo valore più grande in un insieme di dati
-LINEST = REGR.LIN ## Restituisce i parametri di una tendenza lineare
-LOGEST = REGR.LOG ## Restituisce i parametri di una linea di tendenza esponenziale
-LOGINV = INV.LOGNORM ## Restituisce l'inverso di una distribuzione lognormale
-LOGNORMDIST = DISTRIB.LOGNORM ## Restituisce la distribuzione lognormale cumulativa
-MAX = MAX ## Restituisce il valore massimo in un elenco di argomenti
-MAXA = MAX.VALORI ## Restituisce il valore massimo in un elenco di argomenti, inclusi i numeri, il testo e i valori logici
-MEDIAN = MEDIANA ## Restituisce la mediana dei numeri specificati
-MIN = MIN ## Restituisce il valore minimo in un elenco di argomenti
-MINA = MIN.VALORI ## Restituisce il più piccolo valore in un elenco di argomenti, inclusi i numeri, il testo e i valori logici
-MODE = MODA ## Restituisce il valore più comune in un insieme di dati
-NEGBINOMDIST = DISTRIB.BINOM.NEG ## Restituisce la distribuzione binomiale negativa
-NORMDIST = DISTRIB.NORM ## Restituisce la distribuzione cumulativa normale
-NORMINV = INV.NORM ## Restituisce l'inverso della distribuzione cumulativa normale standard
-NORMSDIST = DISTRIB.NORM.ST ## Restituisce la distribuzione cumulativa normale standard
-NORMSINV = INV.NORM.ST ## Restituisce l'inverso della distribuzione cumulativa normale
-PEARSON = PEARSON ## Restituisce il coefficiente del momento di correlazione di Pearson
-PERCENTILE = PERCENTILE ## Restituisce il k-esimo dato percentile di valori in un intervallo
-PERCENTRANK = PERCENT.RANGO ## Restituisce il rango di un valore in un insieme di dati come percentuale
-PERMUT = PERMUTAZIONE ## Restituisce il numero delle permutazioni per un determinato numero di oggetti
-POISSON = POISSON ## Restituisce la distribuzione di Poisson
-PROB = PROBABILITÀ ## Calcola la probabilità che dei valori in un intervallo siano compresi tra due limiti
-QUARTILE = QUARTILE ## Restituisce il quartile di un insieme di dati
-RANK = RANGO ## Restituisce il rango di un numero in un elenco di numeri
-RSQ = RQ ## Restituisce la radice quadrata del coefficiente di momento di correlazione di Pearson
-SKEW = ASIMMETRIA ## Restituisce il grado di asimmetria di una distribuzione
-SLOPE = PENDENZA ## Restituisce la pendenza di una retta di regressione lineare
-SMALL = PICCOLO ## Restituisce il k-esimo valore più piccolo in un insieme di dati
-STANDARDIZE = NORMALIZZA ## Restituisce un valore normalizzato
-STDEV = DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione
-STDEVA = DEV.ST.VALORI ## Restituisce una stima della deviazione standard sulla base di un campione, inclusi i numeri, il testo e i valori logici
-STDEVP = DEV.ST.POP ## Calcola la deviazione standard sulla base di un'intera popolazione
-STDEVPA = DEV.ST.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici
-STEYX = ERR.STD.YX ## Restituisce l'errore standard del valore previsto per y per ogni valore x nella regressione
-TDIST = DISTRIB.T ## Restituisce la distribuzione t di Student
-TINV = INV.T ## Restituisce l'inversa della distribuzione t di Student
-TREND = TENDENZA ## Restituisce i valori lungo una linea di tendenza lineare
-TRIMMEAN = MEDIA.TRONCATA ## Restituisce la media della parte interna di un insieme di dati
-TTEST = TEST.T ## Restituisce la probabilità associata ad un test t di Student
-VAR = VAR ## Stima la varianza sulla base di un campione
-VARA = VAR.VALORI ## Stima la varianza sulla base di un campione, inclusi i numeri, il testo e i valori logici
-VARP = VAR.POP ## Calcola la varianza sulla base dell'intera popolazione
-VARPA = VAR.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici
-WEIBULL = WEIBULL ## Restituisce la distribuzione di Weibull
-ZTEST = TEST.Z ## Restituisce il valore di probabilità a una coda per un test z
-
+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
##
-## Text functions Funzioni di testo
+## Funzioni Web (Web Functions)
##
-ASC = ASC ## Modifica le lettere inglesi o il katakana a doppio byte all'interno di una stringa di caratteri in caratteri a singolo byte
-BAHTTEXT = BAHTTESTO ## Converte un numero in testo, utilizzando il formato valuta ß (baht)
-CHAR = CODICE.CARATT ## Restituisce il carattere specificato dal numero di codice
-CLEAN = LIBERA ## Elimina dal testo tutti i caratteri che non è possibile stampare
-CODE = CODICE ## Restituisce il codice numerico del primo carattere di una stringa di testo
-CONCATENATE = CONCATENA ## Unisce diversi elementi di testo in un unico elemento di testo
-DOLLAR = VALUTA ## Converte un numero in testo, utilizzando il formato valuta € (euro)
-EXACT = IDENTICO ## Verifica se due valori di testo sono uguali
-FIND = TROVA ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole)
-FINDB = TROVA.B ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole)
-FIXED = FISSO ## Formatta un numero come testo con un numero fisso di decimali
-JIS = ORDINAMENTO.JIS ## Modifica le lettere inglesi o i caratteri katakana a byte singolo all'interno di una stringa di caratteri in caratteri a byte doppio.
-LEFT = SINISTRA ## Restituisce il carattere più a sinistra di un valore di testo
-LEFTB = SINISTRA.B ## Restituisce il carattere più a sinistra di un valore di testo
-LEN = LUNGHEZZA ## Restituisce il numero di caratteri di una stringa di testo
-LENB = LUNB ## Restituisce il numero di caratteri di una stringa di testo
-LOWER = MINUSC ## Converte il testo in lettere minuscole
-MID = MEDIA ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata
-MIDB = MEDIA.B ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata
-PHONETIC = FURIGANA ## Estrae i caratteri fonetici (furigana) da una stringa di testo.
-PROPER = MAIUSC.INIZ ## Converte in maiuscolo la prima lettera di ogni parola di un valore di testo
-REPLACE = RIMPIAZZA ## Sostituisce i caratteri all'interno di un testo
-REPLACEB = SOSTITUISCI.B ## Sostituisce i caratteri all'interno di un testo
-REPT = RIPETI ## Ripete un testo per un dato numero di volte
-RIGHT = DESTRA ## Restituisce il carattere più a destra di un valore di testo
-RIGHTB = DESTRA.B ## Restituisce il carattere più a destra di un valore di testo
-SEARCH = RICERCA ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole)
-SEARCHB = CERCA.B ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole)
-SUBSTITUTE = SOSTITUISCI ## Sostituisce il nuovo testo al testo contenuto in una stringa
-T = T ## Converte gli argomenti in testo
-TEXT = TESTO ## Formatta un numero e lo converte in testo
-TRIM = ANNULLA.SPAZI ## Elimina gli spazi dal testo
-UPPER = MAIUSC ## Converte il testo in lettere maiuscole
-VALUE = VALORE ## Converte un argomento di testo in numero
+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
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/config
new file mode 100644
index 00000000000..a7f3be17946
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/config
@@ -0,0 +1,20 @@
+############################################################
+##
+## PhpSpreadsheet - locale settings
+##
+## Norsk Bokmål (Norwegian Bokmål)
+##
+############################################################
+
+ArgumentSeparator = ;
+
+##
+## Error Codes
+##
+NULL
+DIV0
+VALUE = #VERDI!
+REF
+NAME = #NAVN?
+NUM
+NA = #N/D
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/functions
new file mode 100644
index 00000000000..b0a0f9492ae
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/functions
@@ -0,0 +1,538 @@
+############################################################
+##
+## PhpSpreadsheet - function name translations
+##
+## Norsk Bokmål (Norwegian Bokmål)
+##
+############################################################
+
+
+##
+## Kubefunksjoner (Cube Functions)
+##
+CUBEKPIMEMBER = KUBEKPIMEDLEM
+CUBEMEMBER = KUBEMEDLEM
+CUBEMEMBERPROPERTY = KUBEMEDLEMEGENSKAP
+CUBERANKEDMEMBER = KUBERANGERTMEDLEM
+CUBESET = KUBESETT
+CUBESETCOUNT = KUBESETTANTALL
+CUBEVALUE = KUBEVERDI
+
+##
+## Databasefunksjoner (Database Functions)
+##
+DAVERAGE = DGJENNOMSNITT
+DCOUNT = DANTALL
+DCOUNTA = DANTALLA
+DGET = DHENT
+DMAX = DMAKS
+DMIN = DMIN
+DPRODUCT = DPRODUKT
+DSTDEV = DSTDAV
+DSTDEVP = DSTDAVP
+DSUM = DSUMMER
+DVAR = DVARIANS
+DVARP = DVARIANSP
+
+##
+## Dato- og tidsfunksjoner (Date & Time Functions)
+##
+DATE = DATO
+DATEDIF = DATODIFF
+DATESTRING = DATOSTRENG
+DATEVALUE = DATOVERDI
+DAY = DAG
+DAYS = DAGER
+DAYS360 = DAGER360
+EDATE = DAG.ETTER
+EOMONTH = MÅNEDSSLUTT
+HOUR = TIME
+ISOWEEKNUM = ISOUKENR
+MINUTE = MINUTT
+MONTH = MÅNED
+NETWORKDAYS = NETT.ARBEIDSDAGER
+NETWORKDAYS.INTL = NETT.ARBEIDSDAGER.INTL
+NOW = NÅ
+SECOND = SEKUND
+THAIDAYOFWEEK = THAIUKEDAG
+THAIMONTHOFYEAR = THAIMÅNED
+THAIYEAR = THAIÅR
+TIME = TID
+TIMEVALUE = TIDSVERDI
+TODAY = IDAG
+WEEKDAY = UKEDAG
+WEEKNUM = UKENR
+WORKDAY = ARBEIDSDAG
+WORKDAY.INTL = ARBEIDSDAG.INTL
+YEAR = ÅR
+YEARFRAC = ÅRDEL
+
+##
+## Tekniske funksjoner (Engineering Functions)
+##
+BESSELI = BESSELI
+BESSELJ = BESSELJ
+BESSELK = BESSELK
+BESSELY = BESSELY
+BIN2DEC = BINTILDES
+BIN2HEX = BINTILHEKS
+BIN2OCT = BINTILOKT
+BITAND = BITOG
+BITLSHIFT = BITVFORSKYV
+BITOR = BITELLER
+BITRSHIFT = BITHFORSKYV
+BITXOR = BITEKSKLUSIVELLER
+COMPLEX = KOMPLEKS
+CONVERT = KONVERTER
+DEC2BIN = DESTILBIN
+DEC2HEX = DESTILHEKS
+DEC2OCT = DESTILOKT
+DELTA = DELTA
+ERF = FEILF
+ERF.PRECISE = FEILF.PRESIS
+ERFC = FEILFK
+ERFC.PRECISE = FEILFK.PRESIS
+GESTEP = GRENSEVERDI
+HEX2BIN = HEKSTILBIN
+HEX2DEC = HEKSTILDES
+HEX2OCT = HEKSTILOKT
+IMABS = IMABS
+IMAGINARY = IMAGINÆR
+IMARGUMENT = IMARGUMENT
+IMCONJUGATE = IMKONJUGERT
+IMCOS = IMCOS
+IMCOSH = IMCOSH
+IMCOT = IMCOT
+IMCSC = IMCSC
+IMCSCH = IMCSCH
+IMDIV = IMDIV
+IMEXP = IMEKSP
+IMLN = IMLN
+IMLOG10 = IMLOG10
+IMLOG2 = IMLOG2
+IMPOWER = IMOPPHØY
+IMPRODUCT = IMPRODUKT
+IMREAL = IMREELL
+IMSEC = IMSEC
+IMSECH = IMSECH
+IMSIN = IMSIN
+IMSINH = IMSINH
+IMSQRT = IMROT
+IMSUB = IMSUB
+IMSUM = IMSUMMER
+IMTAN = IMTAN
+OCT2BIN = OKTTILBIN
+OCT2DEC = OKTTILDES
+OCT2HEX = OKTTILHEKS
+
+##
+## Økonomiske funksjoner (Financial Functions)
+##
+ACCRINT = PÅLØPT.PERIODISK.RENTE
+ACCRINTM = PÅLØPT.FORFALLSRENTE
+AMORDEGRC = AMORDEGRC
+AMORLINC = AMORLINC
+COUPDAYBS = OBLIG.DAGER.FF
+COUPDAYS = OBLIG.DAGER
+COUPDAYSNC = OBLIG.DAGER.NF
+COUPNCD = OBLIG.DAGER.EF
+COUPNUM = OBLIG.ANTALL
+COUPPCD = OBLIG.DAG.FORRIGE
+CUMIPMT = SAMLET.RENTE
+CUMPRINC = SAMLET.HOVEDSTOL
+DB = DAVSKR
+DDB = DEGRAVS
+DISC = DISKONTERT
+DOLLARDE = DOLLARDE
+DOLLARFR = DOLLARBR
+DURATION = VARIGHET
+EFFECT = EFFEKTIV.RENTE
+FV = SLUTTVERDI
+FVSCHEDULE = SVPLAN
+INTRATE = RENTESATS
+IPMT = RAVDRAG
+IRR = IR
+ISPMT = ER.AVDRAG
+MDURATION = MVARIGHET
+MIRR = MODIR
+NOMINAL = NOMINELL
+NPER = PERIODER
+NPV = NNV
+ODDFPRICE = AVVIKFP.PRIS
+ODDFYIELD = AVVIKFP.AVKASTNING
+ODDLPRICE = AVVIKSP.PRIS
+ODDLYIELD = AVVIKSP.AVKASTNING
+PDURATION = PVARIGHET
+PMT = AVDRAG
+PPMT = AMORT
+PRICE = PRIS
+PRICEDISC = PRIS.DISKONTERT
+PRICEMAT = PRIS.FORFALL
+PV = NÅVERDI
+RATE = RENTE
+RECEIVED = MOTTATT.AVKAST
+RRI = REALISERT.AVKASTNING
+SLN = LINAVS
+SYD = ÅRSAVS
+TBILLEQ = TBILLEKV
+TBILLPRICE = TBILLPRIS
+TBILLYIELD = TBILLAVKASTNING
+VDB = VERDIAVS
+XIRR = XIR
+XNPV = XNNV
+YIELD = AVKAST
+YIELDDISC = AVKAST.DISKONTERT
+YIELDMAT = AVKAST.FORFALL
+
+##
+## Informasjonsfunksjoner (Information Functions)
+##
+CELL = CELLE
+ERROR.TYPE = FEIL.TYPE
+INFO = INFO
+ISBLANK = ERTOM
+ISERR = ERF
+ISERROR = ERFEIL
+ISEVEN = ERPARTALL
+ISFORMULA = ERFORMEL
+ISLOGICAL = ERLOGISK
+ISNA = ERIT
+ISNONTEXT = ERIKKETEKST
+ISNUMBER = ERTALL
+ISODD = ERODDE
+ISREF = ERREF
+ISTEXT = ERTEKST
+N = N
+NA = IT
+SHEET = ARK
+SHEETS = ANTALL.ARK
+TYPE = VERDITYPE
+
+##
+## Logiske funksjoner (Logical Functions)
+##
+AND = OG
+FALSE = USANN
+IF = HVIS
+IFERROR = HVISFEIL
+IFNA = HVIS.IT
+IFS = HVIS.SETT
+NOT = IKKE
+OR = ELLER
+SWITCH = BRYTER
+TRUE = SANN
+XOR = EKSKLUSIVELLER
+
+##
+## Oppslag- og referansefunksjoner (Lookup & Reference Functions)
+##
+ADDRESS = ADRESSE
+AREAS = OMRÅDER
+CHOOSE = VELG
+COLUMN = KOLONNE
+COLUMNS = KOLONNER
+FORMULATEXT = FORMELTEKST
+GETPIVOTDATA = HENTPIVOTDATA
+HLOOKUP = FINN.KOLONNE
+HYPERLINK = HYPERKOBLING
+INDEX = INDEKS
+INDIRECT = INDIREKTE
+LOOKUP = SLÅ.OPP
+MATCH = SAMMENLIGNE
+OFFSET = FORSKYVNING
+ROW = RAD
+ROWS = RADER
+RTD = RTD
+TRANSPOSE = TRANSPONER
+VLOOKUP = FINN.RAD
+
+##
+## Matematikk- og trigonometrifunksjoner (Math & Trig Functions)
+##
+ABS = ABS
+ACOS = ARCCOS
+ACOSH = ARCCOSH
+ACOT = ACOT
+ACOTH = ACOTH
+AGGREGATE = MENGDE
+ARABIC = ARABISK
+ASIN = ARCSIN
+ASINH = ARCSINH
+ATAN = ARCTAN
+ATAN2 = ARCTAN2
+ATANH = ARCTANH
+BASE = GRUNNTALL
+CEILING.MATH = AVRUND.GJELDENDE.MULTIPLUM.OPP.MATEMATISK
+CEILING.PRECISE = AVRUND.GJELDENDE.MULTIPLUM.PRESIS
+COMBIN = KOMBINASJON
+COMBINA = KOMBINASJONA
+COS = COS
+COSH = COSH
+COT = COT
+COTH = COTH
+CSC = CSC
+CSCH = CSCH
+DECIMAL = DESIMAL
+DEGREES = GRADER
+ECMA.CEILING = ECMA.AVRUND.GJELDENDE.MULTIPLUM
+EVEN = AVRUND.TIL.PARTALL
+EXP = EKSP
+FACT = FAKULTET
+FACTDOUBLE = DOBBELFAKT
+FLOOR.MATH = AVRUND.GJELDENDE.MULTIPLUM.NED.MATEMATISK
+FLOOR.PRECISE = AVRUND.GJELDENDE.MULTIPLUM.NED.PRESIS
+GCD = SFF
+INT = HELTALL
+ISO.CEILING = ISO.AVRUND.GJELDENDE.MULTIPLUM
+LCM = MFM
+LN = LN
+LOG = LOG
+LOG10 = LOG10
+MDETERM = MDETERM
+MINVERSE = MINVERS
+MMULT = MMULT
+MOD = REST
+MROUND = MRUND
+MULTINOMIAL = MULTINOMINELL
+MUNIT = MENHET
+ODD = AVRUND.TIL.ODDETALL
+PI = PI
+POWER = OPPHØYD.I
+PRODUCT = PRODUKT
+QUOTIENT = KVOTIENT
+RADIANS = RADIANER
+RAND = TILFELDIG
+RANDBETWEEN = TILFELDIGMELLOM
+ROMAN = ROMERTALL
+ROUND = AVRUND
+ROUNDBAHTDOWN = RUNDAVBAHTNEDOVER
+ROUNDBAHTUP = RUNDAVBAHTOPPOVER
+ROUNDDOWN = AVRUND.NED
+ROUNDUP = AVRUND.OPP
+SEC = SEC
+SECH = SECH
+SERIESSUM = SUMMER.REKKE
+SIGN = FORTEGN
+SIN = SIN
+SINH = SINH
+SQRT = ROT
+SQRTPI = ROTPI
+SUBTOTAL = DELSUM
+SUM = SUMMER
+SUMIF = SUMMERHVIS
+SUMIFS = SUMMER.HVIS.SETT
+SUMPRODUCT = SUMMERPRODUKT
+SUMSQ = SUMMERKVADRAT
+SUMX2MY2 = SUMMERX2MY2
+SUMX2PY2 = SUMMERX2PY2
+SUMXMY2 = SUMMERXMY2
+TAN = TAN
+TANH = TANH
+TRUNC = AVKORT
+
+##
+## Statistiske funksjoner (Statistical Functions)
+##
+AVEDEV = GJENNOMSNITTSAVVIK
+AVERAGE = GJENNOMSNITT
+AVERAGEA = GJENNOMSNITTA
+AVERAGEIF = GJENNOMSNITTHVIS
+AVERAGEIFS = GJENNOMSNITT.HVIS.SETT
+BETA.DIST = BETA.FORDELING.N
+BETA.INV = BETA.INV
+BINOM.DIST = BINOM.FORDELING.N
+BINOM.DIST.RANGE = BINOM.FORDELING.OMRÅDE
+BINOM.INV = BINOM.INV
+CHISQ.DIST = KJIKVADRAT.FORDELING
+CHISQ.DIST.RT = KJIKVADRAT.FORDELING.H
+CHISQ.INV = KJIKVADRAT.INV
+CHISQ.INV.RT = KJIKVADRAT.INV.H
+CHISQ.TEST = KJIKVADRAT.TEST
+CONFIDENCE.NORM = KONFIDENS.NORM
+CONFIDENCE.T = KONFIDENS.T
+CORREL = KORRELASJON
+COUNT = ANTALL
+COUNTA = ANTALLA
+COUNTBLANK = TELLBLANKE
+COUNTIF = ANTALL.HVIS
+COUNTIFS = ANTALL.HVIS.SETT
+COVARIANCE.P = KOVARIANS.P
+COVARIANCE.S = KOVARIANS.S
+DEVSQ = AVVIK.KVADRERT
+EXPON.DIST = EKSP.FORDELING.N
+F.DIST = F.FORDELING
+F.DIST.RT = F.FORDELING.H
+F.INV = F.INV
+F.INV.RT = F.INV.H
+F.TEST = F.TEST
+FISHER = FISHER
+FISHERINV = FISHERINV
+FORECAST.ETS = PROGNOSE.ETS
+FORECAST.ETS.CONFINT = PROGNOSE.ETS.CONFINT
+FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SESONGAVHENGIGHET
+FORECAST.ETS.STAT = PROGNOSE.ETS.STAT
+FORECAST.LINEAR = PROGNOSE.LINEÆR
+FREQUENCY = FREKVENS
+GAMMA = GAMMA
+GAMMA.DIST = GAMMA.FORDELING
+GAMMA.INV = GAMMA.INV
+GAMMALN = GAMMALN
+GAMMALN.PRECISE = GAMMALN.PRESIS
+GAUSS = GAUSS
+GEOMEAN = GJENNOMSNITT.GEOMETRISK
+GROWTH = VEKST
+HARMEAN = GJENNOMSNITT.HARMONISK
+HYPGEOM.DIST = HYPGEOM.FORDELING.N
+INTERCEPT = SKJÆRINGSPUNKT
+KURT = KURT
+LARGE = N.STØRST
+LINEST = RETTLINJE
+LOGEST = KURVE
+LOGNORM.DIST = LOGNORM.FORDELING
+LOGNORM.INV = LOGNORM.INV
+MAX = STØRST
+MAXA = MAKSA
+MAXIFS = MAKS.HVIS.SETT
+MEDIAN = MEDIAN
+MIN = MIN
+MINA = MINA
+MINIFS = MIN.HVIS.SETT
+MODE.MULT = MODUS.MULT
+MODE.SNGL = MODUS.SNGL
+NEGBINOM.DIST = NEGBINOM.FORDELING.N
+NORM.DIST = NORM.FORDELING
+NORM.INV = NORM.INV
+NORM.S.DIST = NORM.S.FORDELING
+NORM.S.INV = NORM.S.INV
+PEARSON = PEARSON
+PERCENTILE.EXC = PERSENTIL.EKS
+PERCENTILE.INC = PERSENTIL.INK
+PERCENTRANK.EXC = PROSENTDEL.EKS
+PERCENTRANK.INC = PROSENTDEL.INK
+PERMUT = PERMUTER
+PERMUTATIONA = PERMUTASJONA
+PHI = PHI
+POISSON.DIST = POISSON.FORDELING
+PROB = SANNSYNLIG
+QUARTILE.EXC = KVARTIL.EKS
+QUARTILE.INC = KVARTIL.INK
+RANK.AVG = RANG.GJSN
+RANK.EQ = RANG.EKV
+RSQ = RKVADRAT
+SKEW = SKJEVFORDELING
+SKEW.P = SKJEVFORDELING.P
+SLOPE = STIGNINGSTALL
+SMALL = N.MINST
+STANDARDIZE = NORMALISER
+STDEV.P = STDAV.P
+STDEV.S = STDAV.S
+STDEVA = STDAVVIKA
+STDEVPA = STDAVVIKPA
+STEYX = STANDARDFEIL
+T.DIST = T.FORDELING
+T.DIST.2T = T.FORDELING.2T
+T.DIST.RT = T.FORDELING.H
+T.INV = T.INV
+T.INV.2T = T.INV.2T
+T.TEST = T.TEST
+TREND = TREND
+TRIMMEAN = TRIMMET.GJENNOMSNITT
+VAR.P = VARIANS.P
+VAR.S = VARIANS.S
+VARA = VARIANSA
+VARPA = VARIANSPA
+WEIBULL.DIST = WEIBULL.DIST.N
+Z.TEST = Z.TEST
+
+##
+## Tekstfunksjoner (Text Functions)
+##
+ASC = STIGENDE
+BAHTTEXT = BAHTTEKST
+CHAR = TEGNKODE
+CLEAN = RENSK
+CODE = KODE
+CONCAT = KJED.SAMMEN
+DOLLAR = VALUTA
+EXACT = EKSAKT
+FIND = FINN
+FIXED = FASTSATT
+ISTHAIDIGIT = ERTHAISIFFER
+LEFT = VENSTRE
+LEN = LENGDE
+LOWER = SMÅ
+MID = DELTEKST
+NUMBERSTRING = TALLSTRENG
+NUMBERVALUE = TALLVERDI
+PHONETIC = FURIGANA
+PROPER = STOR.FORBOKSTAV
+REPLACE = ERSTATT
+REPT = GJENTA
+RIGHT = HØYRE
+SEARCH = SØK
+SUBSTITUTE = BYTT.UT
+T = T
+TEXT = TEKST
+TEXTJOIN = TEKST.KOMBINER
+THAIDIGIT = THAISIFFER
+THAINUMSOUND = THAINUMLYD
+THAINUMSTRING = THAINUMSTRENG
+THAISTRINGLENGTH = THAISTRENGLENGDE
+TRIM = TRIMME
+UNICHAR = UNICODETEGN
+UNICODE = UNICODE
+UPPER = STORE
+VALUE = VERDI
+
+##
+## Nettfunksjoner (Web Functions)
+##
+ENCODEURL = URL.KODE
+FILTERXML = FILTRERXML
+WEBSERVICE = NETTJENESTE
+
+##
+## Kompatibilitetsfunksjoner (Compatibility Functions)
+##
+BETADIST = BETA.FORDELING
+BETAINV = INVERS.BETA.FORDELING
+BINOMDIST = BINOM.FORDELING
+CEILING = AVRUND.GJELDENDE.MULTIPLUM
+CHIDIST = KJI.FORDELING
+CHIINV = INVERS.KJI.FORDELING
+CHITEST = KJI.TEST
+CONCATENATE = KJEDE.SAMMEN
+CONFIDENCE = KONFIDENS
+COVAR = KOVARIANS
+CRITBINOM = GRENSE.BINOM
+EXPONDIST = EKSP.FORDELING
+FDIST = FFORDELING
+FINV = FFORDELING.INVERS
+FLOOR = AVRUND.GJELDENDE.MULTIPLUM.NED
+FORECAST = PROGNOSE
+FTEST = FTEST
+GAMMADIST = GAMMAFORDELING
+GAMMAINV = GAMMAINV
+HYPGEOMDIST = HYPGEOM.FORDELING
+LOGINV = LOGINV
+LOGNORMDIST = LOGNORMFORD
+MODE = MODUS
+NEGBINOMDIST = NEGBINOM.FORDELING
+NORMDIST = NORMALFORDELING
+NORMINV = NORMINV
+NORMSDIST = NORMSFORDELING
+NORMSINV = NORMSINV
+PERCENTILE = PERSENTIL
+PERCENTRANK = PROSENTDEL
+POISSON = POISSON
+QUARTILE = KVARTIL
+RANK = RANG
+STDEV = STDAV
+STDEVP = STDAVP
+TDIST = TFORDELING
+TINV = TINV
+TTEST = TTEST
+VAR = VARIANS
+VARP = VARIANSP
+WEIBULL = WEIBULL.FORDELING
+ZTEST = ZTEST
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/config
index 8376022d1c1..370567a7afb 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Nederlands (Dutch)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = €
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #LEEG!
-DIV0 = #DEEL/0!
-VALUE = #WAARDE!
-REF = #VERW!
-NAME = #NAAM?
-NUM = #GETAL!
-NA = #N/B
+NULL = #LEEG!
+DIV0 = #DEEL/0!
+VALUE = #WAARDE!
+REF = #VERW!
+NAME = #NAAM?
+NUM = #GETAL!
+NA = #N/B
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/functions
index 2518f421672..0e4f1597db0 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/functions
@@ -1,416 +1,536 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
+## PhpSpreadsheet - function name translations
##
+## Nederlands (Dutch)
##
+############################################################
##
-## Add-in and Automation functions Automatiseringsfuncties en functies in invoegtoepassingen
+## Kubusfuncties (Cube Functions)
##
-GETPIVOTDATA = DRAAITABEL.OPHALEN ## Geeft gegevens uit een draaitabelrapport als resultaat
-
+CUBEKPIMEMBER = KUBUSKPILID
+CUBEMEMBER = KUBUSLID
+CUBEMEMBERPROPERTY = KUBUSLIDEIGENSCHAP
+CUBERANKEDMEMBER = KUBUSGERANGSCHIKTLID
+CUBESET = KUBUSSET
+CUBESETCOUNT = KUBUSSETAANTAL
+CUBEVALUE = KUBUSWAARDE
##
-## Cube functions Kubusfuncties
+## Databasefuncties (Database Functions)
##
-CUBEKPIMEMBER = KUBUSKPILID ## Retourneert de naam, eigenschap en waarde van een KPI (prestatie-indicator) en geeft de naam en de eigenschap in de cel weer. Een KPI is een meetbare waarde, zoals de maandelijkse brutowinst of de omzet per kwartaal per werknemer, die wordt gebruikt om de prestaties van een organisatie te bewaken
-CUBEMEMBER = KUBUSLID ## Retourneert een lid of tupel in een kubushiërarchie. Wordt gebruikt om te controleren of het lid of de tupel in de kubus aanwezig is
-CUBEMEMBERPROPERTY = KUBUSLIDEIGENSCHAP ## Retourneert de waarde van een lideigenschap in de kubus. Wordt gebruikt om te controleren of de lidnaam in de kubus bestaat en retourneert de opgegeven eigenschap voor dit lid
-CUBERANKEDMEMBER = KUBUSGERANGCHIKTLID ## Retourneert het zoveelste, gerangschikte lid in een set. Wordt gebruikt om een of meer elementen in een set te retourneren, zoals de tien beste verkopers of de tien beste studenten
-CUBESET = KUBUSSET ## Definieert een berekende set leden of tupels door een ingestelde expressie naar de kubus op de server te sturen, alwaar de set wordt gemaakt en vervolgens wordt geretourneerd naar Microsoft Office Excel
-CUBESETCOUNT = KUBUSSETAANTAL ## Retourneert het aantal onderdelen in een set
-CUBEVALUE = KUBUSWAARDE ## Retourneert een samengestelde waarde van een kubus
-
+DAVERAGE = DBGEMIDDELDE
+DCOUNT = DBAANTAL
+DCOUNTA = DBAANTALC
+DGET = DBLEZEN
+DMAX = DBMAX
+DMIN = DBMIN
+DPRODUCT = DBPRODUCT
+DSTDEV = DBSTDEV
+DSTDEVP = DBSTDEVP
+DSUM = DBSOM
+DVAR = DBVAR
+DVARP = DBVARP
##
-## Database functions Databasefuncties
+## Datum- en tijdfuncties (Date & Time Functions)
##
-DAVERAGE = DBGEMIDDELDE ## Berekent de gemiddelde waarde in geselecteerde databasegegevens
-DCOUNT = DBAANTAL ## Telt de cellen met getallen in een database
-DCOUNTA = DBAANTALC ## Telt de niet-lege cellen in een database
-DGET = DBLEZEN ## Retourneert één record dat voldoet aan de opgegeven criteria uit een database
-DMAX = DBMAX ## Retourneert de maximumwaarde in de geselecteerde databasegegevens
-DMIN = DBMIN ## Retourneert de minimumwaarde in de geselecteerde databasegegevens
-DPRODUCT = DBPRODUCT ## Vermenigvuldigt de waarden in een bepaald veld van de records die voldoen aan de criteria in een database
-DSTDEV = DBSTDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef uit geselecteerde databasegegevens
-DSTDEVP = DBSTDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie van geselecteerde databasegegevens
-DSUM = DBSOM ## Telt de getallen uit een kolom records in de database op die voldoen aan de criteria
-DVAR = DBVAR ## Maakt een schatting van de variantie op basis van een steekproef uit geselecteerde databasegegevens
-DVARP = DBVARP ## Berekent de variantie op basis van de volledige populatie van geselecteerde databasegegevens
-
+DATE = DATUM
+DATESTRING = DATUMNOTATIE
+DATEVALUE = DATUMWAARDE
+DAY = DAG
+DAYS = DAGEN
+DAYS360 = DAGEN360
+EDATE = ZELFDE.DAG
+EOMONTH = LAATSTE.DAG
+HOUR = UUR
+ISOWEEKNUM = ISO.WEEKNUMMER
+MINUTE = MINUUT
+MONTH = MAAND
+NETWORKDAYS = NETTO.WERKDAGEN
+NETWORKDAYS.INTL = NETWERKDAGEN.INTL
+NOW = NU
+SECOND = SECONDE
+THAIDAYOFWEEK = THAIS.WEEKDAG
+THAIMONTHOFYEAR = THAIS.MAAND.VAN.JAAR
+THAIYEAR = THAIS.JAAR
+TIME = TIJD
+TIMEVALUE = TIJDWAARDE
+TODAY = VANDAAG
+WEEKDAY = WEEKDAG
+WEEKNUM = WEEKNUMMER
+WORKDAY = WERKDAG
+WORKDAY.INTL = WERKDAG.INTL
+YEAR = JAAR
+YEARFRAC = JAAR.DEEL
##
-## Date and time functions Datum- en tijdfuncties
+## Technische functies (Engineering Functions)
##
-DATE = DATUM ## Geeft als resultaat het seriële getal van een opgegeven datum
-DATEVALUE = DATUMWAARDE ## Converteert een datum in de vorm van tekst naar een serieel getal
-DAY = DAG ## Converteert een serieel getal naar een dag van de maand
-DAYS360 = DAGEN360 ## Berekent het aantal dagen tussen twee datums op basis van een jaar met 360 dagen
-EDATE = ZELFDE.DAG ## Geeft als resultaat het seriële getal van een datum die het opgegeven aantal maanden voor of na de begindatum ligt
-EOMONTH = LAATSTE.DAG ## Geeft als resultaat het seriële getal van de laatste dag van de maand voor of na het opgegeven aantal maanden
-HOUR = UUR ## Converteert een serieel getal naar uren
-MINUTE = MINUUT ## Converteert een serieel naar getal minuten
-MONTH = MAAND ## Converteert een serieel getal naar een maand
-NETWORKDAYS = NETTO.WERKDAGEN ## Geeft als resultaat het aantal hele werkdagen tussen twee datums
-NOW = NU ## Geeft als resultaat het seriële getal van de huidige datum en tijd
-SECOND = SECONDE ## Converteert een serieel getal naar seconden
-TIME = TIJD ## Geeft als resultaat het seriële getal van een bepaald tijdstip
-TIMEVALUE = TIJDWAARDE ## Converteert de tijd in de vorm van tekst naar een serieel getal
-TODAY = VANDAAG ## Geeft als resultaat het seriële getal van de huidige datum
-WEEKDAY = WEEKDAG ## Converteert een serieel getal naar een weekdag
-WEEKNUM = WEEKNUMMER ## Converteert een serieel getal naar een weeknummer
-WORKDAY = WERKDAG ## Geeft als resultaat het seriële getal van de datum voor of na een bepaald aantal werkdagen
-YEAR = JAAR ## Converteert een serieel getal naar een jaar
-YEARFRAC = JAAR.DEEL ## Geeft als resultaat het gedeelte van het jaar, uitgedrukt in het aantal hele dagen tussen begindatum en einddatum
-
+BESSELI = BESSEL.I
+BESSELJ = BESSEL.J
+BESSELK = BESSEL.K
+BESSELY = BESSEL.Y
+BIN2DEC = BIN.N.DEC
+BIN2HEX = BIN.N.HEX
+BIN2OCT = BIN.N.OCT
+BITAND = BIT.EN
+BITLSHIFT = BIT.VERSCHUIF.LINKS
+BITOR = BIT.OF
+BITRSHIFT = BIT.VERSCHUIF.RECHTS
+BITXOR = BIT.EX.OF
+COMPLEX = COMPLEX
+CONVERT = CONVERTEREN
+DEC2BIN = DEC.N.BIN
+DEC2HEX = DEC.N.HEX
+DEC2OCT = DEC.N.OCT
+DELTA = DELTA
+ERF = FOUTFUNCTIE
+ERF.PRECISE = FOUTFUNCTIE.NAUWKEURIG
+ERFC = FOUT.COMPLEMENT
+ERFC.PRECISE = FOUT.COMPLEMENT.NAUWKEURIG
+GESTEP = GROTER.DAN
+HEX2BIN = HEX.N.BIN
+HEX2DEC = HEX.N.DEC
+HEX2OCT = HEX.N.OCT
+IMABS = C.ABS
+IMAGINARY = C.IM.DEEL
+IMARGUMENT = C.ARGUMENT
+IMCONJUGATE = C.TOEGEVOEGD
+IMCOS = C.COS
+IMCOSH = C.COSH
+IMCOT = C.COT
+IMCSC = C.COSEC
+IMCSCH = C.COSECH
+IMDIV = C.QUOTIENT
+IMEXP = C.EXP
+IMLN = C.LN
+IMLOG10 = C.LOG10
+IMLOG2 = C.LOG2
+IMPOWER = C.MACHT
+IMPRODUCT = C.PRODUCT
+IMREAL = C.REEEL.DEEL
+IMSEC = C.SEC
+IMSECH = C.SECH
+IMSIN = C.SIN
+IMSINH = C.SINH
+IMSQRT = C.WORTEL
+IMSUB = C.VERSCHIL
+IMSUM = C.SOM
+IMTAN = C.TAN
+OCT2BIN = OCT.N.BIN
+OCT2DEC = OCT.N.DEC
+OCT2HEX = OCT.N.HEX
##
-## Engineering functions Technische functies
+## Financiële functies (Financial Functions)
##
-BESSELI = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie In(x)
-BESSELJ = BESSEL.J ## Geeft als resultaat de Bessel-functie Jn(x)
-BESSELK = BESSEL.K ## Geeft als resultaat de gewijzigde Bessel-functie Kn(x)
-BESSELY = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie Yn(x)
-BIN2DEC = BIN.N.DEC ## Converteert een binair getal naar een decimaal getal
-BIN2HEX = BIN.N.HEX ## Converteert een binair getal naar een hexadecimaal getal
-BIN2OCT = BIN.N.OCT ## Converteert een binair getal naar een octaal getal
-COMPLEX = COMPLEX ## Converteert reële en imaginaire coëfficiënten naar een complex getal
-CONVERT = CONVERTEREN ## Converteert een getal in de ene maateenheid naar een getal in een andere maateenheid
-DEC2BIN = DEC.N.BIN ## Converteert een decimaal getal naar een binair getal
-DEC2HEX = DEC.N.HEX ## Converteert een decimaal getal naar een hexadecimaal getal
-DEC2OCT = DEC.N.OCT ## Converteert een decimaal getal naar een octaal getal
-DELTA = DELTA ## Test of twee waarden gelijk zijn
-ERF = FOUTFUNCTIE ## Geeft als resultaat de foutfunctie
-ERFC = FOUT.COMPLEMENT ## Geeft als resultaat de complementaire foutfunctie
-GESTEP = GROTER.DAN ## Test of een getal groter is dan de drempelwaarde
-HEX2BIN = HEX.N.BIN ## Converteert een hexadecimaal getal naar een binair getal
-HEX2DEC = HEX.N.DEC ## Converteert een hexadecimaal getal naar een decimaal getal
-HEX2OCT = HEX.N.OCT ## Converteert een hexadecimaal getal naar een octaal getal
-IMABS = C.ABS ## Geeft als resultaat de absolute waarde (modulus) van een complex getal
-IMAGINARY = C.IM.DEEL ## Geeft als resultaat de imaginaire coëfficiënt van een complex getal
-IMARGUMENT = C.ARGUMENT ## Geeft als resultaat het argument thèta, een hoek uitgedrukt in radialen
-IMCONJUGATE = C.TOEGEVOEGD ## Geeft als resultaat het complexe toegevoegde getal van een complex getal
-IMCOS = C.COS ## Geeft als resultaat de cosinus van een complex getal
-IMDIV = C.QUOTIENT ## Geeft als resultaat het quotiënt van twee complexe getallen
-IMEXP = C.EXP ## Geeft als resultaat de exponent van een complex getal
-IMLN = C.LN ## Geeft als resultaat de natuurlijke logaritme van een complex getal
-IMLOG10 = C.LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een complex getal
-IMLOG2 = C.LOG2 ## Geeft als resultaat de logaritme met grondtal 2 van een complex getal
-IMPOWER = C.MACHT ## Geeft als resultaat een complex getal dat is verheven tot de macht van een geheel getal
-IMPRODUCT = C.PRODUCT ## Geeft als resultaat het product van complexe getallen
-IMREAL = C.REEEL.DEEL ## Geeft als resultaat de reële coëfficiënt van een complex getal
-IMSIN = C.SIN ## Geeft als resultaat de sinus van een complex getal
-IMSQRT = C.WORTEL ## Geeft als resultaat de vierkantswortel van een complex getal
-IMSUB = C.VERSCHIL ## Geeft als resultaat het verschil tussen twee complexe getallen
-IMSUM = C.SOM ## Geeft als resultaat de som van complexe getallen
-OCT2BIN = OCT.N.BIN ## Converteert een octaal getal naar een binair getal
-OCT2DEC = OCT.N.DEC ## Converteert een octaal getal naar een decimaal getal
-OCT2HEX = OCT.N.HEX ## Converteert een octaal getal naar een hexadecimaal getal
-
+ACCRINT = SAMENG.RENTE
+ACCRINTM = SAMENG.RENTE.V
+AMORDEGRC = AMORDEGRC
+AMORLINC = AMORLINC
+COUPDAYBS = COUP.DAGEN.BB
+COUPDAYS = COUP.DAGEN
+COUPDAYSNC = COUP.DAGEN.VV
+COUPNCD = COUP.DATUM.NB
+COUPNUM = COUP.AANTAL
+COUPPCD = COUP.DATUM.VB
+CUMIPMT = CUM.RENTE
+CUMPRINC = CUM.HOOFDSOM
+DB = DB
+DDB = DDB
+DISC = DISCONTO
+DOLLARDE = EURO.DE
+DOLLARFR = EURO.BR
+DURATION = DUUR
+EFFECT = EFFECT.RENTE
+FV = TW
+FVSCHEDULE = TOEK.WAARDE2
+INTRATE = RENTEPERCENTAGE
+IPMT = IBET
+IRR = IR
+ISPMT = ISBET
+MDURATION = AANG.DUUR
+MIRR = GIR
+NOMINAL = NOMINALE.RENTE
+NPER = NPER
+NPV = NHW
+ODDFPRICE = AFW.ET.PRIJS
+ODDFYIELD = AFW.ET.REND
+ODDLPRICE = AFW.LT.PRIJS
+ODDLYIELD = AFW.LT.REND
+PDURATION = PDUUR
+PMT = BET
+PPMT = PBET
+PRICE = PRIJS.NOM
+PRICEDISC = PRIJS.DISCONTO
+PRICEMAT = PRIJS.VERVALDAG
+PV = HW
+RATE = RENTE
+RECEIVED = OPBRENGST
+RRI = RRI
+SLN = LIN.AFSCHR
+SYD = SYD
+TBILLEQ = SCHATK.OBL
+TBILLPRICE = SCHATK.PRIJS
+TBILLYIELD = SCHATK.REND
+VDB = VDB
+XIRR = IR.SCHEMA
+XNPV = NHW2
+YIELD = RENDEMENT
+YIELDDISC = REND.DISCONTO
+YIELDMAT = REND.VERVAL
##
-## Financial functions Financiële functies
+## Informatiefuncties (Information Functions)
##
-ACCRINT = SAMENG.RENTE ## Berekent de opgelopen rente voor een waardepapier waarvan de rente periodiek wordt uitgekeerd
-ACCRINTM = SAMENG.RENTE.V ## Berekent de opgelopen rente voor een waardepapier waarvan de rente op de vervaldatum wordt uitgekeerd
-AMORDEGRC = AMORDEGRC ## Geeft als resultaat de afschrijving voor elke boekingsperiode door een afschrijvingscoëfficiënt toe te passen
-AMORLINC = AMORLINC ## Berekent de afschrijving voor elke boekingsperiode
-COUPDAYBS = COUP.DAGEN.BB ## Berekent het aantal dagen vanaf het begin van de coupontermijn tot de stortingsdatum
-COUPDAYS = COUP.DAGEN ## Geeft als resultaat het aantal dagen in de coupontermijn waarin de stortingsdatum valt
-COUPDAYSNC = COUP.DAGEN.VV ## Geeft als resultaat het aantal dagen vanaf de stortingsdatum tot de volgende couponvervaldatum
-COUPNCD = COUP.DATUM.NB ## Geeft als resultaat de volgende coupondatum na de stortingsdatum
-COUPNUM = COUP.AANTAL ## Geeft als resultaat het aantal coupons dat nog moet worden uitbetaald tussen de stortingsdatum en de vervaldatum
-COUPPCD = COUP.DATUM.VB ## Geeft als resultaat de vorige couponvervaldatum vóór de stortingsdatum
-CUMIPMT = CUM.RENTE ## Geeft als resultaat de cumulatieve rente die tussen twee termijnen is uitgekeerd
-CUMPRINC = CUM.HOOFDSOM ## Geeft als resultaat de cumulatieve hoofdsom van een lening die tussen twee termijnen is terugbetaald
-DB = DB ## Geeft als resultaat de afschrijving van activa voor een bepaalde periode met behulp van de 'fixed declining balance'-methode
-DDB = DDB ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'double declining balance'-methode of een andere methode die u opgeeft
-DISC = DISCONTO ## Geeft als resultaat het discontopercentage voor een waardepapier
-DOLLARDE = EURO.DE ## Converteert een prijs in euro's, uitgedrukt in een breuk, naar een prijs in euro's, uitgedrukt in een decimaal getal
-DOLLARFR = EURO.BR ## Converteert een prijs in euro's, uitgedrukt in een decimaal getal, naar een prijs in euro's, uitgedrukt in een breuk
-DURATION = DUUR ## Geeft als resultaat de gewogen gemiddelde looptijd voor een waardepapier met periodieke rentebetalingen
-EFFECT = EFFECT.RENTE ## Geeft als resultaat het effectieve jaarlijkse rentepercentage
-FV = TW ## Geeft als resultaat de toekomstige waarde van een investering
-FVSCHEDULE = TOEK.WAARDE2 ## Geeft als resultaat de toekomstige waarde van een bepaalde hoofdsom na het toepassen van een reeks samengestelde rentepercentages
-INTRATE = RENTEPERCENTAGE ## Geeft als resultaat het rentepercentage voor een volgestort waardepapier
-IPMT = IBET ## Geeft als resultaat de te betalen rente voor een investering over een bepaalde termijn
-IRR = IR ## Geeft als resultaat de interne rentabiliteit voor een reeks cashflows
-ISPMT = ISBET ## Geeft als resultaat de rente die is betaald tijdens een bepaalde termijn van een investering
-MDURATION = AANG.DUUR ## Geeft als resultaat de aangepaste Macauley-looptijd voor een waardepapier, aangenomen dat de nominale waarde € 100 bedraagt
-MIRR = GIR ## Geeft als resultaat de interne rentabiliteit voor een serie cashflows, waarbij voor betalingen een ander rentepercentage geldt dan voor inkomsten
-NOMINAL = NOMINALE.RENTE ## Geeft als resultaat het nominale jaarlijkse rentepercentage
-NPER = NPER ## Geeft als resultaat het aantal termijnen van een investering
-NPV = NHW ## Geeft als resultaat de netto huidige waarde van een investering op basis van een reeks periodieke cashflows en een discontopercentage
-ODDFPRICE = AFW.ET.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende eerste termijn
-ODDFYIELD = AFW.ET.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende eerste termijn
-ODDLPRICE = AFW.LT.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende laatste termijn
-ODDLYIELD = AFW.LT.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende laatste termijn
-PMT = BET ## Geeft als resultaat de periodieke betaling voor een annuïteit
-PPMT = PBET ## Geeft als resultaat de afbetaling op de hoofdsom voor een bepaalde termijn
-PRICE = PRIJS.NOM ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente periodiek wordt uitgekeerd
-PRICEDISC = PRIJS.DISCONTO ## Geeft als resultaat de prijs per € 100 nominale waarde voor een verdisconteerd waardepapier
-PRICEMAT = PRIJS.VERVALDAG ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum
-PV = HW ## Geeft als resultaat de huidige waarde van een investering
-RATE = RENTE ## Geeft als resultaat het periodieke rentepercentage voor een annuïteit
-RECEIVED = OPBRENGST ## Geeft als resultaat het bedrag dat op de vervaldatum wordt uitgekeerd voor een volgestort waardepapier
-SLN = LIN.AFSCHR ## Geeft als resultaat de lineaire afschrijving van activa over één termijn
-SYD = SYD ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'Sum-Of-Years-Digits'-methode
-TBILLEQ = SCHATK.OBL ## Geeft als resultaat het rendement op schatkistpapier, dat op dezelfde manier wordt berekend als het rendement op obligaties
-TBILLPRICE = SCHATK.PRIJS ## Bepaalt de prijs per € 100 nominale waarde voor schatkistpapier
-TBILLYIELD = SCHATK.REND ## Berekent het rendement voor schatkistpapier
-VDB = VDB ## Geeft als resultaat de afschrijving van activa over een gehele of gedeeltelijke termijn met behulp van de 'declining balance'-methode
-XIRR = IR.SCHEMA ## Berekent de interne rentabiliteit voor een betalingsschema van cashflows
-XNPV = NHW2 ## Berekent de huidige nettowaarde voor een betalingsschema van cashflows
-YIELD = RENDEMENT ## Geeft als resultaat het rendement voor een waardepapier waarvan de rente periodiek wordt uitgekeerd
-YIELDDISC = REND.DISCONTO ## Geeft als resultaat het jaarlijkse rendement voor een verdisconteerd waardepapier, bijvoorbeeld schatkistpapier
-YIELDMAT = REND.VERVAL ## Geeft als resultaat het jaarlijkse rendement voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum
-
+CELL = CEL
+ERROR.TYPE = TYPE.FOUT
+INFO = INFO
+ISBLANK = ISLEEG
+ISERR = ISFOUT2
+ISERROR = ISFOUT
+ISEVEN = IS.EVEN
+ISFORMULA = ISFORMULE
+ISLOGICAL = ISLOGISCH
+ISNA = ISNB
+ISNONTEXT = ISGEENTEKST
+ISNUMBER = ISGETAL
+ISODD = IS.ONEVEN
+ISREF = ISVERWIJZING
+ISTEXT = ISTEKST
+N = N
+NA = NB
+SHEET = BLAD
+SHEETS = BLADEN
+TYPE = TYPE
##
-## Information functions Informatiefuncties
+## Logische functies (Logical Functions)
##
-CELL = CEL ## Geeft als resultaat informatie over de opmaak, locatie of inhoud van een cel
-ERROR.TYPE = TYPE.FOUT ## Geeft als resultaat een getal dat overeenkomt met een van de foutwaarden van Microsoft Excel
-INFO = INFO ## Geeft als resultaat informatie over de huidige besturingsomgeving
-ISBLANK = ISLEEG ## Geeft als resultaat WAAR als de waarde leeg is
-ISERR = ISFOUT2 ## Geeft als resultaat WAAR als de waarde een foutwaarde is, met uitzondering van #N/B
-ISERROR = ISFOUT ## Geeft als resultaat WAAR als de waarde een foutwaarde is
-ISEVEN = IS.EVEN ## Geeft als resultaat WAAR als het getal even is
-ISLOGICAL = ISLOGISCH ## Geeft als resultaat WAAR als de waarde een logische waarde is
-ISNA = ISNB ## Geeft als resultaat WAAR als de waarde de foutwaarde #N/B is
-ISNONTEXT = ISGEENTEKST ## Geeft als resultaat WAAR als de waarde geen tekst is
-ISNUMBER = ISGETAL ## Geeft als resultaat WAAR als de waarde een getal is
-ISODD = IS.ONEVEN ## Geeft als resultaat WAAR als het getal oneven is
-ISREF = ISVERWIJZING ## Geeft als resultaat WAAR als de waarde een verwijzing is
-ISTEXT = ISTEKST ## Geeft als resultaat WAAR als de waarde tekst is
-N = N ## Geeft als resultaat een waarde die is geconverteerd naar een getal
-NA = NB ## Geeft als resultaat de foutwaarde #N/B
-TYPE = TYPE ## Geeft als resultaat een getal dat het gegevenstype van een waarde aangeeft
-
+AND = EN
+FALSE = ONWAAR
+IF = ALS
+IFERROR = ALS.FOUT
+IFNA = ALS.NB
+IFS = ALS.VOORWAARDEN
+NOT = NIET
+OR = OF
+SWITCH = SCHAKELEN
+TRUE = WAAR
+XOR = EX.OF
##
-## Logical functions Logische functies
+## Zoek- en verwijzingsfuncties (Lookup & Reference Functions)
##
-AND = EN ## Geeft als resultaat WAAR als alle argumenten WAAR zijn
-FALSE = ONWAAR ## Geeft als resultaat de logische waarde ONWAAR
-IF = ALS ## Geeft een logische test aan
-IFERROR = ALS.FOUT ## Retourneert een waarde die u opgeeft als een formule een fout oplevert, anders wordt het resultaat van de formule geretourneerd
-NOT = NIET ## Keert de logische waarde van het argument om
-OR = OF ## Geeft als resultaat WAAR als minimaal een van de argumenten WAAR is
-TRUE = WAAR ## Geeft als resultaat de logische waarde WAAR
-
+ADDRESS = ADRES
+AREAS = BEREIKEN
+CHOOSE = KIEZEN
+COLUMN = KOLOM
+COLUMNS = KOLOMMEN
+FORMULATEXT = FORMULETEKST
+GETPIVOTDATA = DRAAITABEL.OPHALEN
+HLOOKUP = HORIZ.ZOEKEN
+HYPERLINK = HYPERLINK
+INDEX = INDEX
+INDIRECT = INDIRECT
+LOOKUP = ZOEKEN
+MATCH = VERGELIJKEN
+OFFSET = VERSCHUIVING
+ROW = RIJ
+ROWS = RIJEN
+RTD = RTG
+TRANSPOSE = TRANSPONEREN
+VLOOKUP = VERT.ZOEKEN
##
-## Lookup and reference functions Zoek- en verwijzingsfuncties
+## Wiskundige en trigonometrische functies (Math & Trig Functions)
##
-ADDRESS = ADRES ## Geeft als resultaat een verwijzing, in de vorm van tekst, naar één bepaalde cel in een werkblad
-AREAS = BEREIKEN ## Geeft als resultaat het aantal bereiken in een verwijzing
-CHOOSE = KIEZEN ## Kiest een waarde uit een lijst met waarden
-COLUMN = KOLOM ## Geeft als resultaat het kolomnummer van een verwijzing
-COLUMNS = KOLOMMEN ## Geeft als resultaat het aantal kolommen in een verwijzing
-HLOOKUP = HORIZ.ZOEKEN ## Zoekt in de bovenste rij van een matrix naar een bepaalde waarde en geeft als resultaat de gevonden waarde in de opgegeven cel
-HYPERLINK = HYPERLINK ## Maakt een snelkoppeling of een sprong waarmee een document wordt geopend dat is opgeslagen op een netwerkserver, een intranet of op internet
-INDEX = INDEX ## Kiest met een index een waarde uit een verwijzing of een matrix
-INDIRECT = INDIRECT ## Geeft als resultaat een verwijzing die wordt aangegeven met een tekstwaarde
-LOOKUP = ZOEKEN ## Zoekt naar bepaalde waarden in een vector of een matrix
-MATCH = VERGELIJKEN ## Zoekt naar bepaalde waarden in een verwijzing of een matrix
-OFFSET = VERSCHUIVING ## Geeft als resultaat een nieuwe verwijzing die is verschoven ten opzichte van een bepaalde verwijzing
-ROW = RIJ ## Geeft als resultaat het rijnummer van een verwijzing
-ROWS = RIJEN ## Geeft als resultaat het aantal rijen in een verwijzing
-RTD = RTG ## Haalt realtimegegevens op uit een programma dat COM-automatisering (automatisering: een methode waarmee de ene toepassing objecten van een andere toepassing of ontwikkelprogramma kan besturen. Automatisering werd vroeger OLE-automatisering genoemd. Automatisering is een industrienorm die deel uitmaakt van het Component Object Model (COM).) ondersteunt
-TRANSPOSE = TRANSPONEREN ## Geeft als resultaat de getransponeerde van een matrix
-VLOOKUP = VERT.ZOEKEN ## Zoekt in de meest linkse kolom van een matrix naar een bepaalde waarde en geeft als resultaat de waarde in de opgegeven cel
-
+ABS = ABS
+ACOS = BOOGCOS
+ACOSH = BOOGCOSH
+ACOT = BOOGCOT
+ACOTH = BOOGCOTH
+AGGREGATE = AGGREGAAT
+ARABIC = ARABISCH
+ASIN = BOOGSIN
+ASINH = BOOGSINH
+ATAN = BOOGTAN
+ATAN2 = BOOGTAN2
+ATANH = BOOGTANH
+BASE = BASIS
+CEILING.MATH = AFRONDEN.BOVEN.WISK
+CEILING.PRECISE = AFRONDEN.BOVEN.NAUWKEURIG
+COMBIN = COMBINATIES
+COMBINA = COMBIN.A
+COS = COS
+COSH = COSH
+COT = COT
+COTH = COTH
+CSC = COSEC
+CSCH = COSECH
+DECIMAL = DECIMAAL
+DEGREES = GRADEN
+ECMA.CEILING = ECMA.AFRONDEN.BOVEN
+EVEN = EVEN
+EXP = EXP
+FACT = FACULTEIT
+FACTDOUBLE = DUBBELE.FACULTEIT
+FLOOR.MATH = AFRONDEN.BENEDEN.WISK
+FLOOR.PRECISE = AFRONDEN.BENEDEN.NAUWKEURIG
+GCD = GGD
+INT = INTEGER
+ISO.CEILING = ISO.AFRONDEN.BOVEN
+LCM = KGV
+LN = LN
+LOG = LOG
+LOG10 = LOG10
+MDETERM = DETERMINANTMAT
+MINVERSE = INVERSEMAT
+MMULT = PRODUCTMAT
+MOD = REST
+MROUND = AFRONDEN.N.VEELVOUD
+MULTINOMIAL = MULTINOMIAAL
+MUNIT = EENHEIDMAT
+ODD = ONEVEN
+PI = PI
+POWER = MACHT
+PRODUCT = PRODUCT
+QUOTIENT = QUOTIENT
+RADIANS = RADIALEN
+RAND = ASELECT
+RANDBETWEEN = ASELECTTUSSEN
+ROMAN = ROMEINS
+ROUND = AFRONDEN
+ROUNDBAHTDOWN = BAHT.AFR.NAAR.BENEDEN
+ROUNDBAHTUP = BAHT.AFR.NAAR.BOVEN
+ROUNDDOWN = AFRONDEN.NAAR.BENEDEN
+ROUNDUP = AFRONDEN.NAAR.BOVEN
+SEC = SEC
+SECH = SECH
+SERIESSUM = SOM.MACHTREEKS
+SIGN = POS.NEG
+SIN = SIN
+SINH = SINH
+SQRT = WORTEL
+SQRTPI = WORTEL.PI
+SUBTOTAL = SUBTOTAAL
+SUM = SOM
+SUMIF = SOM.ALS
+SUMIFS = SOMMEN.ALS
+SUMPRODUCT = SOMPRODUCT
+SUMSQ = KWADRATENSOM
+SUMX2MY2 = SOM.X2MINY2
+SUMX2PY2 = SOM.X2PLUSY2
+SUMXMY2 = SOM.XMINY.2
+TAN = TAN
+TANH = TANH
+TRUNC = GEHEEL
##
-## Math and trigonometry functions Wiskundige en trigonometrische functies
+## Statistische functies (Statistical Functions)
##
-ABS = ABS ## Geeft als resultaat de absolute waarde van een getal
-ACOS = BOOGCOS ## Geeft als resultaat de boogcosinus van een getal
-ACOSH = BOOGCOSH ## Geeft als resultaat de inverse cosinus hyperbolicus van een getal
-ASIN = BOOGSIN ## Geeft als resultaat de boogsinus van een getal
-ASINH = BOOGSINH ## Geeft als resultaat de inverse sinus hyperbolicus van een getal
-ATAN = BOOGTAN ## Geeft als resultaat de boogtangens van een getal
-ATAN2 = BOOGTAN2 ## Geeft als resultaat de boogtangens van de x- en y-coördinaten
-ATANH = BOOGTANH ## Geeft als resultaat de inverse tangens hyperbolicus van een getal
-CEILING = AFRONDEN.BOVEN ## Rondt de absolute waarde van een getal naar boven af op het dichtstbijzijnde gehele getal of het dichtstbijzijnde significante veelvoud
-COMBIN = COMBINATIES ## Geeft als resultaat het aantal combinaties voor een bepaald aantal objecten
-COS = COS ## Geeft als resultaat de cosinus van een getal
-COSH = COSH ## Geeft als resultaat de cosinus hyperbolicus van een getal
-DEGREES = GRADEN ## Converteert radialen naar graden
-EVEN = EVEN ## Rondt het getal af op het dichtstbijzijnde gehele even getal
-EXP = EXP ## Verheft e tot de macht van een bepaald getal
-FACT = FACULTEIT ## Geeft als resultaat de faculteit van een getal
-FACTDOUBLE = DUBBELE.FACULTEIT ## Geeft als resultaat de dubbele faculteit van een getal
-FLOOR = AFRONDEN.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af
-GCD = GGD ## Geeft als resultaat de grootste gemene deler
-INT = INTEGER ## Rondt een getal naar beneden af op het dichtstbijzijnde gehele getal
-LCM = KGV ## Geeft als resultaat het kleinste gemene veelvoud
-LN = LN ## Geeft als resultaat de natuurlijke logaritme van een getal
-LOG = LOG ## Geeft als resultaat de logaritme met het opgegeven grondtal van een getal
-LOG10 = LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een getal
-MDETERM = DETERMINANTMAT ## Geeft als resultaat de determinant van een matrix
-MINVERSE = INVERSEMAT ## Geeft als resultaat de inverse van een matrix
-MMULT = PRODUCTMAT ## Geeft als resultaat het product van twee matrices
-MOD = REST ## Geeft als resultaat het restgetal van een deling
-MROUND = AFRONDEN.N.VEELVOUD ## Geeft als resultaat een getal afgerond op het gewenste veelvoud
-MULTINOMIAL = MULTINOMIAAL ## Geeft als resultaat de multinomiaalcoëfficiënt van een reeks getallen
-ODD = ONEVEN ## Rondt de absolute waarde van het getal naar boven af op het dichtstbijzijnde gehele oneven getal
-PI = PI ## Geeft als resultaat de waarde van pi
-POWER = MACHT ## Verheft een getal tot een macht
-PRODUCT = PRODUCT ## Vermenigvuldigt de argumenten met elkaar
-QUOTIENT = QUOTIENT ## Geeft als resultaat de uitkomst van een deling als geheel getal
-RADIANS = RADIALEN ## Converteert graden naar radialen
-RAND = ASELECT ## Geeft als resultaat een willekeurig getal tussen 0 en 1
-RANDBETWEEN = ASELECTTUSSEN ## Geeft een willekeurig getal tussen de getallen die u hebt opgegeven
-ROMAN = ROMEINS ## Converteert een Arabisch getal naar een Romeins getal en geeft het resultaat weer in de vorm van tekst
-ROUND = AFRONDEN ## Rondt een getal af op het opgegeven aantal decimalen
-ROUNDDOWN = AFRONDEN.NAAR.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af
-ROUNDUP = AFRONDEN.NAAR.BOVEN ## Rondt de absolute waarde van een getal naar boven af
-SERIESSUM = SOM.MACHTREEKS ## Geeft als resultaat de som van een machtreeks die is gebaseerd op de formule
-SIGN = POS.NEG ## Geeft als resultaat het teken van een getal
-SIN = SIN ## Geeft als resultaat de sinus van de opgegeven hoek
-SINH = SINH ## Geeft als resultaat de sinus hyperbolicus van een getal
-SQRT = WORTEL ## Geeft als resultaat de positieve vierkantswortel van een getal
-SQRTPI = WORTEL.PI ## Geeft als resultaat de vierkantswortel van (getal * pi)
-SUBTOTAL = SUBTOTAAL ## Geeft als resultaat een subtotaal voor een bereik
-SUM = SOM ## Telt de argumenten op
-SUMIF = SOM.ALS ## Telt de getallen bij elkaar op die voldoen aan een bepaald criterium
-SUMIFS = SOMMEN.ALS ## Telt de cellen in een bereik op die aan meerdere criteria voldoen
-SUMPRODUCT = SOMPRODUCT ## Geeft als resultaat de som van de producten van de corresponderende matrixelementen
-SUMSQ = KWADRATENSOM ## Geeft als resultaat de som van de kwadraten van de argumenten
-SUMX2MY2 = SOM.X2MINY2 ## Geeft als resultaat de som van het verschil tussen de kwadraten van corresponderende waarden in twee matrices
-SUMX2PY2 = SOM.X2PLUSY2 ## Geeft als resultaat de som van de kwadratensom van corresponderende waarden in twee matrices
-SUMXMY2 = SOM.XMINY.2 ## Geeft als resultaat de som van de kwadraten van de verschillen tussen de corresponderende waarden in twee matrices
-TAN = TAN ## Geeft als resultaat de tangens van een getal
-TANH = TANH ## Geeft als resultaat de tangens hyperbolicus van een getal
-TRUNC = GEHEEL ## Kapt een getal af tot een geheel getal
-
+AVEDEV = GEM.DEVIATIE
+AVERAGE = GEMIDDELDE
+AVERAGEA = GEMIDDELDEA
+AVERAGEIF = GEMIDDELDE.ALS
+AVERAGEIFS = GEMIDDELDEN.ALS
+BETA.DIST = BETA.VERD
+BETA.INV = BETA.INV
+BINOM.DIST = BINOM.VERD
+BINOM.DIST.RANGE = BINOM.VERD.BEREIK
+BINOM.INV = BINOMIALE.INV
+CHISQ.DIST = CHIKW.VERD
+CHISQ.DIST.RT = CHIKW.VERD.RECHTS
+CHISQ.INV = CHIKW.INV
+CHISQ.INV.RT = CHIKW.INV.RECHTS
+CHISQ.TEST = CHIKW.TEST
+CONFIDENCE.NORM = VERTROUWELIJKHEID.NORM
+CONFIDENCE.T = VERTROUWELIJKHEID.T
+CORREL = CORRELATIE
+COUNT = AANTAL
+COUNTA = AANTALARG
+COUNTBLANK = AANTAL.LEGE.CELLEN
+COUNTIF = AANTAL.ALS
+COUNTIFS = AANTALLEN.ALS
+COVARIANCE.P = COVARIANTIE.P
+COVARIANCE.S = COVARIANTIE.S
+DEVSQ = DEV.KWAD
+EXPON.DIST = EXPON.VERD.N
+F.DIST = F.VERD
+F.DIST.RT = F.VERD.RECHTS
+F.INV = F.INV
+F.INV.RT = F.INV.RECHTS
+F.TEST = F.TEST
+FISHER = FISHER
+FISHERINV = FISHER.INV
+FORECAST.ETS = VOORSPELLEN.ETS
+FORECAST.ETS.CONFINT = VOORSPELLEN.ETS.CONFINT
+FORECAST.ETS.SEASONALITY = VOORSPELLEN.ETS.SEASONALITY
+FORECAST.ETS.STAT = FORECAST.ETS.STAT
+FORECAST.LINEAR = VOORSPELLEN.LINEAR
+FREQUENCY = INTERVAL
+GAMMA = GAMMA
+GAMMA.DIST = GAMMA.VERD.N
+GAMMA.INV = GAMMA.INV.N
+GAMMALN = GAMMA.LN
+GAMMALN.PRECISE = GAMMA.LN.NAUWKEURIG
+GAUSS = GAUSS
+GEOMEAN = MEETK.GEM
+GROWTH = GROEI
+HARMEAN = HARM.GEM
+HYPGEOM.DIST = HYPGEOM.VERD
+INTERCEPT = SNIJPUNT
+KURT = KURTOSIS
+LARGE = GROOTSTE
+LINEST = LIJNSCH
+LOGEST = LOGSCH
+LOGNORM.DIST = LOGNORM.VERD
+LOGNORM.INV = LOGNORM.INV
+MAX = MAX
+MAXA = MAXA
+MAXIFS = MAX.ALS.VOORWAARDEN
+MEDIAN = MEDIAAN
+MIN = MIN
+MINA = MINA
+MINIFS = MIN.ALS.VOORWAARDEN
+MODE.MULT = MODUS.MEERV
+MODE.SNGL = MODUS.ENKELV
+NEGBINOM.DIST = NEGBINOM.VERD
+NORM.DIST = NORM.VERD.N
+NORM.INV = NORM.INV.N
+NORM.S.DIST = NORM.S.VERD
+NORM.S.INV = NORM.S.INV
+PEARSON = PEARSON
+PERCENTILE.EXC = PERCENTIEL.EXC
+PERCENTILE.INC = PERCENTIEL.INC
+PERCENTRANK.EXC = PROCENTRANG.EXC
+PERCENTRANK.INC = PROCENTRANG.INC
+PERMUT = PERMUTATIES
+PERMUTATIONA = PERMUTATIE.A
+PHI = PHI
+POISSON.DIST = POISSON.VERD
+PROB = KANS
+QUARTILE.EXC = KWARTIEL.EXC
+QUARTILE.INC = KWARTIEL.INC
+RANK.AVG = RANG.GEMIDDELDE
+RANK.EQ = RANG.GELIJK
+RSQ = R.KWADRAAT
+SKEW = SCHEEFHEID
+SKEW.P = SCHEEFHEID.P
+SLOPE = RICHTING
+SMALL = KLEINSTE
+STANDARDIZE = NORMALISEREN
+STDEV.P = STDEV.P
+STDEV.S = STDEV.S
+STDEVA = STDEVA
+STDEVPA = STDEVPA
+STEYX = STAND.FOUT.YX
+T.DIST = T.DIST
+T.DIST.2T = T.VERD.2T
+T.DIST.RT = T.VERD.RECHTS
+T.INV = T.INV
+T.INV.2T = T.INV.2T
+T.TEST = T.TEST
+TREND = TREND
+TRIMMEAN = GETRIMD.GEM
+VAR.P = VAR.P
+VAR.S = VAR.S
+VARA = VARA
+VARPA = VARPA
+WEIBULL.DIST = WEIBULL.VERD
+Z.TEST = Z.TEST
##
-## Statistical functions Statistische functies
+## Tekstfuncties (Text Functions)
##
-AVEDEV = GEM.DEVIATIE ## Geeft als resultaat het gemiddelde van de absolute deviaties van gegevenspunten ten opzichte van hun gemiddelde waarde
-AVERAGE = GEMIDDELDE ## Geeft als resultaat het gemiddelde van de argumenten
-AVERAGEA = GEMIDDELDEA ## Geeft als resultaat het gemiddelde van de argumenten, inclusief getallen, tekst en logische waarden
-AVERAGEIF = GEMIDDELDE.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen in een bereik die voldoen aan de opgegeven criteria
-AVERAGEIFS = GEMIDDELDEN.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen die aan meerdere criteria voldoen
-BETADIST = BETA.VERD ## Geeft als resultaat de cumulatieve bèta-verdelingsfunctie
-BETAINV = BETA.INV ## Geeft als resultaat de inverse van de cumulatieve verdelingsfunctie voor een gegeven bèta-verdeling
-BINOMDIST = BINOMIALE.VERD ## Geeft als resultaat de binomiale verdeling
-CHIDIST = CHI.KWADRAAT ## Geeft als resultaat de eenzijdige kans van de chi-kwadraatverdeling
-CHIINV = CHI.KWADRAAT.INV ## Geeft als resultaat de inverse van een eenzijdige kans van de chi-kwadraatverdeling
-CHITEST = CHI.TOETS ## Geeft als resultaat de onafhankelijkheidstoets
-CONFIDENCE = BETROUWBAARHEID ## Geeft als resultaat het betrouwbaarheidsinterval van een gemiddelde waarde voor de elementen van een populatie
-CORREL = CORRELATIE ## Geeft als resultaat de correlatiecoëfficiënt van twee gegevensverzamelingen
-COUNT = AANTAL ## Telt het aantal getallen in de argumentenlijst
-COUNTA = AANTALARG ## Telt het aantal waarden in de argumentenlijst
-COUNTBLANK = AANTAL.LEGE.CELLEN ## Telt het aantal lege cellen in een bereik
-COUNTIF = AANTAL.ALS ## Telt in een bereik het aantal cellen die voldoen aan een bepaald criterium
-COUNTIFS = AANTALLEN.ALS ## Telt in een bereik het aantal cellen die voldoen aan meerdere criteria
-COVAR = COVARIANTIE ## Geeft als resultaat de covariantie, het gemiddelde van de producten van de gepaarde deviaties
-CRITBINOM = CRIT.BINOM ## Geeft als resultaat de kleinste waarde waarvoor de binomiale verdeling kleiner is dan of gelijk is aan het criterium
-DEVSQ = DEV.KWAD ## Geeft als resultaat de som van de deviaties in het kwadraat
-EXPONDIST = EXPON.VERD ## Geeft als resultaat de exponentiële verdeling
-FDIST = F.VERDELING ## Geeft als resultaat de F-verdeling
-FINV = F.INVERSE ## Geeft als resultaat de inverse van de F-verdeling
-FISHER = FISHER ## Geeft als resultaat de Fisher-transformatie
-FISHERINV = FISHER.INV ## Geeft als resultaat de inverse van de Fisher-transformatie
-FORECAST = VOORSPELLEN ## Geeft als resultaat een waarde op basis van een lineaire trend
-FREQUENCY = FREQUENTIE ## Geeft als resultaat een frequentieverdeling in de vorm van een verticale matrix
-FTEST = F.TOETS ## Geeft als resultaat een F-toets
-GAMMADIST = GAMMA.VERD ## Geeft als resultaat de gamma-verdeling
-GAMMAINV = GAMMA.INV ## Geeft als resultaat de inverse van de cumulatieve gamma-verdeling
-GAMMALN = GAMMA.LN ## Geeft als resultaat de natuurlijke logaritme van de gamma-functie, G(x)
-GEOMEAN = MEETK.GEM ## Geeft als resultaat het meetkundige gemiddelde
-GROWTH = GROEI ## Geeft als resultaat de waarden voor een exponentiële trend
-HARMEAN = HARM.GEM ## Geeft als resultaat het harmonische gemiddelde
-HYPGEOMDIST = HYPERGEO.VERD ## Geeft als resultaat de hypergeometrische verdeling
-INTERCEPT = SNIJPUNT ## Geeft als resultaat het snijpunt van de lineaire regressielijn met de y-as
-KURT = KURTOSIS ## Geeft als resultaat de kurtosis van een gegevensverzameling
-LARGE = GROOTSTE ## Geeft als resultaat de op k-1 na grootste waarde in een gegevensverzameling
-LINEST = LIJNSCH ## Geeft als resultaat de parameters van een lineaire trend
-LOGEST = LOGSCH ## Geeft als resultaat de parameters van een exponentiële trend
-LOGINV = LOG.NORM.INV ## Geeft als resultaat de inverse van de logaritmische normale verdeling
-LOGNORMDIST = LOG.NORM.VERD ## Geeft als resultaat de cumulatieve logaritmische normale verdeling
-MAX = MAX ## Geeft als resultaat de maximumwaarde in een lijst met argumenten
-MAXA = MAXA ## Geeft als resultaat de maximumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden
-MEDIAN = MEDIAAN ## Geeft als resultaat de mediaan van de opgegeven getallen
-MIN = MIN ## Geeft als resultaat de minimumwaarde in een lijst met argumenten
-MINA = MINA ## Geeft als resultaat de minimumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden
-MODE = MODUS ## Geeft als resultaat de meest voorkomende waarde in een gegevensverzameling
-NEGBINOMDIST = NEG.BINOM.VERD ## Geeft als resultaat de negatieve binomiaalverdeling
-NORMDIST = NORM.VERD ## Geeft als resultaat de cumulatieve normale verdeling
-NORMINV = NORM.INV ## Geeft als resultaat de inverse van de cumulatieve standaardnormale verdeling
-NORMSDIST = STAND.NORM.VERD ## Geeft als resultaat de cumulatieve standaardnormale verdeling
-NORMSINV = STAND.NORM.INV ## Geeft als resultaat de inverse van de cumulatieve normale verdeling
-PEARSON = PEARSON ## Geeft als resultaat de correlatiecoëfficiënt van Pearson
-PERCENTILE = PERCENTIEL ## Geeft als resultaat het k-de percentiel van waarden in een bereik
-PERCENTRANK = PERCENT.RANG ## Geeft als resultaat de positie, in procenten uitgedrukt, van een waarde in de rangorde van een gegevensverzameling
-PERMUT = PERMUTATIES ## Geeft als resultaat het aantal permutaties voor een gegeven aantal objecten
-POISSON = POISSON ## Geeft als resultaat de Poisson-verdeling
-PROB = KANS ## Geeft als resultaat de kans dat waarden zich tussen twee grenzen bevinden
-QUARTILE = KWARTIEL ## Geeft als resultaat het kwartiel van een gegevensverzameling
-RANK = RANG ## Geeft als resultaat het rangnummer van een getal in een lijst getallen
-RSQ = R.KWADRAAT ## Geeft als resultaat het kwadraat van de Pearson-correlatiecoëfficiënt
-SKEW = SCHEEFHEID ## Geeft als resultaat de mate van asymmetrie van een verdeling
-SLOPE = RICHTING ## Geeft als resultaat de richtingscoëfficiënt van een lineaire regressielijn
-SMALL = KLEINSTE ## Geeft als resultaat de op k-1 na kleinste waarde in een gegevensverzameling
-STANDARDIZE = NORMALISEREN ## Geeft als resultaat een genormaliseerde waarde
-STDEV = STDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef
-STDEVA = STDEVA ## Maakt een schatting van de standaarddeviatie op basis van een steekproef, inclusief getallen, tekst en logische waarden
-STDEVP = STDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie
-STDEVPA = STDEVPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden
-STEYX = STAND.FOUT.YX ## Geeft als resultaat de standaardfout in de voorspelde y-waarde voor elke x in een regressie
-TDIST = T.VERD ## Geeft als resultaat de Student T-verdeling
-TINV = T.INV ## Geeft als resultaat de inverse van de Student T-verdeling
-TREND = TREND ## Geeft als resultaat de waarden voor een lineaire trend
-TRIMMEAN = GETRIMD.GEM ## Geeft als resultaat het gemiddelde van waarden in een gegevensverzameling
-TTEST = T.TOETS ## Geeft als resultaat de kans met behulp van de Student T-toets
-VAR = VAR ## Maakt een schatting van de variantie op basis van een steekproef
-VARA = VARA ## Maakt een schatting van de variantie op basis van een steekproef, inclusief getallen, tekst en logische waarden
-VARP = VARP ## Berekent de variantie op basis van de volledige populatie
-VARPA = VARPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden
-WEIBULL = WEIBULL ## Geeft als resultaat de Weibull-verdeling
-ZTEST = Z.TOETS ## Geeft als resultaat de eenzijdige kanswaarde van een Z-toets
-
+BAHTTEXT = BAHT.TEKST
+CHAR = TEKEN
+CLEAN = WISSEN.CONTROL
+CODE = CODE
+CONCAT = TEKST.SAMENV
+DOLLAR = EURO
+EXACT = GELIJK
+FIND = VIND.ALLES
+FIXED = VAST
+ISTHAIDIGIT = IS.THAIS.CIJFER
+LEFT = LINKS
+LEN = LENGTE
+LOWER = KLEINE.LETTERS
+MID = DEEL
+NUMBERSTRING = GETALNOTATIE
+NUMBERVALUE = NUMERIEKE.WAARDE
+PHONETIC = FONETISCH
+PROPER = BEGINLETTERS
+REPLACE = VERVANGEN
+REPT = HERHALING
+RIGHT = RECHTS
+SEARCH = VIND.SPEC
+SUBSTITUTE = SUBSTITUEREN
+T = T
+TEXT = TEKST
+TEXTJOIN = TEKST.COMBINEREN
+THAIDIGIT = THAIS.CIJFER
+THAINUMSOUND = THAIS.GETAL.GELUID
+THAINUMSTRING = THAIS.GETAL.REEKS
+THAISTRINGLENGTH = THAIS.REEKS.LENGTE
+TRIM = SPATIES.WISSEN
+UNICHAR = UNITEKEN
+UNICODE = UNICODE
+UPPER = HOOFDLETTERS
+VALUE = WAARDE
##
-## Text functions Tekstfuncties
+## Webfuncties (Web Functions)
##
-ASC = ASC ## Wijzigt Nederlandse letters of katakanatekens over de volle breedte (dubbel-bytetekens) binnen een tekenreeks in tekens over de halve breedte (enkel-bytetekens)
-BAHTTEXT = BAHT.TEKST ## Converteert een getal naar tekst met de valutanotatie ß (baht)
-CHAR = TEKEN ## Geeft als resultaat het teken dat hoort bij de opgegeven code
-CLEAN = WISSEN.CONTROL ## Verwijdert alle niet-afdrukbare tekens uit een tekst
-CODE = CODE ## Geeft als resultaat de numerieke code voor het eerste teken in een tekenreeks
-CONCATENATE = TEKST.SAMENVOEGEN ## Voegt verschillende tekstfragmenten samen tot één tekstfragment
-DOLLAR = EURO ## Converteert een getal naar tekst met de valutanotatie € (euro)
-EXACT = GELIJK ## Controleert of twee tekenreeksen identiek zijn
-FIND = VIND.ALLES ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters)
-FINDB = VIND.ALLES.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters)
-FIXED = VAST ## Maakt een getal als tekst met een vast aantal decimalen op
-JIS = JIS ## Wijzigt Nederlandse letters of katakanatekens over de halve breedte (enkel-bytetekens) binnen een tekenreeks in tekens over de volle breedte (dubbel-bytetekens)
-LEFT = LINKS ## Geeft als resultaat de meest linkse tekens in een tekenreeks
-LEFTB = LINKSB ## Geeft als resultaat de meest linkse tekens in een tekenreeks
-LEN = LENGTE ## Geeft als resultaat het aantal tekens in een tekenreeks
-LENB = LENGTEB ## Geeft als resultaat het aantal tekens in een tekenreeks
-LOWER = KLEINE.LETTERS ## Zet tekst om in kleine letters
-MID = MIDDEN ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft
-MIDB = DEELB ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft
-PHONETIC = FONETISCH ## Haalt de fonetische tekens (furigana) uit een tekenreeks op
-PROPER = BEGINLETTERS ## Zet de eerste letter van elk woord in een tekst om in een hoofdletter
-REPLACE = VERVANG ## Vervangt tekens binnen een tekst
-REPLACEB = VERVANGENB ## Vervangt tekens binnen een tekst
-REPT = HERHALING ## Herhaalt een tekst een aantal malen
-RIGHT = RECHTS ## Geeft als resultaat de meest rechtse tekens in een tekenreeks
-RIGHTB = RECHTSB ## Geeft als resultaat de meest rechtse tekens in een tekenreeks
-SEARCH = VIND.SPEC ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters)
-SEARCHB = VIND.SPEC.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters)
-SUBSTITUTE = SUBSTITUEREN ## Vervangt oude tekst door nieuwe tekst in een tekenreeks
-T = T ## Converteert de argumenten naar tekst
-TEXT = TEKST ## Maakt een getal op en converteert het getal naar tekst
-TRIM = SPATIES.WISSEN ## Verwijdert de spaties uit een tekst
-UPPER = HOOFDLETTERS ## Zet tekst om in hoofdletters
-VALUE = WAARDE ## Converteert tekst naar een getal
+ENCODEURL = URL.CODEREN
+FILTERXML = XML.FILTEREN
+WEBSERVICE = WEBSERVICE
+
+##
+## Compatibiliteitsfuncties (Compatibility Functions)
+##
+BETADIST = BETAVERD
+BETAINV = BETAINV
+BINOMDIST = BINOMIALE.VERD
+CEILING = AFRONDEN.BOVEN
+CHIDIST = CHI.KWADRAAT
+CHIINV = CHI.KWADRAAT.INV
+CHITEST = CHI.TOETS
+CONCATENATE = TEKST.SAMENVOEGEN
+CONFIDENCE = BETROUWBAARHEID
+COVAR = COVARIANTIE
+CRITBINOM = CRIT.BINOM
+EXPONDIST = EXPON.VERD
+FDIST = F.VERDELING
+FINV = F.INVERSE
+FLOOR = AFRONDEN.BENEDEN
+FORECAST = VOORSPELLEN
+FTEST = F.TOETS
+GAMMADIST = GAMMA.VERD
+GAMMAINV = GAMMA.INV
+HYPGEOMDIST = HYPERGEO.VERD
+LOGINV = LOG.NORM.INV
+LOGNORMDIST = LOG.NORM.VERD
+MODE = MODUS
+NEGBINOMDIST = NEG.BINOM.VERD
+NORMDIST = NORM.VERD
+NORMINV = NORM.INV
+NORMSDIST = STAND.NORM.VERD
+NORMSINV = STAND.NORM.INV
+PERCENTILE = PERCENTIEL
+PERCENTRANK = PERCENT.RANG
+POISSON = POISSON
+QUARTILE = KWARTIEL
+RANK = RANG
+STDEV = STDEV
+STDEVP = STDEVP
+TDIST = T.VERD
+TINV = TINV
+TTEST = T.TOETS
+VAR = VAR
+VARP = VARP
+WEIBULL = WEIBULL
+ZTEST = Z.TOETS
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/config
deleted file mode 100644
index c7f4152a319..00000000000
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/config
+++ /dev/null
@@ -1,24 +0,0 @@
-##
-## PhpSpreadsheet
-##
-
-ArgumentSeparator = ;
-
-
-##
-## (For future use)
-##
-currencySymbol = kr
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #NULL!
-DIV0 = #DIV/0!
-VALUE = #VERDI!
-REF = #REF!
-NAME = #NAVN?
-NUM = #NUM!
-NA = #I/T
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/functions
deleted file mode 100644
index ab2a3793703..00000000000
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/functions
+++ /dev/null
@@ -1,416 +0,0 @@
-##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
-##
-##
-
-
-##
-## Add-in and Automation functions Funksjonene Tillegg og Automatisering
-##
-GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data som er lagret i en pivottabellrapport
-
-
-##
-## Cube functions Kubefunksjoner
-##
-CUBEKPIMEMBER = KUBEKPIMEDLEM ## Returnerer navnet, egenskapen og målet for en viktig ytelsesindikator (KPI), og viser navnet og egenskapen i cellen. En KPI er en målbar enhet, for eksempel månedlig bruttoinntjening eller kvartalsvis inntjening per ansatt, og brukes til å overvåke ytelsen i en organisasjon.
-CUBEMEMBER = KUBEMEDLEM ## Returnerer et medlem eller en tuppel i et kubehierarki. Brukes til å validere at medlemmet eller tuppelen finnes i kuben.
-CUBEMEMBERPROPERTY = KUBEMEDLEMEGENSKAP ## Returnerer verdien til en medlemsegenskap i kuben. Brukes til å validere at et medlemsnavn finnes i kuben, og til å returnere den angitte egenskapen for dette medlemmet.
-CUBERANKEDMEMBER = KUBERANGERTMEDLEM ## Returnerer det n-te, eller rangerte, medlemmet i et sett. Brukes til å returnere ett eller flere elementer i et sett, for eksempel de 10 beste studentene.
-CUBESET = KUBESETT ## Definerer et beregnet sett av medlemmer eller tuppeler ved å sende et settuttrykk til kuben på serveren, noe som oppretter settet og deretter returnerer dette settet til Microsoft Office Excel.
-CUBESETCOUNT = KUBESETTANTALL ## Returnerer antallet elementer i et sett.
-CUBEVALUE = KUBEVERDI ## Returnerer en aggregert verdi fra en kube.
-
-
-##
-## Database functions Databasefunksjoner
-##
-DAVERAGE = DGJENNOMSNITT ## Returnerer gjennomsnittet av merkede databaseposter
-DCOUNT = DANTALL ## Teller celler som inneholder tall i en database
-DCOUNTA = DANTALLA ## Teller celler som ikke er tomme i en database
-DGET = DHENT ## Trekker ut fra en database en post som oppfyller angitte vilkår
-DMAX = DMAKS ## Returnerer maksimumsverdien fra merkede databaseposter
-DMIN = DMIN ## Returnerer minimumsverdien fra merkede databaseposter
-DPRODUCT = DPRODUKT ## Multipliserer verdiene i et bestemt felt med poster som oppfyller vilkårene i en database
-DSTDEV = DSTDAV ## Estimerer standardavviket basert på et utvalg av merkede databaseposter
-DSTDEVP = DSTAVP ## Beregner standardavviket basert på at merkede databaseposter utgjør hele populasjonen
-DSUM = DSUMMER ## Legger til tallene i feltkolonnen med poster, i databasen som oppfyller vilkårene
-DVAR = DVARIANS ## Estimerer variansen basert på et utvalg av merkede databaseposter
-DVARP = DVARIANSP ## Beregner variansen basert på at merkede databaseposter utgjør hele populasjonen
-
-
-##
-## Date and time functions Dato- og tidsfunksjoner
-##
-DATE = DATO ## Returnerer serienummeret som svarer til en bestemt dato
-DATEVALUE = DATOVERDI ## Konverterer en dato med tekstformat til et serienummer
-DAY = DAG ## Konverterer et serienummer til en dag i måneden
-DAYS360 = DAGER360 ## Beregner antall dager mellom to datoer basert på et år med 360 dager
-EDATE = DAG.ETTER ## Returnerer serienummeret som svarer til datoen som er det indikerte antall måneder før eller etter startdatoen
-EOMONTH = MÅNEDSSLUTT ## Returnerer serienummeret som svarer til siste dag i måneden, før eller etter et angitt antall måneder
-HOUR = TIME ## Konverterer et serienummer til en time
-MINUTE = MINUTT ## Konverterer et serienummer til et minutt
-MONTH = MÅNED ## Konverterer et serienummer til en måned
-NETWORKDAYS = NETT.ARBEIDSDAGER ## Returnerer antall hele arbeidsdager mellom to datoer
-NOW = NÅ ## Returnerer serienummeret som svarer til gjeldende dato og klokkeslett
-SECOND = SEKUND ## Konverterer et serienummer til et sekund
-TIME = TID ## Returnerer serienummeret som svarer til et bestemt klokkeslett
-TIMEVALUE = TIDSVERDI ## Konverterer et klokkeslett i tekstformat til et serienummer
-TODAY = IDAG ## Returnerer serienummeret som svarer til dagens dato
-WEEKDAY = UKEDAG ## Konverterer et serienummer til en ukedag
-WEEKNUM = UKENR ## Konverterer et serienummer til et tall som representerer hvilket nummer uken har i et år
-WORKDAY = ARBEIDSDAG ## Returnerer serienummeret som svarer til datoen før eller etter et angitt antall arbeidsdager
-YEAR = ÅR ## Konverterer et serienummer til et år
-YEARFRAC = ÅRDEL ## Returnerer brøkdelen for året, som svarer til antall hele dager mellom startdato og sluttdato
-
-
-##
-## Engineering functions Tekniske funksjoner
-##
-BESSELI = BESSELI ## Returnerer den endrede Bessel-funksjonen In(x)
-BESSELJ = BESSELJ ## Returnerer Bessel-funksjonen Jn(x)
-BESSELK = BESSELK ## Returnerer den endrede Bessel-funksjonen Kn(x)
-BESSELY = BESSELY ## Returnerer Bessel-funksjonen Yn(x)
-BIN2DEC = BINTILDES ## Konverterer et binært tall til et desimaltall
-BIN2HEX = BINTILHEKS ## Konverterer et binært tall til et heksadesimaltall
-BIN2OCT = BINTILOKT ## Konverterer et binært tall til et oktaltall
-COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koeffisienter til et komplekst tall
-CONVERT = KONVERTER ## Konverterer et tall fra ett målsystem til et annet
-DEC2BIN = DESTILBIN ## Konverterer et desimaltall til et binærtall
-DEC2HEX = DESTILHEKS ## Konverterer et heltall i 10-tallsystemet til et heksadesimalt tall
-DEC2OCT = DESTILOKT ## Konverterer et heltall i 10-tallsystemet til et oktaltall
-DELTA = DELTA ## Undersøker om to verdier er like
-ERF = FEILF ## Returnerer feilfunksjonen
-ERFC = FEILFK ## Returnerer den komplementære feilfunksjonen
-GESTEP = GRENSEVERDI ## Tester om et tall er større enn en terskelverdi
-HEX2BIN = HEKSTILBIN ## Konverterer et heksadesimaltall til et binært tall
-HEX2DEC = HEKSTILDES ## Konverterer et heksadesimalt tall til et heltall i 10-tallsystemet
-HEX2OCT = HEKSTILOKT ## Konverterer et heksadesimalt tall til et oktaltall
-IMABS = IMABS ## Returnerer absoluttverdien (koeffisienten) til et komplekst tall
-IMAGINARY = IMAGINÆR ## Returnerer den imaginære koeffisienten til et komplekst tall
-IMARGUMENT = IMARGUMENT ## Returnerer argumentet theta, som er en vinkel uttrykt i radianer
-IMCONJUGATE = IMKONJUGERT ## Returnerer den komplekse konjugaten til et komplekst tall
-IMCOS = IMCOS ## Returnerer cosinus til et komplekst tall
-IMDIV = IMDIV ## Returnerer kvotienten til to komplekse tall
-IMEXP = IMEKSP ## Returnerer eksponenten til et komplekst tall
-IMLN = IMLN ## Returnerer den naturlige logaritmen for et komplekst tall
-IMLOG10 = IMLOG10 ## Returnerer logaritmen med grunntall 10 for et komplekst tall
-IMLOG2 = IMLOG2 ## Returnerer logaritmen med grunntall 2 for et komplekst tall
-IMPOWER = IMOPPHØY ## Returnerer et komplekst tall opphøyd til en heltallspotens
-IMPRODUCT = IMPRODUKT ## Returnerer produktet av komplekse tall
-IMREAL = IMREELL ## Returnerer den reelle koeffisienten til et komplekst tall
-IMSIN = IMSIN ## Returnerer sinus til et komplekst tall
-IMSQRT = IMROT ## Returnerer kvadratroten av et komplekst tall
-IMSUB = IMSUB ## Returnerer differansen mellom to komplekse tall
-IMSUM = IMSUMMER ## Returnerer summen av komplekse tall
-OCT2BIN = OKTTILBIN ## Konverterer et oktaltall til et binært tall
-OCT2DEC = OKTTILDES ## Konverterer et oktaltall til et desimaltall
-OCT2HEX = OKTTILHEKS ## Konverterer et oktaltall til et heksadesimaltall
-
-
-##
-## Financial functions Økonomiske funksjoner
-##
-ACCRINT = PÅLØPT.PERIODISK.RENTE ## Returnerer påløpte renter for et verdipapir som betaler periodisk rente
-ACCRINTM = PÅLØPT.FORFALLSRENTE ## Returnerer den påløpte renten for et verdipapir som betaler rente ved forfall
-AMORDEGRC = AMORDEGRC ## Returnerer avskrivningen for hver regnskapsperiode ved hjelp av en avskrivingskoeffisient
-AMORLINC = AMORLINC ## Returnerer avskrivingen for hver regnskapsperiode
-COUPDAYBS = OBLIG.DAGER.FF ## Returnerer antall dager fra begynnelsen av den rentebærende perioden til innløsningsdatoen
-COUPDAYS = OBLIG.DAGER ## Returnerer antall dager i den rentebærende perioden som inneholder innløsningsdatoen
-COUPDAYSNC = OBLIG.DAGER.NF ## Returnerer antall dager fra betalingsdato til neste renteinnbetalingsdato
-COUPNCD = OBLIG.DAGER.EF ## Returnerer obligasjonsdatoen som kommer etter oppgjørsdatoen
-COUPNUM = OBLIG.ANTALL ## Returnerer antall obligasjoner som skal betales mellom oppgjørsdatoen og forfallsdatoen
-COUPPCD = OBLIG.DAG.FORRIGE ## Returnerer obligasjonsdatoen som kommer før oppgjørsdatoen
-CUMIPMT = SAMLET.RENTE ## Returnerer den kumulative renten som er betalt mellom to perioder
-CUMPRINC = SAMLET.HOVEDSTOL ## Returnerer den kumulative hovedstolen som er betalt for et lån mellom to perioder
-DB = DAVSKR ## Returnerer avskrivningen for et aktivum i en angitt periode, foretatt med fast degressiv avskrivning
-DDB = DEGRAVS ## Returnerer avskrivningen for et aktivum for en gitt periode, ved hjelp av dobbel degressiv avskrivning eller en metode som du selv angir
-DISC = DISKONTERT ## Returnerer diskonteringsraten for et verdipapir
-DOLLARDE = DOLLARDE ## Konverterer en valutapris uttrykt som en brøk, til en valutapris uttrykt som et desimaltall
-DOLLARFR = DOLLARBR ## Konverterer en valutapris uttrykt som et desimaltall, til en valutapris uttrykt som en brøk
-DURATION = VARIGHET ## Returnerer årlig varighet for et verdipapir med renter som betales periodisk
-EFFECT = EFFEKTIV.RENTE ## Returnerer den effektive årlige rentesatsen
-FV = SLUTTVERDI ## Returnerer fremtidig verdi for en investering
-FVSCHEDULE = SVPLAN ## Returnerer den fremtidige verdien av en inngående hovedstol etter å ha anvendt en serie med sammensatte rentesatser
-INTRATE = RENTESATS ## Returnerer rentefoten av et fullfinansiert verdipapir
-IPMT = RAVDRAG ## Returnerer betalte renter på en investering for en gitt periode
-IRR = IR ## Returnerer internrenten for en serie kontantstrømmer
-ISPMT = ER.AVDRAG ## Beregner renten som er betalt for en investering i løpet av en bestemt periode
-MDURATION = MVARIGHET ## Returnerer Macauleys modifiserte varighet for et verdipapir med en antatt pålydende verdi på kr 100,00
-MIRR = MODIR ## Returnerer internrenten der positive og negative kontantstrømmer finansieres med forskjellige satser
-NOMINAL = NOMINELL ## Returnerer årlig nominell rentesats
-NPER = PERIODER ## Returnerer antall perioder for en investering
-NPV = NNV ## Returnerer netto nåverdi for en investering, basert på en serie periodiske kontantstrømmer og en rentesats
-ODDFPRICE = AVVIKFP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde første periode
-ODDFYIELD = AVVIKFP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde første periode
-ODDLPRICE = AVVIKSP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde siste periode
-ODDLYIELD = AVVIKSP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde siste periode
-PMT = AVDRAG ## Returnerer periodisk betaling for en annuitet
-PPMT = AMORT ## Returnerer betalingen på hovedstolen for en investering i en gitt periode
-PRICE = PRIS ## Returnerer prisen per pålydende kr 100 for et verdipapir som gir periodisk avkastning
-PRICEDISC = PRIS.DISKONTERT ## Returnerer prisen per pålydende kr 100 for et diskontert verdipapir
-PRICEMAT = PRIS.FORFALL ## Returnerer prisen per pålydende kr 100 av et verdipapir som betaler rente ved forfall
-PV = NÅVERDI ## Returnerer nåverdien av en investering
-RATE = RENTE ## Returnerer rentesatsen per periode for en annuitet
-RECEIVED = MOTTATT.AVKAST ## Returnerer summen som mottas ved forfallsdato for et fullinvestert verdipapir
-SLN = LINAVS ## Returnerer den lineære avskrivningen for et aktivum i én periode
-SYD = ÅRSAVS ## Returnerer årsavskrivningen for et aktivum i en angitt periode
-TBILLEQ = TBILLEKV ## Returnerer den obligasjonsekvivalente avkastningen for en statsobligasjon
-TBILLPRICE = TBILLPRIS ## Returnerer prisen per pålydende kr 100 for en statsobligasjon
-TBILLYIELD = TBILLAVKASTNING ## Returnerer avkastningen til en statsobligasjon
-VDB = VERDIAVS ## Returnerer avskrivningen for et aktivum i en angitt periode eller delperiode, ved hjelp av degressiv avskrivning
-XIRR = XIR ## Returnerer internrenten for en serie kontantstrømmer som ikke nødvendigvis er periodiske
-XNPV = XNNV ## Returnerer netto nåverdi for en serie kontantstrømmer som ikke nødvendigvis er periodiske
-YIELD = AVKAST ## Returnerer avkastningen på et verdipapir som betaler periodisk rente
-YIELDDISC = AVKAST.DISKONTERT ## Returnerer årlig avkastning for et diskontert verdipapir, for eksempel en statskasseveksel
-YIELDMAT = AVKAST.FORFALL ## Returnerer den årlige avkastningen for et verdipapir som betaler rente ved forfallsdato
-
-
-##
-## Information functions Informasjonsfunksjoner
-##
-CELL = CELLE ## Returnerer informasjon om formatering, plassering eller innholdet til en celle
-ERROR.TYPE = FEIL.TYPE ## Returnerer et tall som svarer til en feiltype
-INFO = INFO ## Returnerer informasjon om gjeldende operativmiljø
-ISBLANK = ERTOM ## Returnerer SANN hvis verdien er tom
-ISERR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst annen feilverdi enn #I/T
-ISERROR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst feilverdi
-ISEVEN = ERPARTALL ## Returnerer SANN hvis tallet er et partall
-ISLOGICAL = ERLOGISK ## Returnerer SANN hvis verdien er en logisk verdi
-ISNA = ERIT ## Returnerer SANN hvis verdien er feilverdien #I/T
-ISNONTEXT = ERIKKETEKST ## Returnerer SANN hvis verdien ikke er tekst
-ISNUMBER = ERTALL ## Returnerer SANN hvis verdien er et tall
-ISODD = ERODDETALL ## Returnerer SANN hvis tallet er et oddetall
-ISREF = ERREF ## Returnerer SANN hvis verdien er en referanse
-ISTEXT = ERTEKST ## Returnerer SANN hvis verdien er tekst
-N = N ## Returnerer en verdi som er konvertert til et tall
-NA = IT ## Returnerer feilverdien #I/T
-TYPE = VERDITYPE ## Returnerer et tall som indikerer datatypen til en verdi
-
-
-##
-## Logical functions Logiske funksjoner
-##
-AND = OG ## Returnerer SANN hvis alle argumentene er lik SANN
-FALSE = USANN ## Returnerer den logiske verdien USANN
-IF = HVIS ## Angir en logisk test som skal utføres
-IFERROR = HVISFEIL ## Returnerer en verdi du angir hvis en formel evaluerer til en feil. Ellers returnerer den resultatet av formelen.
-NOT = IKKE ## Reverserer logikken til argumentet
-OR = ELLER ## Returnerer SANN hvis ett eller flere argumenter er lik SANN
-TRUE = SANN ## Returnerer den logiske verdien SANN
-
-
-##
-## Lookup and reference functions Oppslag- og referansefunksjoner
-##
-ADDRESS = ADRESSE ## Returnerer en referanse som tekst til en enkelt celle i et regneark
-AREAS = OMRÅDER ## Returnerer antall områder i en referanse
-CHOOSE = VELG ## Velger en verdi fra en liste med verdier
-COLUMN = KOLONNE ## Returnerer kolonnenummeret for en referanse
-COLUMNS = KOLONNER ## Returnerer antall kolonner i en referanse
-HLOOKUP = FINN.KOLONNE ## Leter i den øverste raden i en matrise og returnerer verdien for den angitte cellen
-HYPERLINK = HYPERKOBLING ## Oppretter en snarvei eller et hopp som åpner et dokument som er lagret på en nettverksserver, et intranett eller Internett
-INDEX = INDEKS ## Bruker en indeks til å velge en verdi fra en referanse eller matrise
-INDIRECT = INDIREKTE ## Returnerer en referanse angitt av en tekstverdi
-LOOKUP = SLÅ.OPP ## Slår opp verdier i en vektor eller matrise
-MATCH = SAMMENLIGNE ## Slår opp verdier i en referanse eller matrise
-OFFSET = FORSKYVNING ## Returnerer en referanseforskyvning fra en gitt referanse
-ROW = RAD ## Returnerer radnummeret for en referanse
-ROWS = RADER ## Returnerer antall rader i en referanse
-RTD = RTD ## Henter sanntidsdata fra et program som støtter COM-automatisering (automatisering: En måte å arbeide på med programobjekter fra et annet program- eller utviklingsverktøy. Tidligere kalt OLE-automatisering. Automatisering er en bransjestandard og en funksjon i Component Object Model (COM).)
-TRANSPOSE = TRANSPONER ## Returnerer transponeringen av en matrise
-VLOOKUP = FINN.RAD ## Leter i den første kolonnen i en matrise og flytter bortover raden for å returnere verdien til en celle
-
-
-##
-## Math and trigonometry functions Matematikk- og trigonometrifunksjoner
-##
-ABS = ABS ## Returnerer absoluttverdien til et tall
-ACOS = ARCCOS ## Returnerer arcus cosinus til et tall
-ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus til et tall
-ASIN = ARCSIN ## Returnerer arcus sinus til et tall
-ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus til et tall
-ATAN = ARCTAN ## Returnerer arcus tangens til et tall
-ATAN2 = ARCTAN2 ## Returnerer arcus tangens fra x- og y-koordinater
-ATANH = ARCTANH ## Returnerer den inverse hyperbolske tangens til et tall
-CEILING = AVRUND.GJELDENDE.MULTIPLUM ## Runder av et tall til nærmeste heltall eller til nærmeste signifikante multiplum
-COMBIN = KOMBINASJON ## Returnerer antall kombinasjoner for ett gitt antall objekter
-COS = COS ## Returnerer cosinus til et tall
-COSH = COSH ## Returnerer den hyperbolske cosinus til et tall
-DEGREES = GRADER ## Konverterer radianer til grader
-EVEN = AVRUND.TIL.PARTALL ## Runder av et tall oppover til nærmeste heltall som er et partall
-EXP = EKSP ## Returnerer e opphøyd i en angitt potens
-FACT = FAKULTET ## Returnerer fakultet til et tall
-FACTDOUBLE = DOBBELFAKT ## Returnerer et talls doble fakultet
-FLOOR = AVRUND.GJELDENDE.MULTIPLUM.NED ## Avrunder et tall nedover, mot null
-GCD = SFF ## Returnerer høyeste felles divisor
-INT = HELTALL ## Avrunder et tall nedover til nærmeste heltall
-LCM = MFM ## Returnerer minste felles multiplum
-LN = LN ## Returnerer den naturlige logaritmen til et tall
-LOG = LOG ## Returnerer logaritmen for et tall til et angitt grunntall
-LOG10 = LOG10 ## Returnerer logaritmen med grunntall 10 for et tall
-MDETERM = MDETERM ## Returnerer matrisedeterminanten til en matrise
-MINVERSE = MINVERS ## Returnerer den inverse matrisen til en matrise
-MMULT = MMULT ## Returnerer matriseproduktet av to matriser
-MOD = REST ## Returnerer resten fra en divisjon
-MROUND = MRUND ## Returnerer et tall avrundet til det ønskede multiplum
-MULTINOMIAL = MULTINOMINELL ## Returnerer det multinominelle for et sett med tall
-ODD = AVRUND.TIL.ODDETALL ## Runder av et tall oppover til nærmeste heltall som er et oddetall
-PI = PI ## Returnerer verdien av pi
-POWER = OPPHØYD.I ## Returnerer resultatet av et tall opphøyd i en potens
-PRODUCT = PRODUKT ## Multipliserer argumentene
-QUOTIENT = KVOTIENT ## Returnerer heltallsdelen av en divisjon
-RADIANS = RADIANER ## Konverterer grader til radianer
-RAND = TILFELDIG ## Returnerer et tilfeldig tall mellom 0 og 1
-RANDBETWEEN = TILFELDIGMELLOM ## Returnerer et tilfeldig tall innenfor et angitt område
-ROMAN = ROMERTALL ## Konverterer vanlige tall til romertall, som tekst
-ROUND = AVRUND ## Avrunder et tall til et angitt antall sifre
-ROUNDDOWN = AVRUND.NED ## Avrunder et tall nedover, mot null
-ROUNDUP = AVRUND.OPP ## Runder av et tall oppover, bort fra null
-SERIESSUM = SUMMER.REKKE ## Returnerer summen av en geometrisk rekke, basert på formelen
-SIGN = FORTEGN ## Returnerer fortegnet for et tall
-SIN = SIN ## Returnerer sinus til en gitt vinkel
-SINH = SINH ## Returnerer den hyperbolske sinus til et tall
-SQRT = ROT ## Returnerer en positiv kvadratrot
-SQRTPI = ROTPI ## Returnerer kvadratroten av (tall * pi)
-SUBTOTAL = DELSUM ## Returnerer en delsum i en liste eller database
-SUM = SUMMER ## Legger sammen argumentene
-SUMIF = SUMMERHVIS ## Legger sammen cellene angitt ved et gitt vilkår
-SUMIFS = SUMMER.HVIS.SETT ## Legger sammen cellene i et område som oppfyller flere vilkår
-SUMPRODUCT = SUMMERPRODUKT ## Returnerer summen av produktene av tilsvarende matrisekomponenter
-SUMSQ = SUMMERKVADRAT ## Returnerer kvadratsummen av argumentene
-SUMX2MY2 = SUMMERX2MY2 ## Returnerer summen av differansen av kvadratene for tilsvarende verdier i to matriser
-SUMX2PY2 = SUMMERX2PY2 ## Returnerer summen av kvadratsummene for tilsvarende verdier i to matriser
-SUMXMY2 = SUMMERXMY2 ## Returnerer summen av kvadratene av differansen for tilsvarende verdier i to matriser
-TAN = TAN ## Returnerer tangens for et tall
-TANH = TANH ## Returnerer den hyperbolske tangens for et tall
-TRUNC = AVKORT ## Korter av et tall til et heltall
-
-
-##
-## Statistical functions Statistiske funksjoner
-##
-AVEDEV = GJENNOMSNITTSAVVIK ## Returnerer datapunktenes gjennomsnittlige absoluttavvik fra middelverdien
-AVERAGE = GJENNOMSNITT ## Returnerer gjennomsnittet for argumentene
-AVERAGEA = GJENNOMSNITTA ## Returnerer gjennomsnittet for argumentene, inkludert tall, tekst og logiske verdier
-AVERAGEIF = GJENNOMSNITTHVIS ## Returnerer gjennomsnittet (aritmetisk gjennomsnitt) av alle cellene i et område som oppfyller et bestemt vilkår
-AVERAGEIFS = GJENNOMSNITT.HVIS.SETT ## Returnerer gjennomsnittet (aritmetisk middelverdi) av alle celler som oppfyller flere vilkår.
-BETADIST = BETA.FORDELING ## Returnerer den kumulative betafordelingsfunksjonen
-BETAINV = INVERS.BETA.FORDELING ## Returnerer den inverse verdien til fordelingsfunksjonen for en angitt betafordeling
-BINOMDIST = BINOM.FORDELING ## Returnerer den individuelle binomiske sannsynlighetsfordelingen
-CHIDIST = KJI.FORDELING ## Returnerer den ensidige sannsynligheten for en kjikvadrert fordeling
-CHIINV = INVERS.KJI.FORDELING ## Returnerer den inverse av den ensidige sannsynligheten for den kjikvadrerte fordelingen
-CHITEST = KJI.TEST ## Utfører testen for uavhengighet
-CONFIDENCE = KONFIDENS ## Returnerer konfidensintervallet til gjennomsnittet for en populasjon
-CORREL = KORRELASJON ## Returnerer korrelasjonskoeffisienten mellom to datasett
-COUNT = ANTALL ## Teller hvor mange tall som er i argumentlisten
-COUNTA = ANTALLA ## Teller hvor mange verdier som er i argumentlisten
-COUNTBLANK = TELLBLANKE ## Teller antall tomme celler i et område.
-COUNTIF = ANTALL.HVIS ## Teller antall celler i et område som oppfyller gitte vilkår
-COUNTIFS = ANTALL.HVIS.SETT ## Teller antallet ikke-tomme celler i et område som oppfyller flere vilkår
-COVAR = KOVARIANS ## Returnerer kovariansen, gjennomsnittet av produktene av parvise avvik
-CRITBINOM = GRENSE.BINOM ## Returnerer den minste verdien der den kumulative binomiske fordelingen er mindre enn eller lik en vilkårsverdi
-DEVSQ = AVVIK.KVADRERT ## Returnerer summen av kvadrerte avvik
-EXPONDIST = EKSP.FORDELING ## Returnerer eksponentialfordelingen
-FDIST = FFORDELING ## Returnerer F-sannsynlighetsfordelingen
-FINV = FFORDELING.INVERS ## Returnerer den inverse av den sannsynlige F-fordelingen
-FISHER = FISHER ## Returnerer Fisher-transformasjonen
-FISHERINV = FISHERINV ## Returnerer den inverse av Fisher-transformasjonen
-FORECAST = PROGNOSE ## Returnerer en verdi langs en lineær trend
-FREQUENCY = FREKVENS ## Returnerer en frekvensdistribusjon som en loddrett matrise
-FTEST = FTEST ## Returnerer resultatet av en F-test
-GAMMADIST = GAMMAFORDELING ## Returnerer gammafordelingen
-GAMMAINV = GAMMAINV ## Returnerer den inverse av den gammakumulative fordelingen
-GAMMALN = GAMMALN ## Returnerer den naturlige logaritmen til gammafunksjonen G(x)
-GEOMEAN = GJENNOMSNITT.GEOMETRISK ## Returnerer den geometriske middelverdien
-GROWTH = VEKST ## Returnerer verdier langs en eksponentiell trend
-HARMEAN = GJENNOMSNITT.HARMONISK ## Returnerer den harmoniske middelverdien
-HYPGEOMDIST = HYPGEOM.FORDELING ## Returnerer den hypergeometriske fordelingen
-INTERCEPT = SKJÆRINGSPUNKT ## Returnerer skjæringspunktet til den lineære regresjonslinjen
-KURT = KURT ## Returnerer kurtosen til et datasett
-LARGE = N.STØRST ## Returnerer den n-te største verdien i et datasett
-LINEST = RETTLINJE ## Returnerer parameterne til en lineær trend
-LOGEST = KURVE ## Returnerer parameterne til en eksponentiell trend
-LOGINV = LOGINV ## Returnerer den inverse lognormale fordelingen
-LOGNORMDIST = LOGNORMFORD ## Returnerer den kumulative lognormale fordelingen
-MAX = STØRST ## Returnerer maksimumsverdien i en argumentliste
-MAXA = MAKSA ## Returnerer maksimumsverdien i en argumentliste, inkludert tall, tekst og logiske verdier
-MEDIAN = MEDIAN ## Returnerer medianen til tallene som er gitt
-MIN = MIN ## Returnerer minimumsverdien i en argumentliste
-MINA = MINA ## Returnerer den minste verdien i en argumentliste, inkludert tall, tekst og logiske verdier
-MODE = MODUS ## Returnerer den vanligste verdien i et datasett
-NEGBINOMDIST = NEGBINOM.FORDELING ## Returnerer den negative binomiske fordelingen
-NORMDIST = NORMALFORDELING ## Returnerer den kumulative normalfordelingen
-NORMINV = NORMINV ## Returnerer den inverse kumulative normalfordelingen
-NORMSDIST = NORMSFORDELING ## Returnerer standard kumulativ normalfordeling
-NORMSINV = NORMSINV ## Returnerer den inverse av den den kumulative standard normalfordelingen
-PEARSON = PEARSON ## Returnerer produktmomentkorrelasjonskoeffisienten, Pearson
-PERCENTILE = PERSENTIL ## Returnerer den n-te persentil av verdiene i et område
-PERCENTRANK = PROSENTDEL ## Returnerer prosentrangeringen av en verdi i et datasett
-PERMUT = PERMUTER ## Returnerer antall permutasjoner for et gitt antall objekter
-POISSON = POISSON ## Returnerer Poissons sannsynlighetsfordeling
-PROB = SANNSYNLIG ## Returnerer sannsynligheten for at verdier i et område ligger mellom to grenser
-QUARTILE = KVARTIL ## Returnerer kvartilen til et datasett
-RANK = RANG ## Returnerer rangeringen av et tall, eller plassen tallet har i en rekke
-RSQ = RKVADRAT ## Returnerer kvadratet av produktmomentkorrelasjonskoeffisienten (Pearsons r)
-SKEW = SKJEVFORDELING ## Returnerer skjevheten i en fordeling
-SLOPE = STIGNINGSTALL ## Returnerer stigningtallet for den lineære regresjonslinjen
-SMALL = N.MINST ## Returnerer den n-te minste verdien i et datasett
-STANDARDIZE = NORMALISER ## Returnerer en normalisert verdi
-STDEV = STDAV ## Estimere standardavvik på grunnlag av et utvalg
-STDEVA = STDAVVIKA ## Estimerer standardavvik basert på et utvalg, inkludert tall, tekst og logiske verdier
-STDEVP = STDAVP ## Beregner standardavvik basert på hele populasjonen
-STDEVPA = STDAVVIKPA ## Beregner standardavvik basert på hele populasjonen, inkludert tall, tekst og logiske verdier
-STEYX = STANDARDFEIL ## Returnerer standardfeilen for den predikerte y-verdien for hver x i regresjonen
-TDIST = TFORDELING ## Returnerer en Student t-fordeling
-TINV = TINV ## Returnerer den inverse Student t-fordelingen
-TREND = TREND ## Returnerer verdier langs en lineær trend
-TRIMMEAN = TRIMMET.GJENNOMSNITT ## Returnerer den interne middelverdien til et datasett
-TTEST = TTEST ## Returnerer sannsynligheten assosiert med en Student t-test
-VAR = VARIANS ## Estimerer varians basert på et utvalg
-VARA = VARIANSA ## Estimerer varians basert på et utvalg, inkludert tall, tekst og logiske verdier
-VARP = VARIANSP ## Beregner varians basert på hele populasjonen
-VARPA = VARIANSPA ## Beregner varians basert på hele populasjonen, inkludert tall, tekst og logiske verdier
-WEIBULL = WEIBULL.FORDELING ## Returnerer Weibull-fordelingen
-ZTEST = ZTEST ## Returnerer den ensidige sannsynlighetsverdien for en z-test
-
-
-##
-## Text functions Tekstfunksjoner
-##
-ASC = STIGENDE ## Endrer fullbreddes (dobbeltbyte) engelske bokstaver eller katakana i en tegnstreng, til halvbreddes (enkeltbyte) tegn
-BAHTTEXT = BAHTTEKST ## Konverterer et tall til tekst, og bruker valutaformatet ß (baht)
-CHAR = TEGNKODE ## Returnerer tegnet som svarer til kodenummeret
-CLEAN = RENSK ## Fjerner alle tegn som ikke kan skrives ut, fra teksten
-CODE = KODE ## Returnerer en numerisk kode for det første tegnet i en tekststreng
-CONCATENATE = KJEDE.SAMMEN ## Slår sammen flere tekstelementer til ett tekstelement
-DOLLAR = VALUTA ## Konverterer et tall til tekst, og bruker valutaformatet $ (dollar)
-EXACT = EKSAKT ## Kontrollerer om to tekstverdier er like
-FIND = FINN ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver)
-FINDB = FINNB ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver)
-FIXED = FASTSATT ## Formaterer et tall som tekst med et bestemt antall desimaler
-JIS = JIS ## Endrer halvbreddes (enkeltbyte) engelske bokstaver eller katakana i en tegnstreng, til fullbreddes (dobbeltbyte) tegn
-LEFT = VENSTRE ## Returnerer tegnene lengst til venstre i en tekstverdi
-LEFTB = VENSTREB ## Returnerer tegnene lengst til venstre i en tekstverdi
-LEN = LENGDE ## Returnerer antall tegn i en tekststreng
-LENB = LENGDEB ## Returnerer antall tegn i en tekststreng
-LOWER = SMÅ ## Konverterer tekst til små bokstaver
-MID = DELTEKST ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir
-MIDB = DELTEKSTB ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir
-PHONETIC = FURIGANA ## Trekker ut fonetiske tegn (furigana) fra en tekststreng
-PROPER = STOR.FORBOKSTAV ## Gir den første bokstaven i hvert ord i en tekstverdi stor forbokstav
-REPLACE = ERSTATT ## Erstatter tegn i en tekst
-REPLACEB = ERSTATTB ## Erstatter tegn i en tekst
-REPT = GJENTA ## Gjentar tekst et gitt antall ganger
-RIGHT = HØYRE ## Returnerer tegnene lengst til høyre i en tekstverdi
-RIGHTB = HØYREB ## Returnerer tegnene lengst til høyre i en tekstverdi
-SEARCH = SØK ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver)
-SEARCHB = SØKB ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver)
-SUBSTITUTE = BYTT.UT ## Bytter ut gammel tekst med ny tekst i en tekststreng
-T = T ## Konverterer argumentene til tekst
-TEXT = TEKST ## Formaterer et tall og konverterer det til tekst
-TRIM = TRIMME ## Fjerner mellomrom fra tekst
-UPPER = STORE ## Konverterer tekst til store bokstaver
-VALUE = VERDI ## Konverterer et tekstargument til et tall
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/config
index 00f8b9a340b..1d8468ba38b 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Jezyk polski (Polish)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = zł
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #ZERO!
-DIV0 = #DZIEL/0!
-VALUE = #ARG!
-REF = #ADR!
-NAME = #NAZWA?
-NUM = #LICZBA!
-NA = #N/D!
+NULL = #ZERO!
+DIV0 = #DZIEL/0!
+VALUE = #ARG!
+REF = #ADR!
+NAME = #NAZWA?
+NUM = #LICZBA!
+NA = #N/D!
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/functions
index 907a4ff0f8e..d1b43b2ecf2 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/functions
@@ -1,416 +1,536 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
+## PhpSpreadsheet - function name translations
##
+## Jezyk polski (Polish)
##
+############################################################
##
-## Add-in and Automation functions Funkcje dodatków i automatyzacji
+## Funkcje baz danych (Cube Functions)
##
-GETPIVOTDATA = WEŹDANETABELI ## Zwraca dane przechowywane w raporcie tabeli przestawnej.
-
+CUBEKPIMEMBER = ELEMENT.KPI.MODUŁU
+CUBEMEMBER = ELEMENT.MODUŁU
+CUBEMEMBERPROPERTY = WŁAŚCIWOŚĆ.ELEMENTU.MODUŁU
+CUBERANKEDMEMBER = USZEREGOWANY.ELEMENT.MODUŁU
+CUBESET = ZESTAW.MODUŁÓW
+CUBESETCOUNT = LICZNIK.MODUŁÓW.ZESTAWU
+CUBEVALUE = WARTOŚĆ.MODUŁU
##
-## Cube functions Funkcje modułów
+## Funkcje baz danych (Database Functions)
##
-CUBEKPIMEMBER = ELEMENT.KPI.MODUŁU ## Zwraca nazwę, właściwość i miarę kluczowego wskaźnika wydajności (KPI) oraz wyświetla nazwę i właściwość w komórce. Wskaźnik KPI jest miarą ilościową, taką jak miesięczny zysk brutto lub kwartalna fluktuacja pracowników, używaną do monitorowania wydajności organizacji.
-CUBEMEMBER = ELEMENT.MODUŁU ## Zwraca element lub krotkę z hierarchii modułu. Służy do sprawdzania, czy element lub krotka istnieje w module.
-CUBEMEMBERPROPERTY = WŁAŚCIWOŚĆ.ELEMENTU.MODUŁU ## Zwraca wartość właściwości elementu w module. Służy do sprawdzania, czy nazwa elementu istnieje w module, i zwracania określonej właściwości dla tego elementu.
-CUBERANKEDMEMBER = USZEREGOWANY.ELEMENT.MODUŁU ## Zwraca n-ty (albo uszeregowany) element zestawu. Służy do zwracania elementu lub elementów zestawu, na przykład najlepszego sprzedawcy lub 10 najlepszych studentów.
-CUBESET = ZESTAW.MODUŁÓW ## Definiuje obliczony zestaw elementów lub krotek, wysyłając wyrażenie zestawu do serwera modułu, który tworzy zestaw i zwraca go do programu Microsoft Office Excel.
-CUBESETCOUNT = LICZNIK.MODUŁÓW.ZESTAWU ## Zwraca liczbę elementów zestawu.
-CUBEVALUE = WARTOŚĆ.MODUŁU ## Zwraca zagregowaną wartość z modułu.
-
+DAVERAGE = BD.ŚREDNIA
+DCOUNT = BD.ILE.REKORDÓW
+DCOUNTA = BD.ILE.REKORDÓW.A
+DGET = BD.POLE
+DMAX = BD.MAX
+DMIN = BD.MIN
+DPRODUCT = BD.ILOCZYN
+DSTDEV = BD.ODCH.STANDARD
+DSTDEVP = BD.ODCH.STANDARD.POPUL
+DSUM = BD.SUMA
+DVAR = BD.WARIANCJA
+DVARP = BD.WARIANCJA.POPUL
##
-## Database functions Funkcje baz danych
+## Funkcje daty i godziny (Date & Time Functions)
##
-DAVERAGE = BD.ŚREDNIA ## Zwraca wartość średniej wybranych wpisów bazy danych.
-DCOUNT = BD.ILE.REKORDÓW ## Zlicza komórki zawierające liczby w bazie danych.
-DCOUNTA = BD.ILE.REKORDÓW.A ## Zlicza niepuste komórki w bazie danych.
-DGET = BD.POLE ## Wyodrębnia z bazy danych jeden rekord spełniający określone kryteria.
-DMAX = BD.MAX ## Zwraca wartość maksymalną z wybranych wpisów bazy danych.
-DMIN = BD.MIN ## Zwraca wartość minimalną z wybranych wpisów bazy danych.
-DPRODUCT = BD.ILOCZYN ## Mnoży wartości w konkretnym, spełniającym kryteria polu rekordów bazy danych.
-DSTDEV = BD.ODCH.STANDARD ## Szacuje odchylenie standardowe na podstawie próbki z wybranych wpisów bazy danych.
-DSTDEVP = BD.ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji wybranych wpisów bazy danych.
-DSUM = BD.SUMA ## Dodaje liczby w kolumnie pól rekordów bazy danych, które spełniają kryteria.
-DVAR = BD.WARIANCJA ## Szacuje wariancję na podstawie próbki z wybranych wpisów bazy danych.
-DVARP = BD.WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji wybranych wpisów bazy danych.
-
+DATE = DATA
+DATEDIF = DATA.RÓŻNICA
+DATESTRING = DATA.CIĄG.ZNAK
+DATEVALUE = DATA.WARTOŚĆ
+DAY = DZIEŃ
+DAYS = DNI
+DAYS360 = DNI.360
+EDATE = NR.SER.DATY
+EOMONTH = NR.SER.OST.DN.MIES
+HOUR = GODZINA
+ISOWEEKNUM = ISO.NUM.TYG
+MINUTE = MINUTA
+MONTH = MIESIĄC
+NETWORKDAYS = DNI.ROBOCZE
+NETWORKDAYS.INTL = DNI.ROBOCZE.NIESTAND
+NOW = TERAZ
+SECOND = SEKUNDA
+THAIDAYOFWEEK = TAJ.DZIEŃ.TYGODNIA
+THAIMONTHOFYEAR = TAJ.MIESIĄC.ROKU
+THAIYEAR = TAJ.ROK
+TIME = CZAS
+TIMEVALUE = CZAS.WARTOŚĆ
+TODAY = DZIŚ
+WEEKDAY = DZIEŃ.TYG
+WEEKNUM = NUM.TYG
+WORKDAY = DZIEŃ.ROBOCZY
+WORKDAY.INTL = DZIEŃ.ROBOCZY.NIESTAND
+YEAR = ROK
+YEARFRAC = CZĘŚĆ.ROKU
##
-## Date and time functions Funkcje dat, godzin i czasu
+## Funkcje inżynierskie (Engineering Functions)
##
-DATE = DATA ## Zwraca liczbę seryjną dla wybranej daty.
-DATEVALUE = DATA.WARTOŚĆ ## Konwertuje datę w formie tekstu na liczbę seryjną.
-DAY = DZIEŃ ## Konwertuje liczbę seryjną na dzień miesiąca.
-DAYS360 = DNI.360 ## Oblicza liczbę dni między dwiema datami na podstawie roku 360-dniowego.
-EDATE = UPŁDNI ## Zwraca liczbę seryjną daty jako wskazaną liczbę miesięcy przed określoną datą początkową lub po niej.
-EOMONTH = EOMONTH ## Zwraca liczbę seryjną ostatniego dnia miesiąca przed określoną liczbą miesięcy lub po niej.
-HOUR = GODZINA ## Konwertuje liczbę seryjną na godzinę.
-MINUTE = MINUTA ## Konwertuje liczbę seryjną na minutę.
-MONTH = MIESIĄC ## Konwertuje liczbę seryjną na miesiąc.
-NETWORKDAYS = NETWORKDAYS ## Zwraca liczbę pełnych dni roboczych między dwiema datami.
-NOW = TERAZ ## Zwraca liczbę seryjną bieżącej daty i godziny.
-SECOND = SEKUNDA ## Konwertuje liczbę seryjną na sekundę.
-TIME = CZAS ## Zwraca liczbę seryjną określonego czasu.
-TIMEVALUE = CZAS.WARTOŚĆ ## Konwertuje czas w formie tekstu na liczbę seryjną.
-TODAY = DZIŚ ## Zwraca liczbę seryjną dla daty bieżącej.
-WEEKDAY = DZIEŃ.TYG ## Konwertuje liczbę seryjną na dzień tygodnia.
-WEEKNUM = WEEKNUM ## Konwertuje liczbę seryjną na liczbę reprezentującą numer tygodnia w roku.
-WORKDAY = WORKDAY ## Zwraca liczbę seryjną dla daty przed określoną liczbą dni roboczych lub po niej.
-YEAR = ROK ## Konwertuje liczbę seryjną na rok.
-YEARFRAC = YEARFRAC ## Zwraca część roku reprezentowaną przez pełną liczbę dni między datą początkową a datą końcową.
-
+BESSELI = BESSEL.I
+BESSELJ = BESSEL.J
+BESSELK = BESSEL.K
+BESSELY = BESSEL.Y
+BIN2DEC = DWÓJK.NA.DZIES
+BIN2HEX = DWÓJK.NA.SZESN
+BIN2OCT = DWÓJK.NA.ÓSM
+BITAND = BITAND
+BITLSHIFT = BIT.PRZESUNIĘCIE.W.LEWO
+BITOR = BITOR
+BITRSHIFT = BIT.PRZESUNIĘCIE.W.PRAWO
+BITXOR = BITXOR
+COMPLEX = LICZBA.ZESP
+CONVERT = KONWERTUJ
+DEC2BIN = DZIES.NA.DWÓJK
+DEC2HEX = DZIES.NA.SZESN
+DEC2OCT = DZIES.NA.ÓSM
+DELTA = CZY.RÓWNE
+ERF = FUNKCJA.BŁ
+ERF.PRECISE = FUNKCJA.BŁ.DOKŁ
+ERFC = KOMP.FUNKCJA.BŁ
+ERFC.PRECISE = KOMP.FUNKCJA.BŁ.DOKŁ
+GESTEP = SPRAWDŹ.PRÓG
+HEX2BIN = SZESN.NA.DWÓJK
+HEX2DEC = SZESN.NA.DZIES
+HEX2OCT = SZESN.NA.ÓSM
+IMABS = MODUŁ.LICZBY.ZESP
+IMAGINARY = CZ.UROJ.LICZBY.ZESP
+IMARGUMENT = ARG.LICZBY.ZESP
+IMCONJUGATE = SPRZĘŻ.LICZBY.ZESP
+IMCOS = COS.LICZBY.ZESP
+IMCOSH = COSH.LICZBY.ZESP
+IMCOT = COT.LICZBY.ZESP
+IMCSC = CSC.LICZBY.ZESP
+IMCSCH = CSCH.LICZBY.ZESP
+IMDIV = ILORAZ.LICZB.ZESP
+IMEXP = EXP.LICZBY.ZESP
+IMLN = LN.LICZBY.ZESP
+IMLOG10 = LOG10.LICZBY.ZESP
+IMLOG2 = LOG2.LICZBY.ZESP
+IMPOWER = POTĘGA.LICZBY.ZESP
+IMPRODUCT = ILOCZYN.LICZB.ZESP
+IMREAL = CZ.RZECZ.LICZBY.ZESP
+IMSEC = SEC.LICZBY.ZESP
+IMSECH = SECH.LICZBY.ZESP
+IMSIN = SIN.LICZBY.ZESP
+IMSINH = SINH.LICZBY.ZESP
+IMSQRT = PIERWIASTEK.LICZBY.ZESP
+IMSUB = RÓŻN.LICZB.ZESP
+IMSUM = SUMA.LICZB.ZESP
+IMTAN = TAN.LICZBY.ZESP
+OCT2BIN = ÓSM.NA.DWÓJK
+OCT2DEC = ÓSM.NA.DZIES
+OCT2HEX = ÓSM.NA.SZESN
##
-## Engineering functions Funkcje inżynierskie
+## Funkcje finansowe (Financial Functions)
##
-BESSELI = BESSELI ## Zwraca wartość zmodyfikowanej funkcji Bessela In(x).
-BESSELJ = BESSELJ ## Zwraca wartość funkcji Bessela Jn(x).
-BESSELK = BESSELK ## Zwraca wartość zmodyfikowanej funkcji Bessela Kn(x).
-BESSELY = BESSELY ## Zwraca wartość funkcji Bessela Yn(x).
-BIN2DEC = BIN2DEC ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci dziesiętnej.
-BIN2HEX = BIN2HEX ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci szesnastkowej.
-BIN2OCT = BIN2OCT ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci ósemkowej.
-COMPLEX = COMPLEX ## Konwertuje część rzeczywistą i urojoną na liczbę zespoloną.
-CONVERT = CONVERT ## Konwertuje liczbę z jednego systemu miar na inny.
-DEC2BIN = DEC2BIN ## Konwertuje liczbę w postaci dziesiętnej na postać dwójkową.
-DEC2HEX = DEC2HEX ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci szesnastkowej.
-DEC2OCT = DEC2OCT ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci ósemkowej.
-DELTA = DELTA ## Sprawdza, czy dwie wartości są równe.
-ERF = ERF ## Zwraca wartość funkcji błędu.
-ERFC = ERFC ## Zwraca wartość komplementarnej funkcji błędu.
-GESTEP = GESTEP ## Sprawdza, czy liczba jest większa niż wartość progowa.
-HEX2BIN = HEX2BIN ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dwójkowej.
-HEX2DEC = HEX2DEC ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dziesiętnej.
-HEX2OCT = HEX2OCT ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci ósemkowej.
-IMABS = IMABS ## Zwraca wartość bezwzględną (moduł) liczby zespolonej.
-IMAGINARY = IMAGINARY ## Zwraca wartość części urojonej liczby zespolonej.
-IMARGUMENT = IMARGUMENT ## Zwraca wartość argumentu liczby zespolonej, przy czym kąt wyrażony jest w radianach.
-IMCONJUGATE = IMCONJUGATE ## Zwraca wartość liczby sprzężonej danej liczby zespolonej.
-IMCOS = IMCOS ## Zwraca wartość cosinusa liczby zespolonej.
-IMDIV = IMDIV ## Zwraca wartość ilorazu dwóch liczb zespolonych.
-IMEXP = IMEXP ## Zwraca postać wykładniczą liczby zespolonej.
-IMLN = IMLN ## Zwraca wartość logarytmu naturalnego liczby zespolonej.
-IMLOG10 = IMLOG10 ## Zwraca wartość logarytmu dziesiętnego liczby zespolonej.
-IMLOG2 = IMLOG2 ## Zwraca wartość logarytmu liczby zespolonej przy podstawie 2.
-IMPOWER = IMPOWER ## Zwraca wartość liczby zespolonej podniesionej do potęgi całkowitej.
-IMPRODUCT = IMPRODUCT ## Zwraca wartość iloczynu liczb zespolonych.
-IMREAL = IMREAL ## Zwraca wartość części rzeczywistej liczby zespolonej.
-IMSIN = IMSIN ## Zwraca wartość sinusa liczby zespolonej.
-IMSQRT = IMSQRT ## Zwraca wartość pierwiastka kwadratowego z liczby zespolonej.
-IMSUB = IMSUB ## Zwraca wartość różnicy dwóch liczb zespolonych.
-IMSUM = IMSUM ## Zwraca wartość sumy liczb zespolonych.
-OCT2BIN = OCT2BIN ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dwójkowej.
-OCT2DEC = OCT2DEC ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dziesiętnej.
-OCT2HEX = OCT2HEX ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci szesnastkowej.
-
+ACCRINT = NAL.ODS
+ACCRINTM = NAL.ODS.WYKUP
+AMORDEGRC = AMORT.NIELIN
+AMORLINC = AMORT.LIN
+COUPDAYBS = WYPŁ.DNI.OD.POCZ
+COUPDAYS = WYPŁ.DNI
+COUPDAYSNC = WYPŁ.DNI.NAST
+COUPNCD = WYPŁ.DATA.NAST
+COUPNUM = WYPŁ.LICZBA
+COUPPCD = WYPŁ.DATA.POPRZ
+CUMIPMT = SPŁAC.ODS
+CUMPRINC = SPŁAC.KAPIT
+DB = DB
+DDB = DDB
+DISC = STOPA.DYSK
+DOLLARDE = CENA.DZIES
+DOLLARFR = CENA.UŁAM
+DURATION = ROCZ.PRZYCH
+EFFECT = EFEKTYWNA
+FV = FV
+FVSCHEDULE = WART.PRZYSZŁ.KAP
+INTRATE = STOPA.PROC
+IPMT = IPMT
+IRR = IRR
+ISPMT = ISPMT
+MDURATION = ROCZ.PRZYCH.M
+MIRR = MIRR
+NOMINAL = NOMINALNA
+NPER = NPER
+NPV = NPV
+ODDFPRICE = CENA.PIERW.OKR
+ODDFYIELD = RENT.PIERW.OKR
+ODDLPRICE = CENA.OST.OKR
+ODDLYIELD = RENT.OST.OKR
+PDURATION = O.CZAS.TRWANIA
+PMT = PMT
+PPMT = PPMT
+PRICE = CENA
+PRICEDISC = CENA.DYSK
+PRICEMAT = CENA.WYKUP
+PV = PV
+RATE = RATE
+RECEIVED = KWOTA.WYKUP
+RRI = RÓWNOW.STOPA.PROC
+SLN = SLN
+SYD = SYD
+TBILLEQ = RENT.EKW.BS
+TBILLPRICE = CENA.BS
+TBILLYIELD = RENT.BS
+VDB = VDB
+XIRR = XIRR
+XNPV = XNPV
+YIELD = RENTOWNOŚĆ
+YIELDDISC = RENT.DYSK
+YIELDMAT = RENT.WYKUP
##
-## Financial functions Funkcje finansowe
+## Funkcje informacyjne (Information Functions)
##
-ACCRINT = ACCRINT ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem okresowym.
-ACCRINTM = ACCRINTM ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem w terminie wykupu.
-AMORDEGRC = AMORDEGRC ## Zwraca amortyzację dla każdego okresu rozliczeniowego z wykorzystaniem współczynnika amortyzacji.
-AMORLINC = AMORLINC ## Zwraca amortyzację dla każdego okresu rozliczeniowego.
-COUPDAYBS = COUPDAYBS ## Zwraca liczbę dni od początku okresu dywidendy do dnia rozliczeniowego.
-COUPDAYS = COUPDAYS ## Zwraca liczbę dni w okresie dywidendy, z uwzględnieniem dnia rozliczeniowego.
-COUPDAYSNC = COUPDAYSNC ## Zwraca liczbę dni od dnia rozliczeniowego do daty następnego dnia dywidendy.
-COUPNCD = COUPNCD ## Zwraca dzień następnej dywidendy po dniu rozliczeniowym.
-COUPNUM = COUPNUM ## Zwraca liczbę dywidend płatnych między dniem rozliczeniowym a dniem wykupu.
-COUPPCD = COUPPCD ## Zwraca dzień poprzedniej dywidendy przed dniem rozliczeniowym.
-CUMIPMT = CUMIPMT ## Zwraca wartość procentu składanego płatnego między dwoma okresami.
-CUMPRINC = CUMPRINC ## Zwraca wartość kapitału skumulowanego spłaty pożyczki między dwoma okresami.
-DB = DB ## Zwraca amortyzację środka trwałego w danym okresie metodą degresywną z zastosowaniem stałej bazowej.
-DDB = DDB ## Zwraca amortyzację środka trwałego za podany okres metodą degresywną z zastosowaniem podwójnej bazowej lub metodą określoną przez użytkownika.
-DISC = DISC ## Zwraca wartość stopy dyskontowej papieru wartościowego.
-DOLLARDE = DOLLARDE ## Konwertuje cenę w postaci ułamkowej na cenę wyrażoną w postaci dziesiętnej.
-DOLLARFR = DOLLARFR ## Konwertuje cenę wyrażoną w postaci dziesiętnej na cenę wyrażoną w postaci ułamkowej.
-DURATION = DURATION ## Zwraca wartość rocznego przychodu z papieru wartościowego o okresowych wypłatach oprocentowania.
-EFFECT = EFFECT ## Zwraca wartość efektywnej rocznej stopy procentowej.
-FV = FV ## Zwraca przyszłą wartość lokaty.
-FVSCHEDULE = FVSCHEDULE ## Zwraca przyszłą wartość kapitału początkowego wraz z szeregiem procentów składanych.
-INTRATE = INTRATE ## Zwraca wartość stopy procentowej papieru wartościowego całkowicie ulokowanego.
-IPMT = IPMT ## Zwraca wysokość spłaty oprocentowania lokaty za dany okres.
-IRR = IRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii przepływów gotówkowych.
-ISPMT = ISPMT ## Oblicza wysokość spłaty oprocentowania za dany okres lokaty.
-MDURATION = MDURATION ## Zwraca wartość zmodyfikowanego okresu Macauleya dla papieru wartościowego o założonej wartości nominalnej 100 zł.
-MIRR = MIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla przypadku, gdy dodatnie i ujemne przepływy gotówkowe mają różne stopy.
-NOMINAL = NOMINAL ## Zwraca wysokość nominalnej rocznej stopy procentowej.
-NPER = NPER ## Zwraca liczbę okresów dla lokaty.
-NPV = NPV ## Zwraca wartość bieżącą netto lokaty na podstawie szeregu okresowych przepływów gotówkowych i stopy dyskontowej.
-ODDFPRICE = ODDFPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym pierwszym okresem.
-ODDFYIELD = ODDFYIELD ## Zwraca rentowność papieru wartościowego z nietypowym pierwszym okresem.
-ODDLPRICE = ODDLPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym ostatnim okresem.
-ODDLYIELD = ODDLYIELD ## Zwraca rentowność papieru wartościowego z nietypowym ostatnim okresem.
-PMT = PMT ## Zwraca wartość okresowej płatności raty rocznej.
-PPMT = PPMT ## Zwraca wysokość spłaty kapitału w przypadku lokaty dla danego okresu.
-PRICE = PRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem okresowym.
-PRICEDISC = PRICEDISC ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego zdyskontowanego.
-PRICEMAT = PRICEMAT ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem w terminie wykupu.
-PV = PV ## Zwraca wartość bieżącą lokaty.
-RATE = RATE ## Zwraca wysokość stopy procentowej w okresie raty rocznej.
-RECEIVED = RECEIVED ## Zwraca wartość kapitału otrzymanego przy wykupie papieru wartościowego całkowicie ulokowanego.
-SLN = SLN ## Zwraca amortyzację środka trwałego za jeden okres metodą liniową.
-SYD = SYD ## Zwraca amortyzację środka trwałego za dany okres metodą sumy cyfr lat amortyzacji.
-TBILLEQ = TBILLEQ ## Zwraca rentowność ekwiwalentu obligacji dla bonu skarbowego.
-TBILLPRICE = TBILLPRICE ## Zwraca cenę za 100 zł wartości nominalnej bonu skarbowego.
-TBILLYIELD = TBILLYIELD ## Zwraca rentowność bonu skarbowego.
-VDB = VDB ## Oblicza amortyzację środka trwałego w danym okresie lub jego części metodą degresywną.
-XIRR = XIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych.
-XNPV = XNPV ## Zwraca wartość bieżącą netto dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych.
-YIELD = YIELD ## Zwraca rentowność papieru wartościowego z oprocentowaniem okresowym.
-YIELDDISC = YIELDDISC ## Zwraca roczną rentowność zdyskontowanego papieru wartościowego, na przykład bonu skarbowego.
-YIELDMAT = YIELDMAT ## Zwraca roczną rentowność papieru wartościowego oprocentowanego przy wykupie.
-
+CELL = KOMÓRKA
+ERROR.TYPE = NR.BŁĘDU
+INFO = INFO
+ISBLANK = CZY.PUSTA
+ISERR = CZY.BŁ
+ISERROR = CZY.BŁĄD
+ISEVEN = CZY.PARZYSTE
+ISFORMULA = CZY.FORMUŁA
+ISLOGICAL = CZY.LOGICZNA
+ISNA = CZY.BRAK
+ISNONTEXT = CZY.NIE.TEKST
+ISNUMBER = CZY.LICZBA
+ISODD = CZY.NIEPARZYSTE
+ISREF = CZY.ADR
+ISTEXT = CZY.TEKST
+N = N
+NA = BRAK
+SHEET = ARKUSZ
+SHEETS = ARKUSZE
+TYPE = TYP
##
-## Information functions Funkcje informacyjne
+## Funkcje logiczne (Logical Functions)
##
-CELL = KOMÓRKA ## Zwraca informacje o formacie, położeniu lub zawartości komórki.
-ERROR.TYPE = NR.BŁĘDU ## Zwraca liczbę odpowiadającą typowi błędu.
-INFO = INFO ## Zwraca informację o aktualnym środowisku pracy.
-ISBLANK = CZY.PUSTA ## Zwraca wartość PRAWDA, jeśli wartość jest pusta.
-ISERR = CZY.BŁ ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu, z wyjątkiem #N/D!.
-ISERROR = CZY.BŁĄD ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu.
-ISEVEN = ISEVEN ## Zwraca wartość PRAWDA, jeśli liczba jest parzysta.
-ISLOGICAL = CZY.LOGICZNA ## Zwraca wartość PRAWDA, jeśli wartość jest wartością logiczną.
-ISNA = CZY.BRAK ## Zwraca wartość PRAWDA, jeśli wartość jest wartością błędu #N/D!.
-ISNONTEXT = CZY.NIE.TEKST ## Zwraca wartość PRAWDA, jeśli wartość nie jest tekstem.
-ISNUMBER = CZY.LICZBA ## Zwraca wartość PRAWDA, jeśli wartość jest liczbą.
-ISODD = ISODD ## Zwraca wartość PRAWDA, jeśli liczba jest nieparzysta.
-ISREF = CZY.ADR ## Zwraca wartość PRAWDA, jeśli wartość jest odwołaniem.
-ISTEXT = CZY.TEKST ## Zwraca wartość PRAWDA, jeśli wartość jest tekstem.
-N = L ## Zwraca wartość przekonwertowaną na postać liczbową.
-NA = BRAK ## Zwraca wartość błędu #N/D!.
-TYPE = TYP ## Zwraca liczbę wskazującą typ danych wartości.
-
+AND = ORAZ
+FALSE = FAŁSZ
+IF = JEŻELI
+IFERROR = JEŻELI.BŁĄD
+IFNA = JEŻELI.ND
+IFS = WARUNKI
+NOT = NIE
+OR = LUB
+SWITCH = PRZEŁĄCZ
+TRUE = PRAWDA
+XOR = XOR
##
-## Logical functions Funkcje logiczne
+## Funkcje wyszukiwania i odwołań (Lookup & Reference Functions)
##
-AND = ORAZ ## Zwraca wartość PRAWDA, jeśli wszystkie argumenty mają wartość PRAWDA.
-FALSE = FAŁSZ ## Zwraca wartość logiczną FAŁSZ.
-IF = JEŻELI ## Określa warunek logiczny do sprawdzenia.
-IFERROR = JEŻELI.BŁĄD ## Zwraca określoną wartość, jeśli wynikiem obliczenia formuły jest błąd; w przeciwnym przypadku zwraca wynik formuły.
-NOT = NIE ## Odwraca wartość logiczną argumentu.
-OR = LUB ## Zwraca wartość PRAWDA, jeśli co najmniej jeden z argumentów ma wartość PRAWDA.
-TRUE = PRAWDA ## Zwraca wartość logiczną PRAWDA.
-
+ADDRESS = ADRES
+AREAS = OBSZARY
+CHOOSE = WYBIERZ
+COLUMN = NR.KOLUMNY
+COLUMNS = LICZBA.KOLUMN
+FORMULATEXT = FORMUŁA.TEKST
+GETPIVOTDATA = WEŹDANETABELI
+HLOOKUP = WYSZUKAJ.POZIOMO
+HYPERLINK = HIPERŁĄCZE
+INDEX = INDEKS
+INDIRECT = ADR.POŚR
+LOOKUP = WYSZUKAJ
+MATCH = PODAJ.POZYCJĘ
+OFFSET = PRZESUNIĘCIE
+ROW = WIERSZ
+ROWS = ILE.WIERSZY
+RTD = DANE.CZASU.RZECZ
+TRANSPOSE = TRANSPONUJ
+VLOOKUP = WYSZUKAJ.PIONOWO
##
-## Lookup and reference functions Funkcje wyszukiwania i odwołań
+## Funkcje matematyczne i trygonometryczne (Math & Trig Functions)
##
-ADDRESS = ADRES ## Zwraca odwołanie do jednej komórki w arkuszu jako wartość tekstową.
-AREAS = OBSZARY ## Zwraca liczbę obszarów występujących w odwołaniu.
-CHOOSE = WYBIERZ ## Wybiera wartość z listy wartości.
-COLUMN = NR.KOLUMNY ## Zwraca numer kolumny z odwołania.
-COLUMNS = LICZBA.KOLUMN ## Zwraca liczbę kolumn dla danego odwołania.
-HLOOKUP = WYSZUKAJ.POZIOMO ## Przegląda górny wiersz tablicy i zwraca wartość wskazanej komórki.
-HYPERLINK = HIPERŁĄCZE ## Tworzy skrót lub skok, który pozwala otwierać dokument przechowywany na serwerze sieciowym, w sieci intranet lub w Internecie.
-INDEX = INDEKS ## Używa indeksu do wybierania wartości z odwołania lub tablicy.
-INDIRECT = ADR.POŚR ## Zwraca odwołanie określone przez wartość tekstową.
-LOOKUP = WYSZUKAJ ## Wyszukuje wartości w wektorze lub tablicy.
-MATCH = PODAJ.POZYCJĘ ## Wyszukuje wartości w odwołaniu lub w tablicy.
-OFFSET = PRZESUNIĘCIE ## Zwraca adres przesunięty od danego odwołania.
-ROW = WIERSZ ## Zwraca numer wiersza odwołania.
-ROWS = ILE.WIERSZY ## Zwraca liczbę wierszy dla danego odwołania.
-RTD = RTD ## Pobiera dane w czasie rzeczywistym z programu obsługującego automatyzację COM (Automatyzacja: Sposób pracy z obiektami aplikacji pochodzącymi z innej aplikacji lub narzędzia projektowania. Nazywana wcześniej Automatyzacją OLE, Automatyzacja jest standardem przemysłowym i funkcją obiektowego modelu składników (COM, Component Object Model).).
-TRANSPOSE = TRANSPONUJ ## Zwraca transponowaną tablicę.
-VLOOKUP = WYSZUKAJ.PIONOWO ## Przeszukuje pierwszą kolumnę tablicy i przechodzi wzdłuż wiersza, aby zwrócić wartość komórki.
-
+ABS = MODUŁ.LICZBY
+ACOS = ACOS
+ACOSH = ACOSH
+ACOT = ACOT
+ACOTH = ACOTH
+AGGREGATE = AGREGUJ
+ARABIC = ARABSKIE
+ASIN = ASIN
+ASINH = ASINH
+ATAN = ATAN
+ATAN2 = ATAN2
+ATANH = ATANH
+BASE = PODSTAWA
+CEILING.MATH = ZAOKR.W.GÓRĘ.MATEMATYCZNE
+CEILING.PRECISE = ZAOKR.W.GÓRĘ.DOKŁ
+COMBIN = KOMBINACJE
+COMBINA = KOMBINACJE.A
+COS = COS
+COSH = COSH
+COT = COT
+COTH = COTH
+CSC = CSC
+CSCH = CSCH
+DECIMAL = DZIESIĘTNA
+DEGREES = STOPNIE
+ECMA.CEILING = ECMA.ZAOKR.W.GÓRĘ
+EVEN = ZAOKR.DO.PARZ
+EXP = EXP
+FACT = SILNIA
+FACTDOUBLE = SILNIA.DWUKR
+FLOOR.MATH = ZAOKR.W.DÓŁ.MATEMATYCZNE
+FLOOR.PRECISE = ZAOKR.W.DÓŁ.DOKŁ
+GCD = NAJW.WSP.DZIEL
+INT = ZAOKR.DO.CAŁK
+ISO.CEILING = ISO.ZAOKR.W.GÓRĘ
+LCM = NAJMN.WSP.WIEL
+LN = LN
+LOG = LOG
+LOG10 = LOG10
+MDETERM = WYZNACZNIK.MACIERZY
+MINVERSE = MACIERZ.ODW
+MMULT = MACIERZ.ILOCZYN
+MOD = MOD
+MROUND = ZAOKR.DO.WIELOKR
+MULTINOMIAL = WIELOMIAN
+MUNIT = MACIERZ.JEDNOSTKOWA
+ODD = ZAOKR.DO.NPARZ
+PI = PI
+POWER = POTĘGA
+PRODUCT = ILOCZYN
+QUOTIENT = CZ.CAŁK.DZIELENIA
+RADIANS = RADIANY
+RAND = LOS
+RANDBETWEEN = LOS.ZAKR
+ROMAN = RZYMSKIE
+ROUND = ZAOKR
+ROUNDBAHTDOWN = ZAOKR.DÓŁ.BAT
+ROUNDBAHTUP = ZAOKR.GÓRA.BAT
+ROUNDDOWN = ZAOKR.DÓŁ
+ROUNDUP = ZAOKR.GÓRA
+SEC = SEC
+SECH = SECH
+SERIESSUM = SUMA.SZER.POT
+SIGN = ZNAK.LICZBY
+SIN = SIN
+SINH = SINH
+SQRT = PIERWIASTEK
+SQRTPI = PIERW.PI
+SUBTOTAL = SUMY.CZĘŚCIOWE
+SUM = SUMA
+SUMIF = SUMA.JEŻELI
+SUMIFS = SUMA.WARUNKÓW
+SUMPRODUCT = SUMA.ILOCZYNÓW
+SUMSQ = SUMA.KWADRATÓW
+SUMX2MY2 = SUMA.X2.M.Y2
+SUMX2PY2 = SUMA.X2.P.Y2
+SUMXMY2 = SUMA.XMY.2
+TAN = TAN
+TANH = TANH
+TRUNC = LICZBA.CAŁK
##
-## Math and trigonometry functions Funkcje matematyczne i trygonometryczne
+## Funkcje statystyczne (Statistical Functions)
##
-ABS = MODUŁ.LICZBY ## Zwraca wartość absolutną liczby.
-ACOS = ACOS ## Zwraca arcus cosinus liczby.
-ACOSH = ACOSH ## Zwraca arcus cosinus hiperboliczny liczby.
-ASIN = ASIN ## Zwraca arcus sinus liczby.
-ASINH = ASINH ## Zwraca arcus sinus hiperboliczny liczby.
-ATAN = ATAN ## Zwraca arcus tangens liczby.
-ATAN2 = ATAN2 ## Zwraca arcus tangens liczby na podstawie współrzędnych x i y.
-ATANH = ATANH ## Zwraca arcus tangens hiperboliczny liczby.
-CEILING = ZAOKR.W.GÓRĘ ## Zaokrągla liczbę do najbliższej liczby całkowitej lub do najbliższej wielokrotności dokładności.
-COMBIN = KOMBINACJE ## Zwraca liczbę kombinacji dla danej liczby obiektów.
-COS = COS ## Zwraca cosinus liczby.
-COSH = COSH ## Zwraca cosinus hiperboliczny liczby.
-DEGREES = STOPNIE ## Konwertuje radiany na stopnie.
-EVEN = ZAOKR.DO.PARZ ## Zaokrągla liczbę w górę do najbliższej liczby parzystej.
-EXP = EXP ## Zwraca wartość liczby e podniesionej do potęgi określonej przez podaną liczbę.
-FACT = SILNIA ## Zwraca silnię liczby.
-FACTDOUBLE = FACTDOUBLE ## Zwraca podwójną silnię liczby.
-FLOOR = ZAOKR.W.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera.
-GCD = GCD ## Zwraca największy wspólny dzielnik.
-INT = ZAOKR.DO.CAŁK ## Zaokrągla liczbę w dół do najbliższej liczby całkowitej.
-LCM = LCM ## Zwraca najmniejszą wspólną wielokrotność.
-LN = LN ## Zwraca logarytm naturalny podanej liczby.
-LOG = LOG ## Zwraca logarytm danej liczby przy zadanej podstawie.
-LOG10 = LOG10 ## Zwraca logarytm dziesiętny liczby.
-MDETERM = WYZNACZNIK.MACIERZY ## Zwraca wyznacznik macierzy tablicy.
-MINVERSE = MACIERZ.ODW ## Zwraca odwrotność macierzy tablicy.
-MMULT = MACIERZ.ILOCZYN ## Zwraca iloczyn macierzy dwóch tablic.
-MOD = MOD ## Zwraca resztę z dzielenia.
-MROUND = MROUND ## Zwraca liczbę zaokrągloną do żądanej wielokrotności.
-MULTINOMIAL = MULTINOMIAL ## Zwraca wielomian dla zbioru liczb.
-ODD = ZAOKR.DO.NPARZ ## Zaokrągla liczbę w górę do najbliższej liczby nieparzystej.
-PI = PI ## Zwraca wartość liczby Pi.
-POWER = POTĘGA ## Zwraca liczbę podniesioną do potęgi.
-PRODUCT = ILOCZYN ## Mnoży argumenty.
-QUOTIENT = QUOTIENT ## Zwraca iloraz (całkowity).
-RADIANS = RADIANY ## Konwertuje stopnie na radiany.
-RAND = LOS ## Zwraca liczbę pseudolosową z zakresu od 0 do 1.
-RANDBETWEEN = RANDBETWEEN ## Zwraca liczbę pseudolosową z zakresu określonego przez podane argumenty.
-ROMAN = RZYMSKIE ## Konwertuje liczbę arabską na rzymską jako tekst.
-ROUND = ZAOKR ## Zaokrągla liczbę do określonej liczby cyfr.
-ROUNDDOWN = ZAOKR.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera.
-ROUNDUP = ZAOKR.GÓRA ## Zaokrągla liczbę w górę, w kierunku od zera.
-SERIESSUM = SERIESSUM ## Zwraca sumę szeregu potęgowego na podstawie wzoru.
-SIGN = ZNAK.LICZBY ## Zwraca znak liczby.
-SIN = SIN ## Zwraca sinus danego kąta.
-SINH = SINH ## Zwraca sinus hiperboliczny liczby.
-SQRT = PIERWIASTEK ## Zwraca dodatni pierwiastek kwadratowy.
-SQRTPI = SQRTPI ## Zwraca pierwiastek kwadratowy iloczynu (liczba * Pi).
-SUBTOTAL = SUMY.POŚREDNIE ## Zwraca sumę częściową listy lub bazy danych.
-SUM = SUMA ## Dodaje argumenty.
-SUMIF = SUMA.JEŻELI ## Dodaje komórki określone przez podane kryterium.
-SUMIFS = SUMA.WARUNKÓW ## Dodaje komórki w zakresie, które spełniają wiele kryteriów.
-SUMPRODUCT = SUMA.ILOCZYNÓW ## Zwraca sumę iloczynów odpowiednich elementów tablicy.
-SUMSQ = SUMA.KWADRATÓW ## Zwraca sumę kwadratów argumentów.
-SUMX2MY2 = SUMA.X2.M.Y2 ## Zwraca sumę różnic kwadratów odpowiednich wartości w dwóch tablicach.
-SUMX2PY2 = SUMA.X2.P.Y2 ## Zwraca sumę sum kwadratów odpowiednich wartości w dwóch tablicach.
-SUMXMY2 = SUMA.XMY.2 ## Zwraca sumę kwadratów różnic odpowiednich wartości w dwóch tablicach.
-TAN = TAN ## Zwraca tangens liczby.
-TANH = TANH ## Zwraca tangens hiperboliczny liczby.
-TRUNC = LICZBA.CAŁK ## Przycina liczbę do wartości całkowitej.
-
+AVEDEV = ODCH.ŚREDNIE
+AVERAGE = ŚREDNIA
+AVERAGEA = ŚREDNIA.A
+AVERAGEIF = ŚREDNIA.JEŻELI
+AVERAGEIFS = ŚREDNIA.WARUNKÓW
+BETA.DIST = ROZKŁ.BETA
+BETA.INV = ROZKŁ.BETA.ODWR
+BINOM.DIST = ROZKŁ.DWUM
+BINOM.DIST.RANGE = ROZKŁ.DWUM.ZAKRES
+BINOM.INV = ROZKŁ.DWUM.ODWR
+CHISQ.DIST = ROZKŁ.CHI
+CHISQ.DIST.RT = ROZKŁ.CHI.PS
+CHISQ.INV = ROZKŁ.CHI.ODWR
+CHISQ.INV.RT = ROZKŁ.CHI.ODWR.PS
+CHISQ.TEST = CHI.TEST
+CONFIDENCE.NORM = UFNOŚĆ.NORM
+CONFIDENCE.T = UFNOŚĆ.T
+CORREL = WSP.KORELACJI
+COUNT = ILE.LICZB
+COUNTA = ILE.NIEPUSTYCH
+COUNTBLANK = LICZ.PUSTE
+COUNTIF = LICZ.JEŻELI
+COUNTIFS = LICZ.WARUNKI
+COVARIANCE.P = KOWARIANCJA.POPUL
+COVARIANCE.S = KOWARIANCJA.PRÓBKI
+DEVSQ = ODCH.KWADRATOWE
+EXPON.DIST = ROZKŁ.EXP
+F.DIST = ROZKŁ.F
+F.DIST.RT = ROZKŁ.F.PS
+F.INV = ROZKŁ.F.ODWR
+F.INV.RT = ROZKŁ.F.ODWR.PS
+F.TEST = F.TEST
+FISHER = ROZKŁAD.FISHER
+FISHERINV = ROZKŁAD.FISHER.ODW
+FORECAST.ETS = REGLINX.ETS
+FORECAST.ETS.CONFINT = REGLINX.ETS.CONFINT
+FORECAST.ETS.SEASONALITY = REGLINX.ETS.SEZONOWOŚĆ
+FORECAST.ETS.STAT = REGLINX.ETS.STATYSTYKA
+FORECAST.LINEAR = REGLINX.LINIOWA
+FREQUENCY = CZĘSTOŚĆ
+GAMMA = GAMMA
+GAMMA.DIST = ROZKŁ.GAMMA
+GAMMA.INV = ROZKŁ.GAMMA.ODWR
+GAMMALN = ROZKŁAD.LIN.GAMMA
+GAMMALN.PRECISE = ROZKŁAD.LIN.GAMMA.DOKŁ
+GAUSS = GAUSS
+GEOMEAN = ŚREDNIA.GEOMETRYCZNA
+GROWTH = REGEXPW
+HARMEAN = ŚREDNIA.HARMONICZNA
+HYPGEOM.DIST = ROZKŁ.HIPERGEOM
+INTERCEPT = ODCIĘTA
+KURT = KURTOZA
+LARGE = MAX.K
+LINEST = REGLINP
+LOGEST = REGEXPP
+LOGNORM.DIST = ROZKŁ.LOG
+LOGNORM.INV = ROZKŁ.LOG.ODWR
+MAX = MAX
+MAXA = MAX.A
+MAXIFS = MAKS.WARUNKÓW
+MEDIAN = MEDIANA
+MIN = MIN
+MINA = MIN.A
+MINIFS = MIN.WARUNKÓW
+MODE.MULT = WYST.NAJCZĘŚCIEJ.TABL
+MODE.SNGL = WYST.NAJCZĘŚCIEJ.WART
+NEGBINOM.DIST = ROZKŁ.DWUM.PRZEC
+NORM.DIST = ROZKŁ.NORMALNY
+NORM.INV = ROZKŁ.NORMALNY.ODWR
+NORM.S.DIST = ROZKŁ.NORMALNY.S
+NORM.S.INV = ROZKŁ.NORMALNY.S.ODWR
+PEARSON = PEARSON
+PERCENTILE.EXC = PERCENTYL.PRZEDZ.OTW
+PERCENTILE.INC = PERCENTYL.PRZEDZ.ZAMK
+PERCENTRANK.EXC = PROC.POZ.PRZEDZ.OTW
+PERCENTRANK.INC = PROC.POZ.PRZEDZ.ZAMK
+PERMUT = PERMUTACJE
+PERMUTATIONA = PERMUTACJE.A
+PHI = PHI
+POISSON.DIST = ROZKŁ.POISSON
+PROB = PRAWDPD
+QUARTILE.EXC = KWARTYL.PRZEDZ.OTW
+QUARTILE.INC = KWARTYL.PRZEDZ.ZAMK
+RANK.AVG = POZYCJA.ŚR
+RANK.EQ = POZYCJA.NAJW
+RSQ = R.KWADRAT
+SKEW = SKOŚNOŚĆ
+SKEW.P = SKOŚNOŚĆ.P
+SLOPE = NACHYLENIE
+SMALL = MIN.K
+STANDARDIZE = NORMALIZUJ
+STDEV.P = ODCH.STAND.POPUL
+STDEV.S = ODCH.STANDARD.PRÓBKI
+STDEVA = ODCH.STANDARDOWE.A
+STDEVPA = ODCH.STANDARD.POPUL.A
+STEYX = REGBŁSTD
+T.DIST = ROZKŁ.T
+T.DIST.2T = ROZKŁ.T.DS
+T.DIST.RT = ROZKŁ.T.PS
+T.INV = ROZKŁ.T.ODWR
+T.INV.2T = ROZKŁ.T.ODWR.DS
+T.TEST = T.TEST
+TREND = REGLINW
+TRIMMEAN = ŚREDNIA.WEWN
+VAR.P = WARIANCJA.POP
+VAR.S = WARIANCJA.PRÓBKI
+VARA = WARIANCJA.A
+VARPA = WARIANCJA.POPUL.A
+WEIBULL.DIST = ROZKŁ.WEIBULL
+Z.TEST = Z.TEST
##
-## Statistical functions Funkcje statystyczne
+## Funkcje tekstowe (Text Functions)
##
-AVEDEV = ODCH.ŚREDNIE ## Zwraca średnią wartość odchyleń absolutnych punktów danych od ich wartości średniej.
-AVERAGE = ŚREDNIA ## Zwraca wartość średnią argumentów.
-AVERAGEA = ŚREDNIA.A ## Zwraca wartość średnią argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych.
-AVERAGEIF = ŚREDNIA.JEŻELI ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek w zakresie, które spełniają podane kryteria.
-AVERAGEIFS = ŚREDNIA.WARUNKÓW ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek, które spełniają jedno lub więcej kryteriów.
-BETADIST = ROZKŁAD.BETA ## Zwraca skumulowaną funkcję gęstości prawdopodobieństwa beta.
-BETAINV = ROZKŁAD.BETA.ODW ## Zwraca odwrotność skumulowanej funkcji gęstości prawdopodobieństwa beta.
-BINOMDIST = ROZKŁAD.DWUM ## Zwraca pojedynczy składnik dwumianowego rozkładu prawdopodobieństwa.
-CHIDIST = ROZKŁAD.CHI ## Zwraca wartość jednostronnego prawdopodobieństwa rozkładu chi-kwadrat.
-CHIINV = ROZKŁAD.CHI.ODW ## Zwraca odwrotność wartości jednostronnego prawdopodobieństwa rozkładu chi-kwadrat.
-CHITEST = TEST.CHI ## Zwraca test niezależności.
-CONFIDENCE = UFNOŚĆ ## Zwraca interwał ufności dla średniej populacji.
-CORREL = WSP.KORELACJI ## Zwraca współczynnik korelacji dwóch zbiorów danych.
-COUNT = ILE.LICZB ## Zlicza liczby znajdujące się na liście argumentów.
-COUNTA = ILE.NIEPUSTYCH ## Zlicza wartości znajdujące się na liście argumentów.
-COUNTBLANK = LICZ.PUSTE ## Zwraca liczbę pustych komórek w pewnym zakresie.
-COUNTIF = LICZ.JEŻELI ## Zlicza komórki wewnątrz zakresu, które spełniają podane kryteria.
-COUNTIFS = LICZ.WARUNKI ## Zlicza komórki wewnątrz zakresu, które spełniają wiele kryteriów.
-COVAR = KOWARIANCJA ## Zwraca kowariancję, czyli średnią wartość iloczynów odpowiednich odchyleń.
-CRITBINOM = PRÓG.ROZKŁAD.DWUM ## Zwraca najmniejszą wartość, dla której skumulowany rozkład dwumianowy jest mniejszy niż wartość kryterium lub równy jej.
-DEVSQ = ODCH.KWADRATOWE ## Zwraca sumę kwadratów odchyleń.
-EXPONDIST = ROZKŁAD.EXP ## Zwraca rozkład wykładniczy.
-FDIST = ROZKŁAD.F ## Zwraca rozkład prawdopodobieństwa F.
-FINV = ROZKŁAD.F.ODW ## Zwraca odwrotność rozkładu prawdopodobieństwa F.
-FISHER = ROZKŁAD.FISHER ## Zwraca transformację Fishera.
-FISHERINV = ROZKŁAD.FISHER.ODW ## Zwraca odwrotność transformacji Fishera.
-FORECAST = REGLINX ## Zwraca wartość trendu liniowego.
-FREQUENCY = CZĘSTOŚĆ ## Zwraca rozkład częstotliwości jako tablicę pionową.
-FTEST = TEST.F ## Zwraca wynik testu F.
-GAMMADIST = ROZKŁAD.GAMMA ## Zwraca rozkład gamma.
-GAMMAINV = ROZKŁAD.GAMMA.ODW ## Zwraca odwrotność skumulowanego rozkładu gamma.
-GAMMALN = ROZKŁAD.LIN.GAMMA ## Zwraca logarytm naturalny funkcji gamma, Γ(x).
-GEOMEAN = ŚREDNIA.GEOMETRYCZNA ## Zwraca średnią geometryczną.
-GROWTH = REGEXPW ## Zwraca wartości trendu wykładniczego.
-HARMEAN = ŚREDNIA.HARMONICZNA ## Zwraca średnią harmoniczną.
-HYPGEOMDIST = ROZKŁAD.HIPERGEOM ## Zwraca rozkład hipergeometryczny.
-INTERCEPT = ODCIĘTA ## Zwraca punkt przecięcia osi pionowej z linią regresji liniowej.
-KURT = KURTOZA ## Zwraca kurtozę zbioru danych.
-LARGE = MAX.K ## Zwraca k-tą największą wartość ze zbioru danych.
-LINEST = REGLINP ## Zwraca parametry trendu liniowego.
-LOGEST = REGEXPP ## Zwraca parametry trendu wykładniczego.
-LOGINV = ROZKŁAD.LOG.ODW ## Zwraca odwrotność rozkładu logarytmu naturalnego.
-LOGNORMDIST = ROZKŁAD.LOG ## Zwraca skumulowany rozkład logarytmu naturalnego.
-MAX = MAX ## Zwraca maksymalną wartość listy argumentów.
-MAXA = MAX.A ## Zwraca maksymalną wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych.
-MEDIAN = MEDIANA ## Zwraca medianę podanych liczb.
-MIN = MIN ## Zwraca minimalną wartość listy argumentów.
-MINA = MIN.A ## Zwraca najmniejszą wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych.
-MODE = WYST.NAJCZĘŚCIEJ ## Zwraca wartość najczęściej występującą w zbiorze danych.
-NEGBINOMDIST = ROZKŁAD.DWUM.PRZEC ## Zwraca ujemny rozkład dwumianowy.
-NORMDIST = ROZKŁAD.NORMALNY ## Zwraca rozkład normalny skumulowany.
-NORMINV = ROZKŁAD.NORMALNY.ODW ## Zwraca odwrotność rozkładu normalnego skumulowanego.
-NORMSDIST = ROZKŁAD.NORMALNY.S ## Zwraca standardowy rozkład normalny skumulowany.
-NORMSINV = ROZKŁAD.NORMALNY.S.ODW ## Zwraca odwrotność standardowego rozkładu normalnego skumulowanego.
-PEARSON = PEARSON ## Zwraca współczynnik korelacji momentu iloczynu Pearsona.
-PERCENTILE = PERCENTYL ## Wyznacza k-ty percentyl wartości w zakresie.
-PERCENTRANK = PROCENT.POZYCJA ## Zwraca procentową pozycję wartości w zbiorze danych.
-PERMUT = PERMUTACJE ## Zwraca liczbę permutacji dla danej liczby obiektów.
-POISSON = ROZKŁAD.POISSON ## Zwraca rozkład Poissona.
-PROB = PRAWDPD ## Zwraca prawdopodobieństwo, że wartości w zakresie leżą pomiędzy dwiema granicami.
-QUARTILE = KWARTYL ## Wyznacza kwartyl zbioru danych.
-RANK = POZYCJA ## Zwraca pozycję liczby na liście liczb.
-RSQ = R.KWADRAT ## Zwraca kwadrat współczynnika korelacji momentu iloczynu Pearsona.
-SKEW = SKOŚNOŚĆ ## Zwraca skośność rozkładu.
-SLOPE = NACHYLENIE ## Zwraca nachylenie linii regresji liniowej.
-SMALL = MIN.K ## Zwraca k-tą najmniejszą wartość ze zbioru danych.
-STANDARDIZE = NORMALIZUJ ## Zwraca wartość znormalizowaną.
-STDEV = ODCH.STANDARDOWE ## Szacuje odchylenie standardowe na podstawie próbki.
-STDEVA = ODCH.STANDARDOWE.A ## Szacuje odchylenie standardowe na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych.
-STDEVP = ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji.
-STDEVPA = ODCH.STANDARD.POPUL.A ## Oblicza odchylenie standardowe na podstawie całej populacji, z uwzględnieniem liczb, teksów i wartości logicznych.
-STEYX = REGBŁSTD ## Zwraca błąd standardowy przewidzianej wartości y dla każdej wartości x w regresji.
-TDIST = ROZKŁAD.T ## Zwraca rozkład t-Studenta.
-TINV = ROZKŁAD.T.ODW ## Zwraca odwrotność rozkładu t-Studenta.
-TREND = REGLINW ## Zwraca wartości trendu liniowego.
-TRIMMEAN = ŚREDNIA.WEWN ## Zwraca średnią wartość dla wnętrza zbioru danych.
-TTEST = TEST.T ## Zwraca prawdopodobieństwo związane z testem t-Studenta.
-VAR = WARIANCJA ## Szacuje wariancję na podstawie próbki.
-VARA = WARIANCJA.A ## Szacuje wariancję na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych.
-VARP = WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji.
-VARPA = WARIANCJA.POPUL.A ## Oblicza wariancję na podstawie całej populacji, z uwzględnieniem liczb, tekstów i wartości logicznych.
-WEIBULL = ROZKŁAD.WEIBULL ## Zwraca rozkład Weibulla.
-ZTEST = TEST.Z ## Zwraca wartość jednostronnego prawdopodobieństwa testu z.
-
+BAHTTEXT = BAT.TEKST
+CHAR = ZNAK
+CLEAN = OCZYŚĆ
+CODE = KOD
+CONCAT = ZŁĄCZ.TEKST
+DOLLAR = KWOTA
+EXACT = PORÓWNAJ
+FIND = ZNAJDŹ
+FIXED = ZAOKR.DO.TEKST
+ISTHAIDIGIT = CZY.CYFRA.TAJ
+LEFT = LEWY
+LEN = DŁ
+LOWER = LITERY.MAŁE
+MID = FRAGMENT.TEKSTU
+NUMBERSTRING = LICZBA.CIĄG.ZNAK
+NUMBERVALUE = WARTOŚĆ.LICZBOWA
+PROPER = Z.WIELKIEJ.LITERY
+REPLACE = ZASTĄP
+REPT = POWT
+RIGHT = PRAWY
+SEARCH = SZUKAJ.TEKST
+SUBSTITUTE = PODSTAW
+T = T
+TEXT = TEKST
+TEXTJOIN = POŁĄCZ.TEKSTY
+THAIDIGIT = TAJ.CYFRA
+THAINUMSOUND = TAJ.DŹWIĘK.NUM
+THAINUMSTRING = TAJ.CIĄG.NUM
+THAISTRINGLENGTH = TAJ.DŁUGOŚĆ.CIĄGU
+TRIM = USUŃ.ZBĘDNE.ODSTĘPY
+UNICHAR = ZNAK.UNICODE
+UNICODE = UNICODE
+UPPER = LITERY.WIELKIE
+VALUE = WARTOŚĆ
##
-## Text functions Funkcje tekstowe
+## Funkcje sieci Web (Web Functions)
##
-ASC = ASC ## Zamienia litery angielskie lub katakana o pełnej szerokości (dwubajtowe) w ciągu znaków na znaki o szerokości połówkowej (jednobajtowe).
-BAHTTEXT = BAHTTEXT ## Konwertuje liczbę na tekst, stosując format walutowy ß (baht).
-CHAR = ZNAK ## Zwraca znak o podanym numerze kodu.
-CLEAN = OCZYŚĆ ## Usuwa z tekstu wszystkie znaki, które nie mogą być drukowane.
-CODE = KOD ## Zwraca kod numeryczny pierwszego znaku w ciągu tekstowym.
-CONCATENATE = ZŁĄCZ.TEKSTY ## Łączy kilka oddzielnych tekstów w jeden tekst.
-DOLLAR = KWOTA ## Konwertuje liczbę na tekst, stosując format walutowy $ (dolar).
-EXACT = PORÓWNAJ ## Sprawdza identyczność dwóch wartości tekstowych.
-FIND = ZNAJDŹ ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter).
-FINDB = ZNAJDŹB ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter).
-FIXED = ZAOKR.DO.TEKST ## Formatuje liczbę jako tekst przy stałej liczbie miejsc dziesiętnych.
-JIS = JIS ## Zmienia litery angielskie lub katakana o szerokości połówkowej (jednobajtowe) w ciągu znaków na znaki o pełnej szerokości (dwubajtowe).
-LEFT = LEWY ## Zwraca skrajne lewe znaki z wartości tekstowej.
-LEFTB = LEWYB ## Zwraca skrajne lewe znaki z wartości tekstowej.
-LEN = DŁ ## Zwraca liczbę znaków ciągu tekstowego.
-LENB = DŁ.B ## Zwraca liczbę znaków ciągu tekstowego.
-LOWER = LITERY.MAŁE ## Konwertuje wielkie litery tekstu na małe litery.
-MID = FRAGMENT.TEKSTU ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji.
-MIDB = FRAGMENT.TEKSTU.B ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji.
-PHONETIC = PHONETIC ## Wybiera znaki fonetyczne (furigana) z ciągu tekstowego.
-PROPER = Z.WIELKIEJ.LITERY ## Zastępuje pierwszą literę każdego wyrazu tekstu wielką literą.
-REPLACE = ZASTĄP ## Zastępuje znaki w tekście.
-REPLACEB = ZASTĄP.B ## Zastępuje znaki w tekście.
-REPT = POWT ## Powiela tekst daną liczbę razy.
-RIGHT = PRAWY ## Zwraca skrajne prawe znaki z wartości tekstowej.
-RIGHTB = PRAWYB ## Zwraca skrajne prawe znaki z wartości tekstowej.
-SEARCH = SZUKAJ.TEKST ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter).
-SEARCHB = SZUKAJ.TEKST.B ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter).
-SUBSTITUTE = PODSTAW ## Podstawia nowy tekst w miejsce poprzedniego tekstu w ciągu tekstowym.
-T = T ## Konwertuje argumenty na tekst.
-TEXT = TEKST ## Formatuje liczbę i konwertuje ją na tekst.
-TRIM = USUŃ.ZBĘDNE.ODSTĘPY ## Usuwa spacje z tekstu.
-UPPER = LITERY.WIELKIE ## Konwertuje znaki tekstu na wielkie litery.
-VALUE = WARTOŚĆ ## Konwertuje argument tekstowy na liczbę.
+ENCODEURL = ENCODEURL
+FILTERXML = FILTERXML
+WEBSERVICE = WEBSERVICE
+
+##
+## Funkcje zgodności (Compatibility Functions)
+##
+BETADIST = ROZKŁAD.BETA
+BETAINV = ROZKŁAD.BETA.ODW
+BINOMDIST = ROZKŁAD.DWUM
+CEILING = ZAOKR.W.GÓRĘ
+CHIDIST = ROZKŁAD.CHI
+CHIINV = ROZKŁAD.CHI.ODW
+CHITEST = TEST.CHI
+CONCATENATE = ZŁĄCZ.TEKSTY
+CONFIDENCE = UFNOŚĆ
+COVAR = KOWARIANCJA
+CRITBINOM = PRÓG.ROZKŁAD.DWUM
+EXPONDIST = ROZKŁAD.EXP
+FDIST = ROZKŁAD.F
+FINV = ROZKŁAD.F.ODW
+FLOOR = ZAOKR.W.DÓŁ
+FORECAST = REGLINX
+FTEST = TEST.F
+GAMMADIST = ROZKŁAD.GAMMA
+GAMMAINV = ROZKŁAD.GAMMA.ODW
+HYPGEOMDIST = ROZKŁAD.HIPERGEOM
+LOGINV = ROZKŁAD.LOG.ODW
+LOGNORMDIST = ROZKŁAD.LOG
+MODE = WYST.NAJCZĘŚCIEJ
+NEGBINOMDIST = ROZKŁAD.DWUM.PRZEC
+NORMDIST = ROZKŁAD.NORMALNY
+NORMINV = ROZKŁAD.NORMALNY.ODW
+NORMSDIST = ROZKŁAD.NORMALNY.S
+NORMSINV = ROZKŁAD.NORMALNY.S.ODW
+PERCENTILE = PERCENTYL
+PERCENTRANK = PROCENT.POZYCJA
+POISSON = ROZKŁAD.POISSON
+QUARTILE = KWARTYL
+RANK = POZYCJA
+STDEV = ODCH.STANDARDOWE
+STDEVP = ODCH.STANDARD.POPUL
+TDIST = ROZKŁAD.T
+TINV = ROZKŁAD.T.ODW
+TTEST = TEST.T
+VAR = WARIANCJA
+VARP = WARIANCJA.POPUL
+WEIBULL = ROZKŁAD.WEIBULL
+ZTEST = TEST.Z
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/config
index 904f99f1a07..c39057c734c 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Português Brasileiro (Brazilian Portuguese)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = R$
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #NULO!
-DIV0 = #DIV/0!
-VALUE = #VALOR!
-REF = #REF!
-NAME = #NOME?
-NUM = #NÚM!
-NA = #N/D
+NULL = #NULO!
+DIV0
+VALUE = #VALOR!
+REF
+NAME = #NOME?
+NUM = #NÚM!
+NA = #N/D
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/functions
index a062a7fad51..feba30d9a94 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/functions
@@ -1,408 +1,527 @@
+############################################################
##
-## Add-in and Automation functions Funções Suplemento e Automação
+## PhpSpreadsheet - function name translations
##
-GETPIVOTDATA = INFODADOSTABELADINÂMICA ## Retorna os dados armazenados em um relatório de tabela dinâmica
+## Português Brasileiro (Brazilian Portuguese)
+##
+############################################################
##
-## Cube functions Funções de Cubo
+## Funções de cubo (Cube Functions)
##
-CUBEKPIMEMBER = MEMBROKPICUBO ## Retorna o nome de um KPI (indicador de desempenho-chave), uma propriedade e uma medida e exibe o nome e a propriedade na célula. Um KPI é uma medida quantificável, como o lucro bruto mensal ou a rotatividade trimestral dos funcionários, usada para monitorar o desempenho de uma organização.
-CUBEMEMBER = MEMBROCUBO ## Retorna um membro ou tupla em uma hierarquia de cubo. Use para validar se o membro ou tupla existe no cubo.
-CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Retorna o valor da propriedade de um membro no cubo. Usada para validar a existência do nome do membro no cubo e para retornar a propriedade especificada para esse membro.
-CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Retorna o enésimo membro, ou o membro ordenado, em um conjunto. Use para retornar um ou mais elementos em um conjunto, assim como o melhor vendedor ou os dez melhores alunos.
-CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou tuplas enviando uma expressão do conjunto para o cubo no servidor, que cria o conjunto e o retorna para o Microsoft Office Excel.
-CUBESETCOUNT = CONTAGEMCONJUNTOCUBO ## Retorna o número de itens em um conjunto.
-CUBEVALUE = VALORCUBO ## Retorna um valor agregado de um cubo.
-
+CUBEKPIMEMBER = MEMBROKPICUBO
+CUBEMEMBER = MEMBROCUBO
+CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO
+CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO
+CUBESET = CONJUNTOCUBO
+CUBESETCOUNT = CONTAGEMCONJUNTOCUBO
+CUBEVALUE = VALORCUBO
##
-## Database functions Funções de banco de dados
+## Funções de banco de dados (Database Functions)
##
-DAVERAGE = BDMÉDIA ## Retorna a média das entradas selecionadas de um banco de dados
-DCOUNT = BDCONTAR ## Conta as células que contêm números em um banco de dados
-DCOUNTA = BDCONTARA ## Conta células não vazias em um banco de dados
-DGET = BDEXTRAIR ## Extrai de um banco de dados um único registro que corresponde a um critério específico
-DMAX = BDMÁX ## Retorna o valor máximo de entradas selecionadas de um banco de dados
-DMIN = BDMÍN ## Retorna o valor mínimo de entradas selecionadas de um banco de dados
-DPRODUCT = BDMULTIPL ## Multiplica os valores em um campo específico de registros que correspondem ao critério em um banco de dados
-DSTDEV = BDEST ## Estima o desvio padrão com base em uma amostra de entradas selecionadas de um banco de dados
-DSTDEVP = BDDESVPA ## Calcula o desvio padrão com base na população inteira de entradas selecionadas de um banco de dados
-DSUM = BDSOMA ## Adiciona os números à coluna de campos de registros do banco de dados que correspondem ao critério
-DVAR = BDVAREST ## Estima a variância com base em uma amostra de entradas selecionadas de um banco de dados
-DVARP = BDVARP ## Calcula a variância com base na população inteira de entradas selecionadas de um banco de dados
-
+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
##
-## Date and time functions Funções de data e hora
+## Funções de data e hora (Date & Time Functions)
##
-DATE = DATA ## Retorna o número de série de uma data específica
-DATEVALUE = DATA.VALOR ## Converte uma data na forma de texto para um número de série
-DAY = DIA ## Converte um número de série em um dia do mês
-DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base em um ano de 360 dias
-EDATE = DATAM ## Retorna o número de série da data que é o número indicado de meses antes ou depois da data inicial
-EOMONTH = FIMMÊS ## Retorna o número de série do último dia do mês antes ou depois de um número especificado de meses
-HOUR = HORA ## Converte um número de série em uma hora
-MINUTE = MINUTO ## Converte um número de série em um minuto
-MONTH = MÊS ## Converte um número de série em um mês
-NETWORKDAYS = DIATRABALHOTOTAL ## Retorna o número de dias úteis inteiros entre duas datas
-NOW = AGORA ## Retorna o número de série seqüencial da data e hora atuais
-SECOND = SEGUNDO ## Converte um número de série em um segundo
-TIME = HORA ## Retorna o número de série de uma hora específica
-TIMEVALUE = VALOR.TEMPO ## Converte um horário na forma de texto para um número de série
-TODAY = HOJE ## Retorna o número de série da data de hoje
-WEEKDAY = DIA.DA.SEMANA ## Converte um número de série em um dia da semana
-WEEKNUM = NÚMSEMANA ## Converte um número de série em um número que representa onde a semana cai numericamente em um ano
-WORKDAY = DIATRABALHO ## Retorna o número de série da data antes ou depois de um número específico de dias úteis
-YEAR = ANO ## Converte um número de série em um ano
-YEARFRAC = FRAÇÃOANO ## Retorna a fração do ano que representa o número de dias entre data_inicial e data_final
-
+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
##
-## Engineering functions Funções de engenharia
+## Funções de engenharia (Engineering Functions)
##
-BESSELI = BESSELI ## Retorna a função de Bessel In(x) modificada
-BESSELJ = BESSELJ ## Retorna a função de Bessel Jn(x)
-BESSELK = BESSELK ## Retorna a função de Bessel Kn(x) modificada
-BESSELY = BESSELY ## Retorna a função de Bessel Yn(x)
-BIN2DEC = BIN2DEC ## Converte um número binário em decimal
-BIN2HEX = BIN2HEX ## Converte um número binário em hexadecimal
-BIN2OCT = BIN2OCT ## Converte um número binário em octal
-COMPLEX = COMPLEX ## Converte coeficientes reais e imaginários e um número complexo
-CONVERT = CONVERTER ## Converte um número de um sistema de medida para outro
-DEC2BIN = DECABIN ## Converte um número decimal em binário
-DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal
-DEC2OCT = DECAOCT ## Converte um número decimal em octal
-DELTA = DELTA ## Testa se dois valores são iguais
-ERF = FUNERRO ## Retorna a função de erro
-ERFC = FUNERROCOMPL ## Retorna a função de erro complementar
-GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite
-HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário
-HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal
-HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal
-IMABS = IMABS ## Retorna o valor absoluto (módulo) de um número complexo
-IMAGINARY = IMAGINÁRIO ## Retorna o coeficiente imaginário de um número complexo
-IMARGUMENT = IMARG ## Retorna o argumento teta, um ângulo expresso em radianos
-IMCONJUGATE = IMCONJ ## Retorna o conjugado complexo de um número complexo
-IMCOS = IMCOS ## Retorna o cosseno de um número complexo
-IMDIV = IMDIV ## Retorna o quociente de dois números complexos
-IMEXP = IMEXP ## Retorna o exponencial de um número complexo
-IMLN = IMLN ## Retorna o logaritmo natural de um número complexo
-IMLOG10 = IMLOG10 ## Retorna o logaritmo de base 10 de um número complexo
-IMLOG2 = IMLOG2 ## Retorna o logaritmo de base 2 de um número complexo
-IMPOWER = IMPOT ## Retorna um número complexo elevado a uma potência inteira
-IMPRODUCT = IMPROD ## Retorna o produto de números complexos
-IMREAL = IMREAL ## Retorna o coeficiente real de um número complexo
-IMSIN = IMSENO ## Retorna o seno de um número complexo
-IMSQRT = IMRAIZ ## Retorna a raiz quadrada de um número complexo
-IMSUB = IMSUBTR ## Retorna a diferença entre dois números complexos
-IMSUM = IMSOMA ## Retorna a soma de números complexos
-OCT2BIN = OCTABIN ## Converte um número octal em binário
-OCT2DEC = OCTADEC ## Converte um número octal em decimal
-OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal
-
+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
##
-## Financial functions Funções financeiras
+## Funções financeiras (Financial Functions)
##
-ACCRINT = JUROSACUM ## Retorna a taxa de juros acumulados de um título que paga uma taxa periódica de juros
-ACCRINTM = JUROSACUMV ## Retorna os juros acumulados de um título que paga juros no vencimento
-AMORDEGRC = AMORDEGRC ## Retorna a depreciação para cada período contábil usando o coeficiente de depreciação
-AMORLINC = AMORLINC ## Retorna a depreciação para cada período contábil
-COUPDAYBS = CUPDIASINLIQ ## Retorna o número de dias do início do período de cupom até a data de liquidação
-COUPDAYS = CUPDIAS ## Retorna o número de dias no período de cupom que contém a data de quitação
-COUPDAYSNC = CUPDIASPRÓX ## Retorna o número de dias da data de liquidação até a data do próximo cupom
-COUPNCD = CUPDATAPRÓX ## Retorna a próxima data de cupom após a data de quitação
-COUPNUM = CUPNÚM ## Retorna o número de cupons pagáveis entre as datas de quitação e vencimento
-COUPPCD = CUPDATAANT ## Retorna a data de cupom anterior à data de quitação
-CUMIPMT = PGTOJURACUM ## Retorna os juros acumulados pagos entre dois períodos
-CUMPRINC = PGTOCAPACUM ## Retorna o capital acumulado pago sobre um empréstimo entre dois períodos
-DB = BD ## Retorna a depreciação de um ativo para um período especificado, usando o método de balanço de declínio fixo
-DDB = BDD ## Retorna a depreciação de um ativo com relação a um período especificado usando o método de saldos decrescentes duplos ou qualquer outro método especificado por você
-DISC = DESC ## Retorna a taxa de desconto de um título
-DOLLARDE = MOEDADEC ## Converte um preço em formato de moeda, na forma fracionária, em um preço na forma decimal
-DOLLARFR = MOEDAFRA ## Converte um preço, apresentado na forma decimal, em um preço apresentado na forma fracionária
-DURATION = DURAÇÃO ## Retorna a duração anual de um título com pagamentos de juros periódicos
-EFFECT = EFETIVA ## Retorna a taxa de juros anual efetiva
-FV = VF ## Retorna o valor futuro de um investimento
-FVSCHEDULE = VFPLANO ## Retorna o valor futuro de um capital inicial após a aplicação de uma série de taxas de juros compostas
-INTRATE = TAXAJUROS ## Retorna a taxa de juros de um título totalmente investido
-IPMT = IPGTO ## Retorna o pagamento de juros para um investimento em um determinado período
-IRR = TIR ## Retorna a taxa interna de retorno de uma série de fluxos de caixa
-ISPMT = ÉPGTO ## Calcula os juros pagos durante um período específico de um investimento
-MDURATION = MDURAÇÃO ## Retorna a duração de Macauley modificada para um título com um valor de paridade equivalente a R$ 100
-MIRR = MTIR ## Calcula a taxa interna de retorno em que fluxos de caixa positivos e negativos são financiados com diferentes taxas
-NOMINAL = NOMINAL ## Retorna a taxa de juros nominal anual
-NPER = NPER ## Retorna o número de períodos de um investimento
-NPV = VPL ## Retorna o valor líquido atual de um investimento com base em uma série de fluxos de caixa periódicos e em uma taxa de desconto
-ODDFPRICE = PREÇOPRIMINC ## Retorna o preço por R$ 100 de valor nominal de um título com um primeiro período indefinido
-ODDFYIELD = LUCROPRIMINC ## Retorna o rendimento de um título com um primeiro período indefinido
-ODDLPRICE = PREÇOÚLTINC ## Retorna o preço por R$ 100 de valor nominal de um título com um último período de cupom indefinido
-ODDLYIELD = LUCROÚLTINC ## Retorna o rendimento de um título com um último período indefinido
-PMT = PGTO ## Retorna o pagamento periódico de uma anuidade
-PPMT = PPGTO ## Retorna o pagamento de capital para determinado período de investimento
-PRICE = PREÇO ## Retorna a preço por R$ 100,00 de valor nominal de um título que paga juros periódicos
-PRICEDISC = PREÇODESC ## Retorna o preço por R$ 100,00 de valor nominal de um título descontado
-PRICEMAT = PREÇOVENC ## Retorna o preço por R$ 100,00 de valor nominal de um título que paga juros no vencimento
-PV = VP ## Retorna o valor presente de um investimento
-RATE = TAXA ## Retorna a taxa de juros por período de uma anuidade
-RECEIVED = RECEBER ## Retorna a quantia recebida no vencimento de um título totalmente investido
-SLN = DPD ## Retorna a depreciação em linha reta de um ativo durante um período
-SYD = SDA ## Retorna a depreciação dos dígitos da soma dos anos de um ativo para um período especificado
-TBILLEQ = OTN ## Retorna o rendimento de um título equivalente a uma obrigação do Tesouro
-TBILLPRICE = OTNVALOR ## Retorna o preço por R$ 100,00 de valor nominal de uma obrigação do Tesouro
-TBILLYIELD = OTNLUCRO ## Retorna o rendimento de uma obrigação do Tesouro
-VDB = BDV ## Retorna a depreciação de um ativo para um período especificado ou parcial usando um método de balanço declinante
-XIRR = XTIR ## Fornece a taxa interna de retorno para um programa de fluxos de caixa que não é necessariamente periódico
-XNPV = XVPL ## Retorna o valor presente líquido de um programa de fluxos de caixa que não é necessariamente periódico
-YIELD = LUCRO ## Retorna o lucro de um título que paga juros periódicos
-YIELDDISC = LUCRODESC ## Retorna o rendimento anual de um título descontado. Por exemplo, uma obrigação do Tesouro
-YIELDMAT = LUCROVENC ## Retorna o lucro anual de um título que paga juros no vencimento
-
+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
##
-## Information functions Funções de informação
+## Funções de informação (Information Functions)
##
-CELL = CÉL ## Retorna informações sobre formatação, localização ou conteúdo de uma célula
-ERROR.TYPE = TIPO.ERRO ## Retorna um número correspondente a um tipo de erro
-INFO = INFORMAÇÃO ## Retorna informações sobre o ambiente operacional atual
-ISBLANK = ÉCÉL.VAZIA ## Retorna VERDADEIRO se o valor for vazio
-ISERR = ÉERRO ## Retorna VERDADEIRO se o valor for um valor de erro diferente de #N/D
-ISERROR = ÉERROS ## Retorna VERDADEIRO se o valor for um valor de erro
-ISEVEN = ÉPAR ## Retorna VERDADEIRO se o número for par
-ISLOGICAL = ÉLÓGICO ## Retorna VERDADEIRO se o valor for um valor lógico
-ISNA = É.NÃO.DISP ## Retorna VERDADEIRO se o valor for o valor de erro #N/D
-ISNONTEXT = É.NÃO.TEXTO ## Retorna VERDADEIRO se o valor for diferente de texto
-ISNUMBER = ÉNÚM ## Retorna VERDADEIRO se o valor for um número
-ISODD = ÉIMPAR ## Retorna VERDADEIRO se o número for ímpar
-ISREF = ÉREF ## Retorna VERDADEIRO se o valor for uma referência
-ISTEXT = ÉTEXTO ## Retorna VERDADEIRO se o valor for texto
-N = N ## Retorna um valor convertido em um número
-NA = NÃO.DISP ## Retorna o valor de erro #N/D
-TYPE = TIPO ## Retorna um número indicando o tipo de dados de um valor
-
+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
##
-## Logical functions Funções lógicas
+## Funções lógicas (Logical Functions)
##
-AND = E ## Retorna VERDADEIRO se todos os seus argumentos forem VERDADEIROS
-FALSE = FALSO ## Retorna o valor lógico FALSO
-IF = SE ## Especifica um teste lógico a ser executado
-IFERROR = SEERRO ## Retornará um valor que você especifica se uma fórmula for avaliada para um erro; do contrário, retornará o resultado da fórmula
-NOT = NÃO ## Inverte o valor lógico do argumento
-OR = OU ## Retorna VERDADEIRO se um dos argumentos for VERDADEIRO
-TRUE = VERDADEIRO ## Retorna o valor lógico VERDADEIRO
-
+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
##
-## Lookup and reference functions Funções de pesquisa e referência
+## Funções de pesquisa e referência (Lookup & Reference Functions)
##
-ADDRESS = ENDEREÇO ## Retorna uma referência como texto para uma única célula em uma planilha
-AREAS = ÁREAS ## Retorna o número de áreas em uma referência
-CHOOSE = ESCOLHER ## Escolhe um valor a partir de uma lista de valores
-COLUMN = COL ## Retorna o número da coluna de uma referência
-COLUMNS = COLS ## Retorna o número de colunas em uma referência
-HLOOKUP = PROCH ## Procura na linha superior de uma matriz e retorna o valor da célula especificada
-HYPERLINK = HYPERLINK ## Cria um atalho ou salto que abre um documento armazenado em um servidor de rede, uma intranet ou na Internet
-INDEX = ÍNDICE ## Usa um índice para escolher um valor de uma referência ou matriz
-INDIRECT = INDIRETO ## Retorna uma referência indicada por um valor de texto
-LOOKUP = PROC ## Procura valores em um vetor ou em uma matriz
-MATCH = CORRESP ## Procura valores em uma referência ou em uma matriz
-OFFSET = DESLOC ## Retorna um deslocamento de referência com base em uma determinada referência
-ROW = LIN ## Retorna o número da linha de uma referência
-ROWS = LINS ## Retorna o número de linhas em uma referência
-RTD = RTD ## Recupera dados em tempo real de um programa que ofereça suporte a automação COM (automação: uma forma de trabalhar com objetos de um aplicativo a partir de outro aplicativo ou ferramenta de desenvolvimento. Chamada inicialmente de automação OLE, a automação é um padrão industrial e um recurso do modelo de objeto componente (COM).)
-TRANSPOSE = TRANSPOR ## Retorna a transposição de uma matriz
-VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e move ao longo da linha para retornar o valor de uma célula
-
+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
##
-## Math and trigonometry functions Funções matemáticas e trigonométricas
+## Funções matemáticas e trigonométricas (Math & Trig Functions)
##
-ABS = ABS ## Retorna o valor absoluto de um número
-ACOS = ACOS ## Retorna o arco cosseno de um número
-ACOSH = ACOSH ## Retorna o cosseno hiperbólico inverso de um número
-ASIN = ASEN ## Retorna o arco seno de um número
-ASINH = ASENH ## Retorna o seno hiperbólico inverso de um número
-ATAN = ATAN ## Retorna o arco tangente de um número
-ATAN2 = ATAN2 ## Retorna o arco tangente das coordenadas x e y especificadas
-ATANH = ATANH ## Retorna a tangente hiperbólica inversa de um número
-CEILING = TETO ## Arredonda um número para o inteiro mais próximo ou para o múltiplo mais próximo de significância
-COMBIN = COMBIN ## Retorna o número de combinações de um determinado número de objetos
-COS = COS ## Retorna o cosseno de um número
-COSH = COSH ## Retorna o cosseno hiperbólico de um número
-DEGREES = GRAUS ## Converte radianos em graus
-EVEN = PAR ## Arredonda um número para cima até o inteiro par mais próximo
-EXP = EXP ## Retorna e elevado à potência de um número especificado
-FACT = FATORIAL ## Retorna o fatorial de um número
-FACTDOUBLE = FATDUPLO ## Retorna o fatorial duplo de um número
-FLOOR = ARREDMULTB ## Arredonda um número para baixo até zero
-GCD = MDC ## Retorna o máximo divisor comum
-INT = INT ## Arredonda um número para baixo até o número inteiro mais próximo
-LCM = MMC ## Retorna o mínimo múltiplo comum
-LN = LN ## Retorna o logaritmo natural de um número
-LOG = LOG ## Retorna o logaritmo de um número de uma base especificada
-LOG10 = LOG10 ## Retorna o logaritmo de base 10 de um número
-MDETERM = MATRIZ.DETERM ## Retorna o determinante de uma matriz de uma variável do tipo matriz
-MINVERSE = MATRIZ.INVERSO ## Retorna a matriz inversa de uma matriz
-MMULT = MATRIZ.MULT ## Retorna o produto de duas matrizes
-MOD = RESTO ## Retorna o resto da divisão
-MROUND = MARRED ## Retorna um número arredondado ao múltiplo desejado
-MULTINOMIAL = MULTINOMIAL ## Retorna o multinomial de um conjunto de números
-ODD = ÍMPAR ## Arredonda um número para cima até o inteiro ímpar mais próximo
-PI = PI ## Retorna o valor de Pi
-POWER = POTÊNCIA ## Fornece o resultado de um número elevado a uma potência
-PRODUCT = MULT ## Multiplica seus argumentos
-QUOTIENT = QUOCIENTE ## Retorna a parte inteira de uma divisão
-RADIANS = RADIANOS ## Converte graus em radianos
-RAND = ALEATÓRIO ## Retorna um número aleatório entre 0 e 1
-RANDBETWEEN = ALEATÓRIOENTRE ## Retorna um número aleatório entre os números especificados
-ROMAN = ROMANO ## Converte um algarismo arábico em romano, como texto
-ROUND = ARRED ## Arredonda um número até uma quantidade especificada de dígitos
-ROUNDDOWN = ARREDONDAR.PARA.BAIXO ## Arredonda um número para baixo até zero
-ROUNDUP = ARREDONDAR.PARA.CIMA ## Arredonda um número para cima, afastando-o de zero
-SERIESSUM = SOMASEQÜÊNCIA ## Retorna a soma de uma série polinomial baseada na fórmula
-SIGN = SINAL ## Retorna o sinal de um número
-SIN = SEN ## Retorna o seno de um ângulo dado
-SINH = SENH ## Retorna o seno hiperbólico de um número
-SQRT = RAIZ ## Retorna uma raiz quadrada positiva
-SQRTPI = RAIZPI ## Retorna a raiz quadrada de (núm* pi)
-SUBTOTAL = SUBTOTAL ## Retorna um subtotal em uma lista ou em um banco de dados
-SUM = SOMA ## Soma seus argumentos
-SUMIF = SOMASE ## Adiciona as células especificadas por um determinado critério
-SUMIFS = SOMASE ## Adiciona as células em um intervalo que atende a vários critérios
-SUMPRODUCT = SOMARPRODUTO ## Retorna a soma dos produtos de componentes correspondentes de matrizes
-SUMSQ = SOMAQUAD ## Retorna a soma dos quadrados dos argumentos
-SUMX2MY2 = SOMAX2DY2 ## Retorna a soma da diferença dos quadrados dos valores correspondentes em duas matrizes
-SUMX2PY2 = SOMAX2SY2 ## Retorna a soma da soma dos quadrados dos valores correspondentes em duas matrizes
-SUMXMY2 = SOMAXMY2 ## Retorna a soma dos quadrados das diferenças dos valores correspondentes em duas matrizes
-TAN = TAN ## Retorna a tangente de um número
-TANH = TANH ## Retorna a tangente hiperbólica de um número
-TRUNC = TRUNCAR ## Trunca um número para um inteiro
-
+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
##
-## Statistical functions Funções estatísticas
+## Funções estatísticas (Statistical Functions)
##
-AVEDEV = DESV.MÉDIO ## Retorna a média aritmética dos desvios médios dos pontos de dados a partir de sua média
-AVERAGE = MÉDIA ## Retorna a média dos argumentos
-AVERAGEA = MÉDIAA ## Retorna a média dos argumentos, inclusive números, texto e valores lógicos
-AVERAGEIF = MÉDIASE ## Retorna a média (média aritmética) de todas as células em um intervalo que atendem a um determinado critério
-AVERAGEIFS = MÉDIASES ## Retorna a média (média aritmética) de todas as células que atendem a múltiplos critérios.
-BETADIST = DISTBETA ## Retorna a função de distribuição cumulativa beta
-BETAINV = BETA.ACUM.INV ## Retorna o inverso da função de distribuição cumulativa para uma distribuição beta especificada
-BINOMDIST = DISTRBINOM ## Retorna a probabilidade de distribuição binomial do termo individual
-CHIDIST = DIST.QUI ## Retorna a probabilidade unicaudal da distribuição qui-quadrada
-CHIINV = INV.QUI ## Retorna o inverso da probabilidade uni-caudal da distribuição qui-quadrada
-CHITEST = TESTE.QUI ## Retorna o teste para independência
-CONFIDENCE = INT.CONFIANÇA ## Retorna o intervalo de confiança para uma média da população
-CORREL = CORREL ## Retorna o coeficiente de correlação entre dois conjuntos de dados
-COUNT = CONT.NÚM ## Calcula quantos números há na lista de argumentos
-COUNTA = CONT.VALORES ## Calcula quantos valores há na lista de argumentos
-COUNTBLANK = CONTAR.VAZIO ## Conta o número de células vazias no intervalo especificado
-COUNTIF = CONT.SE ## Calcula o número de células não vazias em um intervalo que corresponde a determinados critérios
-COUNTIFS = CONT.SES ## Conta o número de células dentro de um intervalo que atende a múltiplos critérios
-COVAR = COVAR ## Retorna a covariância, a média dos produtos dos desvios pares
-CRITBINOM = CRIT.BINOM ## Retorna o menor valor para o qual a distribuição binomial cumulativa é menor ou igual ao valor padrão
-DEVSQ = DESVQ ## Retorna a soma dos quadrados dos desvios
-EXPONDIST = DISTEXPON ## Retorna a distribuição exponencial
-FDIST = DISTF ## Retorna a distribuição de probabilidade F
-FINV = INVF ## Retorna o inverso da distribuição de probabilidades F
-FISHER = FISHER ## Retorna a transformação Fisher
-FISHERINV = FISHERINV ## Retorna o inverso da transformação Fisher
-FORECAST = PREVISÃO ## Retorna um valor ao longo de uma linha reta
-FREQUENCY = FREQÜÊNCIA ## Retorna uma distribuição de freqüência como uma matriz vertical
-FTEST = TESTEF ## Retorna o resultado de um teste F
-GAMMADIST = DISTGAMA ## Retorna a distribuição gama
-GAMMAINV = INVGAMA ## Retorna o inverso da distribuição cumulativa gama
-GAMMALN = LNGAMA ## Retorna o logaritmo natural da função gama, G(x)
-GEOMEAN = MÉDIA.GEOMÉTRICA ## Retorna a média geométrica
-GROWTH = CRESCIMENTO ## Retorna valores ao longo de uma tendência exponencial
-HARMEAN = MÉDIA.HARMÔNICA ## Retorna a média harmônica
-HYPGEOMDIST = DIST.HIPERGEOM ## Retorna a distribuição hipergeométrica
-INTERCEPT = INTERCEPÇÃO ## Retorna a intercepção da linha de regressão linear
-KURT = CURT ## Retorna a curtose de um conjunto de dados
-LARGE = MAIOR ## Retorna o maior valor k-ésimo de um conjunto de dados
-LINEST = PROJ.LIN ## Retorna os parâmetros de uma tendência linear
-LOGEST = PROJ.LOG ## Retorna os parâmetros de uma tendência exponencial
-LOGINV = INVLOG ## Retorna o inverso da distribuição lognormal
-LOGNORMDIST = DIST.LOGNORMAL ## Retorna a distribuição lognormal cumulativa
-MAX = MÁXIMO ## Retorna o valor máximo em uma lista de argumentos
-MAXA = MÁXIMOA ## Retorna o maior valor em uma lista de argumentos, inclusive números, texto e valores lógicos
-MEDIAN = MED ## Retorna a mediana dos números indicados
-MIN = MÍNIMO ## Retorna o valor mínimo em uma lista de argumentos
-MINA = MÍNIMOA ## Retorna o menor valor em uma lista de argumentos, inclusive números, texto e valores lógicos
-MODE = MODO ## Retorna o valor mais comum em um conjunto de dados
-NEGBINOMDIST = DIST.BIN.NEG ## Retorna a distribuição binomial negativa
-NORMDIST = DIST.NORM ## Retorna a distribuição cumulativa normal
-NORMINV = INV.NORM ## Retorna o inverso da distribuição cumulativa normal
-NORMSDIST = DIST.NORMP ## Retorna a distribuição cumulativa normal padrão
-NORMSINV = INV.NORMP ## Retorna o inverso da distribuição cumulativa normal padrão
-PEARSON = PEARSON ## Retorna o coeficiente de correlação do momento do produto Pearson
-PERCENTILE = PERCENTIL ## Retorna o k-ésimo percentil de valores em um intervalo
-PERCENTRANK = ORDEM.PORCENTUAL ## Retorna a ordem percentual de um valor em um conjunto de dados
-PERMUT = PERMUT ## Retorna o número de permutações de um determinado número de objetos
-POISSON = POISSON ## Retorna a distribuição Poisson
-PROB = PROB ## Retorna a probabilidade de valores em um intervalo estarem entre dois limites
-QUARTILE = QUARTIL ## Retorna o quartil do conjunto de dados
-RANK = ORDEM ## Retorna a posição de um número em uma lista de números
-RSQ = RQUAD ## Retorna o quadrado do coeficiente de correlação do momento do produto de Pearson
-SKEW = DISTORÇÃO ## Retorna a distorção de uma distribuição
-SLOPE = INCLINAÇÃO ## Retorna a inclinação da linha de regressão linear
-SMALL = MENOR ## Retorna o menor valor k-ésimo do conjunto de dados
-STANDARDIZE = PADRONIZAR ## Retorna um valor normalizado
-STDEV = DESVPAD ## Estima o desvio padrão com base em uma amostra
-STDEVA = DESVPADA ## Estima o desvio padrão com base em uma amostra, inclusive números, texto e valores lógicos
-STDEVP = DESVPADP ## Calcula o desvio padrão com base na população total
-STDEVPA = DESVPADPA ## Calcula o desvio padrão com base na população total, inclusive números, texto e valores lógicos
-STEYX = EPADYX ## Retorna o erro padrão do valor-y previsto para cada x da regressão
-TDIST = DISTT ## Retorna a distribuição t de Student
-TINV = INVT ## Retorna o inverso da distribuição t de Student
-TREND = TENDÊNCIA ## Retorna valores ao longo de uma tendência linear
-TRIMMEAN = MÉDIA.INTERNA ## Retorna a média do interior de um conjunto de dados
-TTEST = TESTET ## Retorna a probabilidade associada ao teste t de Student
-VAR = VAR ## Estima a variância com base em uma amostra
-VARA = VARA ## Estima a variância com base em uma amostra, inclusive números, texto e valores lógicos
-VARP = VARP ## Calcula a variância com base na população inteira
-VARPA = VARPA ## Calcula a variância com base na população total, inclusive números, texto e valores lógicos
-WEIBULL = WEIBULL ## Retorna a distribuição Weibull
-ZTEST = TESTEZ ## Retorna o valor de probabilidade uni-caudal de um teste-z
-
+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
##
-## Text functions Funções de texto
+## Funções de texto (Text Functions)
##
-ASC = ASC ## Altera letras do inglês ou katakana de largura total (bytes duplos) dentro de uma seqüência de caracteres para caracteres de meia largura (byte único)
-BAHTTEXT = BAHTTEXT ## Converte um número em um texto, usando o formato de moeda ß (baht)
-CHAR = CARACT ## Retorna o caractere especificado pelo número de código
-CLEAN = TIRAR ## Remove todos os caracteres do texto que não podem ser impressos
-CODE = CÓDIGO ## Retorna um código numérico para o primeiro caractere de uma seqüência de caracteres de texto
-CONCATENATE = CONCATENAR ## Agrupa vários itens de texto em um único item de texto
-DOLLAR = MOEDA ## Converte um número em texto, usando o formato de moeda $ (dólar)
-EXACT = EXATO ## Verifica se dois valores de texto são idênticos
-FIND = PROCURAR ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas)
-FINDB = PROCURARB ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas)
-FIXED = DEF.NÚM.DEC ## Formata um número como texto com um número fixo de decimais
-JIS = JIS ## Altera letras do inglês ou katakana de meia largura (byte único) dentro de uma seqüência de caracteres para caracteres de largura total (bytes duplos)
-LEFT = ESQUERDA ## Retorna os caracteres mais à esquerda de um valor de texto
-LEFTB = ESQUERDAB ## Retorna os caracteres mais à esquerda de um valor de texto
-LEN = NÚM.CARACT ## Retorna o número de caracteres em uma seqüência de texto
-LENB = NÚM.CARACTB ## Retorna o número de caracteres em uma seqüência de texto
-LOWER = MINÚSCULA ## Converte texto para minúsculas
-MID = EXT.TEXTO ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada
-MIDB = EXT.TEXTOB ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada
-PHONETIC = FONÉTICA ## Extrai os caracteres fonéticos (furigana) de uma seqüência de caracteres de texto
-PROPER = PRI.MAIÚSCULA ## Coloca a primeira letra de cada palavra em maiúscula em um valor de texto
-REPLACE = MUDAR ## Muda os caracteres dentro do texto
-REPLACEB = MUDARB ## Muda os caracteres dentro do texto
-REPT = REPT ## Repete o texto um determinado número de vezes
-RIGHT = DIREITA ## Retorna os caracteres mais à direita de um valor de texto
-RIGHTB = DIREITAB ## Retorna os caracteres mais à direita de um valor de texto
-SEARCH = LOCALIZAR ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas)
-SEARCHB = LOCALIZARB ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas)
-SUBSTITUTE = SUBSTITUIR ## Substitui um novo texto por um texto antigo em uma seqüência de texto
-T = T ## Converte os argumentos em texto
-TEXT = TEXTO ## Formata um número e o converte em texto
-TRIM = ARRUMAR ## Remove espaços do texto
-UPPER = MAIÚSCULA ## Converte o texto em maiúsculas
-VALUE = VALOR ## Converte um argumento de texto em um número
+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
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/config
index cd85c17aae5..e661830b3dc 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Português (Portuguese)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = €
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #NULO!
-DIV0 = #DIV/0!
-VALUE = #VALOR!
-REF = #REF!
-NAME = #NOME?
-NUM = #NÚM!
-NA = #N/D
+NULL = #NULO!
+DIV0
+VALUE = #VALOR!
+REF
+NAME = #NOME?
+NUM = #NÚM!
+NA = #N/D
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/functions
index ba4eb471bad..8a94d82606f 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/functions
@@ -1,408 +1,537 @@
+############################################################
##
-## Add-in and Automation functions Funções de Suplemento e Automatização
+## PhpSpreadsheet - function name translations
##
-GETPIVOTDATA = OBTERDADOSDIN ## Devolve dados armazenados num relatório de Tabela Dinâmica
+## Português (Portuguese)
+##
+############################################################
##
-## Cube functions Funções de cubo
+## Funções de cubo (Cube Functions)
##
-CUBEKPIMEMBER = MEMBROKPICUBO ## Devolve o nome, propriedade e medição de um KPI (key performance indicator) e apresenta o nome e a propriedade na célula. Um KPI é uma medida quantificável, como, por exemplo, o lucro mensal bruto ou a rotatividade trimestral de pessoal, utilizada para monitorizar o desempenho de uma organização.
-CUBEMEMBER = MEMBROCUBO ## Devolve um membro ou cadeia de identificação numa hierarquia de cubo. Utilizada para validar a existência do membro ou cadeia de identificação no cubo.
-CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Devolve o valor de uma propriedade de membro no cubo. Utilizada para validar a existência de um nome de membro no cubo e para devolver a propriedade especificada para esse membro.
-CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Devolve o enésimo ou a classificação mais alta num conjunto. Utilizada para devolver um ou mais elementos num conjunto, tal como o melhor vendedor ou os 10 melhores alunos.
-CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou cadeias de identificação enviando uma expressão de conjunto para o cubo no servidor, que cria o conjunto e, em seguida, devolve o conjunto ao Microsoft Office Excel.
-CUBESETCOUNT = CONTARCONJUNTOCUBO ## Devolve o número de itens num conjunto.
-CUBEVALUE = VALORCUBO ## Devolve um valor agregado do cubo.
-
+CUBEKPIMEMBER = MEMBROKPICUBO
+CUBEMEMBER = MEMBROCUBO
+CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO
+CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO
+CUBESET = CONJUNTOCUBO
+CUBESETCOUNT = CONTARCONJUNTOCUBO
+CUBEVALUE = VALORCUBO
##
-## Database functions Funções de base de dados
+## Funções de base de dados (Database Functions)
##
-DAVERAGE = BDMÉDIA ## Devolve a média das entradas da base de dados seleccionadas
-DCOUNT = BDCONTAR ## Conta as células que contêm números numa base de dados
-DCOUNTA = BDCONTAR.VAL ## Conta as células que não estejam em branco numa base de dados
-DGET = BDOBTER ## Extrai de uma base de dados um único registo que corresponde aos critérios especificados
-DMAX = BDMÁX ## Devolve o valor máximo das entradas da base de dados seleccionadas
-DMIN = BDMÍN ## Devolve o valor mínimo das entradas da base de dados seleccionadas
-DPRODUCT = BDMULTIPL ## Multiplica os valores de um determinado campo de registos que correspondem aos critérios numa base de dados
-DSTDEV = BDDESVPAD ## Calcula o desvio-padrão com base numa amostra de entradas da base de dados seleccionadas
-DSTDEVP = BDDESVPADP ## Calcula o desvio-padrão com base na população total das entradas da base de dados seleccionadas
-DSUM = BDSOMA ## Adiciona os números na coluna de campo dos registos de base de dados que correspondem aos critérios
-DVAR = BDVAR ## Calcula a variância com base numa amostra das entradas de base de dados seleccionadas
-DVARP = BDVARP ## Calcula a variância com base na população total das entradas de base de dados seleccionadas
-
+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
##
-## Date and time functions Funções de data e hora
+## Funções de data e hora (Date & Time Functions)
##
-DATE = DATA ## Devolve o número de série de uma determinada data
-DATEVALUE = DATA.VALOR ## Converte uma data em forma de texto num número de série
-DAY = DIA ## Converte um número de série num dia do mês
-DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base num ano com 360 dias
-EDATE = DATAM ## Devolve um número de série de data que corresponde ao número de meses indicado antes ou depois da data de início
-EOMONTH = FIMMÊS ## Devolve o número de série do último dia do mês antes ou depois de um número de meses especificado
-HOUR = HORA ## Converte um número de série numa hora
-MINUTE = MINUTO ## Converte um número de série num minuto
-MONTH = MÊS ## Converte um número de série num mês
-NETWORKDAYS = DIATRABALHOTOTAL ## Devolve o número total de dias úteis entre duas datas
-NOW = AGORA ## Devolve o número de série da data e hora actuais
-SECOND = SEGUNDO ## Converte um número de série num segundo
-TIME = TEMPO ## Devolve o número de série de um determinado tempo
-TIMEVALUE = VALOR.TEMPO ## Converte um tempo em forma de texto num número de série
-TODAY = HOJE ## Devolve o número de série da data actual
-WEEKDAY = DIA.SEMANA ## Converte um número de série num dia da semana
-WEEKNUM = NÚMSEMANA ## Converte um número de série num número que representa o número da semana num determinado ano
-WORKDAY = DIA.TRABALHO ## Devolve o número de série da data antes ou depois de um número de dias úteis especificado
-YEAR = ANO ## Converte um número de série num ano
-YEARFRAC = FRACÇÃOANO ## Devolve a fracção de ano que representa o número de dias inteiros entre a data_de_início e a data_de_fim
-
+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
##
-## Engineering functions Funções de engenharia
+## Funções de engenharia (Engineering Functions)
##
-BESSELI = BESSELI ## Devolve a função de Bessel modificada In(x)
-BESSELJ = BESSELJ ## Devolve a função de Bessel Jn(x)
-BESSELK = BESSELK ## Devolve a função de Bessel modificada Kn(x)
-BESSELY = BESSELY ## Devolve a função de Bessel Yn(x)
-BIN2DEC = BINADEC ## Converte um número binário em decimal
-BIN2HEX = BINAHEX ## Converte um número binário em hexadecimal
-BIN2OCT = BINAOCT ## Converte um número binário em octal
-COMPLEX = COMPLEXO ## Converte coeficientes reais e imaginários num número complexo
-CONVERT = CONVERTER ## Converte um número de um sistema de medida noutro
-DEC2BIN = DECABIN ## Converte um número decimal em binário
-DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal
-DEC2OCT = DECAOCT ## Converte um número decimal em octal
-DELTA = DELTA ## Testa se dois valores são iguais
-ERF = FUNCERRO ## Devolve a função de erro
-ERFC = FUNCERROCOMPL ## Devolve a função de erro complementar
-GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite
-HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário
-HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal
-HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal
-IMABS = IMABS ## Devolve o valor absoluto (módulo) de um número complexo
-IMAGINARY = IMAGINÁRIO ## Devolve o coeficiente imaginário de um número complexo
-IMARGUMENT = IMARG ## Devolve o argumento Teta, um ângulo expresso em radianos
-IMCONJUGATE = IMCONJ ## Devolve o conjugado complexo de um número complexo
-IMCOS = IMCOS ## Devolve o co-seno de um número complexo
-IMDIV = IMDIV ## Devolve o quociente de dois números complexos
-IMEXP = IMEXP ## Devolve o exponencial de um número complexo
-IMLN = IMLN ## Devolve o logaritmo natural de um número complexo
-IMLOG10 = IMLOG10 ## Devolve o logaritmo de base 10 de um número complexo
-IMLOG2 = IMLOG2 ## Devolve o logaritmo de base 2 de um número complexo
-IMPOWER = IMPOT ## Devolve um número complexo elevado a uma potência inteira
-IMPRODUCT = IMPROD ## Devolve o produto de números complexos
-IMREAL = IMREAL ## Devolve o coeficiente real de um número complexo
-IMSIN = IMSENO ## Devolve o seno de um número complexo
-IMSQRT = IMRAIZ ## Devolve a raiz quadrada de um número complexo
-IMSUB = IMSUBTR ## Devolve a diferença entre dois números complexos
-IMSUM = IMSOMA ## Devolve a soma de números complexos
-OCT2BIN = OCTABIN ## Converte um número octal em binário
-OCT2DEC = OCTADEC ## Converte um número octal em decimal
-OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal
-
+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
##
-## Financial functions Funções financeiras
+## Funções financeiras (Financial Functions)
##
-ACCRINT = JUROSACUM ## Devolve os juros acumulados de um título que paga juros periódicos
-ACCRINTM = JUROSACUMV ## Devolve os juros acumulados de um título que paga juros no vencimento
-AMORDEGRC = AMORDEGRC ## Devolve a depreciação correspondente a cada período contabilístico utilizando um coeficiente de depreciação
-AMORLINC = AMORLINC ## Devolve a depreciação correspondente a cada período contabilístico
-COUPDAYBS = CUPDIASINLIQ ## Devolve o número de dias entre o início do período do cupão e a data de regularização
-COUPDAYS = CUPDIAS ## Devolve o número de dias no período do cupão que contém a data de regularização
-COUPDAYSNC = CUPDIASPRÓX ## Devolve o número de dias entre a data de regularização e a data do cupão seguinte
-COUPNCD = CUPDATAPRÓX ## Devolve a data do cupão seguinte após a data de regularização
-COUPNUM = CUPNÚM ## Devolve o número de cupões a serem pagos entre a data de regularização e a data de vencimento
-COUPPCD = CUPDATAANT ## Devolve a data do cupão anterior antes da data de regularização
-CUMIPMT = PGTOJURACUM ## Devolve os juros cumulativos pagos entre dois períodos
-CUMPRINC = PGTOCAPACUM ## Devolve o capital cumulativo pago a título de empréstimo entre dois períodos
-DB = BD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas fixas
-DDB = BDD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas duplas ou qualquer outro método especificado
-DISC = DESC ## Devolve a taxa de desconto de um título
-DOLLARDE = MOEDADEC ## Converte um preço em unidade monetária, expresso como uma fracção, num preço em unidade monetária, expresso como um número decimal
-DOLLARFR = MOEDAFRA ## Converte um preço em unidade monetária, expresso como um número decimal, num preço em unidade monetária, expresso como uma fracção
-DURATION = DURAÇÃO ## Devolve a duração anual de um título com pagamentos de juros periódicos
-EFFECT = EFECTIVA ## Devolve a taxa de juros anual efectiva
-FV = VF ## Devolve o valor futuro de um investimento
-FVSCHEDULE = VFPLANO ## Devolve o valor futuro de um capital inicial após a aplicação de uma série de taxas de juro compostas
-INTRATE = TAXAJUROS ## Devolve a taxa de juros de um título investido na totalidade
-IPMT = IPGTO ## Devolve o pagamento dos juros de um investimento durante um determinado período
-IRR = TIR ## Devolve a taxa de rentabilidade interna para uma série de fluxos monetários
-ISPMT = É.PGTO ## Calcula os juros pagos durante um período específico de um investimento
-MDURATION = MDURAÇÃO ## Devolve a duração modificada de Macauley de um título com um valor de paridade equivalente a € 100
-MIRR = MTIR ## Devolve a taxa interna de rentabilidade em que os fluxos monetários positivos e negativos são financiados com taxas diferentes
-NOMINAL = NOMINAL ## Devolve a taxa de juros nominal anual
-NPER = NPER ## Devolve o número de períodos de um investimento
-NPV = VAL ## Devolve o valor actual líquido de um investimento com base numa série de fluxos monetários periódicos e numa taxa de desconto
-ODDFPRICE = PREÇOPRIMINC ## Devolve o preço por € 100 do valor nominal de um título com um período inicial incompleto
-ODDFYIELD = LUCROPRIMINC ## Devolve o lucro de um título com um período inicial incompleto
-ODDLPRICE = PREÇOÚLTINC ## Devolve o preço por € 100 do valor nominal de um título com um período final incompleto
-ODDLYIELD = LUCROÚLTINC ## Devolve o lucro de um título com um período final incompleto
-PMT = PGTO ## Devolve o pagamento periódico de uma anuidade
-PPMT = PPGTO ## Devolve o pagamento sobre o capital de um investimento num determinado período
-PRICE = PREÇO ## Devolve o preço por € 100 do valor nominal de um título que paga juros periódicos
-PRICEDISC = PREÇODESC ## Devolve o preço por € 100 do valor nominal de um título descontado
-PRICEMAT = PREÇOVENC ## Devolve o preço por € 100 do valor nominal de um título que paga juros no vencimento
-PV = VA ## Devolve o valor actual de um investimento
-RATE = TAXA ## Devolve a taxa de juros por período de uma anuidade
-RECEIVED = RECEBER ## Devolve o montante recebido no vencimento de um título investido na totalidade
-SLN = AMORT ## Devolve uma depreciação linear de um activo durante um período
-SYD = AMORTD ## Devolve a depreciação por algarismos da soma dos anos de um activo durante um período especificado
-TBILLEQ = OTN ## Devolve o lucro de um título equivalente a uma Obrigação do Tesouro
-TBILLPRICE = OTNVALOR ## Devolve o preço por € 100 de valor nominal de uma Obrigação do Tesouro
-TBILLYIELD = OTNLUCRO ## Devolve o lucro de uma Obrigação do Tesouro
-VDB = BDV ## Devolve a depreciação de um activo relativo a um período específico ou parcial utilizando um método de quotas degressivas
-XIRR = XTIR ## Devolve a taxa interna de rentabilidade de um plano de fluxos monetários que não seja necessariamente periódica
-XNPV = XVAL ## Devolve o valor actual líquido de um plano de fluxos monetários que não seja necessariamente periódico
-YIELD = LUCRO ## Devolve o lucro de um título que paga juros periódicos
-YIELDDISC = LUCRODESC ## Devolve o lucro anual de um título emitido abaixo do valor nominal, por exemplo, uma Obrigação do Tesouro
-YIELDMAT = LUCROVENC ## Devolve o lucro anual de um título que paga juros na data de vencimento
-
+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
##
-## Information functions Funções de informação
+## Funções de informação (Information Functions)
##
-CELL = CÉL ## Devolve informações sobre a formatação, localização ou conteúdo de uma célula
-ERROR.TYPE = TIPO.ERRO ## Devolve um número correspondente a um tipo de erro
-INFO = INFORMAÇÃO ## Devolve informações sobre o ambiente de funcionamento actual
-ISBLANK = É.CÉL.VAZIA ## Devolve VERDADEIRO se o valor estiver em branco
-ISERR = É.ERROS ## Devolve VERDADEIRO se o valor for um valor de erro diferente de #N/D
-ISERROR = É.ERRO ## Devolve VERDADEIRO se o valor for um valor de erro
-ISEVEN = ÉPAR ## Devolve VERDADEIRO se o número for par
-ISLOGICAL = É.LÓGICO ## Devolve VERDADEIRO se o valor for lógico
-ISNA = É.NÃO.DISP ## Devolve VERDADEIRO se o valor for o valor de erro #N/D
-ISNONTEXT = É.NÃO.TEXTO ## Devolve VERDADEIRO se o valor não for texto
-ISNUMBER = É.NÚM ## Devolve VERDADEIRO se o valor for um número
-ISODD = ÉÍMPAR ## Devolve VERDADEIRO se o número for ímpar
-ISREF = É.REF ## Devolve VERDADEIRO se o valor for uma referência
-ISTEXT = É.TEXTO ## Devolve VERDADEIRO se o valor for texto
-N = N ## Devolve um valor convertido num número
-NA = NÃO.DISP ## Devolve o valor de erro #N/D
-TYPE = TIPO ## Devolve um número que indica o tipo de dados de um valor
-
+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
##
-## Logical functions Funções lógicas
+## Funções lógicas (Logical Functions)
##
-AND = E ## Devolve VERDADEIRO se todos os respectivos argumentos corresponderem a VERDADEIRO
-FALSE = FALSO ## Devolve o valor lógico FALSO
-IF = SE ## Especifica um teste lógico a ser executado
-IFERROR = SE.ERRO ## Devolve um valor definido pelo utilizador se ocorrer um erro na fórmula, e devolve o resultado da fórmula se não ocorrer nenhum erro
-NOT = NÃO ## Inverte a lógica do respectivo argumento
-OR = OU ## Devolve VERDADEIRO se qualquer argumento for VERDADEIRO
-TRUE = VERDADEIRO ## Devolve o valor lógico VERDADEIRO
-
+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
##
-## Lookup and reference functions Funções de pesquisa e referência
+## Funções de pesquisa e referência (Lookup & Reference Functions)
##
-ADDRESS = ENDEREÇO ## Devolve uma referência a uma única célula numa folha de cálculo como texto
-AREAS = ÁREAS ## Devolve o número de áreas numa referência
-CHOOSE = SELECCIONAR ## Selecciona um valor a partir de uma lista de valores
-COLUMN = COL ## Devolve o número da coluna de uma referência
-COLUMNS = COLS ## Devolve o número de colunas numa referência
-HLOOKUP = PROCH ## Procura na linha superior de uma matriz e devolve o valor da célula indicada
-HYPERLINK = HIPERLIGAÇÃO ## Cria um atalho ou hiperligação que abre um documento armazenado num servidor de rede, numa intranet ou na Internet
-INDEX = ÍNDICE ## Utiliza um índice para escolher um valor de uma referência ou de uma matriz
-INDIRECT = INDIRECTO ## Devolve uma referência indicada por um valor de texto
-LOOKUP = PROC ## Procura valores num vector ou numa matriz
-MATCH = CORRESP ## Procura valores numa referência ou numa matriz
-OFFSET = DESLOCAMENTO ## Devolve o deslocamento de referência de uma determinada referência
-ROW = LIN ## Devolve o número da linha de uma referência
-ROWS = LINS ## Devolve o número de linhas numa referência
-RTD = RTD ## Obtém dados em tempo real a partir de um programa que suporte automatização COM (automatização: modo de trabalhar com objectos de uma aplicação a partir de outra aplicação ou ferramenta de desenvolvimento. Anteriormente conhecida como automatização OLE, a automatização é uma norma da indústria de software e uma funcionalidade COM (Component Object Model).)
-TRANSPOSE = TRANSPOR ## Devolve a transposição de uma matriz
-VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e percorre a linha para devolver o valor de uma célula
-
+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
##
-## Math and trigonometry functions Funções matemáticas e trigonométricas
+## Funções matemáticas e trigonométricas (Math & Trig Functions)
##
-ABS = ABS ## Devolve o valor absoluto de um número
-ACOS = ACOS ## Devolve o arco de co-seno de um número
-ACOSH = ACOSH ## Devolve o co-seno hiperbólico inverso de um número
-ASIN = ASEN ## Devolve o arco de seno de um número
-ASINH = ASENH ## Devolve o seno hiperbólico inverso de um número
-ATAN = ATAN ## Devolve o arco de tangente de um número
-ATAN2 = ATAN2 ## Devolve o arco de tangente das coordenadas x e y
-ATANH = ATANH ## Devolve a tangente hiperbólica inversa de um número
-CEILING = ARRED.EXCESSO ## Arredonda um número para o número inteiro mais próximo ou para o múltiplo de significância mais próximo
-COMBIN = COMBIN ## Devolve o número de combinações de um determinado número de objectos
-COS = COS ## Devolve o co-seno de um número
-COSH = COSH ## Devolve o co-seno hiperbólico de um número
-DEGREES = GRAUS ## Converte radianos em graus
-EVEN = PAR ## Arredonda um número por excesso para o número inteiro mais próximo
-EXP = EXP ## Devolve e elevado à potência de um determinado número
-FACT = FACTORIAL ## Devolve o factorial de um número
-FACTDOUBLE = FACTDUPLO ## Devolve o factorial duplo de um número
-FLOOR = ARRED.DEFEITO ## Arredonda um número por defeito até zero
-GCD = MDC ## Devolve o maior divisor comum
-INT = INT ## Arredonda um número por defeito para o número inteiro mais próximo
-LCM = MMC ## Devolve o mínimo múltiplo comum
-LN = LN ## Devolve o logaritmo natural de um número
-LOG = LOG ## Devolve o logaritmo de um número com uma base especificada
-LOG10 = LOG10 ## Devolve o logaritmo de base 10 de um número
-MDETERM = MATRIZ.DETERM ## Devolve o determinante matricial de uma matriz
-MINVERSE = MATRIZ.INVERSA ## Devolve o inverso matricial de uma matriz
-MMULT = MATRIZ.MULT ## Devolve o produto matricial de duas matrizes
-MOD = RESTO ## Devolve o resto da divisão
-MROUND = MARRED ## Devolve um número arredondado para o múltiplo pretendido
-MULTINOMIAL = POLINOMIAL ## Devolve o polinomial de um conjunto de números
-ODD = ÍMPAR ## Arredonda por excesso um número para o número inteiro ímpar mais próximo
-PI = PI ## Devolve o valor de pi
-POWER = POTÊNCIA ## Devolve o resultado de um número elevado a uma potência
-PRODUCT = PRODUTO ## Multiplica os respectivos argumentos
-QUOTIENT = QUOCIENTE ## Devolve a parte inteira de uma divisão
-RADIANS = RADIANOS ## Converte graus em radianos
-RAND = ALEATÓRIO ## Devolve um número aleatório entre 0 e 1
-RANDBETWEEN = ALEATÓRIOENTRE ## Devolve um número aleatório entre os números especificados
-ROMAN = ROMANO ## Converte um número árabe em romano, como texto
-ROUND = ARRED ## Arredonda um número para um número de dígitos especificado
-ROUNDDOWN = ARRED.PARA.BAIXO ## Arredonda um número por defeito até zero
-ROUNDUP = ARRED.PARA.CIMA ## Arredonda um número por excesso, afastando-o de zero
-SERIESSUM = SOMASÉRIE ## Devolve a soma de uma série de potências baseada na fórmula
-SIGN = SINAL ## Devolve o sinal de um número
-SIN = SEN ## Devolve o seno de um determinado ângulo
-SINH = SENH ## Devolve o seno hiperbólico de um número
-SQRT = RAIZQ ## Devolve uma raiz quadrada positiva
-SQRTPI = RAIZPI ## Devolve a raiz quadrada de (núm * pi)
-SUBTOTAL = SUBTOTAL ## Devolve um subtotal numa lista ou base de dados
-SUM = SOMA ## Adiciona os respectivos argumentos
-SUMIF = SOMA.SE ## Adiciona as células especificadas por um determinado critério
-SUMIFS = SOMA.SE.S ## Adiciona as células num intervalo que cumpre vários critérios
-SUMPRODUCT = SOMARPRODUTO ## Devolve a soma dos produtos de componentes de matrizes correspondentes
-SUMSQ = SOMARQUAD ## Devolve a soma dos quadrados dos argumentos
-SUMX2MY2 = SOMAX2DY2 ## Devolve a soma da diferença dos quadrados dos valores correspondentes em duas matrizes
-SUMX2PY2 = SOMAX2SY2 ## Devolve a soma da soma dos quadrados dos valores correspondentes em duas matrizes
-SUMXMY2 = SOMAXMY2 ## Devolve a soma dos quadrados da diferença dos valores correspondentes em duas matrizes
-TAN = TAN ## Devolve a tangente de um número
-TANH = TANH ## Devolve a tangente hiperbólica de um número
-TRUNC = TRUNCAR ## Trunca um número para um número inteiro
-
+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
##
-## Statistical functions Funções estatísticas
+## Funções estatísticas (Statistical Functions)
##
-AVEDEV = DESV.MÉDIO ## Devolve a média aritmética dos desvios absolutos à média dos pontos de dados
-AVERAGE = MÉDIA ## Devolve a média dos respectivos argumentos
-AVERAGEA = MÉDIAA ## Devolve uma média dos respectivos argumentos, incluindo números, texto e valores lógicos
-AVERAGEIF = MÉDIA.SE ## Devolve a média aritmética de todas as células num intervalo que cumprem determinado critério
-AVERAGEIFS = MÉDIA.SE.S ## Devolve a média aritmética de todas as células que cumprem múltiplos critérios
-BETADIST = DISTBETA ## Devolve a função de distribuição cumulativa beta
-BETAINV = BETA.ACUM.INV ## Devolve o inverso da função de distribuição cumulativa relativamente a uma distribuição beta específica
-BINOMDIST = DISTRBINOM ## Devolve a probabilidade de distribuição binomial de termo individual
-CHIDIST = DIST.CHI ## Devolve a probabilidade unicaudal da distribuição qui-quadrada
-CHIINV = INV.CHI ## Devolve o inverso da probabilidade unicaudal da distribuição qui-quadrada
-CHITEST = TESTE.CHI ## Devolve o teste para independência
-CONFIDENCE = INT.CONFIANÇA ## Devolve o intervalo de confiança correspondente a uma média de população
-CORREL = CORREL ## Devolve o coeficiente de correlação entre dois conjuntos de dados
-COUNT = CONTAR ## Conta os números que existem na lista de argumentos
-COUNTA = CONTAR.VAL ## Conta os valores que existem na lista de argumentos
-COUNTBLANK = CONTAR.VAZIO ## Conta o número de células em branco num intervalo
-COUNTIF = CONTAR.SE ## Calcula o número de células num intervalo que corresponde aos critérios determinados
-COUNTIFS = CONTAR.SE.S ## Conta o número de células num intervalo que cumprem múltiplos critérios
-COVAR = COVAR ## Devolve a covariância, que é a média dos produtos de desvios de pares
-CRITBINOM = CRIT.BINOM ## Devolve o menor valor em que a distribuição binomial cumulativa é inferior ou igual a um valor de critério
-DEVSQ = DESVQ ## Devolve a soma dos quadrados dos desvios
-EXPONDIST = DISTEXPON ## Devolve a distribuição exponencial
-FDIST = DISTF ## Devolve a distribuição da probabilidade F
-FINV = INVF ## Devolve o inverso da distribuição da probabilidade F
-FISHER = FISHER ## Devolve a transformação Fisher
-FISHERINV = FISHERINV ## Devolve o inverso da transformação Fisher
-FORECAST = PREVISÃO ## Devolve um valor ao longo de uma tendência linear
-FREQUENCY = FREQUÊNCIA ## Devolve uma distribuição de frequência como uma matriz vertical
-FTEST = TESTEF ## Devolve o resultado de um teste F
-GAMMADIST = DISTGAMA ## Devolve a distribuição gama
-GAMMAINV = INVGAMA ## Devolve o inverso da distribuição gama cumulativa
-GAMMALN = LNGAMA ## Devolve o logaritmo natural da função gama, Γ(x)
-GEOMEAN = MÉDIA.GEOMÉTRICA ## Devolve a média geométrica
-GROWTH = CRESCIMENTO ## Devolve valores ao longo de uma tendência exponencial
-HARMEAN = MÉDIA.HARMÓNICA ## Devolve a média harmónica
-HYPGEOMDIST = DIST.HIPERGEOM ## Devolve a distribuição hipergeométrica
-INTERCEPT = INTERCEPTAR ## Devolve a intercepção da linha de regressão linear
-KURT = CURT ## Devolve a curtose de um conjunto de dados
-LARGE = MAIOR ## Devolve o maior valor k-ésimo de um conjunto de dados
-LINEST = PROJ.LIN ## Devolve os parâmetros de uma tendência linear
-LOGEST = PROJ.LOG ## Devolve os parâmetros de uma tendência exponencial
-LOGINV = INVLOG ## Devolve o inverso da distribuição normal logarítmica
-LOGNORMDIST = DIST.NORMALLOG ## Devolve a distribuição normal logarítmica cumulativa
-MAX = MÁXIMO ## Devolve o valor máximo numa lista de argumentos
-MAXA = MÁXIMOA ## Devolve o valor máximo numa lista de argumentos, incluindo números, texto e valores lógicos
-MEDIAN = MED ## Devolve a mediana dos números indicados
-MIN = MÍNIMO ## Devolve o valor mínimo numa lista de argumentos
-MINA = MÍNIMOA ## Devolve o valor mínimo numa lista de argumentos, incluindo números, texto e valores lógicos
-MODE = MODA ## Devolve o valor mais comum num conjunto de dados
-NEGBINOMDIST = DIST.BIN.NEG ## Devolve a distribuição binominal negativa
-NORMDIST = DIST.NORM ## Devolve a distribuição cumulativa normal
-NORMINV = INV.NORM ## Devolve o inverso da distribuição cumulativa normal
-NORMSDIST = DIST.NORMP ## Devolve a distribuição cumulativa normal padrão
-NORMSINV = INV.NORMP ## Devolve o inverso da distribuição cumulativa normal padrão
-PEARSON = PEARSON ## Devolve o coeficiente de correlação momento/produto de Pearson
-PERCENTILE = PERCENTIL ## Devolve o k-ésimo percentil de valores num intervalo
-PERCENTRANK = ORDEM.PERCENTUAL ## Devolve a ordem percentual de um valor num conjunto de dados
-PERMUT = PERMUTAR ## Devolve o número de permutações de um determinado número de objectos
-POISSON = POISSON ## Devolve a distribuição de Poisson
-PROB = PROB ## Devolve a probabilidade dos valores num intervalo se encontrarem entre dois limites
-QUARTILE = QUARTIL ## Devolve o quartil de um conjunto de dados
-RANK = ORDEM ## Devolve a ordem de um número numa lista numérica
-RSQ = RQUAD ## Devolve o quadrado do coeficiente de correlação momento/produto de Pearson
-SKEW = DISTORÇÃO ## Devolve a distorção de uma distribuição
-SLOPE = DECLIVE ## Devolve o declive da linha de regressão linear
-SMALL = MENOR ## Devolve o menor valor de k-ésimo de um conjunto de dados
-STANDARDIZE = NORMALIZAR ## Devolve um valor normalizado
-STDEV = DESVPAD ## Calcula o desvio-padrão com base numa amostra
-STDEVA = DESVPADA ## Calcula o desvio-padrão com base numa amostra, incluindo números, texto e valores lógicos
-STDEVP = DESVPADP ## Calcula o desvio-padrão com base na população total
-STDEVPA = DESVPADPA ## Calcula o desvio-padrão com base na população total, incluindo números, texto e valores lógicos
-STEYX = EPADYX ## Devolve o erro-padrão do valor de y previsto para cada x na regressão
-TDIST = DISTT ## Devolve a distribuição t de Student
-TINV = INVT ## Devolve o inverso da distribuição t de Student
-TREND = TENDÊNCIA ## Devolve valores ao longo de uma tendência linear
-TRIMMEAN = MÉDIA.INTERNA ## Devolve a média do interior de um conjunto de dados
-TTEST = TESTET ## Devolve a probabilidade associada ao teste t de Student
-VAR = VAR ## Calcula a variância com base numa amostra
-VARA = VARA ## Calcula a variância com base numa amostra, incluindo números, texto e valores lógicos
-VARP = VARP ## Calcula a variância com base na população total
-VARPA = VARPA ## Calcula a variância com base na população total, incluindo números, texto e valores lógicos
-WEIBULL = WEIBULL ## Devolve a distribuição Weibull
-ZTEST = TESTEZ ## Devolve o valor de probabilidade unicaudal de um teste-z
-
+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
##
-## Text functions Funções de texto
+## Funções de texto (Text Functions)
##
-ASC = ASC ## Altera letras ou katakana de largura total (byte duplo) numa cadeia de caracteres para caracteres de largura média (byte único)
-BAHTTEXT = TEXTO.BAHT ## Converte um número em texto, utilizando o formato monetário ß (baht)
-CHAR = CARÁCT ## Devolve o carácter especificado pelo número de código
-CLEAN = LIMPAR ## Remove do texto todos os caracteres não imprimíveis
-CODE = CÓDIGO ## Devolve um código numérico correspondente ao primeiro carácter numa cadeia de texto
-CONCATENATE = CONCATENAR ## Agrupa vários itens de texto num único item de texto
-DOLLAR = MOEDA ## Converte um número em texto, utilizando o formato monetário € (Euro)
-EXACT = EXACTO ## Verifica se dois valores de texto são idênticos
-FIND = LOCALIZAR ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas)
-FINDB = LOCALIZARB ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas)
-FIXED = FIXA ## Formata um número como texto com um número fixo de decimais
-JIS = JIS ## Altera letras ou katakana de largura média (byte único) numa cadeia de caracteres para caracteres de largura total (byte duplo)
-LEFT = ESQUERDA ## Devolve os caracteres mais à esquerda de um valor de texto
-LEFTB = ESQUERDAB ## Devolve os caracteres mais à esquerda de um valor de texto
-LEN = NÚM.CARACT ## Devolve o número de caracteres de uma cadeia de texto
-LENB = NÚM.CARACTB ## Devolve o número de caracteres de uma cadeia de texto
-LOWER = MINÚSCULAS ## Converte o texto em minúsculas
-MID = SEG.TEXTO ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada
-MIDB = SEG.TEXTOB ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada
-PHONETIC = FONÉTICA ## Retira os caracteres fonéticos (furigana) de uma cadeia de texto
-PROPER = INICIAL.MAIÚSCULA ## Coloca em maiúsculas a primeira letra de cada palavra de um valor de texto
-REPLACE = SUBSTITUIR ## Substitui caracteres no texto
-REPLACEB = SUBSTITUIRB ## Substitui caracteres no texto
-REPT = REPETIR ## Repete texto um determinado número de vezes
-RIGHT = DIREITA ## Devolve os caracteres mais à direita de um valor de texto
-RIGHTB = DIREITAB ## Devolve os caracteres mais à direita de um valor de texto
-SEARCH = PROCURAR ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas)
-SEARCHB = PROCURARB ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas)
-SUBSTITUTE = SUBST ## Substitui texto novo por texto antigo numa cadeia de texto
-T = T ## Converte os respectivos argumentos em texto
-TEXT = TEXTO ## Formata um número e converte-o em texto
-TRIM = COMPACTAR ## Remove espaços do texto
-UPPER = MAIÚSCULAS ## Converte texto em maiúsculas
-VALUE = VALOR ## Converte um argumento de texto num número
+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
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/config
index 9ee9e6ccafc..2a5a0db8362 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## русский язык (Russian)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = р
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #ПУСТО!
-DIV0 = #ДЕЛ/0!
-VALUE = #ЗНАЧ!
-REF = #ССЫЛ!
-NAME = #ИМЯ?
-NUM = #ЧИСЛО!
-NA = #Н/Д
+NULL = #ПУСТО!
+DIV0 = #ДЕЛ/0!
+VALUE = #ЗНАЧ!
+REF = #ССЫЛКА!
+NAME = #ИМЯ?
+NUM = #ЧИСЛО!
+NA = #Н/Д
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/functions
index 3597dbf89df..7f9ce783287 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/functions
@@ -1,416 +1,536 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from information provided by web-junior (http://www.web-junior.net/)
+## PhpSpreadsheet - function name translations
##
+## русский язык (Russian)
##
+############################################################
##
-## Add-in and Automation functions Функции надстроек и автоматизации
+## Функции кубов (Cube Functions)
##
-GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ ## Возвращает данные, хранящиеся в отчете сводной таблицы.
-
+CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП
+CUBEMEMBER = КУБЭЛЕМЕНТ
+CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА
+CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ
+CUBESET = КУБМНОЖ
+CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ
+CUBEVALUE = КУБЗНАЧЕНИЕ
##
-## Cube functions Функции Куб
+## Функции для работы с базами данных (Database Functions)
##
-CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП ## Возвращает свойство ключевого индикатора производительности «(КИП)» и отображает имя «КИП» в ячейке. «КИП» представляет собой количественную величину, такую как ежемесячная валовая прибыль или ежеквартальная текучесть кадров, используемой для контроля эффективности работы организации.
-CUBEMEMBER = КУБЭЛЕМЕНТ ## Возвращает элемент или кортеж из куба. Используется для проверки существования элемента или кортежа в кубе.
-CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА ## Возвращает значение свойства элемента из куба. Используется для проверки существования имени элемента в кубе и возвращает указанное свойство для этого элемента.
-CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ ## Возвращает n-ый или ранжированный элемент в множество. Используется для возвращения одного или нескольких элементов в множество, например, лучшего продавца или 10 лучших студентов.
-CUBESET = КУБМНОЖ ## Определяет вычислительное множество элементов или кортежей, отправляя на сервер выражение, которое создает множество, а затем возвращает его в Microsoft Office Excel.
-CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ ## Возвращает число элементов множества.
-CUBEVALUE = КУБЗНАЧЕНИЕ ## Возвращает обобщенное значение из куба.
-
+DAVERAGE = ДСРЗНАЧ
+DCOUNT = БСЧЁТ
+DCOUNTA = БСЧЁТА
+DGET = БИЗВЛЕЧЬ
+DMAX = ДМАКС
+DMIN = ДМИН
+DPRODUCT = БДПРОИЗВЕД
+DSTDEV = ДСТАНДОТКЛ
+DSTDEVP = ДСТАНДОТКЛП
+DSUM = БДСУММ
+DVAR = БДДИСП
+DVARP = БДДИСПП
##
-## Database functions Функции для работы с базами данных
+## Функции даты и времени (Date & Time Functions)
##
-DAVERAGE = ДСРЗНАЧ ## Возвращает среднее значение выбранных записей базы данных.
-DCOUNT = БСЧЁТ ## Подсчитывает количество числовых ячеек в базе данных.
-DCOUNTA = БСЧЁТА ## Подсчитывает количество непустых ячеек в базе данных.
-DGET = БИЗВЛЕЧЬ ## Извлекает из базы данных одну запись, удовлетворяющую заданному условию.
-DMAX = ДМАКС ## Возвращает максимальное значение среди выделенных записей базы данных.
-DMIN = ДМИН ## Возвращает минимальное значение среди выделенных записей базы данных.
-DPRODUCT = БДПРОИЗВЕД ## Перемножает значения определенного поля в записях базы данных, удовлетворяющих условию.
-DSTDEV = ДСТАНДОТКЛ ## Оценивает стандартное отклонение по выборке для выделенных записей базы данных.
-DSTDEVP = ДСТАНДОТКЛП ## Вычисляет стандартное отклонение по генеральной совокупности для выделенных записей базы данных
-DSUM = БДСУММ ## Суммирует числа в поле для записей базы данных, удовлетворяющих условию.
-DVAR = БДДИСП ## Оценивает дисперсию по выборке из выделенных записей базы данных
-DVARP = БДДИСПП ## Вычисляет дисперсию по генеральной совокупности для выделенных записей базы данных
-
+DATE = ДАТА
+DATEDIF = РАЗНДАТ
+DATESTRING = СТРОКАДАННЫХ
+DATEVALUE = ДАТАЗНАЧ
+DAY = ДЕНЬ
+DAYS = ДНИ
+DAYS360 = ДНЕЙ360
+EDATE = ДАТАМЕС
+EOMONTH = КОНМЕСЯЦА
+HOUR = ЧАС
+ISOWEEKNUM = НОМНЕДЕЛИ.ISO
+MINUTE = МИНУТЫ
+MONTH = МЕСЯЦ
+NETWORKDAYS = ЧИСТРАБДНИ
+NETWORKDAYS.INTL = ЧИСТРАБДНИ.МЕЖД
+NOW = ТДАТА
+SECOND = СЕКУНДЫ
+THAIDAYOFWEEK = ТАЙДЕНЬНЕД
+THAIMONTHOFYEAR = ТАЙМЕСЯЦ
+THAIYEAR = ТАЙГОД
+TIME = ВРЕМЯ
+TIMEVALUE = ВРЕМЗНАЧ
+TODAY = СЕГОДНЯ
+WEEKDAY = ДЕНЬНЕД
+WEEKNUM = НОМНЕДЕЛИ
+WORKDAY = РАБДЕНЬ
+WORKDAY.INTL = РАБДЕНЬ.МЕЖД
+YEAR = ГОД
+YEARFRAC = ДОЛЯГОДА
##
-## Date and time functions Функции даты и времени
+## Инженерные функции (Engineering Functions)
##
-DATE = ДАТА ## Возвращает заданную дату в числовом формате.
-DATEVALUE = ДАТАЗНАЧ ## Преобразует дату из текстового формата в числовой формат.
-DAY = ДЕНЬ ## Преобразует дату в числовом формате в день месяца.
-DAYS360 = ДНЕЙ360 ## Вычисляет количество дней между двумя датами на основе 360-дневного года.
-EDATE = ДАТАМЕС ## Возвращает дату в числовом формате, отстоящую на заданное число месяцев вперед или назад от начальной даты.
-EOMONTH = КОНМЕСЯЦА ## Возвращает дату в числовом формате для последнего дня месяца, отстоящего вперед или назад на заданное число месяцев.
-HOUR = ЧАС ## Преобразует дату в числовом формате в часы.
-MINUTE = МИНУТЫ ## Преобразует дату в числовом формате в минуты.
-MONTH = МЕСЯЦ ## Преобразует дату в числовом формате в месяцы.
-NETWORKDAYS = ЧИСТРАБДНИ ## Возвращает количество рабочих дней между двумя датами.
-NOW = ТДАТА ## Возвращает текущую дату и время в числовом формате.
-SECOND = СЕКУНДЫ ## Преобразует дату в числовом формате в секунды.
-TIME = ВРЕМЯ ## Возвращает заданное время в числовом формате.
-TIMEVALUE = ВРЕМЗНАЧ ## Преобразует время из текстового формата в числовой формат.
-TODAY = СЕГОДНЯ ## Возвращает текущую дату в числовом формате.
-WEEKDAY = ДЕНЬНЕД ## Преобразует дату в числовом формате в день недели.
-WEEKNUM = НОМНЕДЕЛИ ## Преобразует числовое представление в число, которое указывает, на какую неделю года приходится указанная дата.
-WORKDAY = РАБДЕНЬ ## Возвращает дату в числовом формате, отстоящую вперед или назад на заданное количество рабочих дней.
-YEAR = ГОД ## Преобразует дату в числовом формате в год.
-YEARFRAC = ДОЛЯГОДА ## Возвращает долю года, которую составляет количество дней между начальной и конечной датами.
-
+BESSELI = БЕССЕЛЬ.I
+BESSELJ = БЕССЕЛЬ.J
+BESSELK = БЕССЕЛЬ.K
+BESSELY = БЕССЕЛЬ.Y
+BIN2DEC = ДВ.В.ДЕС
+BIN2HEX = ДВ.В.ШЕСТН
+BIN2OCT = ДВ.В.ВОСЬМ
+BITAND = БИТ.И
+BITLSHIFT = БИТ.СДВИГЛ
+BITOR = БИТ.ИЛИ
+BITRSHIFT = БИТ.СДВИГП
+BITXOR = БИТ.ИСКЛИЛИ
+COMPLEX = КОМПЛЕКСН
+CONVERT = ПРЕОБР
+DEC2BIN = ДЕС.В.ДВ
+DEC2HEX = ДЕС.В.ШЕСТН
+DEC2OCT = ДЕС.В.ВОСЬМ
+DELTA = ДЕЛЬТА
+ERF = ФОШ
+ERF.PRECISE = ФОШ.ТОЧН
+ERFC = ДФОШ
+ERFC.PRECISE = ДФОШ.ТОЧН
+GESTEP = ПОРОГ
+HEX2BIN = ШЕСТН.В.ДВ
+HEX2DEC = ШЕСТН.В.ДЕС
+HEX2OCT = ШЕСТН.В.ВОСЬМ
+IMABS = МНИМ.ABS
+IMAGINARY = МНИМ.ЧАСТЬ
+IMARGUMENT = МНИМ.АРГУМЕНТ
+IMCONJUGATE = МНИМ.СОПРЯЖ
+IMCOS = МНИМ.COS
+IMCOSH = МНИМ.COSH
+IMCOT = МНИМ.COT
+IMCSC = МНИМ.CSC
+IMCSCH = МНИМ.CSCH
+IMDIV = МНИМ.ДЕЛ
+IMEXP = МНИМ.EXP
+IMLN = МНИМ.LN
+IMLOG10 = МНИМ.LOG10
+IMLOG2 = МНИМ.LOG2
+IMPOWER = МНИМ.СТЕПЕНЬ
+IMPRODUCT = МНИМ.ПРОИЗВЕД
+IMREAL = МНИМ.ВЕЩ
+IMSEC = МНИМ.SEC
+IMSECH = МНИМ.SECH
+IMSIN = МНИМ.SIN
+IMSINH = МНИМ.SINH
+IMSQRT = МНИМ.КОРЕНЬ
+IMSUB = МНИМ.РАЗН
+IMSUM = МНИМ.СУММ
+IMTAN = МНИМ.TAN
+OCT2BIN = ВОСЬМ.В.ДВ
+OCT2DEC = ВОСЬМ.В.ДЕС
+OCT2HEX = ВОСЬМ.В.ШЕСТН
##
-## Engineering functions Инженерные функции
+## Финансовые функции (Financial 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 = ВОСЬМ.В.ШЕСТН ## Преобразует восьмеричное число в шестнадцатеричное.
-
+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 = МДЛИТ
+MIRR = МВСД
+NOMINAL = НОМИНАЛ
+NPER = КПЕР
+NPV = ЧПС
+ODDFPRICE = ЦЕНАПЕРВНЕРЕГ
+ODDFYIELD = ДОХОДПЕРВНЕРЕГ
+ODDLPRICE = ЦЕНАПОСЛНЕРЕГ
+ODDLYIELD = ДОХОДПОСЛНЕРЕГ
+PDURATION = ПДЛИТ
+PMT = ПЛТ
+PPMT = ОСПЛТ
+PRICE = ЦЕНА
+PRICEDISC = ЦЕНАСКИДКА
+PRICEMAT = ЦЕНАПОГАШ
+PV = ПС
+RATE = СТАВКА
+RECEIVED = ПОЛУЧЕНО
+RRI = ЭКВ.СТАВКА
+SLN = АПЛ
+SYD = АСЧ
+TBILLEQ = РАВНОКЧЕК
+TBILLPRICE = ЦЕНАКЧЕК
+TBILLYIELD = ДОХОДКЧЕК
+VDB = ПУО
+XIRR = ЧИСТВНДОХ
+XNPV = ЧИСТНЗ
+YIELD = ДОХОД
+YIELDDISC = ДОХОДСКИДКА
+YIELDMAT = ДОХОДПОГАШ
##
-## Financial functions Финансовые функции
+## Информационные функции (Information 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 = ДОХОДПОГАШ ## Возвращает годовой доход от ценных бумаг, проценты по которым выплачиваются в срок погашения.
-
+CELL = ЯЧЕЙКА
+ERROR.TYPE = ТИП.ОШИБКИ
+INFO = ИНФОРМ
+ISBLANK = ЕПУСТО
+ISERR = ЕОШ
+ISERROR = ЕОШИБКА
+ISEVEN = ЕЧЁТН
+ISFORMULA = ЕФОРМУЛА
+ISLOGICAL = ЕЛОГИЧ
+ISNA = ЕНД
+ISNONTEXT = ЕНЕТЕКСТ
+ISNUMBER = ЕЧИСЛО
+ISODD = ЕНЕЧЁТ
+ISREF = ЕССЫЛКА
+ISTEXT = ЕТЕКСТ
+N = Ч
+NA = НД
+SHEET = ЛИСТ
+SHEETS = ЛИСТЫ
+TYPE = ТИП
##
-## Information functions Информационные функции
+## Логические функции (Logical Functions)
##
-CELL = ЯЧЕЙКА ## Возвращает информацию о формате, расположении или содержимом ячейки.
-ERROR.TYPE = ТИП.ОШИБКИ ## Возвращает числовой код, соответствующий типу ошибки.
-INFO = ИНФОРМ ## Возвращает информацию о текущей операционной среде.
-ISBLANK = ЕПУСТО ## Возвращает значение ИСТИНА, если аргумент является ссылкой на пустую ячейку.
-ISERR = ЕОШ ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки, кроме #Н/Д.
-ISERROR = ЕОШИБКА ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки.
-ISEVEN = ЕЧЁТН ## Возвращает значение ИСТИНА, если значение аргумента является четным числом.
-ISLOGICAL = ЕЛОГИЧ ## Возвращает значение ИСТИНА, если аргумент ссылается на логическое значение.
-ISNA = ЕНД ## Возвращает значение ИСТИНА, если аргумент ссылается на значение ошибки #Н/Д.
-ISNONTEXT = ЕНЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента не является текстом.
-ISNUMBER = ЕЧИСЛО ## Возвращает значение ИСТИНА, если аргумент ссылается на число.
-ISODD = ЕНЕЧЁТ ## Возвращает значение ИСТИНА, если значение аргумента является нечетным числом.
-ISREF = ЕССЫЛКА ## Возвращает значение ИСТИНА, если значение аргумента является ссылкой.
-ISTEXT = ЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента является текстом.
-N = Ч ## Возвращает значение, преобразованное в число.
-NA = НД ## Возвращает значение ошибки #Н/Д.
-TYPE = ТИП ## Возвращает число, обозначающее тип данных значения.
-
+AND = И
+FALSE = ЛОЖЬ
+IF = ЕСЛИ
+IFERROR = ЕСЛИОШИБКА
+IFNA = ЕСНД
+IFS = УСЛОВИЯ
+NOT = НЕ
+OR = ИЛИ
+SWITCH = ПЕРЕКЛЮЧ
+TRUE = ИСТИНА
+XOR = ИСКЛИЛИ
##
-## Logical functions Логические функции
+## Функции ссылки и поиска (Lookup & Reference Functions)
##
-AND = И ## Renvoie VRAI si tous ses arguments sont VRAI.
-FALSE = ЛОЖЬ ## Возвращает логическое значение ЛОЖЬ.
-IF = ЕСЛИ ## Выполняет проверку условия.
-IFERROR = ЕСЛИОШИБКА ## Возвращает введённое значение, если вычисление по формуле вызывает ошибку; в противном случае функция возвращает результат вычисления.
-NOT = НЕ ## Меняет логическое значение своего аргумента на противоположное.
-OR = ИЛИ ## Возвращает значение ИСТИНА, если хотя бы один аргумент имеет значение ИСТИНА.
-TRUE = ИСТИНА ## Возвращает логическое значение ИСТИНА.
-
+ADDRESS = АДРЕС
+AREAS = ОБЛАСТИ
+CHOOSE = ВЫБОР
+COLUMN = СТОЛБЕЦ
+COLUMNS = ЧИСЛСТОЛБ
+FORMULATEXT = Ф.ТЕКСТ
+GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ
+HLOOKUP = ГПР
+HYPERLINK = ГИПЕРССЫЛКА
+INDEX = ИНДЕКС
+INDIRECT = ДВССЫЛ
+LOOKUP = ПРОСМОТР
+MATCH = ПОИСКПОЗ
+OFFSET = СМЕЩ
+ROW = СТРОКА
+ROWS = ЧСТРОК
+RTD = ДРВ
+TRANSPOSE = ТРАНСП
+VLOOKUP = ВПР
##
-## Lookup and reference functions Функции ссылки и поиска
+## Математические и тригонометрические функции (Math & Trig Functions)
##
-ADDRESS = АДРЕС ## Возвращает ссылку на отдельную ячейку листа в виде текста.
-AREAS = ОБЛАСТИ ## Возвращает количество областей в ссылке.
-CHOOSE = ВЫБОР ## Выбирает значение из списка значений по индексу.
-COLUMN = СТОЛБЕЦ ## Возвращает номер столбца, на который указывает ссылка.
-COLUMNS = ЧИСЛСТОЛБ ## Возвращает количество столбцов в ссылке.
-HLOOKUP = ГПР ## Ищет в первой строке массива и возвращает значение отмеченной ячейки
-HYPERLINK = ГИПЕРССЫЛКА ## Создает ссылку, открывающую документ, который находится на сервере сети, в интрасети или в Интернете.
-INDEX = ИНДЕКС ## Использует индекс для выбора значения из ссылки или массива.
-INDIRECT = ДВССЫЛ ## Возвращает ссылку, заданную текстовым значением.
-LOOKUP = ПРОСМОТР ## Ищет значения в векторе или массиве.
-MATCH = ПОИСКПОЗ ## Ищет значения в ссылке или массиве.
-OFFSET = СМЕЩ ## Возвращает смещение ссылки относительно заданной ссылки.
-ROW = СТРОКА ## Возвращает номер строки, определяемой ссылкой.
-ROWS = ЧСТРОК ## Возвращает количество строк в ссылке.
-RTD = ДРВ ## Извлекает данные реального времени из программ, поддерживающих автоматизацию COM (Программирование объектов. Стандартное средство для работы с объектами некоторого приложения из другого приложения или средства разработки. Программирование объектов (ранее называемое программированием OLE) является функцией модели COM (Component Object Model, модель компонентных объектов).).
-TRANSPOSE = ТРАНСП ## Возвращает транспонированный массив.
-VLOOKUP = ВПР ## Ищет значение в первом столбце массива и возвращает значение из ячейки в найденной строке и указанном столбце.
-
+ABS = ABS
+ACOS = ACOS
+ACOSH = ACOSH
+ACOT = ACOT
+ACOTH = ACOTH
+AGGREGATE = АГРЕГАТ
+ARABIC = АРАБСКОЕ
+ASIN = ASIN
+ASINH = ASINH
+ATAN = ATAN
+ATAN2 = ATAN2
+ATANH = ATANH
+BASE = ОСНОВАНИЕ
+CEILING.MATH = ОКРВВЕРХ.МАТ
+CEILING.PRECISE = ОКРВВЕРХ.ТОЧН
+COMBIN = ЧИСЛКОМБ
+COMBINA = ЧИСЛКОМБА
+COS = COS
+COSH = COSH
+COT = COT
+COTH = COTH
+CSC = CSC
+CSCH = CSCH
+DECIMAL = ДЕС
+DEGREES = ГРАДУСЫ
+ECMA.CEILING = ECMA.ОКРВВЕРХ
+EVEN = ЧЁТН
+EXP = EXP
+FACT = ФАКТР
+FACTDOUBLE = ДВФАКТР
+FLOOR.MATH = ОКРВНИЗ.МАТ
+FLOOR.PRECISE = ОКРВНИЗ.ТОЧН
+GCD = НОД
+INT = ЦЕЛОЕ
+ISO.CEILING = ISO.ОКРВВЕРХ
+LCM = НОК
+LN = LN
+LOG = LOG
+LOG10 = LOG10
+MDETERM = МОПРЕД
+MINVERSE = МОБР
+MMULT = МУМНОЖ
+MOD = ОСТАТ
+MROUND = ОКРУГЛТ
+MULTINOMIAL = МУЛЬТИНОМ
+MUNIT = МЕДИН
+ODD = НЕЧЁТ
+PI = ПИ
+POWER = СТЕПЕНЬ
+PRODUCT = ПРОИЗВЕД
+QUOTIENT = ЧАСТНОЕ
+RADIANS = РАДИАНЫ
+RAND = СЛЧИС
+RANDBETWEEN = СЛУЧМЕЖДУ
+ROMAN = РИМСКОЕ
+ROUND = ОКРУГЛ
+ROUNDBAHTDOWN = ОКРУГЛБАТВНИЗ
+ROUNDBAHTUP = ОКРУГЛБАТВВЕРХ
+ROUNDDOWN = ОКРУГЛВНИЗ
+ROUNDUP = ОКРУГЛВВЕРХ
+SEC = SEC
+SECH = SECH
+SERIESSUM = РЯД.СУММ
+SIGN = ЗНАК
+SIN = SIN
+SINH = SINH
+SQRT = КОРЕНЬ
+SQRTPI = КОРЕНЬПИ
+SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ
+SUM = СУММ
+SUMIF = СУММЕСЛИ
+SUMIFS = СУММЕСЛИМН
+SUMPRODUCT = СУММПРОИЗВ
+SUMSQ = СУММКВ
+SUMX2MY2 = СУММРАЗНКВ
+SUMX2PY2 = СУММСУММКВ
+SUMXMY2 = СУММКВРАЗН
+TAN = TAN
+TANH = TANH
+TRUNC = ОТБР
##
-## Math and trigonometry functions Математические и тригонометрические функции
+## Статистические функции (Statistical 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 = ОТБР ## Отбрасывает дробную часть числа.
-
+AVEDEV = СРОТКЛ
+AVERAGE = СРЗНАЧ
+AVERAGEA = СРЗНАЧА
+AVERAGEIF = СРЗНАЧЕСЛИ
+AVERAGEIFS = СРЗНАЧЕСЛИМН
+BETA.DIST = БЕТА.РАСП
+BETA.INV = БЕТА.ОБР
+BINOM.DIST = БИНОМ.РАСП
+BINOM.DIST.RANGE = БИНОМ.РАСП.ДИАП
+BINOM.INV = БИНОМ.ОБР
+CHISQ.DIST = ХИ2.РАСП
+CHISQ.DIST.RT = ХИ2.РАСП.ПХ
+CHISQ.INV = ХИ2.ОБР
+CHISQ.INV.RT = ХИ2.ОБР.ПХ
+CHISQ.TEST = ХИ2.ТЕСТ
+CONFIDENCE.NORM = ДОВЕРИТ.НОРМ
+CONFIDENCE.T = ДОВЕРИТ.СТЬЮДЕНТ
+CORREL = КОРРЕЛ
+COUNT = СЧЁТ
+COUNTA = СЧЁТЗ
+COUNTBLANK = СЧИТАТЬПУСТОТЫ
+COUNTIF = СЧЁТЕСЛИ
+COUNTIFS = СЧЁТЕСЛИМН
+COVARIANCE.P = КОВАРИАЦИЯ.Г
+COVARIANCE.S = КОВАРИАЦИЯ.В
+DEVSQ = КВАДРОТКЛ
+EXPON.DIST = ЭКСП.РАСП
+F.DIST = F.РАСП
+F.DIST.RT = F.РАСП.ПХ
+F.INV = F.ОБР
+F.INV.RT = F.ОБР.ПХ
+F.TEST = F.ТЕСТ
+FISHER = ФИШЕР
+FISHERINV = ФИШЕРОБР
+FORECAST.ETS = ПРЕДСКАЗ.ETS
+FORECAST.ETS.CONFINT = ПРЕДСКАЗ.ЕTS.ДОВИНТЕРВАЛ
+FORECAST.ETS.SEASONALITY = ПРЕДСКАЗ.ETS.СЕЗОННОСТЬ
+FORECAST.ETS.STAT = ПРЕДСКАЗ.ETS.СТАТ
+FORECAST.LINEAR = ПРЕДСКАЗ.ЛИНЕЙН
+FREQUENCY = ЧАСТОТА
+GAMMA = ГАММА
+GAMMA.DIST = ГАММА.РАСП
+GAMMA.INV = ГАММА.ОБР
+GAMMALN = ГАММАНЛОГ
+GAMMALN.PRECISE = ГАММАНЛОГ.ТОЧН
+GAUSS = ГАУСС
+GEOMEAN = СРГЕОМ
+GROWTH = РОСТ
+HARMEAN = СРГАРМ
+HYPGEOM.DIST = ГИПЕРГЕОМ.РАСП
+INTERCEPT = ОТРЕЗОК
+KURT = ЭКСЦЕСС
+LARGE = НАИБОЛЬШИЙ
+LINEST = ЛИНЕЙН
+LOGEST = ЛГРФПРИБЛ
+LOGNORM.DIST = ЛОГНОРМ.РАСП
+LOGNORM.INV = ЛОГНОРМ.ОБР
+MAX = МАКС
+MAXA = МАКСА
+MAXIFS = МАКСЕСЛИ
+MEDIAN = МЕДИАНА
+MIN = МИН
+MINA = МИНА
+MINIFS = МИНЕСЛИ
+MODE.MULT = МОДА.НСК
+MODE.SNGL = МОДА.ОДН
+NEGBINOM.DIST = ОТРБИНОМ.РАСП
+NORM.DIST = НОРМ.РАСП
+NORM.INV = НОРМ.ОБР
+NORM.S.DIST = НОРМ.СТ.РАСП
+NORM.S.INV = НОРМ.СТ.ОБР
+PEARSON = PEARSON
+PERCENTILE.EXC = ПРОЦЕНТИЛЬ.ИСКЛ
+PERCENTILE.INC = ПРОЦЕНТИЛЬ.ВКЛ
+PERCENTRANK.EXC = ПРОЦЕНТРАНГ.ИСКЛ
+PERCENTRANK.INC = ПРОЦЕНТРАНГ.ВКЛ
+PERMUT = ПЕРЕСТ
+PERMUTATIONA = ПЕРЕСТА
+PHI = ФИ
+POISSON.DIST = ПУАССОН.РАСП
+PROB = ВЕРОЯТНОСТЬ
+QUARTILE.EXC = КВАРТИЛЬ.ИСКЛ
+QUARTILE.INC = КВАРТИЛЬ.ВКЛ
+RANK.AVG = РАНГ.СР
+RANK.EQ = РАНГ.РВ
+RSQ = КВПИРСОН
+SKEW = СКОС
+SKEW.P = СКОС.Г
+SLOPE = НАКЛОН
+SMALL = НАИМЕНЬШИЙ
+STANDARDIZE = НОРМАЛИЗАЦИЯ
+STDEV.P = СТАНДОТКЛОН.Г
+STDEV.S = СТАНДОТКЛОН.В
+STDEVA = СТАНДОТКЛОНА
+STDEVPA = СТАНДОТКЛОНПА
+STEYX = СТОШYX
+T.DIST = СТЬЮДЕНТ.РАСП
+T.DIST.2T = СТЬЮДЕНТ.РАСП.2Х
+T.DIST.RT = СТЬЮДЕНТ.РАСП.ПХ
+T.INV = СТЬЮДЕНТ.ОБР
+T.INV.2T = СТЬЮДЕНТ.ОБР.2Х
+T.TEST = СТЬЮДЕНТ.ТЕСТ
+TREND = ТЕНДЕНЦИЯ
+TRIMMEAN = УРЕЗСРЕДНЕЕ
+VAR.P = ДИСП.Г
+VAR.S = ДИСП.В
+VARA = ДИСПА
+VARPA = ДИСПРА
+WEIBULL.DIST = ВЕЙБУЛЛ.РАСП
+Z.TEST = Z.ТЕСТ
##
-## Statistical functions Статистические функции
+## Текстовые функции (Text 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-теста.
-
+BAHTTEXT = БАТТЕКСТ
+CHAR = СИМВОЛ
+CLEAN = ПЕЧСИМВ
+CODE = КОДСИМВ
+CONCAT = СЦЕП
+DOLLAR = РУБЛЬ
+EXACT = СОВПАД
+FIND = НАЙТИ
+FIXED = ФИКСИРОВАННЫЙ
+ISTHAIDIGIT = TAYRAKAMIYSA
+LEFT = ЛЕВСИМВ
+LEN = ДЛСТР
+LOWER = СТРОЧН
+MID = ПСТР
+NUMBERSTRING = СТРОКАЧИСЕЛ
+NUMBERVALUE = ЧЗНАЧ
+PROPER = ПРОПНАЧ
+REPLACE = ЗАМЕНИТЬ
+REPT = ПОВТОР
+RIGHT = ПРАВСИМВ
+SEARCH = ПОИСК
+SUBSTITUTE = ПОДСТАВИТЬ
+T = Т
+TEXT = ТЕКСТ
+TEXTJOIN = ОБЪЕДИНИТЬ
+THAIDIGIT = ТАЙЦИФРА
+THAINUMSOUND = ТАЙЧИСЛОВЗВУК
+THAINUMSTRING = ТАЙЧИСЛОВСТРОКУ
+THAISTRINGLENGTH = ТАЙДЛИНАСТРОКИ
+TRIM = СЖПРОБЕЛЫ
+UNICHAR = ЮНИСИМВ
+UNICODE = UNICODE
+UPPER = ПРОПИСН
+VALUE = ЗНАЧЕН
##
-## Text functions Текстовые функции
+## Веб-функции (Web 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 = ЗНАЧЕН ## Преобразует текстовый аргумент в число.
+ENCODEURL = КОДИР.URL
+FILTERXML = ФИЛЬТР.XML
+WEBSERVICE = ВЕБСЛУЖБА
+
+##
+## Функции совместимости (Compatibility Functions)
+##
+BETADIST = БЕТАРАСП
+BETAINV = БЕТАОБР
+BINOMDIST = БИНОМРАСП
+CEILING = ОКРВВЕРХ
+CHIDIST = ХИ2РАСП
+CHIINV = ХИ2ОБР
+CHITEST = ХИ2ТЕСТ
+CONCATENATE = СЦЕПИТЬ
+CONFIDENCE = ДОВЕРИТ
+COVAR = КОВАР
+CRITBINOM = КРИТБИНОМ
+EXPONDIST = ЭКСПРАСП
+FDIST = FРАСП
+FINV = FРАСПОБР
+FLOOR = ОКРВНИЗ
+FORECAST = ПРЕДСКАЗ
+FTEST = ФТЕСТ
+GAMMADIST = ГАММАРАСП
+GAMMAINV = ГАММАОБР
+HYPGEOMDIST = ГИПЕРГЕОМЕТ
+LOGINV = ЛОГНОРМОБР
+LOGNORMDIST = ЛОГНОРМРАСП
+MODE = МОДА
+NEGBINOMDIST = ОТРБИНОМРАСП
+NORMDIST = НОРМРАСП
+NORMINV = НОРМОБР
+NORMSDIST = НОРМСТРАСП
+NORMSINV = НОРМСТОБР
+PERCENTILE = ПЕРСЕНТИЛЬ
+PERCENTRANK = ПРОЦЕНТРАНГ
+POISSON = ПУАССОН
+QUARTILE = КВАРТИЛЬ
+RANK = РАНГ
+STDEV = СТАНДОТКЛОН
+STDEVP = СТАНДОТКЛОНП
+TDIST = СТЬЮДРАСП
+TINV = СТЬЮДРАСПОБР
+TTEST = ТТЕСТ
+VAR = ДИСП
+VARP = ДИСПР
+WEIBULL = ВЕЙБУЛЛ
+ZTEST = ZТЕСТ
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/config
index bf72cc4f125..c7440f71cdb 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Svenska (Swedish)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = kr
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #Skärning!
-DIV0 = #Division/0!
-VALUE = #Värdefel!
-REF = #Referens!
-NAME = #Namn?
-NUM = #Ogiltigt!
-NA = #Saknas!
+NULL = #SKÄRNING!
+DIV0 = #DIVISION/0!
+VALUE = #VÄRDEFEL!
+REF = #REFERENS!
+NAME = #NAMN?
+NUM = #OGILTIGT!
+NA = #SAKNAS!
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/functions
index 73b2deb5eb2..2531b4c1dcf 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/functions
@@ -1,408 +1,532 @@
+############################################################
##
-## Add-in and Automation functions Tilläggs- och automatiseringsfunktioner
+## PhpSpreadsheet - function name translations
##
-GETPIVOTDATA = HÄMTA.PIVOTDATA ## Returnerar data som lagrats i en pivottabellrapport
+## Svenska (Swedish)
+##
+############################################################
##
-## Cube functions Kubfunktioner
+## Kubfunktioner (Cube Functions)
##
-CUBEKPIMEMBER = KUBKPIMEDLEM ## Returnerar namn, egenskap och mått för en KPI och visar namnet och egenskapen i cellen. En KPI, eller prestandaindikator, är ett kvantifierbart mått, t.ex. månatlig bruttovinst eller personalomsättning per kvartal, som används för att analysera ett företags resultat.
-CUBEMEMBER = KUBMEDLEM ## Returnerar en medlem eller ett par i en kubhierarki. Används för att verifiera att medlemmen eller paret finns i kuben.
-CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP ## Returnerar värdet för en medlemsegenskap i kuben. Används för att verifiera att ett medlemsnamn finns i kuben, samt för att returnera den angivna egenskapen för medlemmen.
-CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM ## Returnerar den n:te, eller rangordnade, medlemmen i en uppsättning. Används för att returnera ett eller flera element i en uppsättning, till exempelvis den bästa försäljaren eller de tio bästa eleverna.
-CUBESET = KUBINSTÄLLNING ## Definierar en beräknad uppsättning medlemmar eller par genom att skicka ett bestämt uttryck till kuben på servern, som skapar uppsättningen och sedan returnerar den till Microsoft Office Excel.
-CUBESETCOUNT = KUBINSTÄLLNINGANTAL ## Returnerar antalet objekt i en uppsättning.
-CUBEVALUE = KUBVÄRDE ## Returnerar ett mängdvärde från en kub.
-
+CUBEKPIMEMBER = KUBKPIMEDLEM
+CUBEMEMBER = KUBMEDLEM
+CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP
+CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM
+CUBESET = KUBUPPSÄTTNING
+CUBESETCOUNT = KUBUPPSÄTTNINGANTAL
+CUBEVALUE = KUBVÄRDE
##
-## Database functions Databasfunktioner
+## Databasfunktioner (Database Functions)
##
-DAVERAGE = DMEDEL ## Returnerar medelvärdet av databasposterna
-DCOUNT = DANTAL ## Räknar antalet celler som innehåller tal i en databas
-DCOUNTA = DANTALV ## Räknar ifyllda celler i en databas
-DGET = DHÄMTA ## Hämtar en enstaka post från en databas som uppfyller de angivna villkoren
-DMAX = DMAX ## Returnerar det största värdet från databasposterna
-DMIN = DMIN ## Returnerar det minsta värdet från databasposterna
-DPRODUCT = DPRODUKT ## Multiplicerar värdena i ett visst fält i poster som uppfyller villkoret
-DSTDEV = DSTDAV ## Uppskattar standardavvikelsen baserat på ett urval av databasposterna
-DSTDEVP = DSTDAVP ## Beräknar standardavvikelsen utifrån hela populationen av valda databasposter
-DSUM = DSUMMA ## Summerar talen i kolumnfält i databasposter som uppfyller villkoret
-DVAR = DVARIANS ## Uppskattar variansen baserat på ett urval av databasposterna
-DVARP = DVARIANSP ## Beräknar variansen utifrån hela populationen av valda databasposter
-
+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
##
-## Date and time functions Tid- och datumfunktioner
+## Tid- och datumfunktioner (Date & Time Functions)
##
-DATE = DATUM ## Returnerar ett serienummer för ett visst datum
-DATEVALUE = DATUMVÄRDE ## Konverterar ett datum i textformat till ett serienummer
-DAY = DAG ## Konverterar ett serienummer till dag i månaden
-DAYS360 = DAGAR360 ## Beräknar antalet dagar mellan två datum baserat på ett 360-dagarsår
-EDATE = EDATUM ## Returnerar serienumret för ett datum som infaller ett visst antal månader före eller efter startdatumet
-EOMONTH = SLUTMÅNAD ## Returnerar serienumret för sista dagen i månaden ett visst antal månader tidigare eller senare
-HOUR = TIMME ## Konverterar ett serienummer till en timme
-MINUTE = MINUT ## Konverterar ett serienummer till en minut
-MONTH = MÅNAD ## Konverterar ett serienummer till en månad
-NETWORKDAYS = NETTOARBETSDAGAR ## Returnerar antalet hela arbetsdagar mellan två datum
-NOW = NU ## Returnerar serienumret för dagens datum och aktuell tid
-SECOND = SEKUND ## Konverterar ett serienummer till en sekund
-TIME = KLOCKSLAG ## Returnerar serienumret för en viss tid
-TIMEVALUE = TIDVÄRDE ## Konverterar en tid i textformat till ett serienummer
-TODAY = IDAG ## Returnerar serienumret för dagens datum
-WEEKDAY = VECKODAG ## Konverterar ett serienummer till en dag i veckan
-WEEKNUM = VECKONR ## Konverterar ett serienummer till ett veckonummer
-WORKDAY = ARBETSDAGAR ## Returnerar serienumret för ett datum ett visst antal arbetsdagar tidigare eller senare
-YEAR = ÅR ## Konverterar ett serienummer till ett år
-YEARFRAC = ÅRDEL ## Returnerar en del av ett år som representerar antalet hela dagar mellan start- och slutdatum
-
+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
##
-## Engineering functions Tekniska funktioner
+## Tekniska funktioner (Engineering Functions)
##
-BESSELI = BESSELI ## Returnerar den modifierade Bessel-funktionen In(x)
-BESSELJ = BESSELJ ## Returnerar Bessel-funktionen Jn(x)
-BESSELK = BESSELK ## Returnerar den modifierade Bessel-funktionen Kn(x)
-BESSELY = BESSELY ## Returnerar Bessel-funktionen Yn(x)
-BIN2DEC = BIN.TILL.DEC ## Omvandlar ett binärt tal till decimalt
-BIN2HEX = BIN.TILL.HEX ## Omvandlar ett binärt tal till hexadecimalt
-BIN2OCT = BIN.TILL.OKT ## Omvandlar ett binärt tal till oktalt
-COMPLEX = KOMPLEX ## Omvandlar reella och imaginära koefficienter till ett komplext tal
-CONVERT = KONVERTERA ## Omvandlar ett tal från ett måttsystem till ett annat
-DEC2BIN = DEC.TILL.BIN ## Omvandlar ett decimalt tal till binärt
-DEC2HEX = DEC.TILL.HEX ## Omvandlar ett decimalt tal till hexadecimalt
-DEC2OCT = DEC.TILL.OKT ## Omvandlar ett decimalt tal till oktalt
-DELTA = DELTA ## Testar om två värden är lika
-ERF = FELF ## Returnerar felfunktionen
-ERFC = FELFK ## Returnerar den komplementära felfunktionen
-GESTEP = SLSTEG ## Testar om ett tal är större än ett tröskelvärde
-HEX2BIN = HEX.TILL.BIN ## Omvandlar ett hexadecimalt tal till binärt
-HEX2DEC = HEX.TILL.DEC ## Omvandlar ett hexadecimalt tal till decimalt
-HEX2OCT = HEX.TILL.OKT ## Omvandlar ett hexadecimalt tal till oktalt
-IMABS = IMABS ## Returnerar absolutvärdet (modulus) för ett komplext tal
-IMAGINARY = IMAGINÄR ## Returnerar den imaginära koefficienten för ett komplext tal
-IMARGUMENT = IMARGUMENT ## Returnerar det komplexa talets argument, en vinkel uttryckt i radianer
-IMCONJUGATE = IMKONJUGAT ## Returnerar det komplexa talets konjugat
-IMCOS = IMCOS ## Returnerar cosinus för ett komplext tal
-IMDIV = IMDIV ## Returnerar kvoten för två komplexa tal
-IMEXP = IMEUPPHÖJT ## Returnerar exponenten för ett komplext tal
-IMLN = IMLN ## Returnerar den naturliga logaritmen för ett komplext tal
-IMLOG10 = IMLOG10 ## Returnerar 10-logaritmen för ett komplext tal
-IMLOG2 = IMLOG2 ## Returnerar 2-logaritmen för ett komplext tal
-IMPOWER = IMUPPHÖJT ## Returnerar ett komplext tal upphöjt till en exponent
-IMPRODUCT = IMPRODUKT ## Returnerar produkten av komplexa tal
-IMREAL = IMREAL ## Returnerar den reella koefficienten för ett komplext tal
-IMSIN = IMSIN ## Returnerar sinus för ett komplext tal
-IMSQRT = IMROT ## Returnerar kvadratroten av ett komplext tal
-IMSUB = IMDIFF ## Returnerar differensen mellan två komplexa tal
-IMSUM = IMSUM ## Returnerar summan av komplexa tal
-OCT2BIN = OKT.TILL.BIN ## Omvandlar ett oktalt tal till binärt
-OCT2DEC = OKT.TILL.DEC ## Omvandlar ett oktalt tal till decimalt
-OCT2HEX = OKT.TILL.HEX ## Omvandlar ett oktalt tal till hexadecimalt
-
+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
##
-## Financial functions Finansiella funktioner
+## Finansiella funktioner (Financial Functions)
##
-ACCRINT = UPPLRÄNTA ## Returnerar den upplupna räntan för värdepapper med periodisk ränta
-ACCRINTM = UPPLOBLRÄNTA ## Returnerar den upplupna räntan för ett värdepapper som ger avkastning på förfallodagen
-AMORDEGRC = AMORDEGRC ## Returnerar avskrivningen för varje redovisningsperiod med hjälp av en avskrivningskoefficient
-AMORLINC = AMORLINC ## Returnerar avskrivningen för varje redovisningsperiod
-COUPDAYBS = KUPDAGBB ## Returnerar antal dagar från början av kupongperioden till likviddagen
-COUPDAYS = KUPDAGARS ## Returnerar antalet dagar i kupongperioden som innehåller betalningsdatumet
-COUPDAYSNC = KUPDAGNK ## Returnerar antalet dagar från betalningsdatumet till nästa kupongdatum
-COUPNCD = KUPNKD ## Returnerar nästa kupongdatum efter likviddagen
-COUPNUM = KUPANT ## Returnerar kuponger som förfaller till betalning mellan likviddagen och förfallodagen
-COUPPCD = KUPFKD ## Returnerar föregående kupongdatum före likviddagen
-CUMIPMT = KUMRÄNTA ## Returnerar den ackumulerade räntan som betalats mellan två perioder
-CUMPRINC = KUMPRIS ## Returnerar det ackumulerade kapitalbeloppet som betalats på ett lån mellan två perioder
-DB = DB ## Returnerar avskrivningen för en tillgång under en angiven tid enligt metoden för fast degressiv avskrivning
-DDB = DEGAVSKR ## Returnerar en tillgångs värdeminskning under en viss period med hjälp av dubbel degressiv avskrivning eller någon annan metod som du anger
-DISC = DISK ## Returnerar diskonteringsräntan för ett värdepapper
-DOLLARDE = DECTAL ## Omvandlar ett pris uttryckt som ett bråk till ett decimaltal
-DOLLARFR = BRÅK ## Omvandlar ett pris i kronor uttryckt som ett decimaltal till ett bråk
-DURATION = LÖPTID ## Returnerar den årliga löptiden för en säkerhet med periodiska räntebetalningar
-EFFECT = EFFRÄNTA ## Returnerar den årliga effektiva räntesatsen
-FV = SLUTVÄRDE ## Returnerar det framtida värdet på en investering
-FVSCHEDULE = FÖRRÄNTNING ## Returnerar det framtida värdet av ett begynnelsekapital beräknat på olika räntenivåer
-INTRATE = ÅRSRÄNTA ## Returnerar räntesatsen för ett betalt värdepapper
-IPMT = RBETALNING ## Returnerar räntedelen av en betalning för en given period
-IRR = IR ## Returnerar internräntan för en serie betalningar
-ISPMT = RALÅN ## Beräknar räntan som har betalats under en specifik betalningsperiod
-MDURATION = MLÖPTID ## Returnerar den modifierade Macauley-löptiden för ett värdepapper med det antagna nominella värdet 100 kr
-MIRR = MODIR ## Returnerar internräntan där positiva och negativa betalningar finansieras med olika räntor
-NOMINAL = NOMRÄNTA ## Returnerar den årliga nominella räntesatsen
-NPER = PERIODER ## Returnerar antalet perioder för en investering
-NPV = NETNUVÄRDE ## Returnerar nuvärdet av en serie periodiska betalningar vid en given diskonteringsränta
-ODDFPRICE = UDDAFPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda första period
-ODDFYIELD = UDDAFAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda första period
-ODDLPRICE = UDDASPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda sista period
-ODDLYIELD = UDDASAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda sista period
-PMT = BETALNING ## Returnerar den periodiska betalningen för en annuitet
-PPMT = AMORT ## Returnerar amorteringsdelen av en annuitetsbetalning för en given period
-PRICE = PRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger periodisk ränta
-PRICEDISC = PRISDISK ## Returnerar priset per 100 kr nominellt värde för ett diskonterat värdepapper
-PRICEMAT = PRISFÖRF ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger ränta på förfallodagen
-PV = PV ## Returnerar nuvärdet av en serie lika stora periodiska betalningar
-RATE = RÄNTA ## Returnerar räntesatsen per period i en annuitet
-RECEIVED = BELOPP ## Returnerar beloppet som utdelas på förfallodagen för ett betalat värdepapper
-SLN = LINAVSKR ## Returnerar den linjära avskrivningen för en tillgång under en period
-SYD = ÅRSAVSKR ## Returnerar den årliga avskrivningssumman för en tillgång under en angiven period
-TBILLEQ = SSVXEKV ## Returnerar avkastningen motsvarande en obligation för en statsskuldväxel
-TBILLPRICE = SSVXPRIS ## Returnerar priset per 100 kr nominellt värde för en statsskuldväxel
-TBILLYIELD = SSVXRÄNTA ## Returnerar avkastningen för en statsskuldväxel
-VDB = VDEGRAVSKR ## Returnerar avskrivningen för en tillgång under en angiven period (med degressiv avskrivning)
-XIRR = XIRR ## Returnerar internräntan för en serie betalningar som inte nödvändigtvis är periodiska
-XNPV = XNUVÄRDE ## Returnerar det nuvarande nettovärdet för en serie betalningar som inte nödvändigtvis är periodiska
-YIELD = NOMAVK ## Returnerar avkastningen för ett värdepapper som ger periodisk ränta
-YIELDDISC = NOMAVKDISK ## Returnerar den årliga avkastningen för diskonterade värdepapper, exempelvis en statsskuldväxel
-YIELDMAT = NOMAVKFÖRF ## Returnerar den årliga avkastningen för ett värdepapper som ger ränta på förfallodagen
-
+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
##
-## Information functions Informationsfunktioner
+## Informationsfunktioner (Information Functions)
##
-CELL = CELL ## Returnerar information om formatering, plats och innehåll i en cell
-ERROR.TYPE = FEL.TYP ## Returnerar ett tal som motsvarar ett felvärde
-INFO = INFO ## Returnerar information om operativsystemet
-ISBLANK = ÄRREF ## Returnerar SANT om värdet är tomt
-ISERR = Ä ## Returnerar SANT om värdet är ett felvärde annat än #SAKNAS!
-ISERROR = ÄRFEL ## Returnerar SANT om värdet är ett felvärde
-ISEVEN = ÄRJÄMN ## Returnerar SANT om talet är jämnt
-ISLOGICAL = ÄREJTEXT ## Returnerar SANT om värdet är ett logiskt värde
-ISNA = ÄRLOGISK ## Returnerar SANT om värdet är felvärdet #SAKNAS!
-ISNONTEXT = ÄRSAKNAD ## Returnerar SANT om värdet inte är text
-ISNUMBER = ÄRTAL ## Returnerar SANT om värdet är ett tal
-ISODD = ÄRUDDA ## Returnerar SANT om talet är udda
-ISREF = ÄRTOM ## Returnerar SANT om värdet är en referens
-ISTEXT = ÄRTEXT ## Returnerar SANT om värdet är text
-N = N ## Returnerar ett värde omvandlat till ett tal
-NA = SAKNAS ## Returnerar felvärdet #SAKNAS!
-TYPE = VÄRDETYP ## Returnerar ett tal som anger värdets datatyp
-
+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
##
-## Logical functions Logiska funktioner
+## Logiska funktioner (Logical Functions)
##
-AND = OCH ## Returnerar SANT om alla argument är sanna
-FALSE = FALSKT ## Returnerar det logiska värdet FALSKT
-IF = OM ## Anger vilket logiskt test som ska utföras
-IFERROR = OMFEL ## Returnerar ett värde som du anger om en formel utvärderar till ett fel; annars returneras resultatet av formeln
-NOT = ICKE ## Inverterar logiken för argumenten
-OR = ELLER ## Returnerar SANT om något argument är SANT
-TRUE = SANT ## Returnerar det logiska värdet SANT
-
+AND = OCH
+FALSE = FALSKT
+IF = OM
+IFERROR = OMFEL
+IFNA = OMSAKNAS
+IFS = IFS
+NOT = ICKE
+OR = ELLER
+SWITCH = VÄXLA
+TRUE = SANT
+XOR = XELLER
##
-## Lookup and reference functions Sök- och referensfunktioner
+## Sök- och referensfunktioner (Lookup & Reference Functions)
##
-ADDRESS = ADRESS ## Returnerar en referens som text till en enstaka cell i ett kalkylblad
-AREAS = OMRÅDEN ## Returnerar antalet områden i en referens
-CHOOSE = VÄLJ ## Väljer ett värde i en lista över värden
-COLUMN = KOLUMN ## Returnerar kolumnnumret för en referens
-COLUMNS = KOLUMNER ## Returnerar antalet kolumner i en referens
-HLOOKUP = LETAKOLUMN ## Söker i den översta raden i en matris och returnerar värdet för angiven cell
-HYPERLINK = HYPERLÄNK ## Skapar en genväg eller ett hopp till ett dokument i nätverket, i ett intranät eller på Internet
-INDEX = INDEX ## Använder ett index för ett välja ett värde i en referens eller matris
-INDIRECT = INDIREKT ## Returnerar en referens som anges av ett textvärde
-LOOKUP = LETAUPP ## Letar upp värden i en vektor eller matris
-MATCH = PASSA ## Letar upp värden i en referens eller matris
-OFFSET = FÖRSKJUTNING ## Returnerar en referens förskjuten i förhållande till en given referens
-ROW = RAD ## Returnerar radnumret för en referens
-ROWS = RADER ## Returnerar antalet rader i en referens
-RTD = RTD ## Hämtar realtidsdata från ett program som stöder COM-automation (Automation: Ett sätt att arbeta med ett programs objekt från ett annat program eller utvecklingsverktyg. Detta kallades tidigare för OLE Automation, och är en branschstandard och ingår i Component Object Model (COM).)
-TRANSPOSE = TRANSPONERA ## Transponerar en matris
-VLOOKUP = LETARAD ## Letar i den första kolumnen i en matris och flyttar över raden för att returnera värdet för en cell
-
+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
##
-## Math and trigonometry functions Matematiska och trigonometriska funktioner
+## Matematiska och trigonometriska funktioner (Math & Trig Functions)
##
-ABS = ABS ## Returnerar absolutvärdet av ett tal
-ACOS = ARCCOS ## Returnerar arcus cosinus för ett tal
-ACOSH = ARCCOSH ## Returnerar inverterad hyperbolisk cosinus för ett tal
-ASIN = ARCSIN ## Returnerar arcus cosinus för ett tal
-ASINH = ARCSINH ## Returnerar hyperbolisk arcus sinus för ett tal
-ATAN = ARCTAN ## Returnerar arcus tangens för ett tal
-ATAN2 = ARCTAN2 ## Returnerar arcus tangens för en x- och en y- koordinat
-ATANH = ARCTANH ## Returnerar hyperbolisk arcus tangens för ett tal
-CEILING = RUNDA.UPP ## Avrundar ett tal till närmaste heltal eller närmaste signifikanta multipel
-COMBIN = KOMBIN ## Returnerar antalet kombinationer för ett givet antal objekt
-COS = COS ## Returnerar cosinus för ett tal
-COSH = COSH ## Returnerar hyperboliskt cosinus för ett tal
-DEGREES = GRADER ## Omvandlar radianer till grader
-EVEN = JÄMN ## Avrundar ett tal uppåt till närmaste heltal
-EXP = EXP ## Returnerar e upphöjt till ett givet tal
-FACT = FAKULTET ## Returnerar fakulteten för ett tal
-FACTDOUBLE = DUBBELFAKULTET ## Returnerar dubbelfakulteten för ett tal
-FLOOR = RUNDA.NED ## Avrundar ett tal nedåt mot noll
-GCD = SGD ## Returnerar den största gemensamma nämnaren
-INT = HELTAL ## Avrundar ett tal nedåt till närmaste heltal
-LCM = MGM ## Returnerar den minsta gemensamma multipeln
-LN = LN ## Returnerar den naturliga logaritmen för ett tal
-LOG = LOG ## Returnerar logaritmen för ett tal för en given bas
-LOG10 = LOG10 ## Returnerar 10-logaritmen för ett tal
-MDETERM = MDETERM ## Returnerar matrisen som är avgörandet av en matris
-MINVERSE = MINVERT ## Returnerar matrisinversen av en matris
-MMULT = MMULT ## Returnerar matrisprodukten av två matriser
-MOD = REST ## Returnerar resten vid en division
-MROUND = MAVRUNDA ## Returnerar ett tal avrundat till en given multipel
-MULTINOMIAL = MULTINOMIAL ## Returnerar multinomialen för en uppsättning tal
-ODD = UDDA ## Avrundar ett tal uppåt till närmaste udda heltal
-PI = PI ## Returnerar värdet pi
-POWER = UPPHÖJT.TILL ## Returnerar resultatet av ett tal upphöjt till en exponent
-PRODUCT = PRODUKT ## Multiplicerar argumenten
-QUOTIENT = KVOT ## Returnerar heltalsdelen av en division
-RADIANS = RADIANER ## Omvandlar grader till radianer
-RAND = SLUMP ## Returnerar ett slumptal mellan 0 och 1
-RANDBETWEEN = SLUMP.MELLAN ## Returnerar ett slumptal mellan de tal som du anger
-ROMAN = ROMERSK ## Omvandlar vanliga (arabiska) siffror till romerska som text
-ROUND = AVRUNDA ## Avrundar ett tal till ett angivet antal siffror
-ROUNDDOWN = AVRUNDA.NEDÅT ## Avrundar ett tal nedåt mot noll
-ROUNDUP = AVRUNDA.UPPÅT ## Avrundar ett tal uppåt, från noll
-SERIESSUM = SERIESUMMA ## Returnerar summan av en potensserie baserat på formeln
-SIGN = TECKEN ## Returnerar tecknet för ett tal
-SIN = SIN ## Returnerar sinus för en given vinkel
-SINH = SINH ## Returnerar hyperbolisk sinus för ett tal
-SQRT = ROT ## Returnerar den positiva kvadratroten
-SQRTPI = ROTPI ## Returnerar kvadratroten för (tal * pi)
-SUBTOTAL = DELSUMMA ## Returnerar en delsumma i en lista eller databas
-SUM = SUMMA ## Summerar argumenten
-SUMIF = SUMMA.OM ## Summerar celler enligt ett angivet villkor
-SUMIFS = SUMMA.OMF ## Lägger till cellerna i ett område som uppfyller flera kriterier
-SUMPRODUCT = PRODUKTSUMMA ## Returnerar summan av produkterna i motsvarande matriskomponenter
-SUMSQ = KVADRATSUMMA ## Returnerar summan av argumentens kvadrater
-SUMX2MY2 = SUMMAX2MY2 ## Returnerar summan av differensen mellan kvadraterna för motsvarande värden i två matriser
-SUMX2PY2 = SUMMAX2PY2 ## Returnerar summan av summan av kvadraterna av motsvarande värden i två matriser
-SUMXMY2 = SUMMAXMY2 ## Returnerar summan av kvadraten av skillnaden mellan motsvarande värden i två matriser
-TAN = TAN ## Returnerar tangens för ett tal
-TANH = TANH ## Returnerar hyperbolisk tangens för ett tal
-TRUNC = AVKORTA ## Avkortar ett tal till ett heltal
-
+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
##
-## Statistical functions Statistiska funktioner
+## Statistiska funktioner (Statistical Functions)
##
-AVEDEV = MEDELAVV ## Returnerar medelvärdet för datapunkters absoluta avvikelse från deras medelvärde
-AVERAGE = MEDEL ## Returnerar medelvärdet av argumenten
-AVERAGEA = AVERAGEA ## Returnerar medelvärdet av argumenten, inklusive tal, text och logiska värden
-AVERAGEIF = MEDELOM ## Returnerar medelvärdet (aritmetiskt medelvärde) för alla celler i ett område som uppfyller ett givet kriterium
-AVERAGEIFS = MEDELOMF ## Returnerar medelvärdet (det aritmetiska medelvärdet) för alla celler som uppfyller flera villkor.
-BETADIST = BETAFÖRD ## Returnerar den kumulativa betafördelningsfunktionen
-BETAINV = BETAINV ## Returnerar inversen till den kumulativa fördelningsfunktionen för en viss betafördelning
-BINOMDIST = BINOMFÖRD ## Returnerar den individuella binomialfördelningen
-CHIDIST = CHI2FÖRD ## Returnerar den ensidiga sannolikheten av c2-fördelningen
-CHIINV = CHI2INV ## Returnerar inversen av chi2-fördelningen
-CHITEST = CHI2TEST ## Returnerar oberoendetesten
-CONFIDENCE = KONFIDENS ## Returnerar konfidensintervallet för en populations medelvärde
-CORREL = KORREL ## Returnerar korrelationskoefficienten mellan två datamängder
-COUNT = ANTAL ## Räknar hur många tal som finns bland argumenten
-COUNTA = ANTALV ## Räknar hur många värden som finns bland argumenten
-COUNTBLANK = ANTAL.TOMMA ## Räknar antalet tomma celler i ett område
-COUNTIF = ANTAL.OM ## Räknar antalet celler i ett område som uppfyller angivna villkor.
-COUNTIFS = ANTAL.OMF ## Räknar antalet celler i ett område som uppfyller flera villkor.
-COVAR = KOVAR ## Returnerar kovariansen, d.v.s. medelvärdet av produkterna för parade avvikelser
-CRITBINOM = KRITBINOM ## Returnerar det minsta värdet för vilket den kumulativa binomialfördelningen är mindre än eller lika med ett villkorsvärde
-DEVSQ = KVADAVV ## Returnerar summan av kvadrater på avvikelser
-EXPONDIST = EXPONFÖRD ## Returnerar exponentialfördelningen
-FDIST = FFÖRD ## Returnerar F-sannolikhetsfördelningen
-FINV = FINV ## Returnerar inversen till F-sannolikhetsfördelningen
-FISHER = FISHER ## Returnerar Fisher-transformationen
-FISHERINV = FISHERINV ## Returnerar inversen till Fisher-transformationen
-FORECAST = PREDIKTION ## Returnerar ett värde längs en linjär trendlinje
-FREQUENCY = FREKVENS ## Returnerar en frekvensfördelning som en lodrät matris
-FTEST = FTEST ## Returnerar resultatet av en F-test
-GAMMADIST = GAMMAFÖRD ## Returnerar gammafördelningen
-GAMMAINV = GAMMAINV ## Returnerar inversen till den kumulativa gammafördelningen
-GAMMALN = GAMMALN ## Returnerar den naturliga logaritmen för gammafunktionen, G(x)
-GEOMEAN = GEOMEDEL ## Returnerar det geometriska medelvärdet
-GROWTH = EXPTREND ## Returnerar värden längs en exponentiell trend
-HARMEAN = HARMMEDEL ## Returnerar det harmoniska medelvärdet
-HYPGEOMDIST = HYPGEOMFÖRD ## Returnerar den hypergeometriska fördelningen
-INTERCEPT = SKÄRNINGSPUNKT ## Returnerar skärningspunkten för en linjär regressionslinje
-KURT = TOPPIGHET ## Returnerar toppigheten av en mängd data
-LARGE = STÖRSTA ## Returnerar det n:te största värdet i en mängd data
-LINEST = REGR ## Returnerar parametrar till en linjär trendlinje
-LOGEST = EXPREGR ## Returnerar parametrarna i en exponentiell trend
-LOGINV = LOGINV ## Returnerar inversen till den lognormala fördelningen
-LOGNORMDIST = LOGNORMFÖRD ## Returnerar den kumulativa lognormala fördelningen
-MAX = MAX ## Returnerar det största värdet i en lista av argument
-MAXA = MAXA ## Returnerar det största värdet i en lista av argument, inklusive tal, text och logiska värden
-MEDIAN = MEDIAN ## Returnerar medianen för angivna tal
-MIN = MIN ## Returnerar det minsta värdet i en lista med argument
-MINA = MINA ## Returnerar det minsta värdet i en lista över argument, inklusive tal, text och logiska värden
-MODE = TYPVÄRDE ## Returnerar det vanligaste värdet i en datamängd
-NEGBINOMDIST = NEGBINOMFÖRD ## Returnerar den negativa binomialfördelningen
-NORMDIST = NORMFÖRD ## Returnerar den kumulativa normalfördelningen
-NORMINV = NORMINV ## Returnerar inversen till den kumulativa normalfördelningen
-NORMSDIST = NORMSFÖRD ## Returnerar den kumulativa standardnormalfördelningen
-NORMSINV = NORMSINV ## Returnerar inversen till den kumulativa standardnormalfördelningen
-PEARSON = PEARSON ## Returnerar korrelationskoefficienten till Pearsons momentprodukt
-PERCENTILE = PERCENTIL ## Returnerar den n:te percentilen av värden i ett område
-PERCENTRANK = PROCENTRANG ## Returnerar procentrangen för ett värde i en datamängd
-PERMUT = PERMUT ## Returnerar antal permutationer för ett givet antal objekt
-POISSON = POISSON ## Returnerar Poisson-fördelningen
-PROB = SANNOLIKHET ## Returnerar sannolikheten att värden i ett område ligger mellan två gränser
-QUARTILE = KVARTIL ## Returnerar kvartilen av en mängd data
-RANK = RANG ## Returnerar rangordningen för ett tal i en lista med tal
-RSQ = RKV ## Returnerar kvadraten av Pearsons produktmomentkorrelationskoefficient
-SKEW = SNEDHET ## Returnerar snedheten för en fördelning
-SLOPE = LUTNING ## Returnerar lutningen på en linjär regressionslinje
-SMALL = MINSTA ## Returnerar det n:te minsta värdet i en mängd data
-STANDARDIZE = STANDARDISERA ## Returnerar ett normaliserat värde
-STDEV = STDAV ## Uppskattar standardavvikelsen baserat på ett urval
-STDEVA = STDEVA ## Uppskattar standardavvikelsen baserat på ett urval, inklusive tal, text och logiska värden
-STDEVP = STDAVP ## Beräknar standardavvikelsen baserat på hela populationen
-STDEVPA = STDEVPA ## Beräknar standardavvikelsen baserat på hela populationen, inklusive tal, text och logiska värden
-STEYX = STDFELYX ## Returnerar standardfelet för ett förutspått y-värde för varje x-värde i regressionen
-TDIST = TFÖRD ## Returnerar Students t-fördelning
-TINV = TINV ## Returnerar inversen till Students t-fördelning
-TREND = TREND ## Returnerar värden längs en linjär trend
-TRIMMEAN = TRIMMEDEL ## Returnerar medelvärdet av mittpunkterna i en datamängd
-TTEST = TTEST ## Returnerar sannolikheten beräknad ur Students t-test
-VAR = VARIANS ## Uppskattar variansen baserat på ett urval
-VARA = VARA ## Uppskattar variansen baserat på ett urval, inklusive tal, text och logiska värden
-VARP = VARIANSP ## Beräknar variansen baserat på hela populationen
-VARPA = VARPA ## Beräknar variansen baserat på hela populationen, inklusive tal, text och logiska värden
-WEIBULL = WEIBULL ## Returnerar Weibull-fördelningen
-ZTEST = ZTEST ## Returnerar det ensidiga sannolikhetsvärdet av ett z-test
-
+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
##
-## Text functions Textfunktioner
+## Textfunktioner (Text Functions)
##
-ASC = ASC ## Ändrar helbredds (dubbel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med halvt breddsteg (enkel byte)
-BAHTTEXT = BAHTTEXT ## Omvandlar ett tal till text med valutaformatet ß (baht)
-CHAR = TECKENKOD ## Returnerar tecknet som anges av kod
-CLEAN = STÄDA ## Tar bort alla icke utskrivbara tecken i en text
-CODE = KOD ## Returnerar en numerisk kod för det första tecknet i en textsträng
-CONCATENATE = SAMMANFOGA ## Sammanfogar flera textdelar till en textsträng
-DOLLAR = VALUTA ## Omvandlar ett tal till text med valutaformat
-EXACT = EXAKT ## Kontrollerar om två textvärden är identiska
-FIND = HITTA ## Hittar en text i en annan (skiljer på gemener och versaler)
-FINDB = HITTAB ## Hittar en text i en annan (skiljer på gemener och versaler)
-FIXED = FASTTAL ## Formaterar ett tal som text med ett fast antal decimaler
-JIS = JIS ## Ändrar halvbredds (enkel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med helt breddsteg (dubbel byte)
-LEFT = VÄNSTER ## Returnerar tecken längst till vänster i en sträng
-LEFTB = VÄNSTERB ## Returnerar tecken längst till vänster i en sträng
-LEN = LÄNGD ## Returnerar antalet tecken i en textsträng
-LENB = LÄNGDB ## Returnerar antalet tecken i en textsträng
-LOWER = GEMENER ## Omvandlar text till gemener
-MID = EXTEXT ## Returnerar angivet antal tecken från en text med början vid den position som du anger
-MIDB = EXTEXTB ## Returnerar angivet antal tecken från en text med början vid den position som du anger
-PHONETIC = PHONETIC ## Returnerar de fonetiska (furigana) tecknen i en textsträng
-PROPER = INITIAL ## Ändrar första bokstaven i varje ord i ett textvärde till versal
-REPLACE = ERSÄTT ## Ersätter tecken i text
-REPLACEB = ERSÄTTB ## Ersätter tecken i text
-REPT = REP ## Upprepar en text ett bestämt antal gånger
-RIGHT = HÖGER ## Returnerar tecken längst till höger i en sträng
-RIGHTB = HÖGERB ## Returnerar tecken längst till höger i en sträng
-SEARCH = SÖK ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler)
-SEARCHB = SÖKB ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler)
-SUBSTITUTE = BYT.UT ## Ersätter gammal text med ny text i en textsträng
-T = T ## Omvandlar argumenten till text
-TEXT = TEXT ## Formaterar ett tal och omvandlar det till text
-TRIM = RENSA ## Tar bort blanksteg från text
-UPPER = VERSALER ## Omvandlar text till versaler
-VALUE = TEXTNUM ## Omvandlar ett textargument till ett tal
+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
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/config b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/config
index 266e000f6ac..63d22fd0f77 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/config
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/config
@@ -1,24 +1,20 @@
+############################################################
##
-## PhpSpreadsheet
+## PhpSpreadsheet - locale settings
##
+## Türkçe (Turkish)
+##
+############################################################
-ArgumentSeparator = ;
-
+ArgumentSeparator = ;
##
-## (For future use)
+## Error Codes
##
-currencySymbol = YTL
-
-
-##
-## Excel Error Codes (For future use)
-
-##
-NULL = #BOŞ!
-DIV0 = #SAYI/0!
-VALUE = #DEĞER!
-REF = #BAŞV!
-NAME = #AD?
-NUM = #SAYI!
-NA = #YOK
+NULL = #BOŞ!
+DIV0 = #SAYI/0!
+VALUE = #DEĞER!
+REF = #BAŞV!
+NAME = #AD?
+NUM = #SAYI!
+NA = #YOK
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/functions b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/functions
index f03563a797a..f872274f971 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/functions
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/functions
@@ -1,416 +1,537 @@
+############################################################
##
-## PhpSpreadsheet
-##
-## Data in this file derived from https://www.excel-function-translation.com/
+## PhpSpreadsheet - function name translations
##
+## Türkçe (Turkish)
##
+############################################################
##
-## Add-in and Automation functions Eklenti ve Otomasyon fonksiyonları
+## Küp işlevleri (Cube Functions)
##
-GETPIVOTDATA = ÖZETVERİAL ## Bir Özet Tablo raporunda saklanan verileri verir.
-
+CUBEKPIMEMBER = KÜPKPIÜYESİ
+CUBEMEMBER = KÜPÜYESİ
+CUBEMEMBERPROPERTY = KÜPÜYEÖZELLİĞİ
+CUBERANKEDMEMBER = DERECELİKÜPÜYESİ
+CUBESET = KÜPKÜMESİ
+CUBESETCOUNT = KÜPKÜMESAYISI
+CUBEVALUE = KÜPDEĞERİ
##
-## Cube functions Küp işlevleri
+## Veritabanı işlevleri (Database Functions)
##
-CUBEKPIMEMBER = KÜPKPIÜYE ## Kilit performans göstergesi (KPI-Key Performance Indicator) adını, özelliğini ve ölçüsünü verir ve hücredeki ad ve özelliği gösterir. KPI, bir kurumun performansını izlemek için kullanılan aylık brüt kâr ya da üç aylık çalışan giriş çıkışları gibi ölçülebilen bir birimdir.
-CUBEMEMBER = KÜPÜYE ## Bir küp hiyerarşisinde bir üyeyi veya kaydı verir. Üye veya kaydın küpte varolduğunu doğrulamak için kullanılır.
-CUBEMEMBERPROPERTY = KÜPÜYEÖZELLİĞİ ## Bir küpte bir üyenin özelliğinin değerini verir. Küp içinde üye adının varlığını doğrulamak ve bu üyenin belli özelliklerini getirmek için kullanılır.
-CUBERANKEDMEMBER = KÜPÜYESIRASI ## Bir küme içindeki üyenin derecesini veya kaçıncı olduğunu verir. En iyi satış elemanı, veya en iyi on öğrenci gibi bir kümedeki bir veya daha fazla öğeyi getirmek için kullanılır.
-CUBESET = KÜPKÜME ## Kümeyi oluşturan ve ardından bu kümeyi Microsoft Office Excel'e getiren sunucudaki küpe küme ifadelerini göndererek hesaplanan üye veya kayıt kümesini tanımlar.
-CUBESETCOUNT = KÜPKÜMESAY ## Bir kümedeki öğelerin sayısını getirir.
-CUBEVALUE = KÜPDEĞER ## Bir küpten toplam değeri getirir.
-
+DAVERAGE = VSEÇORT
+DCOUNT = VSEÇSAY
+DCOUNTA = VSEÇSAYDOLU
+DGET = VAL
+DMAX = VSEÇMAK
+DMIN = VSEÇMİN
+DPRODUCT = VSEÇÇARP
+DSTDEV = VSEÇSTDSAPMA
+DSTDEVP = VSEÇSTDSAPMAS
+DSUM = VSEÇTOPLA
+DVAR = VSEÇVAR
+DVARP = VSEÇVARS
##
-## Database functions Veritabanı işlevleri
+## Tarih ve saat işlevleri (Date & Time Functions)
##
-DAVERAGE = VSEÇORT ## Seçili veritabanı girdilerinin ortalamasını verir.
-DCOUNT = VSEÇSAY ## Veritabanında sayı içeren hücre sayısını hesaplar.
-DCOUNTA = VSEÇSAYDOLU ## Veritabanındaki boş olmayan hücreleri sayar.
-DGET = VAL ## Veritabanından, belirtilen ölçütlerle eşleşen tek bir rapor çıkarır.
-DMAX = VSEÇMAK ## Seçili veritabanı girişlerinin en yüksek değerini verir.
-DMIN = VSEÇMİN ## Seçili veritabanı girişlerinin en düşük değerini verir.
-DPRODUCT = VSEÇÇARP ## Kayıtların belli bir alanında bulunan, bir veritabanındaki ölçütlerle eşleşen değerleri çarpar.
-DSTDEV = VSEÇSTDSAPMA ## Seçili veritabanı girişlerinden oluşan bir örneğe dayanarak, standart sapmayı tahmin eder.
-DSTDEVP = VSEÇSTDSAPMAS ## Standart sapmayı, seçili veritabanı girişlerinin tüm popülasyonunu esas alarak hesaplar.
-DSUM = VSEÇTOPLA ## Kayıtların alan sütununda bulunan, ölçütle eşleşen sayıları toplar.
-DVAR = VSEÇVAR ## Seçili veritabanı girişlerinden oluşan bir örneği esas alarak farkı tahmin eder.
-DVARP = VSEÇVARS ## Seçili veritabanı girişlerinin tüm popülasyonunu esas alarak farkı hesaplar.
-
+DATE = TARİH
+DATEDIF = ETARİHLİ
+DATESTRING = TARİHDİZİ
+DATEVALUE = TARİHSAYISI
+DAY = GÜN
+DAYS = GÜNSAY
+DAYS360 = GÜN360
+EDATE = SERİTARİH
+EOMONTH = SERİAY
+HOUR = SAAT
+ISOWEEKNUM = ISOHAFTASAY
+MINUTE = DAKİKA
+MONTH = AY
+NETWORKDAYS = TAMİŞGÜNÜ
+NETWORKDAYS.INTL = TAMİŞGÜNÜ.ULUSL
+NOW = ŞİMDİ
+SECOND = SANİYE
+THAIDAYOFWEEK = TAYHAFTANINGÜNÜ
+THAIMONTHOFYEAR = TAYYILINAYI
+THAIYEAR = TAYYILI
+TIME = ZAMAN
+TIMEVALUE = ZAMANSAYISI
+TODAY = BUGÜN
+WEEKDAY = HAFTANINGÜNÜ
+WEEKNUM = HAFTASAY
+WORKDAY = İŞGÜNÜ
+WORKDAY.INTL = İŞGÜNÜ.ULUSL
+YEAR = YIL
+YEARFRAC = YILORAN
##
-## Date and time functions Tarih ve saat işlevleri
+## Mühendislik işlevleri (Engineering Functions)
##
-DATE = TARİH ## Belirli bir tarihin seri numarasını verir.
-DATEVALUE = TARİHSAYISI ## Metin biçimindeki bir tarihi seri numarasına dönüştürür.
-DAY = GÜN ## Seri numarasını, ayın bir gününe dönüştürür.
-DAYS360 = GÜN360 ## İki tarih arasındaki gün sayısını, 360 günlük yılı esas alarak hesaplar.
-EDATE = SERİTARİH ## Başlangıç tarihinden itibaren, belirtilen ay sayısından önce veya sonraki tarihin seri numarasını verir.
-EOMONTH = SERİAY ## Belirtilen sayıda ay önce veya sonraki ayın son gününün seri numarasını verir.
-HOUR = SAAT ## Bir seri numarasını saate dönüştürür.
-MINUTE = DAKİKA ## Bir seri numarasını dakikaya dönüştürür.
-MONTH = AY ## Bir seri numarasını aya dönüştürür.
-NETWORKDAYS = TAMİŞGÜNÜ ## İki tarih arasındaki tam çalışma günlerinin sayısını verir.
-NOW = ŞİMDİ ## Geçerli tarihin ve saatin seri numarasını verir.
-SECOND = SANİYE ## Bir seri numarasını saniyeye dönüştürür.
-TIME = ZAMAN ## Belirli bir zamanın seri numarasını verir.
-TIMEVALUE = ZAMANSAYISI ## Metin biçimindeki zamanı seri numarasına dönüştürür.
-TODAY = BUGÜN ## Bugünün tarihini seri numarasına dönüştürür.
-WEEKDAY = HAFTANINGÜNÜ ## Bir seri numarasını, haftanın gününe dönüştürür.
-WEEKNUM = HAFTASAY ## Dizisel değerini, haftanın yıl içinde bulunduğu konumu sayısal olarak gösteren sayıya dönüştürür.
-WORKDAY = İŞGÜNÜ ## Belirtilen sayıda çalışma günü öncesinin ya da sonrasının tarihinin seri numarasını verir.
-YEAR = YIL ## Bir seri numarasını yıla dönüştürür.
-YEARFRAC = YILORAN ## Başlangıç_tarihi ve bitiş_tarihi arasındaki tam günleri gösteren yıl kesrini verir.
-
+BESSELI = BESSELI
+BESSELJ = BESSELJ
+BESSELK = BESSELK
+BESSELY = BESSELY
+BIN2DEC = BIN2DEC
+BIN2HEX = BIN2HEX
+BIN2OCT = BIN2OCT
+BITAND = BİTVE
+BITLSHIFT = BİTSOLAKAYDIR
+BITOR = BİTVEYA
+BITRSHIFT = BİTSAĞAKAYDIR
+BITXOR = BİTÖZELVEYA
+COMPLEX = KARMAŞIK
+CONVERT = ÇEVİR
+DEC2BIN = DEC2BIN
+DEC2HEX = DEC2HEX
+DEC2OCT = DEC2OCT
+DELTA = DELTA
+ERF = HATAİŞLEV
+ERF.PRECISE = HATAİŞLEV.DUYARLI
+ERFC = TÜMHATAİŞLEV
+ERFC.PRECISE = TÜMHATAİŞLEV.DUYARLI
+GESTEP = BESINIR
+HEX2BIN = HEX2BIN
+HEX2DEC = HEX2DEC
+HEX2OCT = HEX2OCT
+IMABS = SANMUTLAK
+IMAGINARY = SANAL
+IMARGUMENT = SANBAĞ_DEĞİŞKEN
+IMCONJUGATE = SANEŞLENEK
+IMCOS = SANCOS
+IMCOSH = SANCOSH
+IMCOT = SANCOT
+IMCSC = SANCSC
+IMCSCH = SANCSCH
+IMDIV = SANBÖL
+IMEXP = SANÜS
+IMLN = SANLN
+IMLOG10 = SANLOG10
+IMLOG2 = SANLOG2
+IMPOWER = SANKUVVET
+IMPRODUCT = SANÇARP
+IMREAL = SANGERÇEK
+IMSEC = SANSEC
+IMSECH = SANSECH
+IMSIN = SANSIN
+IMSINH = SANSINH
+IMSQRT = SANKAREKÖK
+IMSUB = SANTOPLA
+IMSUM = SANÇIKAR
+IMTAN = SANTAN
+OCT2BIN = OCT2BIN
+OCT2DEC = OCT2DEC
+OCT2HEX = OCT2HEX
##
-## Engineering functions Mühendislik işlevleri
+## Finansal işlevler (Financial Functions)
##
-BESSELI = BESSELI ## Değiştirilmiş Bessel fonksiyonu In(x)'i verir.
-BESSELJ = BESSELJ ## Bessel fonksiyonu Jn(x)'i verir.
-BESSELK = BESSELK ## Değiştirilmiş Bessel fonksiyonu Kn(x)'i verir.
-BESSELY = BESSELY ## Bessel fonksiyonu Yn(x)'i verir.
-BIN2DEC = BIN2DEC ## İkili bir sayıyı, ondalık sayıya dönüştürür.
-BIN2HEX = BIN2HEX ## İkili bir sayıyı, onaltılıya dönüştürür.
-BIN2OCT = BIN2OCT ## İkili bir sayıyı, sekizliye dönüştürür.
-COMPLEX = KARMAŞIK ## Gerçek ve sanal katsayıları, karmaşık sayıya dönüştürür.
-CONVERT = ÇEVİR ## Bir sayıyı, bir ölçüm sisteminden bir başka ölçüm sistemine dönüştürür.
-DEC2BIN = DEC2BIN ## Ondalık bir sayıyı, ikiliye dönüştürür.
-DEC2HEX = DEC2HEX ## Ondalık bir sayıyı, onaltılıya dönüştürür.
-DEC2OCT = DEC2OCT ## Ondalık bir sayıyı sekizliğe dönüştürür.
-DELTA = DELTA ## İki değerin eşit olup olmadığını sınar.
-ERF = HATAİŞLEV ## Hata işlevini verir.
-ERFC = TÜMHATAİŞLEV ## Tümleyici hata işlevini verir.
-GESTEP = BESINIR ## Bir sayının eşik değerinden büyük olup olmadığını sınar.
-HEX2BIN = HEX2BIN ## Onaltılı bir sayıyı ikiliye dönüştürür.
-HEX2DEC = HEX2DEC ## Onaltılı bir sayıyı ondalığa dönüştürür.
-HEX2OCT = HEX2OCT ## Onaltılı bir sayıyı sekizliğe dönüştürür.
-IMABS = SANMUTLAK ## Karmaşık bir sayının mutlak değerini (modül) verir.
-IMAGINARY = SANAL ## Karmaşık bir sayının sanal katsayısını verir.
-IMARGUMENT = SANBAĞ_DEĞİŞKEN ## Radyanlarla belirtilen bir açı olan teta bağımsız değişkenini verir.
-IMCONJUGATE = SANEŞLENEK ## Karmaşık bir sayının karmaşık eşleniğini verir.
-IMCOS = SANCOS ## Karmaşık bir sayının kosinüsünü verir.
-IMDIV = SANBÖL ## İki karmaşık sayının bölümünü verir.
-IMEXP = SANÜS ## Karmaşık bir sayının üssünü verir.
-IMLN = SANLN ## Karmaşık bir sayının doğal logaritmasını verir.
-IMLOG10 = SANLOG10 ## Karmaşık bir sayının, 10 tabanında logaritmasını verir.
-IMLOG2 = SANLOG2 ## Karmaşık bir sayının 2 tabanında logaritmasını verir.
-IMPOWER = SANÜSSÜ ## Karmaşık bir sayıyı, bir tamsayı üssüne yükseltilmiş olarak verir.
-IMPRODUCT = SANÇARP ## Karmaşık sayıların çarpımını verir.
-IMREAL = SANGERÇEK ## Karmaşık bir sayının, gerçek katsayısını verir.
-IMSIN = SANSIN ## Karmaşık bir sayının sinüsünü verir.
-IMSQRT = SANKAREKÖK ## Karmaşık bir sayının karekökünü verir.
-IMSUB = SANÇIKAR ## İki karmaşık sayının farkını verir.
-IMSUM = SANTOPLA ## Karmaşık sayıların toplamını verir.
-OCT2BIN = OCT2BIN ## Sekizli bir sayıyı ikiliye dönüştürür.
-OCT2DEC = OCT2DEC ## Sekizli bir sayıyı ondalığa dönüştürür.
-OCT2HEX = OCT2HEX ## Sekizli bir sayıyı onaltılıya dönüştürür.
-
+ACCRINT = GERÇEKFAİZ
+ACCRINTM = GERÇEKFAİZV
+AMORDEGRC = AMORDEGRC
+AMORLINC = AMORLINC
+COUPDAYBS = KUPONGÜNBD
+COUPDAYS = KUPONGÜN
+COUPDAYSNC = KUPONGÜNDSK
+COUPNCD = KUPONGÜNSKT
+COUPNUM = KUPONSAYI
+COUPPCD = KUPONGÜNÖKT
+CUMIPMT = TOPÖDENENFAİZ
+CUMPRINC = TOPANAPARA
+DB = AZALANBAKİYE
+DDB = ÇİFTAZALANBAKİYE
+DISC = İNDİRİM
+DOLLARDE = LİRAON
+DOLLARFR = LİRAKES
+DURATION = SÜRE
+EFFECT = ETKİN
+FV = GD
+FVSCHEDULE = GDPROGRAM
+INTRATE = FAİZORANI
+IPMT = FAİZTUTARI
+IRR = İÇ_VERİM_ORANI
+ISPMT = ISPMT
+MDURATION = MSÜRE
+MIRR = D_İÇ_VERİM_ORANI
+NOMINAL = NOMİNAL
+NPER = TAKSİT_SAYISI
+NPV = NBD
+ODDFPRICE = TEKYDEĞER
+ODDFYIELD = TEKYÖDEME
+ODDLPRICE = TEKSDEĞER
+ODDLYIELD = TEKSÖDEME
+PDURATION = PSÜRE
+PMT = DEVRESEL_ÖDEME
+PPMT = ANA_PARA_ÖDEMESİ
+PRICE = DEĞER
+PRICEDISC = DEĞERİND
+PRICEMAT = DEĞERVADE
+PV = BD
+RATE = FAİZ_ORANI
+RECEIVED = GETİRİ
+RRI = GERÇEKLEŞENYATIRIMGETİRİSİ
+SLN = DA
+SYD = YAT
+TBILLEQ = HTAHEŞ
+TBILLPRICE = HTAHDEĞER
+TBILLYIELD = HTAHÖDEME
+VDB = DAB
+XIRR = AİÇVERİMORANI
+XNPV = ANBD
+YIELD = ÖDEME
+YIELDDISC = ÖDEMEİND
+YIELDMAT = ÖDEMEVADE
##
-## Financial functions Finansal fonksiyonlar
+## Bilgi işlevleri (Information Functions)
##
-ACCRINT = GERÇEKFAİZ ## Dönemsel faiz ödeyen hisse senedine ilişkin tahakkuk eden faizi getirir.
-ACCRINTM = GERÇEKFAİZV ## Vadesinde ödeme yapan bir tahvilin tahakkuk etmiş faizini verir.
-AMORDEGRC = AMORDEGRC ## Yıpranma katsayısı kullanarak her hesap döneminin değer kaybını verir.
-AMORLINC = AMORLINC ## Her hesap dönemi içindeki yıpranmayı verir.
-COUPDAYBS = KUPONGÜNBD ## Kupon süresinin başlangıcından alış tarihine kadar olan süredeki gün sayısını verir.
-COUPDAYS = KUPONGÜN ## Kupon süresindeki, gün sayısını, alış tarihini de içermek üzere, verir.
-COUPDAYSNC = KUPONGÜNDSK ## Alış tarihinden bir sonraki kupon tarihine kadar olan gün sayısını verir.
-COUPNCD = KUPONGÜNSKT ## Alış tarihinden bir sonraki kupon tarihini verir.
-COUPNUM = KUPONSAYI ## Alış tarihiyle vade tarihi arasında ödenecek kuponların sayısını verir.
-COUPPCD = KUPONGÜNÖKT ## Alış tarihinden bir önceki kupon tarihini verir.
-CUMIPMT = AİÇVERİMORANI ## İki dönem arasında ödenen kümülatif faizi verir.
-CUMPRINC = ANA_PARA_ÖDEMESİ ## İki dönem arasında bir borç üzerine ödenen birikimli temeli verir.
-DB = AZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, sabit azalan bakiye yöntemini kullanarak verir.
-DDB = ÇİFTAZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, çift azalan bakiye yöntemi ya da sizin belirttiğiniz başka bir yöntemi kullanarak verir.
-DISC = İNDİRİM ## Bir tahvilin indirim oranını verir.
-DOLLARDE = LİRAON ## Kesir olarak tanımlanmış lira fiyatını, ondalık sayı olarak tanımlanmış lira fiyatına dönüştürür.
-DOLLARFR = LİRAKES ## Ondalık sayı olarak tanımlanmış lira fiyatını, kesir olarak tanımlanmış lira fiyatına dönüştürür.
-DURATION = SÜRE ## Belli aralıklarla faiz ödemesi yapan bir tahvilin yıllık süresini verir.
-EFFECT = ETKİN ## Efektif yıllık faiz oranını verir.
-FV = ANBD ## Bir yatırımın gelecekteki değerini verir.
-FVSCHEDULE = GDPROGRAM ## Bir seri birleşik faiz oranı uyguladıktan sonra, bir başlangıçtaki anaparanın gelecekteki değerini verir.
-INTRATE = FAİZORANI ## Tam olarak yatırım yapılmış bir tahvilin faiz oranını verir.
-IPMT = FAİZTUTARI ## Bir yatırımın verilen bir süre için faiz ödemesini verir.
-IRR = İÇ_VERİM_ORANI ## Bir para akışı serisi için, iç verim oranını verir.
-ISPMT = ISPMT ## Yatırımın belirli bir dönemi boyunca ödenen faizi hesaplar.
-MDURATION = MSÜRE ## Varsayılan par değeri 10.000.000 lira olan bir tahvil için Macauley değiştirilmiş süreyi verir.
-MIRR = D_İÇ_VERİM_ORANI ## Pozitif ve negatif para akışlarının farklı oranlarda finanse edildiği durumlarda, iç verim oranını verir.
-NOMINAL = NOMİNAL ## Yıllık nominal faiz oranını verir.
-NPER = DÖNEM_SAYISI ## Bir yatırımın dönem sayısını verir.
-NPV = NBD ## Bir yatırımın bugünkü net değerini, bir dönemsel para akışları serisine ve bir indirim oranına bağlı olarak verir.
-ODDFPRICE = TEKYDEĞER ## Tek bir ilk dönemi olan bir tahvilin değerini, her 100.000.000 lirada bir verir.
-ODDFYIELD = TEKYÖDEME ## Tek bir ilk dönemi olan bir tahvilin ödemesini verir.
-ODDLPRICE = TEKSDEĞER ## Tek bir son dönemi olan bir tahvilin fiyatını her 10.000.000 lirada bir verir.
-ODDLYIELD = TEKSÖDEME ## Tek bir son dönemi olan bir tahvilin ödemesini verir.
-PMT = DEVRESEL_ÖDEME ## Bir yıllık dönemsel ödemeyi verir.
-PPMT = ANA_PARA_ÖDEMESİ ## Verilen bir süre için, bir yatırımın anaparasına dayanan ödemeyi verir.
-PRICE = DEĞER ## Dönemsel faiz ödeyen bir tahvilin fiyatını 10.000.00 liralık değer başına verir.
-PRICEDISC = DEĞERİND ## İndirimli bir tahvilin fiyatını 10.000.000 liralık nominal değer başına verir.
-PRICEMAT = DEĞERVADE ## Faizini vade sonunda ödeyen bir tahvilin fiyatını 10.000.000 nominal değer başına verir.
-PV = BD ## Bir yatırımın bugünkü değerini verir.
-RATE = FAİZ_ORANI ## Bir yıllık dönem başına düşen faiz oranını verir.
-RECEIVED = GETİRİ ## Tam olarak yatırılmış bir tahvilin vadesinin bitiminde alınan miktarı verir.
-SLN = DA ## Bir malın bir dönem içindeki doğrusal yıpranmasını verir.
-SYD = YAT ## Bir malın belirli bir dönem için olan amortismanını verir.
-TBILLEQ = HTAHEŞ ## Bir Hazine bonosunun bono eşdeğeri ödemesini verir.
-TBILLPRICE = HTAHDEĞER ## Bir Hazine bonosunun değerini, 10.000.000 liralık nominal değer başına verir.
-TBILLYIELD = HTAHÖDEME ## Bir Hazine bonosunun ödemesini verir.
-VDB = DAB ## Bir malın amortismanını, belirlenmiş ya da kısmi bir dönem için, bir azalan bakiye yöntemi kullanarak verir.
-XIRR = AİÇVERİMORANI ## Dönemsel olması gerekmeyen bir para akışları programı için, iç verim oranını verir.
-XNPV = ANBD ## Dönemsel olması gerekmeyen bir para akışları programı için, bugünkü net değeri verir.
-YIELD = ÖDEME ## Belirli aralıklarla faiz ödeyen bir tahvilin ödemesini verir.
-YIELDDISC = ÖDEMEİND ## İndirimli bir tahvilin yıllık ödemesini verir; örneğin, bir Hazine bonosunun.
-YIELDMAT = ÖDEMEVADE ## Vadesinin bitiminde faiz ödeyen bir tahvilin yıllık ödemesini verir.
-
+CELL = HÜCRE
+ERROR.TYPE = HATA.TİPİ
+INFO = BİLGİ
+ISBLANK = EBOŞSA
+ISERR = EHATA
+ISERROR = EHATALIYSA
+ISEVEN = ÇİFTMİ
+ISFORMULA = EFORMÜLSE
+ISLOGICAL = EMANTIKSALSA
+ISNA = EYOKSA
+ISNONTEXT = EMETİNDEĞİLSE
+ISNUMBER = ESAYIYSA
+ISODD = TEKMİ
+ISREF = EREFSE
+ISTEXT = EMETİNSE
+N = S
+NA = YOKSAY
+SHEET = SAYFA
+SHEETS = SAYFALAR
+TYPE = TÜR
##
-## Information functions Bilgi fonksiyonları
+## Mantıksal işlevler (Logical Functions)
##
-CELL = HÜCRE ## Bir hücrenin biçimlendirmesi, konumu ya da içeriği hakkında bilgi verir.
-ERROR.TYPE = HATA.TİPİ ## Bir hata türüne ilişkin sayıları verir.
-INFO = BİLGİ ## Geçerli işletim ortamı hakkında bilgi verir.
-ISBLANK = EBOŞSA ## Değer boşsa, DOĞRU verir.
-ISERR = EHATA ## Değer, #YOK dışındaki bir hata değeriyse, DOĞRU verir.
-ISERROR = EHATALIYSA ## Değer, herhangi bir hata değeriyse, DOĞRU verir.
-ISEVEN = ÇİFTTİR ## Sayı çiftse, DOĞRU verir.
-ISLOGICAL = EMANTIKSALSA ## Değer, mantıksal bir değerse, DOĞRU verir.
-ISNA = EYOKSA ## Değer, #YOK hata değeriyse, DOĞRU verir.
-ISNONTEXT = EMETİNDEĞİLSE ## Değer, metin değilse, DOĞRU verir.
-ISNUMBER = ESAYIYSA ## Değer, bir sayıysa, DOĞRU verir.
-ISODD = TEKTİR ## Sayı tekse, DOĞRU verir.
-ISREF = EREFSE ## Değer bir başvuruysa, DOĞRU verir.
-ISTEXT = EMETİNSE ## Değer bir metinse DOĞRU verir.
-N = N ## Sayıya dönüştürülmüş bir değer verir.
-NA = YOKSAY ## #YOK hata değerini verir.
-TYPE = TİP ## Bir değerin veri türünü belirten bir sayı verir.
-
+AND = VE
+FALSE = YANLIŞ
+IF = EĞER
+IFERROR = EĞERHATA
+IFNA = EĞERYOKSA
+IFS = ÇOKEĞER
+NOT = DEĞİL
+OR = YADA
+SWITCH = İLKEŞLEŞEN
+TRUE = DOĞRU
+XOR = ÖZELVEYA
##
-## Logical functions Mantıksal fonksiyonlar
+## Arama ve başvuru işlevleri (Lookup & Reference Functions)
##
-AND = VE ## Bütün bağımsız değişkenleri DOĞRU ise, DOĞRU verir.
-FALSE = YANLIŞ ## YANLIŞ mantıksal değerini verir.
-IF = EĞER ## Gerçekleştirilecek bir mantıksal sınama belirtir.
-IFERROR = EĞERHATA ## Formül hatalıysa belirttiğiniz değeri verir; bunun dışındaki durumlarda formülün sonucunu verir.
-NOT = DEĞİL ## Bağımsız değişkeninin mantığını tersine çevirir.
-OR = YADA ## Bağımsız değişkenlerden herhangi birisi DOĞRU ise, DOĞRU verir.
-TRUE = DOĞRU ## DOĞRU mantıksal değerini verir.
-
+ADDRESS = ADRES
+AREAS = ALANSAY
+CHOOSE = ELEMAN
+COLUMN = SÜTUN
+COLUMNS = SÜTUNSAY
+FORMULATEXT = FORMÜLMETNİ
+GETPIVOTDATA = ÖZETVERİAL
+HLOOKUP = YATAYARA
+HYPERLINK = KÖPRÜ
+INDEX = İNDİS
+INDIRECT = DOLAYLI
+LOOKUP = ARA
+MATCH = KAÇINCI
+OFFSET = KAYDIR
+ROW = SATIR
+ROWS = SATIRSAY
+RTD = GZV
+TRANSPOSE = DEVRİK_DÖNÜŞÜM
+VLOOKUP = DÜŞEYARA
##
-## Lookup and reference functions Arama ve Başvuru fonksiyonları
+## Matematik ve trigonometri işlevleri (Math & Trig Functions)
##
-ADDRESS = ADRES ## Bir başvuruyu, çalışma sayfasındaki tek bir hücreye metin olarak verir.
-AREAS = ALANSAY ## Renvoie le nombre de zones dans une référence.
-CHOOSE = ELEMAN ## Değerler listesinden bir değer seçer.
-COLUMN = SÜTUN ## Bir başvurunun sütun sayısını verir.
-COLUMNS = SÜTUNSAY ## Bir başvurudaki sütunların sayısını verir.
-HLOOKUP = YATAYARA ## Bir dizinin en üst satırına bakar ve belirtilen hücrenin değerini verir.
-HYPERLINK = KÖPRÜ ## Bir ağ sunucusunda, bir intranette ya da Internet'te depolanan bir belgeyi açan bir kısayol ya da atlama oluşturur.
-INDEX = İNDİS ## Başvurudan veya diziden bir değer seçmek için, bir dizin kullanır.
-INDIRECT = DOLAYLI ## Metin değeriyle belirtilen bir başvuru verir.
-LOOKUP = ARA ## Bir vektördeki veya dizideki değerleri arar.
-MATCH = KAÇINCI ## Bir başvurudaki veya dizideki değerleri arar.
-OFFSET = KAYDIR ## Verilen bir başvurudan, bir başvuru kaydırmayı verir.
-ROW = SATIR ## Bir başvurunun satır sayısını verir.
-ROWS = SATIRSAY ## Bir başvurudaki satırların sayısını verir.
-RTD = RTD ## COM otomasyonunu destekleyen programdan gerçek zaman verileri alır.
-TRANSPOSE = DEVRİK_DÖNÜŞÜM ## Bir dizinin devrik dönüşümünü verir.
-VLOOKUP = DÜŞEYARA ## Bir dizinin ilk sütununa bakar ve bir hücrenin değerini vermek için satır boyunca hareket eder.
-
+ABS = MUTLAK
+ACOS = ACOS
+ACOSH = ACOSH
+ACOT = ACOT
+ACOTH = ACOTH
+AGGREGATE = TOPLAMA
+ARABIC = ARAP
+ASIN = ASİN
+ASINH = ASİNH
+ATAN = ATAN
+ATAN2 = ATAN2
+ATANH = ATANH
+BASE = TABAN
+CEILING.MATH = TAVANAYUVARLA.MATEMATİK
+CEILING.PRECISE = TAVANAYUVARLA.DUYARLI
+COMBIN = KOMBİNASYON
+COMBINA = KOMBİNASYONA
+COS = COS
+COSH = COSH
+COT = COT
+COTH = COTH
+CSC = CSC
+CSCH = CSCH
+DECIMAL = ONDALIK
+DEGREES = DERECE
+ECMA.CEILING = ECMA.TAVAN
+EVEN = ÇİFT
+EXP = ÜS
+FACT = ÇARPINIM
+FACTDOUBLE = ÇİFTFAKTÖR
+FLOOR.MATH = TABANAYUVARLA.MATEMATİK
+FLOOR.PRECISE = TABANAYUVARLA.DUYARLI
+GCD = OBEB
+INT = TAMSAYI
+ISO.CEILING = ISO.TAVAN
+LCM = OKEK
+LN = LN
+LOG = LOG
+LOG10 = LOG10
+MDETERM = DETERMİNANT
+MINVERSE = DİZEY_TERS
+MMULT = DÇARP
+MOD = MOD
+MROUND = KYUVARLA
+MULTINOMIAL = ÇOKTERİMLİ
+MUNIT = BİRİMMATRİS
+ODD = TEK
+PI = Pİ
+POWER = KUVVET
+PRODUCT = ÇARPIM
+QUOTIENT = BÖLÜM
+RADIANS = RADYAN
+RAND = S_SAYI_ÜRET
+RANDBETWEEN = RASTGELEARADA
+ROMAN = ROMEN
+ROUND = YUVARLA
+ROUNDBAHTDOWN = BAHTAŞAĞIYUVARLA
+ROUNDBAHTUP = BAHTYUKARIYUVARLA
+ROUNDDOWN = AŞAĞIYUVARLA
+ROUNDUP = YUKARIYUVARLA
+SEC = SEC
+SECH = SECH
+SERIESSUM = SERİTOPLA
+SIGN = İŞARET
+SIN = SİN
+SINH = SİNH
+SQRT = KAREKÖK
+SQRTPI = KAREKÖKPİ
+SUBTOTAL = ALTTOPLAM
+SUM = TOPLA
+SUMIF = ETOPLA
+SUMIFS = ÇOKETOPLA
+SUMPRODUCT = TOPLA.ÇARPIM
+SUMSQ = TOPKARE
+SUMX2MY2 = TOPX2EY2
+SUMX2PY2 = TOPX2AY2
+SUMXMY2 = TOPXEY2
+TAN = TAN
+TANH = TANH
+TRUNC = NSAT
##
-## Math and trigonometry functions Matematik ve trigonometri fonksiyonları
+## İstatistik işlevleri (Statistical Functions)
##
-ABS = MUTLAK ## Bir sayının mutlak değerini verir.
-ACOS = ACOS ## Bir sayının ark kosinüsünü verir.
-ACOSH = ACOSH ## Bir sayının ters hiperbolik kosinüsünü verir.
-ASIN = ASİN ## Bir sayının ark sinüsünü verir.
-ASINH = ASİNH ## Bir sayının ters hiperbolik sinüsünü verir.
-ATAN = ATAN ## Bir sayının ark tanjantını verir.
-ATAN2 = ATAN2 ## Ark tanjantı, x- ve y- koordinatlarından verir.
-ATANH = ATANH ## Bir sayının ters hiperbolik tanjantını verir.
-CEILING = TAVANAYUVARLA ## Bir sayıyı, en yakın tamsayıya ya da en yakın katına yuvarlar.
-COMBIN = KOMBİNASYON ## Verilen sayıda öğenin kombinasyon sayısını verir.
-COS = COS ## Bir sayının kosinüsünü verir.
-COSH = COSH ## Bir sayının hiperbolik kosinüsünü verir.
-DEGREES = DERECE ## Radyanları dereceye dönüştürür.
-EVEN = ÇİFT ## Bir sayıyı, en yakın daha büyük çift tamsayıya yuvarlar.
-EXP = ÜS ## e'yi, verilen bir sayının üssüne yükseltilmiş olarak verir.
-FACT = ÇARPINIM ## Bir sayının faktörünü verir.
-FACTDOUBLE = ÇİFTFAKTÖR ## Bir sayının çift çarpınımını verir.
-FLOOR = TABANAYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar.
-GCD = OBEB ## En büyük ortak böleni verir.
-INT = TAMSAYI ## Bir sayıyı aşağıya doğru en yakın tamsayıya yuvarlar.
-LCM = OKEK ## En küçük ortak katı verir.
-LN = LN ## Bir sayının doğal logaritmasını verir.
-LOG = LOG ## Bir sayının, belirtilen bir tabandaki logaritmasını verir.
-LOG10 = LOG10 ## Bir sayının 10 tabanında logaritmasını verir.
-MDETERM = DETERMİNANT ## Bir dizinin dizey determinantını verir.
-MINVERSE = DİZEY_TERS ## Bir dizinin dizey tersini verir.
-MMULT = DÇARP ## İki dizinin dizey çarpımını verir.
-MOD = MODÜLO ## Bölmeden kalanı verir.
-MROUND = KYUVARLA ## İstenen kata yuvarlanmış bir sayı verir.
-MULTINOMIAL = ÇOKTERİMLİ ## Bir sayılar kümesinin çok terimlisini verir.
-ODD = TEK ## Bir sayıyı en yakın daha büyük tek sayıya yuvarlar.
-PI = Pİ ## Pi değerini verir.
-POWER = KUVVET ## Bir üsse yükseltilmiş sayının sonucunu verir.
-PRODUCT = ÇARPIM ## Bağımsız değişkenlerini çarpar.
-QUOTIENT = BÖLÜM ## Bir bölme işleminin tamsayı kısmını verir.
-RADIANS = RADYAN ## Dereceleri radyanlara dönüştürür.
-RAND = S_SAYI_ÜRET ## 0 ile 1 arasında rastgele bir sayı verir.
-RANDBETWEEN = RASTGELEARALIK ## Belirttiğiniz sayılar arasında rastgele bir sayı verir.
-ROMAN = ROMEN ## Bir normal rakamı, metin olarak, romen rakamına çevirir.
-ROUND = YUVARLA ## Bir sayıyı, belirtilen basamak sayısına yuvarlar.
-ROUNDDOWN = AŞAĞIYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar.
-ROUNDUP = YUKARIYUVARLA ## Bir sayıyı daha büyük sayıya, sıfırdan ıraksayarak yuvarlar.
-SERIESSUM = SERİTOPLA ## Bir üs serisinin toplamını, formüle bağlı olarak verir.
-SIGN = İŞARET ## Bir sayının işaretini verir.
-SIN = SİN ## Verilen bir açının sinüsünü verir.
-SINH = SİNH ## Bir sayının hiperbolik sinüsünü verir.
-SQRT = KAREKÖK ## Pozitif bir karekök verir.
-SQRTPI = KAREKÖKPİ ## (* Pi sayısının) kare kökünü verir.
-SUBTOTAL = ALTTOPLAM ## Bir listedeki ya da veritabanındaki bir alt toplamı verir.
-SUM = TOPLA ## Bağımsız değişkenlerini toplar.
-SUMIF = ETOPLA ## Verilen ölçütle belirlenen hücreleri toplar.
-SUMIFS = SUMIFS ## Bir aralıktaki, birden fazla ölçüte uyan hücreleri ekler.
-SUMPRODUCT = TOPLA.ÇARPIM ## İlişkili dizi bileşenlerinin çarpımlarının toplamını verir.
-SUMSQ = TOPKARE ## Bağımsız değişkenlerin karelerinin toplamını verir.
-SUMX2MY2 = TOPX2EY2 ## İki dizideki ilişkili değerlerin farkının toplamını verir.
-SUMX2PY2 = TOPX2AY2 ## İki dizideki ilişkili değerlerin karelerinin toplamının toplamını verir.
-SUMXMY2 = TOPXEY2 ## İki dizideki ilişkili değerlerin farklarının karelerinin toplamını verir.
-TAN = TAN ## Bir sayının tanjantını verir.
-TANH = TANH ## Bir sayının hiperbolik tanjantını verir.
-TRUNC = NSAT ## Bir sayının, tamsayı durumuna gelecek şekilde, fazlalıklarını atar.
-
+AVEDEV = ORTSAP
+AVERAGE = ORTALAMA
+AVERAGEA = ORTALAMAA
+AVERAGEIF = EĞERORTALAMA
+AVERAGEIFS = ÇOKEĞERORTALAMA
+BETA.DIST = BETA.DAĞ
+BETA.INV = BETA.TERS
+BINOM.DIST = BİNOM.DAĞ
+BINOM.DIST.RANGE = BİNOM.DAĞ.ARALIK
+BINOM.INV = BİNOM.TERS
+CHISQ.DIST = KİKARE.DAĞ
+CHISQ.DIST.RT = KİKARE.DAĞ.SAĞK
+CHISQ.INV = KİKARE.TERS
+CHISQ.INV.RT = KİKARE.TERS.SAĞK
+CHISQ.TEST = KİKARE.TEST
+CONFIDENCE.NORM = GÜVENİLİRLİK.NORM
+CONFIDENCE.T = GÜVENİLİRLİK.T
+CORREL = KORELASYON
+COUNT = BAĞ_DEĞ_SAY
+COUNTA = BAĞ_DEĞ_DOLU_SAY
+COUNTBLANK = BOŞLUKSAY
+COUNTIF = EĞERSAY
+COUNTIFS = ÇOKEĞERSAY
+COVARIANCE.P = KOVARYANS.P
+COVARIANCE.S = KOVARYANS.S
+DEVSQ = SAPKARE
+EXPON.DIST = ÜSTEL.DAĞ
+F.DIST = F.DAĞ
+F.DIST.RT = F.DAĞ.SAĞK
+F.INV = F.TERS
+F.INV.RT = F.TERS.SAĞK
+F.TEST = F.TEST
+FISHER = FISHER
+FISHERINV = FISHERTERS
+FORECAST.ETS = TAHMİN.ETS
+FORECAST.ETS.CONFINT = TAHMİN.ETS.GVNARAL
+FORECAST.ETS.SEASONALITY = TAHMİN.ETS.MEVSİMSELLİK
+FORECAST.ETS.STAT = TAHMİN.ETS.İSTAT
+FORECAST.LINEAR = TAHMİN.DOĞRUSAL
+FREQUENCY = SIKLIK
+GAMMA = GAMA
+GAMMA.DIST = GAMA.DAĞ
+GAMMA.INV = GAMA.TERS
+GAMMALN = GAMALN
+GAMMALN.PRECISE = GAMALN.DUYARLI
+GAUSS = GAUSS
+GEOMEAN = GEOORT
+GROWTH = BÜYÜME
+HARMEAN = HARORT
+HYPGEOM.DIST = HİPERGEOM.DAĞ
+INTERCEPT = KESMENOKTASI
+KURT = BASIKLIK
+LARGE = BÜYÜK
+LINEST = DOT
+LOGEST = LOT
+LOGNORM.DIST = LOGNORM.DAĞ
+LOGNORM.INV = LOGNORM.TERS
+MAX = MAK
+MAXA = MAKA
+MAXIFS = ÇOKEĞERMAK
+MEDIAN = ORTANCA
+MIN = MİN
+MINA = MİNA
+MINIFS = ÇOKEĞERMİN
+MODE.MULT = ENÇOK_OLAN.ÇOK
+MODE.SNGL = ENÇOK_OLAN.TEK
+NEGBINOM.DIST = NEGBİNOM.DAĞ
+NORM.DIST = NORM.DAĞ
+NORM.INV = NORM.TERS
+NORM.S.DIST = NORM.S.DAĞ
+NORM.S.INV = NORM.S.TERS
+PEARSON = PEARSON
+PERCENTILE.EXC = YÜZDEBİRLİK.HRC
+PERCENTILE.INC = YÜZDEBİRLİK.DHL
+PERCENTRANK.EXC = YÜZDERANK.HRC
+PERCENTRANK.INC = YÜZDERANK.DHL
+PERMUT = PERMÜTASYON
+PERMUTATIONA = PERMÜTASYONA
+PHI = PHI
+POISSON.DIST = POISSON.DAĞ
+PROB = OLASILIK
+QUARTILE.EXC = DÖRTTEBİRLİK.HRC
+QUARTILE.INC = DÖRTTEBİRLİK.DHL
+RANK.AVG = RANK.ORT
+RANK.EQ = RANK.EŞİT
+RSQ = RKARE
+SKEW = ÇARPIKLIK
+SKEW.P = ÇARPIKLIK.P
+SLOPE = EĞİM
+SMALL = KÜÇÜK
+STANDARDIZE = STANDARTLAŞTIRMA
+STDEV.P = STDSAPMA.P
+STDEV.S = STDSAPMA.S
+STDEVA = STDSAPMAA
+STDEVPA = STDSAPMASA
+STEYX = STHYX
+T.DIST = T.DAĞ
+T.DIST.2T = T.DAĞ.2K
+T.DIST.RT = T.DAĞ.SAĞK
+T.INV = T.TERS
+T.INV.2T = T.TERS.2K
+T.TEST = T.TEST
+TREND = EĞİLİM
+TRIMMEAN = KIRPORTALAMA
+VAR.P = VAR.P
+VAR.S = VAR.S
+VARA = VARA
+VARPA = VARSA
+WEIBULL.DIST = WEIBULL.DAĞ
+Z.TEST = Z.TEST
##
-## Statistical functions İstatistiksel fonksiyonlar
+## Metin işlevleri (Text Functions)
##
-AVEDEV = ORTSAP ## Veri noktalarının ortalamalarından mutlak sapmalarının ortalamasını verir.
-AVERAGE = ORTALAMA ## Bağımsız değişkenlerinin ortalamasını verir.
-AVERAGEA = ORTALAMAA ## Bağımsız değişkenlerinin, sayılar, metin ve mantıksal değerleri içermek üzere ortalamasını verir.
-AVERAGEIF = EĞERORTALAMA ## Verili ölçütü karşılayan bir aralıktaki bütün hücrelerin ortalamasını (aritmetik ortalama) hesaplar.
-AVERAGEIFS = EĞERLERORTALAMA ## Birden çok ölçüte uyan tüm hücrelerin ortalamasını (aritmetik ortalama) hesaplar.
-BETADIST = BETADAĞ ## Beta birikimli dağılım fonksiyonunu verir.
-BETAINV = BETATERS ## Belirli bir beta dağılımı için birikimli dağılım fonksiyonunun tersini verir.
-BINOMDIST = BİNOMDAĞ ## Tek terimli binom dağılımı olasılığını verir.
-CHIDIST = KİKAREDAĞ ## Kikare dağılımın tek kuyruklu olasılığını verir.
-CHIINV = KİKARETERS ## Kikare dağılımın kuyruklu olasılığının tersini verir.
-CHITEST = KİKARETEST ## Bağımsızlık sınamalarını verir.
-CONFIDENCE = GÜVENİRLİK ## Bir popülasyon ortalaması için güvenirlik aralığını verir.
-CORREL = KORELASYON ## İki veri kümesi arasındaki bağlantı katsayısını verir.
-COUNT = BAĞ_DEĞ_SAY ## Bağımsız değişkenler listesinde kaç tane sayı bulunduğunu sayar.
-COUNTA = BAĞ_DEĞ_DOLU_SAY ## Bağımsız değişkenler listesinde kaç tane değer bulunduğunu sayar.
-COUNTBLANK = BOŞLUKSAY ## Aralıktaki boş hücre sayısını hesaplar.
-COUNTIF = EĞERSAY ## Verilen ölçütlere uyan bir aralık içindeki hücreleri sayar.
-COUNTIFS = ÇOKEĞERSAY ## Birden çok ölçüte uyan bir aralık içindeki hücreleri sayar.
-COVAR = KOVARYANS ## Eşleştirilmiş sapmaların ortalaması olan kovaryansı verir.
-CRITBINOM = KRİTİKBİNOM ## Birikimli binom dağılımının bir ölçüt değerinden küçük veya ölçüt değerine eşit olduğu en küçük değeri verir.
-DEVSQ = SAPKARE ## Sapmaların karelerinin toplamını verir.
-EXPONDIST = ÜSTELDAĞ ## Üstel dağılımı verir.
-FDIST = FDAĞ ## F olasılık dağılımını verir.
-FINV = FTERS ## F olasılık dağılımının tersini verir.
-FISHER = FISHER ## Fisher dönüşümünü verir.
-FISHERINV = FISHERTERS ## Fisher dönüşümünün tersini verir.
-FORECAST = TAHMİN ## Bir doğrusal eğilim boyunca bir değer verir.
-FREQUENCY = SIKLIK ## Bir sıklık dağılımını, dikey bir dizi olarak verir.
-FTEST = FTEST ## Bir F-test'in sonucunu verir.
-GAMMADIST = GAMADAĞ ## Gama dağılımını verir.
-GAMMAINV = GAMATERS ## Gama kümülatif dağılımının tersini verir.
-GAMMALN = GAMALN ## Gama fonksiyonunun (?(x)) doğal logaritmasını verir.
-GEOMEAN = GEOORT ## Geometrik ortayı verir.
-GROWTH = BÜYÜME ## Üstel bir eğilim boyunca değerler verir.
-HARMEAN = HARORT ## Harmonik ortayı verir.
-HYPGEOMDIST = HİPERGEOMDAĞ ## Hipergeometrik dağılımı verir.
-INTERCEPT = KESMENOKTASI ## Doğrusal çakıştırma çizgisinin kesişme noktasını verir.
-KURT = BASIKLIK ## Bir veri kümesinin basıklığını verir.
-LARGE = BÜYÜK ## Bir veri kümesinde k. en büyük değeri verir.
-LINEST = DOT ## Doğrusal bir eğilimin parametrelerini verir.
-LOGEST = LOT ## Üstel bir eğilimin parametrelerini verir.
-LOGINV = LOGTERS ## Bir lognormal dağılımının tersini verir.
-LOGNORMDIST = LOGNORMDAĞ ## Birikimli lognormal dağılımını verir.
-MAX = MAK ## Bir bağımsız değişkenler listesindeki en büyük değeri verir.
-MAXA = MAKA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri içermek üzere, en büyük değeri verir.
-MEDIAN = ORTANCA ## Belirtilen sayıların orta değerini verir.
-MIN = MİN ## Bir bağımsız değişkenler listesindeki en küçük değeri verir.
-MINA = MİNA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri de içermek üzere, en küçük değeri verir.
-MODE = ENÇOK_OLAN ## Bir veri kümesindeki en sık rastlanan değeri verir.
-NEGBINOMDIST = NEGBİNOMDAĞ ## Negatif binom dağılımını verir.
-NORMDIST = NORMDAĞ ## Normal birikimli dağılımı verir.
-NORMINV = NORMTERS ## Normal kümülatif dağılımın tersini verir.
-NORMSDIST = NORMSDAĞ ## Standart normal birikimli dağılımı verir.
-NORMSINV = NORMSTERS ## Standart normal birikimli dağılımın tersini verir.
-PEARSON = PEARSON ## Pearson çarpım moment korelasyon katsayısını verir.
-PERCENTILE = YÜZDEBİRLİK ## Bir aralık içerisinde bulunan değerlerin k. frekans toplamını verir.
-PERCENTRANK = YÜZDERANK ## Bir veri kümesindeki bir değerin yüzde mertebesini verir.
-PERMUT = PERMÜTASYON ## Verilen sayıda nesne için permütasyon sayısını verir.
-POISSON = POISSON ## Poisson dağılımını verir.
-PROB = OLASILIK ## Bir aralıktaki değerlerin iki sınır arasında olması olasılığını verir.
-QUARTILE = DÖRTTEBİRLİK ## Bir veri kümesinin dörtte birliğini verir.
-RANK = RANK ## Bir sayılar listesinde bir sayının mertebesini verir.
-RSQ = RKARE ## Pearson çarpım moment korelasyon katsayısının karesini verir.
-SKEW = ÇARPIKLIK ## Bir dağılımın çarpıklığını verir.
-SLOPE = EĞİM ## Doğrusal çakışma çizgisinin eğimini verir.
-SMALL = KÜÇÜK ## Bir veri kümesinde k. en küçük değeri verir.
-STANDARDIZE = STANDARTLAŞTIRMA ## Normalleştirilmiş bir değer verir.
-STDEV = STDSAPMA ## Bir örneğe dayanarak standart sapmayı tahmin eder.
-STDEVA = STDSAPMAA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder.
-STDEVP = STDSAPMAS ## Standart sapmayı, tüm popülasyona bağlı olarak hesaplar.
-STDEVPA = STDSAPMASA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar.
-STEYX = STHYX ## Regresyondaki her x için tahmini y değerinin standart hatasını verir.
-TDIST = TDAĞ ## T-dağılımını verir.
-TINV = TTERS ## T-dağılımının tersini verir.
-TREND = EĞİLİM ## Doğrusal bir eğilim boyunca değerler verir.
-TRIMMEAN = KIRPORTALAMA ## Bir veri kümesinin içinin ortalamasını verir.
-TTEST = TTEST ## T-test'le ilişkilendirilmiş olasılığı verir.
-VAR = VAR ## Varyansı, bir örneğe bağlı olarak tahmin eder.
-VARA = VARA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder.
-VARP = VARS ## Varyansı, tüm popülasyona dayanarak hesaplar.
-VARPA = VARSA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar.
-WEIBULL = WEIBULL ## Weibull dağılımını hesaplar.
-ZTEST = ZTEST ## Z-testinin tek kuyruklu olasılık değerini hesaplar.
-
+BAHTTEXT = BAHTMETİN
+CHAR = DAMGA
+CLEAN = TEMİZ
+CODE = KOD
+CONCAT = ARALIKBİRLEŞTİR
+DOLLAR = LİRA
+EXACT = ÖZDEŞ
+FIND = BUL
+FIXED = SAYIDÜZENLE
+ISTHAIDIGIT = TAYRAKAMIYSA
+LEFT = SOLDAN
+LEN = UZUNLUK
+LOWER = KÜÇÜKHARF
+MID = PARÇAAL
+NUMBERSTRING = SAYIDİZİ
+NUMBERVALUE = SAYIDEĞERİ
+PHONETIC = SES
+PROPER = YAZIM.DÜZENİ
+REPLACE = DEĞİŞTİR
+REPT = YİNELE
+RIGHT = SAĞDAN
+SEARCH = MBUL
+SUBSTITUTE = YERİNEKOY
+T = M
+TEXT = METNEÇEVİR
+TEXTJOIN = METİNBİRLEŞTİR
+THAIDIGIT = TAYRAKAM
+THAINUMSOUND = TAYSAYISES
+THAINUMSTRING = TAYSAYIDİZE
+THAISTRINGLENGTH = TAYDİZEUZUNLUĞU
+TRIM = KIRP
+UNICHAR = UNICODEKARAKTERİ
+UNICODE = UNICODE
+UPPER = BÜYÜKHARF
+VALUE = SAYIYAÇEVİR
##
-## Text functions Metin fonksiyonları
+## Metin işlevleri (Web Functions)
##
-ASC = ASC ## Bir karakter dizesindeki çift enli (iki bayt) İngilizce harfleri veya katakanayı yarım enli (tek bayt) karakterlerle değiştirir.
-BAHTTEXT = BAHTTEXT ## Sayıyı, ß (baht) para birimi biçimini kullanarak metne dönüştürür.
-CHAR = DAMGA ## Kod sayısıyla belirtilen karakteri verir.
-CLEAN = TEMİZ ## Metindeki bütün yazdırılamaz karakterleri kaldırır.
-CODE = KOD ## Bir metin dizesindeki ilk karakter için sayısal bir kod verir.
-CONCATENATE = BİRLEŞTİR ## Pek çok metin öğesini bir metin öğesi olarak birleştirir.
-DOLLAR = LİRA ## Bir sayıyı YTL (yeni Türk lirası) para birimi biçimini kullanarak metne dönüştürür.
-EXACT = ÖZDEŞ ## İki metin değerinin özdeş olup olmadığını anlamak için, değerleri denetler.
-FIND = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır).
-FINDB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır).
-FIXED = SAYIDÜZENLE ## Bir sayıyı, sabit sayıda ondalıkla, metin olarak biçimlendirir.
-JIS = JIS ## Bir karakter dizesindeki tek enli (tek bayt) İngilizce harfleri veya katakanayı çift enli (iki bayt) karakterlerle değiştirir.
-LEFT = SOL ## Bir metin değerinden en soldaki karakterleri verir.
-LEFTB = SOLB ## Bir metin değerinden en soldaki karakterleri verir.
-LEN = UZUNLUK ## Bir metin dizesindeki karakter sayısını verir.
-LENB = UZUNLUKB ## Bir metin dizesindeki karakter sayısını verir.
-LOWER = KÜÇÜKHARF ## Metni küçük harfe çevirir.
-MID = ORTA ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir.
-MIDB = ORTAB ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir.
-PHONETIC = SES ## Metin dizesinden ses (furigana) karakterlerini ayıklar.
-PROPER = YAZIM.DÜZENİ ## Bir metin değerinin her bir sözcüğünün ilk harfini büyük harfe çevirir.
-REPLACE = DEĞİŞTİR ## Metnin içindeki karakterleri değiştirir.
-REPLACEB = DEĞİŞTİRB ## Metnin içindeki karakterleri değiştirir.
-REPT = YİNELE ## Metni belirtilen sayıda yineler.
-RIGHT = SAĞ ## Bir metin değerinden en sağdaki karakterleri verir.
-RIGHTB = SAĞB ## Bir metin değerinden en sağdaki karakterleri verir.
-SEARCH = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir).
-SEARCHB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir).
-SUBSTITUTE = YERİNEKOY ## Bir metin dizesinde, eski metnin yerine yeni metin koyar.
-T = M ## Bağımsız değerlerini metne dönüştürür.
-TEXT = METNEÇEVİR ## Bir sayıyı biçimlendirir ve metne dönüştürür.
-TRIM = KIRP ## Metindeki boşlukları kaldırır.
-UPPER = BÜYÜKHARF ## Metni büyük harfe çevirir.
-VALUE = SAYIYAÇEVİR ## Bir metin bağımsız değişkenini sayıya dönüştürür.
+ENCODEURL = URLKODLA
+FILTERXML = XMLFİLTRELE
+WEBSERVICE = WEBHİZMETİ
+
+##
+## Uyumluluk işlevleri (Compatibility Functions)
+##
+BETADIST = BETADAĞ
+BETAINV = BETATERS
+BINOMDIST = BİNOMDAĞ
+CEILING = TAVANAYUVARLA
+CHIDIST = KİKAREDAĞ
+CHIINV = KİKARETERS
+CHITEST = KİKARETEST
+CONCATENATE = BİRLEŞTİR
+CONFIDENCE = GÜVENİRLİK
+COVAR = KOVARYANS
+CRITBINOM = KRİTİKBİNOM
+EXPONDIST = ÜSTELDAĞ
+FDIST = FDAĞ
+FINV = FTERS
+FLOOR = TABANAYUVARLA
+FORECAST = TAHMİN
+FTEST = FTEST
+GAMMADIST = GAMADAĞ
+GAMMAINV = GAMATERS
+HYPGEOMDIST = HİPERGEOMDAĞ
+LOGINV = LOGTERS
+LOGNORMDIST = LOGNORMDAĞ
+MODE = ENÇOK_OLAN
+NEGBINOMDIST = NEGBİNOMDAĞ
+NORMDIST = NORMDAĞ
+NORMINV = NORMTERS
+NORMSDIST = NORMSDAĞ
+NORMSINV = NORMSTERS
+PERCENTILE = YÜZDEBİRLİK
+PERCENTRANK = YÜZDERANK
+POISSON = POISSON
+QUARTILE = DÖRTTEBİRLİK
+RANK = RANK
+STDEV = STDSAPMA
+STDEVP = STDSAPMAS
+TDIST = TDAĞ
+TINV = TTERS
+TTEST = TTEST
+VAR = VAR
+VARP = VARS
+WEIBULL = WEIBULL
+ZTEST = ZTEST
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AddressHelper.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AddressHelper.php
index 04fa3b8ceec..499d248c28d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AddressHelper.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AddressHelper.php
@@ -6,6 +6,8 @@ use PhpOffice\PhpSpreadsheet\Exception;
class AddressHelper
{
+ public const R1C1_COORDINATE_REGEX = '/(R((?:\[-?\d*\])|(?:\d*))?)(C((?:\[-?\d*\])|(?:\d*))?)/i';
+
/**
* Converts an R1C1 format cell address to an A1 format cell address.
*/
@@ -27,7 +29,7 @@ class AddressHelper
}
// Bracketed R references are relative to the current row
if ($rowReference[0] === '[') {
- $rowReference = $currentRowNumber + trim($rowReference, '[]');
+ $rowReference = $currentRowNumber + (int) trim($rowReference, '[]');
}
$columnReference = $cellReference[4];
// Empty C reference is the current column
@@ -36,7 +38,7 @@ class AddressHelper
}
// Bracketed C references are relative to the current column
if (is_string($columnReference) && $columnReference[0] === '[') {
- $columnReference = $currentColumnNumber + trim($columnReference, '[]');
+ $columnReference = $currentColumnNumber + (int) trim($columnReference, '[]');
}
if ($columnReference <= 0 || $rowReference <= 0) {
@@ -47,8 +49,24 @@ class AddressHelper
return $A1CellReference;
}
+ protected static function convertSpreadsheetMLFormula(string $formula): string
+ {
+ $formula = substr($formula, 3);
+ $temp = explode('"', $formula);
+ $key = false;
+ foreach ($temp as &$value) {
+ // Only replace in alternate array entries (i.e. non-quoted blocks)
+ if ($key = !$key) {
+ $value = str_replace(['[.', ':.', ']'], ['', ':', ''], $value);
+ }
+ }
+ unset($value);
+
+ return implode('"', $temp);
+ }
+
/**
- * Converts a formula that uses R1C1 format cell address to an A1 format cell address.
+ * Converts a formula that uses R1C1/SpreadsheetXML format cell address to an A1 format cell address.
*/
public static function convertFormulaToA1(
string $formula,
@@ -56,41 +74,33 @@ class AddressHelper
int $currentColumnNumber = 1
): string {
if (substr($formula, 0, 3) == 'of:') {
- $formula = substr($formula, 3);
- $temp = explode('"', $formula);
- $key = false;
- foreach ($temp as &$value) {
- // Only replace in alternate array entries (i.e. non-quoted blocks)
- if ($key = !$key) {
- $value = str_replace(['[.', '.', ']'], '', $value);
- }
- }
- } else {
- // Convert R1C1 style references to A1 style references (but only when not quoted)
- $temp = explode('"', $formula);
- $key = false;
- foreach ($temp as &$value) {
- // Only replace in alternate array entries (i.e. non-quoted blocks)
- if ($key = !$key) {
- preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
- // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
- // through the formula from left to right. Reversing means that we work right to left.through
- // the formula
- $cellReferences = array_reverse($cellReferences);
- // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
- // then modify the formula to use that new reference
- foreach ($cellReferences as $cellReference) {
- $A1CellReference = self::convertToA1($cellReference[0][0], $currentRowNumber, $currentColumnNumber);
- $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
- }
+ // We have an old-style SpreadsheetML Formula
+ return self::convertSpreadsheetMLFormula($formula);
+ }
+
+ // Convert R1C1 style references to A1 style references (but only when not quoted)
+ $temp = explode('"', $formula);
+ $key = false;
+ foreach ($temp as &$value) {
+ // Only replace in alternate array entries (i.e. non-quoted blocks)
+ if ($key = !$key) {
+ preg_match_all(self::R1C1_COORDINATE_REGEX, $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
+ // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
+ // through the formula from left to right. Reversing means that we work right to left.through
+ // the formula
+ $cellReferences = array_reverse($cellReferences);
+ // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
+ // then modify the formula to use that new reference
+ foreach ($cellReferences as $cellReference) {
+ $A1CellReference = self::convertToA1($cellReference[0][0], $currentRowNumber, $currentColumnNumber);
+ $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
}
}
}
unset($value);
- // Then rebuild the formula string
- $formula = implode('"', $temp);
- return $formula;
+ // Then rebuild the formula string
+ return implode('"', $temp);
}
/**
@@ -102,14 +112,23 @@ class AddressHelper
?int $currentRowNumber = null,
?int $currentColumnNumber = null
): string {
- $validityCheck = preg_match('/^\$?([A-Z]{1,3})\$?(\d{1,7})$/i', $address, $cellReference);
+ $validityCheck = preg_match(Coordinate::A1_COORDINATE_REGEX, $address, $cellReference);
if ($validityCheck === 0) {
throw new Exception('Invalid A1-format Cell Reference');
}
- $columnId = Coordinate::columnIndexFromString($cellReference[1]);
- $rowId = (int) $cellReference[2];
+ $columnId = Coordinate::columnIndexFromString($cellReference['col_ref']);
+ if ($cellReference['absolute_col'] === '$') {
+ // Column must be absolute address
+ $currentColumnNumber = null;
+ }
+
+ $rowId = (int) $cellReference['row_ref'];
+ if ($cellReference['absolute_row'] === '$') {
+ // Row must be absolute address
+ $currentRowNumber = null;
+ }
if ($currentRowNumber !== null) {
if ($rowId === $currentRowNumber) {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php
index cf638d05ab5..025a687bce7 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AdvancedValueBinder.php
@@ -20,8 +20,10 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
*/
public function bindValue(Cell $cell, $value = null)
{
- // sanitize UTF-8 strings
- if (is_string($value)) {
+ if ($value === null) {
+ return parent::bindValue($cell, $value);
+ } elseif (is_string($value)) {
+ // sanitize UTF-8 strings
$value = StringHelper::sanitizeUTF8($value);
}
@@ -41,50 +43,16 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
return true;
}
- // Check for number in scientific format
- if (preg_match('/^' . Calculation::CALCULATION_REGEXP_NUMBER . '$/', $value)) {
- $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC);
-
- return true;
- }
-
- // Check for fraction
+ // Check for fractions
if (preg_match('/^([+-]?)\s*(\d+)\s?\/\s*(\d+)$/', $value, $matches)) {
- // Convert value to number
- $value = $matches[2] / $matches[3];
- if ($matches[1] == '-') {
- $value = 0 - $value;
- }
- $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC);
- // Set style
- $cell->getWorksheet()->getStyle($cell->getCoordinate())
- ->getNumberFormat()->setFormatCode('??/??');
-
- return true;
+ return $this->setProperFraction($matches, $cell);
} elseif (preg_match('/^([+-]?)(\d*) +(\d*)\s?\/\s*(\d*)$/', $value, $matches)) {
- // Convert value to number
- $value = $matches[2] + ($matches[3] / $matches[4]);
- if ($matches[1] == '-') {
- $value = 0 - $value;
- }
- $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC);
- // Set style
- $cell->getWorksheet()->getStyle($cell->getCoordinate())
- ->getNumberFormat()->setFormatCode('# ??/??');
-
- return true;
+ return $this->setImproperFraction($matches, $cell);
}
// Check for percentage
if (preg_match('/^\-?\d*\.?\d*\s?\%$/', $value)) {
- // Convert value to number
- $value = (float) str_replace('%', '', $value) / 100;
- $cell->setValueExplicit($value, DataType::TYPE_NUMERIC);
- // Set style
- $cell->getWorksheet()->getStyle($cell->getCoordinate())
- ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00);
-
- return true;
+ return $this->setPercentage($value, $cell);
}
// Check for currency
@@ -115,29 +83,12 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
// Check for time without seconds e.g. '9:45', '09:45'
if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d$/', $value)) {
- // Convert value to number
- [$h, $m] = explode(':', $value);
- $days = $h / 24 + $m / 1440;
- $cell->setValueExplicit($days, DataType::TYPE_NUMERIC);
- // Set style
- $cell->getWorksheet()->getStyle($cell->getCoordinate())
- ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME3);
-
- return true;
+ return $this->setTimeHoursMinutes($value, $cell);
}
// Check for time with seconds '9:45:59', '09:45:59'
if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)) {
- // Convert value to number
- [$h, $m, $s] = explode(':', $value);
- $days = $h / 24 + $m / 1440 + $s / 86400;
- // Convert value to number
- $cell->setValueExplicit($days, DataType::TYPE_NUMERIC);
- // Set style
- $cell->getWorksheet()->getStyle($cell->getCoordinate())
- ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME4);
-
- return true;
+ return $this->setTimeHoursMinutesSeconds($value, $cell);
}
// Check for datetime, e.g. '2008-12-31', '2008-12-31 15:59', '2008-12-31 15:59:10'
@@ -158,7 +109,6 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
// Check for newline character "\n"
if (strpos($value, "\n") !== false) {
- $value = StringHelper::sanitizeUTF8($value);
$cell->setValueExplicit($value, DataType::TYPE_STRING);
// Set style
$cell->getWorksheet()->getStyle($cell->getCoordinate())
@@ -171,4 +121,85 @@ class AdvancedValueBinder extends DefaultValueBinder implements IValueBinder
// Not bound yet? Use parent...
return parent::bindValue($cell, $value);
}
+
+ protected function setImproperFraction(array $matches, Cell $cell): bool
+ {
+ // Convert value to number
+ $value = $matches[2] + ($matches[3] / $matches[4]);
+ if ($matches[1] === '-') {
+ $value = 0 - $value;
+ }
+ $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC);
+
+ // Build the number format mask based on the size of the matched values
+ $dividend = str_repeat('?', strlen($matches[3]));
+ $divisor = str_repeat('?', strlen($matches[4]));
+ $fractionMask = "# {$dividend}/{$divisor}";
+ // Set style
+ $cell->getWorksheet()->getStyle($cell->getCoordinate())
+ ->getNumberFormat()->setFormatCode($fractionMask);
+
+ return true;
+ }
+
+ protected function setProperFraction(array $matches, Cell $cell): bool
+ {
+ // Convert value to number
+ $value = $matches[2] / $matches[3];
+ if ($matches[1] === '-') {
+ $value = 0 - $value;
+ }
+ $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC);
+
+ // Build the number format mask based on the size of the matched values
+ $dividend = str_repeat('?', strlen($matches[2]));
+ $divisor = str_repeat('?', strlen($matches[3]));
+ $fractionMask = "{$dividend}/{$divisor}";
+ // Set style
+ $cell->getWorksheet()->getStyle($cell->getCoordinate())
+ ->getNumberFormat()->setFormatCode($fractionMask);
+
+ return true;
+ }
+
+ protected function setPercentage(string $value, Cell $cell): bool
+ {
+ // Convert value to number
+ $value = ((float) str_replace('%', '', $value)) / 100;
+ $cell->setValueExplicit($value, DataType::TYPE_NUMERIC);
+
+ // Set style
+ $cell->getWorksheet()->getStyle($cell->getCoordinate())
+ ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00);
+
+ return true;
+ }
+
+ protected function setTimeHoursMinutes(string $value, Cell $cell): bool
+ {
+ // Convert value to number
+ [$hours, $minutes] = explode(':', $value);
+ $days = ($hours / 24) + ($minutes / 1440);
+ $cell->setValueExplicit($days, DataType::TYPE_NUMERIC);
+
+ // Set style
+ $cell->getWorksheet()->getStyle($cell->getCoordinate())
+ ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME3);
+
+ return true;
+ }
+
+ protected function setTimeHoursMinutesSeconds(string $value, Cell $cell): bool
+ {
+ // Convert value to number
+ [$hours, $minutes, $seconds] = explode(':', $value);
+ $days = ($hours / 24) + ($minutes / 1440) + ($seconds / 86400);
+ $cell->setValueExplicit($days, DataType::TYPE_NUMERIC);
+
+ // Set style
+ $cell->getWorksheet()->getStyle($cell->getCoordinate())
+ ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME4);
+
+ return true;
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php
index 5dee411b5f3..5a9def375e6 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php
@@ -9,6 +9,7 @@ use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
+use Throwable;
class Cell
{
@@ -69,7 +70,7 @@ class Cell
*
* @return $this
*/
- public function updateInCollection()
+ public function updateInCollection(): self
{
$this->parent->update($this);
@@ -78,6 +79,7 @@ class Cell
public function detach(): void
{
+ // @phpstan-ignore-next-line
$this->parent = null;
}
@@ -89,24 +91,24 @@ class Cell
/**
* Create a new Cell.
*
- * @param mixed $pValue
- * @param string $pDataType
+ * @param mixed $value
+ * @param string $dataType
*/
- public function __construct($pValue, $pDataType, Worksheet $pSheet)
+ public function __construct($value, $dataType, Worksheet $worksheet)
{
// Initialise cell value
- $this->value = $pValue;
+ $this->value = $value;
// Set worksheet cache
- $this->parent = $pSheet->getCellCollection();
+ $this->parent = $worksheet->getCellCollection();
// Set datatype?
- if ($pDataType !== null) {
- if ($pDataType == DataType::TYPE_STRING2) {
- $pDataType = DataType::TYPE_STRING;
+ if ($dataType !== null) {
+ if ($dataType == DataType::TYPE_STRING2) {
+ $dataType = DataType::TYPE_STRING;
}
- $this->dataType = $pDataType;
- } elseif (!self::getValueBinder()->bindValue($this, $pValue)) {
+ $this->dataType = $dataType;
+ } elseif (!self::getValueBinder()->bindValue($this, $value)) {
throw new Exception('Value could not be bound to cell.');
}
}
@@ -138,7 +140,16 @@ class Cell
*/
public function getCoordinate()
{
- return $this->parent->getCurrentCoordinate();
+ try {
+ $coordinate = $this->parent->getCurrentCoordinate();
+ } catch (Throwable $e) {
+ $coordinate = null;
+ }
+ if ($coordinate === null) {
+ throw new Exception('Coordinate no longer exists');
+ }
+
+ return $coordinate;
}
/**
@@ -170,13 +181,13 @@ class Cell
*
* Sets the value for a cell, automatically determining the datatype using the value binder
*
- * @param mixed $pValue Value
+ * @param mixed $value Value
*
* @return $this
*/
- public function setValue($pValue)
+ public function setValue($value)
{
- if (!self::getValueBinder()->bindValue($this, $pValue)) {
+ if (!self::getValueBinder()->bindValue($this, $value)) {
throw new Exception('Value could not be bound to cell.');
}
@@ -186,56 +197,56 @@ class Cell
/**
* Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder).
*
- * @param mixed $pValue Value
- * @param string $pDataType Explicit data type, see DataType::TYPE_*
+ * @param mixed $value Value
+ * @param string $dataType Explicit data type, see DataType::TYPE_*
*
* @return Cell
*/
- public function setValueExplicit($pValue, $pDataType)
+ public function setValueExplicit($value, $dataType)
{
// set the value according to data type
- switch ($pDataType) {
+ switch ($dataType) {
case DataType::TYPE_NULL:
- $this->value = $pValue;
+ $this->value = $value;
break;
case DataType::TYPE_STRING2:
- $pDataType = DataType::TYPE_STRING;
+ $dataType = DataType::TYPE_STRING;
// no break
case DataType::TYPE_STRING:
// Synonym for string
case DataType::TYPE_INLINE:
// Rich text
- $this->value = DataType::checkString($pValue);
+ $this->value = DataType::checkString($value);
break;
case DataType::TYPE_NUMERIC:
- if (is_string($pValue) && !is_numeric($pValue)) {
+ if (is_string($value) && !is_numeric($value)) {
throw new Exception('Invalid numeric value for datatype Numeric');
}
- $this->value = 0 + $pValue;
+ $this->value = 0 + $value;
break;
case DataType::TYPE_FORMULA:
- $this->value = (string) $pValue;
+ $this->value = (string) $value;
break;
case DataType::TYPE_BOOL:
- $this->value = (bool) $pValue;
+ $this->value = (bool) $value;
break;
case DataType::TYPE_ERROR:
- $this->value = DataType::checkErrorCode($pValue);
+ $this->value = DataType::checkErrorCode($value);
break;
default:
- throw new Exception('Invalid datatype: ' . $pDataType);
+ throw new Exception('Invalid datatype: ' . $dataType);
break;
}
// set the datatype
- $this->dataType = $pDataType;
+ $this->dataType = $dataType;
return $this->updateInCollection();
}
@@ -252,9 +263,11 @@ class Cell
if ($this->dataType == DataType::TYPE_FORMULA) {
try {
$index = $this->getWorksheet()->getParent()->getActiveSheetIndex();
+ $selected = $this->getWorksheet()->getSelectedCells();
$result = Calculation::getInstance(
$this->getWorksheet()->getParent()
)->calculateCellValue($this, $resetLog);
+ $this->getWorksheet()->setSelectedCells($selected);
$this->getWorksheet()->getParent()->setActiveSheetIndex($index);
// We don't yet handle array returns
if (is_array($result)) {
@@ -265,7 +278,7 @@ class Cell
} catch (Exception $ex) {
if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) {
return $this->calculatedValue; // Fallback for calculations referencing external files.
- } elseif (strpos($ex->getMessage(), 'undefined name') !== false) {
+ } elseif (preg_match('/[Uu]ndefined (name|offset: 2|array key 2)/', $ex->getMessage()) === 1) {
return \PhpOffice\PhpSpreadsheet\Calculation\Functions::NAME();
}
@@ -289,14 +302,14 @@ class Cell
/**
* Set old calculated value (cached).
*
- * @param mixed $pValue Value
+ * @param mixed $originalValue Value
*
* @return Cell
*/
- public function setCalculatedValue($pValue)
+ public function setCalculatedValue($originalValue)
{
- if ($pValue !== null) {
- $this->calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue;
+ if ($originalValue !== null) {
+ $this->calculatedValue = (is_numeric($originalValue)) ? (float) $originalValue : $originalValue;
}
return $this->updateInCollection();
@@ -330,16 +343,16 @@ class Cell
/**
* Set cell data type.
*
- * @param string $pDataType see DataType::TYPE_*
+ * @param string $dataType see DataType::TYPE_*
*
* @return Cell
*/
- public function setDataType($pDataType)
+ public function setDataType($dataType)
{
- if ($pDataType == DataType::TYPE_STRING2) {
- $pDataType = DataType::TYPE_STRING;
+ if ($dataType == DataType::TYPE_STRING2) {
+ $dataType = DataType::TYPE_STRING;
}
- $this->dataType = $pDataType;
+ $this->dataType = $dataType;
return $this->updateInCollection();
}
@@ -384,18 +397,14 @@ class Cell
/**
* Set Data validation rules.
- *
- * @param DataValidation $pDataValidation
- *
- * @return Cell
*/
- public function setDataValidation(?DataValidation $pDataValidation = null)
+ public function setDataValidation(?DataValidation $dataValidation = null): self
{
if (!isset($this->parent)) {
throw new Exception('Cannot set data validation for cell that is not bound to a worksheet');
}
- $this->getWorksheet()->setDataValidation($this->getCoordinate(), $pDataValidation);
+ $this->getWorksheet()->setDataValidation($this->getCoordinate(), $dataValidation);
return $this->updateInCollection();
}
@@ -443,17 +452,15 @@ class Cell
/**
* Set Hyperlink.
*
- * @param Hyperlink $pHyperlink
- *
* @return Cell
*/
- public function setHyperlink(?Hyperlink $pHyperlink = null)
+ public function setHyperlink(?Hyperlink $hyperlink = null)
{
if (!isset($this->parent)) {
throw new Exception('Cannot set hyperlink for cell that is not bound to a worksheet');
}
- $this->getWorksheet()->setHyperlink($this->getCoordinate(), $pHyperlink);
+ $this->getWorksheet()->setHyperlink($this->getCoordinate(), $hyperlink);
return $this->updateInCollection();
}
@@ -475,7 +482,17 @@ class Cell
*/
public function getWorksheet()
{
- return $this->parent->getParent();
+ try {
+ $worksheet = $this->parent->getParent();
+ } catch (Throwable $e) {
+ $worksheet = null;
+ }
+
+ if ($worksheet === null) {
+ throw new Exception('Worksheet no longer exists');
+ }
+
+ return $worksheet;
}
/**
@@ -547,13 +564,13 @@ class Cell
/**
* Is cell in a specific range?
*
- * @param string $pRange Cell range (e.g. A1:A1)
+ * @param string $range Cell range (e.g. A1:A1)
*
* @return bool
*/
- public function isInRange($pRange)
+ public function isInRange($range)
{
- [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange);
+ [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
// Translate properties
$myColumn = Coordinate::columnIndexFromString($this->getColumn());
@@ -635,13 +652,13 @@ class Cell
/**
* Set index to cellXf.
*
- * @param int $pValue
+ * @param int $indexValue
*
* @return Cell
*/
- public function setXfIndex($pValue)
+ public function setXfIndex($indexValue)
{
- $this->xfIndex = $pValue;
+ $this->xfIndex = $indexValue;
return $this->updateInCollection();
}
@@ -649,13 +666,13 @@ class Cell
/**
* Set the formula attributes.
*
- * @param mixed $pAttributes
+ * @param mixed $attributes
*
* @return $this
*/
- public function setFormulaAttributes($pAttributes)
+ public function setFormulaAttributes($attributes)
{
- $this->formulaAttributes = $pAttributes;
+ $this->formulaAttributes = $attributes;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php
index 2afeebe9dd9..b4b76c57d30 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php
@@ -13,6 +13,8 @@ use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
*/
abstract class Coordinate
{
+ public const A1_COORDINATE_REGEX = '/^(?\$?)(?[A-Z]{1,3})(?\$?)(?\d{1,7})$/i';
+
/**
* Default range variable constant.
*
@@ -23,86 +25,103 @@ abstract class Coordinate
/**
* Coordinate from string.
*
- * @param string $pCoordinateString eg: 'A1'
+ * @param string $cellAddress eg: 'A1'
*
- * @return string[] Array containing column and row (indexes 0 and 1)
+ * @return array{0: string, 1: string} Array containing column and row (indexes 0 and 1)
*/
- public static function coordinateFromString($pCoordinateString)
+ public static function coordinateFromString($cellAddress)
{
- if (preg_match('/^([$]?[A-Z]{1,3})([$]?\\d{1,7})$/', $pCoordinateString, $matches)) {
- return [$matches[1], $matches[2]];
- } elseif (self::coordinateIsRange($pCoordinateString)) {
+ if (preg_match(self::A1_COORDINATE_REGEX, $cellAddress, $matches)) {
+ return [$matches['absolute_col'] . $matches['col_ref'], $matches['absolute_row'] . $matches['row_ref']];
+ } elseif (self::coordinateIsRange($cellAddress)) {
throw new Exception('Cell coordinate string can not be a range of cells');
- } elseif ($pCoordinateString == '') {
+ } elseif ($cellAddress == '') {
throw new Exception('Cell coordinate can not be zero-length string');
}
- throw new Exception('Invalid cell coordinate ' . $pCoordinateString);
+ throw new Exception('Invalid cell coordinate ' . $cellAddress);
}
/**
- * Checks if a coordinate represents a range of cells.
+ * Get indexes from a string coordinates.
*
- * @param string $coord eg: 'A1' or 'A1:A2' or 'A1:A2,C1:C2'
+ * @param string $coordinates eg: 'A1', '$B$12'
+ *
+ * @return array{0: int, 1: int} Array containing column index and row index (indexes 0 and 1)
+ */
+ public static function indexesFromString(string $coordinates): array
+ {
+ [$col, $row] = self::coordinateFromString($coordinates);
+
+ return [
+ self::columnIndexFromString(ltrim($col, '$')),
+ (int) ltrim($row, '$'),
+ ];
+ }
+
+ /**
+ * Checks if a Cell Address represents a range of cells.
+ *
+ * @param string $cellAddress eg: 'A1' or 'A1:A2' or 'A1:A2,C1:C2'
*
* @return bool Whether the coordinate represents a range of cells
*/
- public static function coordinateIsRange($coord)
+ public static function coordinateIsRange($cellAddress)
{
- return (strpos($coord, ':') !== false) || (strpos($coord, ',') !== false);
+ return (strpos($cellAddress, ':') !== false) || (strpos($cellAddress, ',') !== false);
}
/**
* Make string row, column or cell coordinate absolute.
*
- * @param string $pCoordinateString e.g. 'A' or '1' or 'A1'
+ * @param string $cellAddress e.g. 'A' or '1' or 'A1'
* Note that this value can be a row or column reference as well as a cell reference
*
* @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1'
*/
- public static function absoluteReference($pCoordinateString)
+ public static function absoluteReference($cellAddress)
{
- if (self::coordinateIsRange($pCoordinateString)) {
+ if (self::coordinateIsRange($cellAddress)) {
throw new Exception('Cell coordinate string can not be a range of cells');
}
// Split out any worksheet name from the reference
- [$worksheet, $pCoordinateString] = Worksheet::extractSheetTitle($pCoordinateString, true);
+ [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
if ($worksheet > '') {
$worksheet .= '!';
}
// Create absolute coordinate
- if (ctype_digit($pCoordinateString)) {
- return $worksheet . '$' . $pCoordinateString;
- } elseif (ctype_alpha($pCoordinateString)) {
- return $worksheet . '$' . strtoupper($pCoordinateString);
+ if (ctype_digit($cellAddress)) {
+ return $worksheet . '$' . $cellAddress;
+ } elseif (ctype_alpha($cellAddress)) {
+ return $worksheet . '$' . strtoupper($cellAddress);
}
- return $worksheet . self::absoluteCoordinate($pCoordinateString);
+ return $worksheet . self::absoluteCoordinate($cellAddress);
}
/**
* Make string coordinate absolute.
*
- * @param string $pCoordinateString e.g. 'A1'
+ * @param string $cellAddress e.g. 'A1'
*
* @return string Absolute coordinate e.g. '$A$1'
*/
- public static function absoluteCoordinate($pCoordinateString)
+ public static function absoluteCoordinate($cellAddress)
{
- if (self::coordinateIsRange($pCoordinateString)) {
+ if (self::coordinateIsRange($cellAddress)) {
throw new Exception('Cell coordinate string can not be a range of cells');
}
// Split out any worksheet name from the coordinate
- [$worksheet, $pCoordinateString] = Worksheet::extractSheetTitle($pCoordinateString, true);
+ [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
if ($worksheet > '') {
$worksheet .= '!';
}
// Create absolute coordinate
- [$column, $row] = self::coordinateFromString($pCoordinateString);
+ [$column, $row] = self::coordinateFromString($cellAddress);
$column = ltrim($column, '$');
$row = ltrim($row, '$');
@@ -112,20 +131,20 @@ abstract class Coordinate
/**
* Split range into coordinate strings.
*
- * @param string $pRange e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4'
+ * @param string $range e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4'
*
* @return array Array containing one or more arrays containing one or two coordinate strings
* e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']]
* or ['B4']
*/
- public static function splitRange($pRange)
+ public static function splitRange($range)
{
// Ensure $pRange is a valid range
- if (empty($pRange)) {
- $pRange = self::DEFAULT_RANGE;
+ if (empty($range)) {
+ $range = self::DEFAULT_RANGE;
}
- $exploded = explode(',', $pRange);
+ $exploded = explode(',', $range);
$counter = count($exploded);
for ($i = 0; $i < $counter; ++$i) {
$exploded[$i] = explode(':', $exploded[$i]);
@@ -137,49 +156,49 @@ abstract class Coordinate
/**
* Build range from coordinate strings.
*
- * @param array $pRange Array containg one or more arrays containing one or two coordinate strings
+ * @param array $range Array containing one or more arrays containing one or two coordinate strings
*
* @return string String representation of $pRange
*/
- public static function buildRange(array $pRange)
+ public static function buildRange(array $range)
{
// Verify range
- if (empty($pRange) || !is_array($pRange[0])) {
+ if (empty($range) || !is_array($range[0])) {
throw new Exception('Range does not contain any information');
}
// Build range
- $counter = count($pRange);
+ $counter = count($range);
for ($i = 0; $i < $counter; ++$i) {
- $pRange[$i] = implode(':', $pRange[$i]);
+ $range[$i] = implode(':', $range[$i]);
}
- return implode(',', $pRange);
+ return implode(',', $range);
}
/**
* Calculate range boundaries.
*
- * @param string $pRange Cell range (e.g. A1:A1)
+ * @param string $range Cell range (e.g. A1:A1)
*
* @return array Range coordinates [Start Cell, End Cell]
* where Start Cell and End Cell are arrays (Column Number, Row Number)
*/
- public static function rangeBoundaries($pRange)
+ public static function rangeBoundaries($range)
{
// Ensure $pRange is a valid range
- if (empty($pRange)) {
- $pRange = self::DEFAULT_RANGE;
+ if (empty($range)) {
+ $range = self::DEFAULT_RANGE;
}
// Uppercase coordinate
- $pRange = strtoupper($pRange);
+ $range = strtoupper($range);
// Extract range
- if (strpos($pRange, ':') === false) {
- $rangeA = $rangeB = $pRange;
+ if (strpos($range, ':') === false) {
+ $rangeA = $rangeB = $range;
} else {
- [$rangeA, $rangeB] = explode(':', $pRange);
+ [$rangeA, $rangeB] = explode(':', $range);
}
// Calculate range outer borders
@@ -196,14 +215,14 @@ abstract class Coordinate
/**
* Calculate range dimension.
*
- * @param string $pRange Cell range (e.g. A1:A1)
+ * @param string $range Cell range (e.g. A1:A1)
*
* @return array Range dimension (width, height)
*/
- public static function rangeDimension($pRange)
+ public static function rangeDimension($range)
{
// Calculate range outer borders
- [$rangeStart, $rangeEnd] = self::rangeBoundaries($pRange);
+ [$rangeStart, $rangeEnd] = self::rangeBoundaries($range);
return [($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1)];
}
@@ -211,26 +230,26 @@ abstract class Coordinate
/**
* Calculate range boundaries.
*
- * @param string $pRange Cell range (e.g. A1:A1)
+ * @param string $range Cell range (e.g. A1:A1)
*
* @return array Range coordinates [Start Cell, End Cell]
* where Start Cell and End Cell are arrays [Column ID, Row Number]
*/
- public static function getRangeBoundaries($pRange)
+ public static function getRangeBoundaries($range)
{
// Ensure $pRange is a valid range
- if (empty($pRange)) {
- $pRange = self::DEFAULT_RANGE;
+ if (empty($range)) {
+ $range = self::DEFAULT_RANGE;
}
// Uppercase coordinate
- $pRange = strtoupper($pRange);
+ $range = strtoupper($range);
// Extract range
- if (strpos($pRange, ':') === false) {
- $rangeA = $rangeB = $pRange;
+ if (strpos($range, ':') === false) {
+ $rangeA = $rangeB = $range;
} else {
- [$rangeA, $rangeB] = explode(':', $pRange);
+ [$rangeA, $rangeB] = explode(':', $range);
}
return [self::coordinateFromString($rangeA), self::coordinateFromString($rangeB)];
@@ -239,19 +258,19 @@ abstract class Coordinate
/**
* Column index from string.
*
- * @param string $pString eg 'A'
+ * @param string $columnAddress eg 'A'
*
* @return int Column index (A = 1)
*/
- public static function columnIndexFromString($pString)
+ public static function columnIndexFromString($columnAddress)
{
// Using a lookup cache adds a slight memory overhead, but boosts speed
// caching using a static within the method is faster than a class static,
// though it's additional memory overhead
static $indexCache = [];
- if (isset($indexCache[$pString])) {
- return $indexCache[$pString];
+ if (isset($indexCache[$columnAddress])) {
+ return $indexCache[$columnAddress];
}
// It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array rather than use ord()
// and make it case insensitive to get rid of the strtoupper() as well. Because it's a static, there's no significant
@@ -263,25 +282,25 @@ abstract class Coordinate
'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19, 't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26,
];
- // We also use the language construct isset() rather than the more costly strlen() function to match the length of $pString
+ // We also use the language construct isset() rather than the more costly strlen() function to match the length of $columnAddress
// for improved performance
- if (isset($pString[0])) {
- if (!isset($pString[1])) {
- $indexCache[$pString] = $columnLookup[$pString];
+ if (isset($columnAddress[0])) {
+ if (!isset($columnAddress[1])) {
+ $indexCache[$columnAddress] = $columnLookup[$columnAddress];
- return $indexCache[$pString];
- } elseif (!isset($pString[2])) {
- $indexCache[$pString] = $columnLookup[$pString[0]] * 26 + $columnLookup[$pString[1]];
+ return $indexCache[$columnAddress];
+ } elseif (!isset($columnAddress[2])) {
+ $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 26 + $columnLookup[$columnAddress[1]];
- return $indexCache[$pString];
- } elseif (!isset($pString[3])) {
- $indexCache[$pString] = $columnLookup[$pString[0]] * 676 + $columnLookup[$pString[1]] * 26 + $columnLookup[$pString[2]];
+ return $indexCache[$columnAddress];
+ } elseif (!isset($columnAddress[3])) {
+ $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 676 + $columnLookup[$columnAddress[1]] * 26 + $columnLookup[$columnAddress[2]];
- return $indexCache[$pString];
+ return $indexCache[$columnAddress];
}
}
- throw new Exception('Column string index can not be ' . ((isset($pString[0])) ? 'longer than 3 characters' : 'empty'));
+ throw new Exception('Column string index can not be ' . ((isset($columnAddress[0])) ? 'longer than 3 characters' : 'empty'));
}
/**
@@ -339,7 +358,8 @@ abstract class Coordinate
private static function processRangeSetOperators(array $operators, array $cells): array
{
- for ($offset = 0; $offset < count($operators); ++$offset) {
+ $operatorCount = count($operators);
+ for ($offset = 0; $offset < $operatorCount; ++$offset) {
$operator = $operators[$offset];
if ($operator !== ' ') {
continue;
@@ -350,6 +370,7 @@ abstract class Coordinate
$operators = array_values($operators);
$cells = array_values($cells);
--$offset;
+ --$operatorCount;
}
return $cells;
@@ -435,16 +456,16 @@ abstract class Coordinate
*
* [ 'A1:A3' => 'x', 'A4' => 'y' ]
*
- * @param array $pCoordCollection associative array mapping coordinates to values
+ * @param array $coordinateCollection associative array mapping coordinates to values
*
* @return array associative array mapping coordinate ranges to valuea
*/
- public static function mergeRangesInCollection(array $pCoordCollection)
+ public static function mergeRangesInCollection(array $coordinateCollection)
{
$hashedValues = [];
$mergedCoordCollection = [];
- foreach ($pCoordCollection as $coord => $value) {
+ foreach ($coordinateCollection as $coord => $value) {
if (self::coordinateIsRange($coord)) {
$mergedCoordCollection[$coord] = $value;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataType.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataType.php
index ba035791787..cee3e1e5eb6 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataType.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataType.php
@@ -45,41 +45,41 @@ class DataType
/**
* Check a string that it satisfies Excel requirements.
*
- * @param null|RichText|string $pValue Value to sanitize to an Excel string
+ * @param null|RichText|string $textValue Value to sanitize to an Excel string
*
* @return null|RichText|string Sanitized value
*/
- public static function checkString($pValue)
+ public static function checkString($textValue)
{
- if ($pValue instanceof RichText) {
+ if ($textValue instanceof RichText) {
// TODO: Sanitize Rich-Text string (max. character count is 32,767)
- return $pValue;
+ return $textValue;
}
// string must never be longer than 32,767 characters, truncate if necessary
- $pValue = StringHelper::substring($pValue, 0, 32767);
+ $textValue = StringHelper::substring($textValue, 0, 32767);
// we require that newline is represented as "\n" in core, not as "\r\n" or "\r"
- $pValue = str_replace(["\r\n", "\r"], "\n", $pValue);
+ $textValue = str_replace(["\r\n", "\r"], "\n", $textValue);
- return $pValue;
+ return $textValue;
}
/**
* Check a value that it is a valid error code.
*
- * @param mixed $pValue Value to sanitize to an Excel error code
+ * @param mixed $value Value to sanitize to an Excel error code
*
* @return string Sanitized value
*/
- public static function checkErrorCode($pValue)
+ public static function checkErrorCode($value)
{
- $pValue = (string) $pValue;
+ $value = (string) $value;
- if (!isset(self::$errorCodes[$pValue])) {
- $pValue = '#NULL!';
+ if (!isset(self::$errorCodes[$value])) {
+ $value = '#NULL!';
}
- return $pValue;
+ return $value;
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidation.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidation.php
index dfeb024c928..7ee53eae076 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidation.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidation.php
@@ -140,13 +140,13 @@ class DataValidation
/**
* Set Formula 1.
*
- * @param string $value
+ * @param string $formula
*
* @return $this
*/
- public function setFormula1($value)
+ public function setFormula1($formula)
{
- $this->formula1 = $value;
+ $this->formula1 = $formula;
return $this;
}
@@ -164,13 +164,13 @@ class DataValidation
/**
* Set Formula 2.
*
- * @param string $value
+ * @param string $formula
*
* @return $this
*/
- public function setFormula2($value)
+ public function setFormula2($formula)
{
- $this->formula2 = $value;
+ $this->formula2 = $formula;
return $this;
}
@@ -188,13 +188,13 @@ class DataValidation
/**
* Set Type.
*
- * @param string $value
+ * @param string $type
*
* @return $this
*/
- public function setType($value)
+ public function setType($type)
{
- $this->type = $value;
+ $this->type = $type;
return $this;
}
@@ -212,13 +212,13 @@ class DataValidation
/**
* Set Error style.
*
- * @param string $value see self::STYLE_*
+ * @param string $errorStyle see self::STYLE_*
*
* @return $this
*/
- public function setErrorStyle($value)
+ public function setErrorStyle($errorStyle)
{
- $this->errorStyle = $value;
+ $this->errorStyle = $errorStyle;
return $this;
}
@@ -236,13 +236,13 @@ class DataValidation
/**
* Set Operator.
*
- * @param string $value
+ * @param string $operator
*
* @return $this
*/
- public function setOperator($value)
+ public function setOperator($operator)
{
- $this->operator = $value;
+ $this->operator = $operator;
return $this;
}
@@ -260,13 +260,13 @@ class DataValidation
/**
* Set Allow Blank.
*
- * @param bool $value
+ * @param bool $allowBlank
*
* @return $this
*/
- public function setAllowBlank($value)
+ public function setAllowBlank($allowBlank)
{
- $this->allowBlank = $value;
+ $this->allowBlank = $allowBlank;
return $this;
}
@@ -284,13 +284,13 @@ class DataValidation
/**
* Set Show DropDown.
*
- * @param bool $value
+ * @param bool $showDropDown
*
* @return $this
*/
- public function setShowDropDown($value)
+ public function setShowDropDown($showDropDown)
{
- $this->showDropDown = $value;
+ $this->showDropDown = $showDropDown;
return $this;
}
@@ -308,13 +308,13 @@ class DataValidation
/**
* Set Show InputMessage.
*
- * @param bool $value
+ * @param bool $showInputMessage
*
* @return $this
*/
- public function setShowInputMessage($value)
+ public function setShowInputMessage($showInputMessage)
{
- $this->showInputMessage = $value;
+ $this->showInputMessage = $showInputMessage;
return $this;
}
@@ -332,13 +332,13 @@ class DataValidation
/**
* Set Show ErrorMessage.
*
- * @param bool $value
+ * @param bool $showErrorMessage
*
* @return $this
*/
- public function setShowErrorMessage($value)
+ public function setShowErrorMessage($showErrorMessage)
{
- $this->showErrorMessage = $value;
+ $this->showErrorMessage = $showErrorMessage;
return $this;
}
@@ -356,13 +356,13 @@ class DataValidation
/**
* Set Error title.
*
- * @param string $value
+ * @param string $errorTitle
*
* @return $this
*/
- public function setErrorTitle($value)
+ public function setErrorTitle($errorTitle)
{
- $this->errorTitle = $value;
+ $this->errorTitle = $errorTitle;
return $this;
}
@@ -380,13 +380,13 @@ class DataValidation
/**
* Set Error.
*
- * @param string $value
+ * @param string $error
*
* @return $this
*/
- public function setError($value)
+ public function setError($error)
{
- $this->error = $value;
+ $this->error = $error;
return $this;
}
@@ -404,13 +404,13 @@ class DataValidation
/**
* Set Prompt title.
*
- * @param string $value
+ * @param string $promptTitle
*
* @return $this
*/
- public function setPromptTitle($value)
+ public function setPromptTitle($promptTitle)
{
- $this->promptTitle = $value;
+ $this->promptTitle = $promptTitle;
return $this;
}
@@ -428,13 +428,13 @@ class DataValidation
/**
* Set Prompt.
*
- * @param string $value
+ * @param string $prompt
*
* @return $this
*/
- public function setPrompt($value)
+ public function setPrompt($prompt)
{
- $this->prompt = $value;
+ $this->prompt = $prompt;
return $this;
}
@@ -460,6 +460,7 @@ class DataValidation
$this->error .
$this->promptTitle .
$this->prompt .
+ $this->sqref .
__CLASS__
);
}
@@ -478,4 +479,19 @@ class DataValidation
}
}
}
+
+ /** @var ?string */
+ private $sqref;
+
+ public function getSqref(): ?string
+ {
+ return $this->sqref;
+ }
+
+ public function setSqref(?string $str): self
+ {
+ $this->sqref = $str;
+
+ return $this;
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DefaultValueBinder.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DefaultValueBinder.php
index 693446e698c..4f2cdf78793 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DefaultValueBinder.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DefaultValueBinder.php
@@ -26,6 +26,7 @@ class DefaultValueBinder implements IValueBinder
if ($value instanceof DateTimeInterface) {
$value = $value->format('Y-m-d H:i:s');
} elseif (!($value instanceof RichText)) {
+ // Attempt to cast any unexpected objects to string
$value = (string) $value;
}
}
@@ -40,39 +41,39 @@ class DefaultValueBinder implements IValueBinder
/**
* DataType for value.
*
- * @param mixed $pValue
+ * @param mixed $value
*
* @return string
*/
- public static function dataTypeForValue($pValue)
+ public static function dataTypeForValue($value)
{
// Match the value against a few data types
- if ($pValue === null) {
+ if ($value === null) {
return DataType::TYPE_NULL;
- } elseif (is_float($pValue) || is_int($pValue)) {
+ } elseif (is_float($value) || is_int($value)) {
return DataType::TYPE_NUMERIC;
- } elseif (is_bool($pValue)) {
+ } elseif (is_bool($value)) {
return DataType::TYPE_BOOL;
- } elseif ($pValue === '') {
+ } elseif ($value === '') {
return DataType::TYPE_STRING;
- } elseif ($pValue instanceof RichText) {
+ } elseif ($value instanceof RichText) {
return DataType::TYPE_INLINE;
- } elseif (is_string($pValue) && $pValue[0] === '=' && strlen($pValue) > 1) {
+ } elseif (is_string($value) && strlen($value) > 1 && $value[0] === '=') {
return DataType::TYPE_FORMULA;
- } elseif (preg_match('/^[\+\-]?(\d+\\.?\d*|\d*\\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $pValue)) {
- $tValue = ltrim($pValue, '+-');
- if (is_string($pValue) && $tValue[0] === '0' && strlen($tValue) > 1 && $tValue[1] !== '.') {
+ } elseif (preg_match('/^[\+\-]?(\d+\\.?\d*|\d*\\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $value)) {
+ $tValue = ltrim($value, '+-');
+ if (is_string($value) && strlen($tValue) > 1 && $tValue[0] === '0' && $tValue[1] !== '.') {
return DataType::TYPE_STRING;
- } elseif ((strpos($pValue, '.') === false) && ($pValue > PHP_INT_MAX)) {
+ } elseif ((strpos($value, '.') === false) && ($value > PHP_INT_MAX)) {
return DataType::TYPE_STRING;
- } elseif (!is_numeric($pValue)) {
+ } elseif (!is_numeric($value)) {
return DataType::TYPE_STRING;
}
return DataType::TYPE_NUMERIC;
- } elseif (is_string($pValue)) {
+ } elseif (is_string($value)) {
$errorCodes = DataType::getErrorCodes();
- if (isset($errorCodes[$pValue])) {
+ if (isset($errorCodes[$value])) {
return DataType::TYPE_ERROR;
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Hyperlink.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Hyperlink.php
index 003d51014d9..ffdcbacd273 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Hyperlink.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Hyperlink.php
@@ -21,14 +21,14 @@ class Hyperlink
/**
* Create a new Hyperlink.
*
- * @param string $pUrl Url to link the cell to
- * @param string $pTooltip Tooltip to display on the hyperlink
+ * @param string $url Url to link the cell to
+ * @param string $tooltip Tooltip to display on the hyperlink
*/
- public function __construct($pUrl = '', $pTooltip = '')
+ public function __construct($url = '', $tooltip = '')
{
// Initialise member variables
- $this->url = $pUrl;
- $this->tooltip = $pTooltip;
+ $this->url = $url;
+ $this->tooltip = $tooltip;
}
/**
@@ -44,13 +44,13 @@ class Hyperlink
/**
* Set URL.
*
- * @param string $value
+ * @param string $url
*
* @return $this
*/
- public function setUrl($value)
+ public function setUrl($url)
{
- $this->url = $value;
+ $this->url = $url;
return $this;
}
@@ -68,13 +68,13 @@ class Hyperlink
/**
* Set tooltip.
*
- * @param string $value
+ * @param string $tooltip
*
* @return $this
*/
- public function setTooltip($value)
+ public function setTooltip($tooltip)
{
- $this->tooltip = $value;
+ $this->tooltip = $tooltip;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php
index 346d025347a..d525faffff2 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php
@@ -2,28 +2,123 @@
namespace PhpOffice\PhpSpreadsheet\Cell;
+use DateTimeInterface;
+use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
class StringValueBinder implements IValueBinder
{
+ /**
+ * @var bool
+ */
+ protected $convertNull = true;
+
+ /**
+ * @var bool
+ */
+ protected $convertBoolean = true;
+
+ /**
+ * @var bool
+ */
+ protected $convertNumeric = true;
+
+ /**
+ * @var bool
+ */
+ protected $convertFormula = true;
+
+ public function setNullConversion(bool $suppressConversion = false): self
+ {
+ $this->convertNull = $suppressConversion;
+
+ return $this;
+ }
+
+ public function setBooleanConversion(bool $suppressConversion = false): self
+ {
+ $this->convertBoolean = $suppressConversion;
+
+ return $this;
+ }
+
+ public function getBooleanConversion(): bool
+ {
+ return $this->convertBoolean;
+ }
+
+ public function setNumericConversion(bool $suppressConversion = false): self
+ {
+ $this->convertNumeric = $suppressConversion;
+
+ return $this;
+ }
+
+ public function setFormulaConversion(bool $suppressConversion = false): self
+ {
+ $this->convertFormula = $suppressConversion;
+
+ return $this;
+ }
+
+ public function setConversionForAllValueTypes(bool $suppressConversion = false): self
+ {
+ $this->convertNull = $suppressConversion;
+ $this->convertBoolean = $suppressConversion;
+ $this->convertNumeric = $suppressConversion;
+ $this->convertFormula = $suppressConversion;
+
+ return $this;
+ }
+
/**
* Bind value to a cell.
*
* @param Cell $cell Cell to bind value to
* @param mixed $value Value to bind in cell
- *
- * @return bool
*/
public function bindValue(Cell $cell, $value)
{
+ if (is_object($value)) {
+ return $this->bindObjectValue($cell, $value);
+ }
+
// sanitize UTF-8 strings
if (is_string($value)) {
$value = StringHelper::sanitizeUTF8($value);
}
+ if ($value === null && $this->convertNull === false) {
+ $cell->setValueExplicit($value, DataType::TYPE_NULL);
+ } elseif (is_bool($value) && $this->convertBoolean === false) {
+ $cell->setValueExplicit($value, DataType::TYPE_BOOL);
+ } elseif ((is_int($value) || is_float($value)) && $this->convertNumeric === false) {
+ $cell->setValueExplicit($value, DataType::TYPE_NUMERIC);
+ } elseif (is_string($value) && strlen($value) > 1 && $value[0] === '=' && $this->convertFormula === false) {
+ $cell->setValueExplicit($value, DataType::TYPE_FORMULA);
+ } else {
+ if (is_string($value) && strlen($value) > 1 && $value[0] === '=') {
+ $cell->getStyle()->setQuotePrefix(true);
+ }
+ $cell->setValueExplicit((string) $value, DataType::TYPE_STRING);
+ }
+
+ return true;
+ }
+
+ protected function bindObjectValue(Cell $cell, object $value): bool
+ {
+ // Handle any objects that might be injected
+ if ($value instanceof DateTimeInterface) {
+ $value = $value->format('Y-m-d H:i:s');
+ } elseif ($value instanceof RichText) {
+ $cell->setValueExplicit($value, DataType::TYPE_INLINE);
+
+ return true;
+ }
+
$cell->setValueExplicit((string) $value, DataType::TYPE_STRING);
- // Done!
return true;
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Axis.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Axis.php
index 7995c3b3fe9..eeed326db87 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Axis.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Axis.php
@@ -13,7 +13,7 @@ class Axis extends Properties
/**
* Axis Number.
*
- * @var array of mixed
+ * @var mixed[]
*/
private $axisNumber = [
'format' => self::FORMAT_CODE_GENERAL,
@@ -23,7 +23,7 @@ class Axis extends Properties
/**
* Axis Options.
*
- * @var array of mixed
+ * @var mixed[]
*/
private $axisOptions = [
'minimum' => null,
@@ -41,7 +41,7 @@ class Axis extends Properties
/**
* Fill Properties.
*
- * @var array of mixed
+ * @var mixed[]
*/
private $fillProperties = [
'type' => self::EXCEL_COLOR_TYPE_ARGB,
@@ -52,7 +52,7 @@ class Axis extends Properties
/**
* Line Properties.
*
- * @var array of mixed
+ * @var mixed[]
*/
private $lineProperties = [
'type' => self::EXCEL_COLOR_TYPE_ARGB,
@@ -63,7 +63,7 @@ class Axis extends Properties
/**
* Line Style Properties.
*
- * @var array of mixed
+ * @var mixed[]
*/
private $lineStyleProperties = [
'width' => '9525',
@@ -86,7 +86,7 @@ class Axis extends Properties
/**
* Shadow Properties.
*
- * @var array of mixed
+ * @var mixed[]
*/
private $shadowProperties = [
'presets' => self::SHADOW_PRESETS_NOSHADOW,
@@ -111,7 +111,7 @@ class Axis extends Properties
/**
* Glow Properties.
*
- * @var array of mixed
+ * @var mixed[]
*/
private $glowProperties = [
'size' => null,
@@ -125,7 +125,7 @@ class Axis extends Properties
/**
* Soft Edge Properties.
*
- * @var array of mixed
+ * @var mixed[]
*/
private $softEdges = [
'size' => null,
@@ -135,10 +135,8 @@ class Axis extends Properties
* Get Series Data Type.
*
* @param mixed $format_code
- *
- * @return string
*/
- public function setAxisNumberProperties($format_code)
+ public function setAxisNumberProperties($format_code): void
{
$this->axisNumber['format'] = (string) $format_code;
$this->axisNumber['source_linked'] = 0;
@@ -167,30 +165,30 @@ class Axis extends Properties
/**
* Set Axis Options Properties.
*
- * @param string $axis_labels
- * @param string $horizontal_crosses_value
- * @param string $horizontal_crosses
- * @param string $axis_orientation
- * @param string $major_tmt
- * @param string $minor_tmt
+ * @param string $axisLabels
+ * @param string $horizontalCrossesValue
+ * @param string $horizontalCrosses
+ * @param string $axisOrientation
+ * @param string $majorTmt
+ * @param string $minorTmt
* @param string $minimum
* @param string $maximum
- * @param string $major_unit
- * @param string $minor_unit
+ * @param string $majorUnit
+ * @param string $minorUnit
*/
- public function setAxisOptionsProperties($axis_labels, $horizontal_crosses_value = null, $horizontal_crosses = null, $axis_orientation = null, $major_tmt = null, $minor_tmt = null, $minimum = null, $maximum = null, $major_unit = null, $minor_unit = null): void
+ public function setAxisOptionsProperties($axisLabels, $horizontalCrossesValue = null, $horizontalCrosses = null, $axisOrientation = null, $majorTmt = null, $minorTmt = null, $minimum = null, $maximum = null, $majorUnit = null, $minorUnit = null): void
{
- $this->axisOptions['axis_labels'] = (string) $axis_labels;
- ($horizontal_crosses_value !== null) ? $this->axisOptions['horizontal_crosses_value'] = (string) $horizontal_crosses_value : null;
- ($horizontal_crosses !== null) ? $this->axisOptions['horizontal_crosses'] = (string) $horizontal_crosses : null;
- ($axis_orientation !== null) ? $this->axisOptions['orientation'] = (string) $axis_orientation : null;
- ($major_tmt !== null) ? $this->axisOptions['major_tick_mark'] = (string) $major_tmt : null;
- ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null;
- ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null;
+ $this->axisOptions['axis_labels'] = (string) $axisLabels;
+ ($horizontalCrossesValue !== null) ? $this->axisOptions['horizontal_crosses_value'] = (string) $horizontalCrossesValue : null;
+ ($horizontalCrosses !== null) ? $this->axisOptions['horizontal_crosses'] = (string) $horizontalCrosses : null;
+ ($axisOrientation !== null) ? $this->axisOptions['orientation'] = (string) $axisOrientation : null;
+ ($majorTmt !== null) ? $this->axisOptions['major_tick_mark'] = (string) $majorTmt : null;
+ ($minorTmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minorTmt : null;
+ ($minorTmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minorTmt : null;
($minimum !== null) ? $this->axisOptions['minimum'] = (string) $minimum : null;
($maximum !== null) ? $this->axisOptions['maximum'] = (string) $maximum : null;
- ($major_unit !== null) ? $this->axisOptions['major_unit'] = (string) $major_unit : null;
- ($minor_unit !== null) ? $this->axisOptions['minor_unit'] = (string) $minor_unit : null;
+ ($majorUnit !== null) ? $this->axisOptions['major_unit'] = (string) $majorUnit : null;
+ ($minorUnit !== null) ? $this->axisOptions['minor_unit'] = (string) $minorUnit : null;
}
/**
@@ -220,11 +218,11 @@ class Axis extends Properties
*
* @param string $color
* @param int $alpha
- * @param string $type
+ * @param string $AlphaType
*/
- public function setFillParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB): void
+ public function setFillParameters($color, $alpha = 0, $AlphaType = self::EXCEL_COLOR_TYPE_ARGB): void
{
- $this->fillProperties = $this->setColorProperties($color, $alpha, $type);
+ $this->fillProperties = $this->setColorProperties($color, $alpha, $AlphaType);
}
/**
@@ -232,11 +230,11 @@ class Axis extends Properties
*
* @param string $color
* @param int $alpha
- * @param string $type
+ * @param string $alphaType
*/
- public function setLineParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB): void
+ public function setLineParameters($color, $alpha = 0, $alphaType = self::EXCEL_COLOR_TYPE_ARGB): void
{
- $this->lineProperties = $this->setColorProperties($color, $alpha, $type);
+ $this->lineProperties = $this->setColorProperties($color, $alpha, $alphaType);
}
/**
@@ -266,27 +264,27 @@ class Axis extends Properties
/**
* Set Line Style Properties.
*
- * @param float $line_width
- * @param string $compound_type
- * @param string $dash_type
- * @param string $cap_type
- * @param string $join_type
- * @param string $head_arrow_type
- * @param string $head_arrow_size
- * @param string $end_arrow_type
- * @param string $end_arrow_size
+ * @param float $lineWidth
+ * @param string $compoundType
+ * @param string $dashType
+ * @param string $capType
+ * @param string $joinType
+ * @param string $headArrowType
+ * @param string $headArrowSize
+ * @param string $endArrowType
+ * @param string $endArrowSize
*/
- public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null): void
+ public function setLineStyleProperties($lineWidth = null, $compoundType = null, $dashType = null, $capType = null, $joinType = null, $headArrowType = null, $headArrowSize = null, $endArrowType = null, $endArrowSize = null): void
{
- ($line_width !== null) ? $this->lineStyleProperties['width'] = $this->getExcelPointsWidth((float) $line_width) : null;
- ($compound_type !== null) ? $this->lineStyleProperties['compound'] = (string) $compound_type : null;
- ($dash_type !== null) ? $this->lineStyleProperties['dash'] = (string) $dash_type : null;
- ($cap_type !== null) ? $this->lineStyleProperties['cap'] = (string) $cap_type : null;
- ($join_type !== null) ? $this->lineStyleProperties['join'] = (string) $join_type : null;
- ($head_arrow_type !== null) ? $this->lineStyleProperties['arrow']['head']['type'] = (string) $head_arrow_type : null;
- ($head_arrow_size !== null) ? $this->lineStyleProperties['arrow']['head']['size'] = (string) $head_arrow_size : null;
- ($end_arrow_type !== null) ? $this->lineStyleProperties['arrow']['end']['type'] = (string) $end_arrow_type : null;
- ($end_arrow_size !== null) ? $this->lineStyleProperties['arrow']['end']['size'] = (string) $end_arrow_size : null;
+ ($lineWidth !== null) ? $this->lineStyleProperties['width'] = $this->getExcelPointsWidth((float) $lineWidth) : null;
+ ($compoundType !== null) ? $this->lineStyleProperties['compound'] = (string) $compoundType : null;
+ ($dashType !== null) ? $this->lineStyleProperties['dash'] = (string) $dashType : null;
+ ($capType !== null) ? $this->lineStyleProperties['cap'] = (string) $capType : null;
+ ($joinType !== null) ? $this->lineStyleProperties['join'] = (string) $joinType : null;
+ ($headArrowType !== null) ? $this->lineStyleProperties['arrow']['head']['type'] = (string) $headArrowType : null;
+ ($headArrowSize !== null) ? $this->lineStyleProperties['arrow']['head']['size'] = (string) $headArrowSize : null;
+ ($endArrowType !== null) ? $this->lineStyleProperties['arrow']['end']['type'] = (string) $endArrowType : null;
+ ($endArrowSize !== null) ? $this->lineStyleProperties['arrow']['end']['size'] = (string) $endArrowSize : null;
}
/**
@@ -328,38 +326,38 @@ class Axis extends Properties
/**
* Set Shadow Properties.
*
- * @param int $sh_presets
- * @param string $sh_color_value
- * @param string $sh_color_type
- * @param string $sh_color_alpha
- * @param float $sh_blur
- * @param int $sh_angle
- * @param float $sh_distance
+ * @param int $shadowPresets
+ * @param string $colorValue
+ * @param string $colorType
+ * @param string $colorAlpha
+ * @param float $blur
+ * @param int $angle
+ * @param float $distance
*/
- public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null): void
+ public function setShadowProperties($shadowPresets, $colorValue = null, $colorType = null, $colorAlpha = null, $blur = null, $angle = null, $distance = null): void
{
- $this->setShadowPresetsProperties((int) $sh_presets)
+ $this->setShadowPresetsProperties((int) $shadowPresets)
->setShadowColor(
- $sh_color_value === null ? $this->shadowProperties['color']['value'] : $sh_color_value,
- $sh_color_alpha === null ? (int) $this->shadowProperties['color']['alpha'] : $sh_color_alpha,
- $sh_color_type === null ? $this->shadowProperties['color']['type'] : $sh_color_type
+ $colorValue ?? $this->shadowProperties['color']['value'],
+ $colorAlpha ?? (int) $this->shadowProperties['color']['alpha'],
+ $colorType ?? $this->shadowProperties['color']['type']
)
- ->setShadowBlur($sh_blur)
- ->setShadowAngle($sh_angle)
- ->setShadowDistance($sh_distance);
+ ->setShadowBlur($blur)
+ ->setShadowAngle($angle)
+ ->setShadowDistance($distance);
}
/**
* Set Shadow Color.
*
- * @param int $shadow_presets
+ * @param int $presets
*
* @return $this
*/
- private function setShadowPresetsProperties($shadow_presets)
+ private function setShadowPresetsProperties($presets)
{
- $this->shadowProperties['presets'] = $shadow_presets;
- $this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets));
+ $this->shadowProperties['presets'] = $presets;
+ $this->setShadowPropertiesMapValues($this->getShadowPresetsMap($presets));
return $this;
}
@@ -367,21 +365,21 @@ class Axis extends Properties
/**
* Set Shadow Properties from Mapped Values.
*
- * @param mixed &$reference
+ * @param mixed $reference
*
* @return $this
*/
- private function setShadowProperiesMapValues(array $properties_map, &$reference = null)
+ private function setShadowPropertiesMapValues(array $propertiesMap, &$reference = null)
{
$base_reference = $reference;
- foreach ($properties_map as $property_key => $property_val) {
+ foreach ($propertiesMap as $property_key => $property_val) {
if (is_array($property_val)) {
if ($reference === null) {
$reference = &$this->shadowProperties[$property_key];
} else {
$reference = &$reference[$property_key];
}
- $this->setShadowProperiesMapValues($property_val, $reference);
+ $this->setShadowPropertiesMapValues($property_val, $reference);
} else {
if ($base_reference === null) {
$this->shadowProperties[$property_key] = $property_val;
@@ -399,13 +397,13 @@ class Axis extends Properties
*
* @param string $color
* @param int $alpha
- * @param string $type
+ * @param string $alphaType
*
* @return $this
*/
- private function setShadowColor($color, $alpha, $type)
+ private function setShadowColor($color, $alpha, $alphaType)
{
- $this->shadowProperties['color'] = $this->setColorProperties($color, $alpha, $type);
+ $this->shadowProperties['color'] = $this->setColorProperties($color, $alpha, $alphaType);
return $this;
}
@@ -474,17 +472,17 @@ class Axis extends Properties
* Set Glow Properties.
*
* @param float $size
- * @param string $color_value
- * @param int $color_alpha
- * @param string $color_type
+ * @param string $colorValue
+ * @param int $colorAlpha
+ * @param string $colorType
*/
- public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null): void
+ public function setGlowProperties($size, $colorValue = null, $colorAlpha = null, $colorType = null): void
{
$this->setGlowSize($size)
->setGlowColor(
- $color_value === null ? $this->glowProperties['color']['value'] : $color_value,
- $color_alpha === null ? (int) $this->glowProperties['color']['alpha'] : $color_alpha,
- $color_type === null ? $this->glowProperties['color']['type'] : $color_type
+ $colorValue ?? $this->glowProperties['color']['value'],
+ $colorAlpha ?? (int) $this->glowProperties['color']['alpha'],
+ $colorType ?? $this->glowProperties['color']['type']
);
}
@@ -521,13 +519,13 @@ class Axis extends Properties
*
* @param string $color
* @param int $alpha
- * @param string $type
+ * @param string $colorType
*
* @return $this
*/
- private function setGlowColor($color, $alpha, $type)
+ private function setGlowColor($color, $alpha, $colorType)
{
- $this->glowProperties['color'] = $this->setColorProperties($color, $alpha, $type);
+ $this->glowProperties['color'] = $this->setColorProperties($color, $alpha, $colorType);
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php
index 20eb2aee7b6..bed89464ef3 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php
@@ -186,13 +186,11 @@ class Chart
/**
* Set Worksheet.
*
- * @param Worksheet $pValue
- *
* @return $this
*/
- public function setWorksheet(?Worksheet $pValue = null)
+ public function setWorksheet(?Worksheet $worksheet = null)
{
- $this->worksheet = $pValue;
+ $this->worksheet = $worksheet;
return $this;
}
@@ -424,7 +422,7 @@ class Chart
/**
* Get the top left position of the chart.
*
- * @return array an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell
+ * @return array{cell: string, xOffset: int, yOffset: int} an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell
*/
public function getTopLeftPosition()
{
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeries.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeries.php
index 3a44b33529b..067d30e548f 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeries.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeries.php
@@ -75,21 +75,21 @@ class DataSeries
/**
* Order of plots in Series.
*
- * @var array of integer
+ * @var int[]
*/
private $plotOrder = [];
/**
* Plot Label.
*
- * @var array of DataSeriesValues
+ * @var DataSeriesValues[]
*/
private $plotLabel = [];
/**
* Plot Category.
*
- * @var array of DataSeriesValues
+ * @var DataSeriesValues[]
*/
private $plotCategory = [];
@@ -103,7 +103,7 @@ class DataSeries
/**
* Plot Values.
*
- * @var array of DataSeriesValues
+ * @var DataSeriesValues[]
*/
private $plotValues = [];
@@ -231,7 +231,7 @@ class DataSeries
/**
* Get Plot Labels.
*
- * @return array of DataSeriesValues
+ * @return DataSeriesValues[]
*/
public function getPlotLabels()
{
@@ -243,7 +243,7 @@ class DataSeries
*
* @param mixed $index
*
- * @return DataSeriesValues
+ * @return DataSeriesValues|false
*/
public function getPlotLabelByIndex($index)
{
@@ -260,7 +260,7 @@ class DataSeries
/**
* Get Plot Categories.
*
- * @return array of DataSeriesValues
+ * @return DataSeriesValues[]
*/
public function getPlotCategories()
{
@@ -272,7 +272,7 @@ class DataSeries
*
* @param mixed $index
*
- * @return DataSeriesValues
+ * @return DataSeriesValues|false
*/
public function getPlotCategoryByIndex($index)
{
@@ -313,7 +313,7 @@ class DataSeries
/**
* Get Plot Values.
*
- * @return array of DataSeriesValues
+ * @return DataSeriesValues[]
*/
public function getPlotValues()
{
@@ -325,7 +325,7 @@ class DataSeries
*
* @param mixed $index
*
- * @return DataSeriesValues
+ * @return DataSeriesValues|false
*/
public function getPlotValuesByIndex($index)
{
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeriesValues.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeriesValues.php
index c1bd973a46d..88063336bf5 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeriesValues.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeriesValues.php
@@ -55,7 +55,7 @@ class DataSeriesValues
/**
* Data Values.
*
- * @var array of mixed
+ * @var mixed[]
*/
private $dataValues = [];
@@ -313,7 +313,7 @@ class DataSeriesValues
/**
* Get Series Data Values.
*
- * @return array of mixed
+ * @return mixed[]
*/
public function getDataValues()
{
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/GridLines.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/GridLines.php
index 2e424bc246a..84af3ada5a7 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/GridLines.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/GridLines.php
@@ -105,73 +105,73 @@ class GridLines extends Properties
*
* @param string $value
* @param int $alpha
- * @param string $type
+ * @param string $colorType
*/
- public function setLineColorProperties($value, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_STANDARD): void
+ public function setLineColorProperties($value, $alpha = 0, $colorType = self::EXCEL_COLOR_TYPE_STANDARD): void
{
$this->activateObject()
->lineProperties['color'] = $this->setColorProperties(
$value,
$alpha,
- $type
+ $colorType
);
}
/**
* Set Line Color Properties.
*
- * @param float $line_width
- * @param string $compound_type
- * @param string $dash_type
- * @param string $cap_type
- * @param string $join_type
- * @param string $head_arrow_type
- * @param string $head_arrow_size
- * @param string $end_arrow_type
- * @param string $end_arrow_size
+ * @param float $lineWidth
+ * @param string $compoundType
+ * @param string $dashType
+ * @param string $capType
+ * @param string $joinType
+ * @param string $headArrowType
+ * @param string $headArrowSize
+ * @param string $endArrowType
+ * @param string $endArrowSize
*/
- public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null): void
+ public function setLineStyleProperties($lineWidth = null, $compoundType = null, $dashType = null, $capType = null, $joinType = null, $headArrowType = null, $headArrowSize = null, $endArrowType = null, $endArrowSize = null): void
{
$this->activateObject();
- ($line_width !== null)
- ? $this->lineProperties['style']['width'] = $this->getExcelPointsWidth((float) $line_width)
+ ($lineWidth !== null)
+ ? $this->lineProperties['style']['width'] = $this->getExcelPointsWidth((float) $lineWidth)
: null;
- ($compound_type !== null)
- ? $this->lineProperties['style']['compound'] = (string) $compound_type
+ ($compoundType !== null)
+ ? $this->lineProperties['style']['compound'] = (string) $compoundType
: null;
- ($dash_type !== null)
- ? $this->lineProperties['style']['dash'] = (string) $dash_type
+ ($dashType !== null)
+ ? $this->lineProperties['style']['dash'] = (string) $dashType
: null;
- ($cap_type !== null)
- ? $this->lineProperties['style']['cap'] = (string) $cap_type
+ ($capType !== null)
+ ? $this->lineProperties['style']['cap'] = (string) $capType
: null;
- ($join_type !== null)
- ? $this->lineProperties['style']['join'] = (string) $join_type
+ ($joinType !== null)
+ ? $this->lineProperties['style']['join'] = (string) $joinType
: null;
- ($head_arrow_type !== null)
- ? $this->lineProperties['style']['arrow']['head']['type'] = (string) $head_arrow_type
+ ($headArrowType !== null)
+ ? $this->lineProperties['style']['arrow']['head']['type'] = (string) $headArrowType
: null;
- ($head_arrow_size !== null)
- ? $this->lineProperties['style']['arrow']['head']['size'] = (string) $head_arrow_size
+ ($headArrowSize !== null)
+ ? $this->lineProperties['style']['arrow']['head']['size'] = (string) $headArrowSize
: null;
- ($end_arrow_type !== null)
- ? $this->lineProperties['style']['arrow']['end']['type'] = (string) $end_arrow_type
+ ($endArrowType !== null)
+ ? $this->lineProperties['style']['arrow']['end']['type'] = (string) $endArrowType
: null;
- ($end_arrow_size !== null)
- ? $this->lineProperties['style']['arrow']['end']['size'] = (string) $end_arrow_size
+ ($endArrowSize !== null)
+ ? $this->lineProperties['style']['arrow']['end']['size'] = (string) $endArrowSize
: null;
}
/**
* Get Line Color Property.
*
- * @param string $parameter
+ * @param string $propertyName
*
* @return string
*/
- public function getLineColorProperty($parameter)
+ public function getLineColorProperty($propertyName)
{
- return $this->lineProperties['color'][$parameter];
+ return $this->lineProperties['color'][$propertyName];
}
/**
@@ -190,28 +190,28 @@ class GridLines extends Properties
* Set Glow Properties.
*
* @param float $size
- * @param string $color_value
- * @param int $color_alpha
- * @param string $color_type
+ * @param string $colorValue
+ * @param int $colorAlpha
+ * @param string $colorType
*/
- public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null): void
+ public function setGlowProperties($size, $colorValue = null, $colorAlpha = null, $colorType = null): void
{
$this
->activateObject()
->setGlowSize($size)
- ->setGlowColor($color_value, $color_alpha, $color_type);
+ ->setGlowColor($colorValue, $colorAlpha, $colorType);
}
/**
* Get Glow Color Property.
*
- * @param string $property
+ * @param string $propertyName
*
* @return string
*/
- public function getGlowColor($property)
+ public function getGlowColor($propertyName)
{
- return $this->glowProperties['color'][$property];
+ return $this->glowProperties['color'][$propertyName];
}
/**
@@ -243,11 +243,11 @@ class GridLines extends Properties
*
* @param string $color
* @param int $alpha
- * @param string $type
+ * @param string $colorType
*
* @return $this
*/
- private function setGlowColor($color, $alpha, $type)
+ private function setGlowColor($color, $alpha, $colorType)
{
if ($color !== null) {
$this->glowProperties['color']['value'] = (string) $color;
@@ -255,8 +255,8 @@ class GridLines extends Properties
if ($alpha !== null) {
$this->glowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha);
}
- if ($type !== null) {
- $this->glowProperties['color']['type'] = (string) $type;
+ if ($colorType !== null) {
+ $this->glowProperties['color']['type'] = (string) $colorType;
}
return $this;
@@ -265,52 +265,52 @@ class GridLines extends Properties
/**
* Get Line Style Arrow Parameters.
*
- * @param string $arrow_selector
- * @param string $property_selector
+ * @param string $arrowSelector
+ * @param string $propertySelector
*
* @return string
*/
- public function getLineStyleArrowParameters($arrow_selector, $property_selector)
+ public function getLineStyleArrowParameters($arrowSelector, $propertySelector)
{
- return $this->getLineStyleArrowSize($this->lineProperties['style']['arrow'][$arrow_selector]['size'], $property_selector);
+ return $this->getLineStyleArrowSize($this->lineProperties['style']['arrow'][$arrowSelector]['size'], $propertySelector);
}
/**
* Set Shadow Properties.
*
- * @param int $sh_presets
- * @param string $sh_color_value
- * @param string $sh_color_type
- * @param int $sh_color_alpha
- * @param string $sh_blur
- * @param int $sh_angle
- * @param float $sh_distance
+ * @param int $presets
+ * @param string $colorValue
+ * @param string $colorType
+ * @param string $colorAlpha
+ * @param string $blur
+ * @param int $angle
+ * @param float $distance
*/
- public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null): void
+ public function setShadowProperties($presets, $colorValue = null, $colorType = null, $colorAlpha = null, $blur = null, $angle = null, $distance = null): void
{
$this->activateObject()
- ->setShadowPresetsProperties((int) $sh_presets)
+ ->setShadowPresetsProperties((int) $presets)
->setShadowColor(
- $sh_color_value === null ? $this->shadowProperties['color']['value'] : $sh_color_value,
- $sh_color_alpha === null ? (int) $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($sh_color_alpha),
- $sh_color_type === null ? $this->shadowProperties['color']['type'] : $sh_color_type
+ $colorValue ?? $this->shadowProperties['color']['value'],
+ $colorAlpha === null ? (int) $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($colorAlpha),
+ $colorType ?? $this->shadowProperties['color']['type']
)
- ->setShadowBlur($sh_blur)
- ->setShadowAngle($sh_angle)
- ->setShadowDistance($sh_distance);
+ ->setShadowBlur((float) $blur)
+ ->setShadowAngle($angle)
+ ->setShadowDistance($distance);
}
/**
* Set Shadow Presets Properties.
*
- * @param int $shadow_presets
+ * @param int $presets
*
* @return $this
*/
- private function setShadowPresetsProperties($shadow_presets)
+ private function setShadowPresetsProperties($presets)
{
- $this->shadowProperties['presets'] = $shadow_presets;
- $this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets));
+ $this->shadowProperties['presets'] = $presets;
+ $this->setShadowPropertiesMapValues($this->getShadowPresetsMap($presets));
return $this;
}
@@ -318,21 +318,21 @@ class GridLines extends Properties
/**
* Set Shadow Properties Values.
*
- * @param mixed &$reference
+ * @param mixed $reference
*
* @return $this
*/
- private function setShadowProperiesMapValues(array $properties_map, &$reference = null)
+ private function setShadowPropertiesMapValues(array $propertiesMap, &$reference = null)
{
$base_reference = $reference;
- foreach ($properties_map as $property_key => $property_val) {
+ foreach ($propertiesMap as $property_key => $property_val) {
if (is_array($property_val)) {
if ($reference === null) {
$reference = &$this->shadowProperties[$property_key];
} else {
$reference = &$reference[$property_key];
}
- $this->setShadowProperiesMapValues($property_val, $reference);
+ $this->setShadowPropertiesMapValues($property_val, $reference);
} else {
if ($base_reference === null) {
$this->shadowProperties[$property_key] = $property_val;
@@ -350,11 +350,11 @@ class GridLines extends Properties
*
* @param string $color
* @param int $alpha
- * @param string $type
+ * @param string $colorType
*
* @return $this
*/
- private function setShadowColor($color, $alpha, $type)
+ private function setShadowColor($color, $alpha, $colorType)
{
if ($color !== null) {
$this->shadowProperties['color']['value'] = (string) $color;
@@ -362,8 +362,8 @@ class GridLines extends Properties
if ($alpha !== null) {
$this->shadowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha);
}
- if ($type !== null) {
- $this->shadowProperties['color']['type'] = (string) $type;
+ if ($colorType !== null) {
+ $this->shadowProperties['color']['type'] = (string) $colorType;
}
return $this;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Layout.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Layout.php
index 51c8995b064..cea96557d8f 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Layout.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Layout.php
@@ -149,13 +149,13 @@ class Layout
/**
* Set Layout Target.
*
- * @param string $value
+ * @param string $target
*
* @return $this
*/
- public function setLayoutTarget($value)
+ public function setLayoutTarget($target)
{
- $this->layoutTarget = $value;
+ $this->layoutTarget = $target;
return $this;
}
@@ -173,13 +173,13 @@ class Layout
/**
* Set X-Mode.
*
- * @param string $value
+ * @param string $mode
*
* @return $this
*/
- public function setXMode($value)
+ public function setXMode($mode)
{
- $this->xMode = (string) $value;
+ $this->xMode = (string) $mode;
return $this;
}
@@ -197,13 +197,13 @@ class Layout
/**
* Set Y-Mode.
*
- * @param string $value
+ * @param string $mode
*
* @return $this
*/
- public function setYMode($value)
+ public function setYMode($mode)
{
- $this->yMode = (string) $value;
+ $this->yMode = (string) $mode;
return $this;
}
@@ -221,13 +221,13 @@ class Layout
/**
* Set X-Position.
*
- * @param float $value
+ * @param float $position
*
* @return $this
*/
- public function setXPosition($value)
+ public function setXPosition($position)
{
- $this->xPos = (float) $value;
+ $this->xPos = (float) $position;
return $this;
}
@@ -245,13 +245,13 @@ class Layout
/**
* Set Y-Position.
*
- * @param float $value
+ * @param float $position
*
* @return $this
*/
- public function setYPosition($value)
+ public function setYPosition($position)
{
- $this->yPos = (float) $value;
+ $this->yPos = (float) $position;
return $this;
}
@@ -269,13 +269,13 @@ class Layout
/**
* Set Width.
*
- * @param float $value
+ * @param float $width
*
* @return $this
*/
- public function setWidth($value)
+ public function setWidth($width)
{
- $this->width = $value;
+ $this->width = $width;
return $this;
}
@@ -293,13 +293,13 @@ class Layout
/**
* Set Height.
*
- * @param float $value
+ * @param float $height
*
* @return $this
*/
- public function setHeight($value)
+ public function setHeight($height)
{
- $this->height = $value;
+ $this->height = $height;
return $this;
}
@@ -318,13 +318,13 @@ class Layout
* Set show legend key
* Specifies that legend keys should be shown in data labels.
*
- * @param bool $value Show legend key
+ * @param bool $showLegendKey Show legend key
*
* @return $this
*/
- public function setShowLegendKey($value)
+ public function setShowLegendKey($showLegendKey)
{
- $this->showLegendKey = $value;
+ $this->showLegendKey = $showLegendKey;
return $this;
}
@@ -343,13 +343,13 @@ class Layout
* Set show val
* Specifies that the value should be shown in data labels.
*
- * @param bool $value Show val
+ * @param bool $showDataLabelValues Show val
*
* @return $this
*/
- public function setShowVal($value)
+ public function setShowVal($showDataLabelValues)
{
- $this->showVal = $value;
+ $this->showVal = $showDataLabelValues;
return $this;
}
@@ -368,13 +368,13 @@ class Layout
* Set show cat name
* Specifies that the category name should be shown in data labels.
*
- * @param bool $value Show cat name
+ * @param bool $showCategoryName Show cat name
*
* @return $this
*/
- public function setShowCatName($value)
+ public function setShowCatName($showCategoryName)
{
- $this->showCatName = $value;
+ $this->showCatName = $showCategoryName;
return $this;
}
@@ -393,13 +393,13 @@ class Layout
* Set show ser name
* Specifies that the series name should be shown in data labels.
*
- * @param bool $value Show series name
+ * @param bool $showSeriesName Show series name
*
* @return $this
*/
- public function setShowSerName($value)
+ public function setShowSerName($showSeriesName)
{
- $this->showSerName = $value;
+ $this->showSerName = $showSeriesName;
return $this;
}
@@ -418,13 +418,13 @@ class Layout
* Set show percentage
* Specifies that the percentage should be shown in data labels.
*
- * @param bool $value Show percentage
+ * @param bool $showPercentage Show percentage
*
* @return $this
*/
- public function setShowPercent($value)
+ public function setShowPercent($showPercentage)
{
- $this->showPercent = $value;
+ $this->showPercent = $showPercentage;
return $this;
}
@@ -443,13 +443,13 @@ class Layout
* Set show bubble size
* Specifies that the bubble size should be shown in data labels.
*
- * @param bool $value Show bubble size
+ * @param bool $showBubbleSize Show bubble size
*
* @return $this
*/
- public function setShowBubbleSize($value)
+ public function setShowBubbleSize($showBubbleSize)
{
- $this->showBubbleSize = $value;
+ $this->showBubbleSize = $showBubbleSize;
return $this;
}
@@ -468,13 +468,13 @@ class Layout
* Set show leader lines
* Specifies that leader lines should be shown in data labels.
*
- * @param bool $value Show leader lines
+ * @param bool $showLeaderLines Show leader lines
*
* @return $this
*/
- public function setShowLeaderLines($value)
+ public function setShowLeaderLines($showLeaderLines)
{
- $this->showLeaderLines = $value;
+ $this->showLeaderLines = $showLeaderLines;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Legend.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Legend.php
index fc0ed1407c0..2f003cd87b8 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Legend.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Legend.php
@@ -131,18 +131,10 @@ class Legend
* Set allow overlay of other elements?
*
* @param bool $overlay
- *
- * @return bool
*/
- public function setOverlay($overlay)
+ public function setOverlay($overlay): void
{
- if (!is_bool($overlay)) {
- return false;
- }
-
$this->overlay = $overlay;
-
- return true;
}
/**
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/PlotArea.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/PlotArea.php
index 954777cf2f5..ecb7b6c91e1 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/PlotArea.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/PlotArea.php
@@ -43,10 +43,8 @@ class PlotArea
/**
* Get Number of Plot Groups.
- *
- * @return array of DataSeries
*/
- public function getPlotGroupCount()
+ public function getPlotGroupCount(): int
{
return count($this->plotSeries);
}
@@ -69,7 +67,7 @@ class PlotArea
/**
* Get Plot Series.
*
- * @return array of DataSeries
+ * @return DataSeries[]
*/
public function getPlotGroup()
{
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Properties.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Properties.php
index 98095f0d13a..ef22fb5290d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Properties.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Properties.php
@@ -135,16 +135,16 @@ abstract class Properties
return (string) 100 - $alpha . '000';
}
- protected function setColorProperties($color, $alpha, $type)
+ protected function setColorProperties($color, $alpha, $colorType)
{
return [
- 'type' => (string) $type,
+ 'type' => (string) $colorType,
'value' => (string) $color,
'alpha' => (string) $this->getTrueAlpha($alpha),
];
}
- protected function getLineStyleArrowSize($array_selector, $array_kay_selector)
+ protected function getLineStyleArrowSize($arraySelector, $arrayKaySelector)
{
$sizes = [
1 => ['w' => 'sm', 'len' => 'sm'],
@@ -158,10 +158,10 @@ abstract class Properties
9 => ['w' => 'lg', 'len' => 'lg'],
];
- return $sizes[$array_selector][$array_kay_selector];
+ return $sizes[$arraySelector][$arrayKaySelector];
}
- protected function getShadowPresetsMap($shadow_presets_option)
+ protected function getShadowPresetsMap($presetsOption)
{
$presets_options = [
//OUTER
@@ -350,7 +350,7 @@ abstract class Properties
],
];
- return $presets_options[$shadow_presets_option];
+ return $presets_options[$presetsOption];
}
protected function getArrayElementsValue($properties, $elements)
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php
index 02fbfed7ea3..0ab70870a73 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php
@@ -301,6 +301,8 @@ class JpGraph implements IRenderer
$seriesPlots = [];
if ($grouping == 'percentStacked') {
$sumValues = $this->percentageSumCalculation($groupID, $seriesCount);
+ } else {
+ $sumValues = [];
}
// Loop through each data series in turn
@@ -376,6 +378,8 @@ class JpGraph implements IRenderer
$seriesPlots = [];
if ($grouping == 'percentStacked') {
$sumValues = $this->percentageSumCalculation($groupID, $seriesCount);
+ } else {
+ $sumValues = [];
}
// Loop through each data series in turn
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Title.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Title.php
index af9fa088bc3..090c4f3f7f8 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Title.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Title.php
@@ -2,14 +2,16 @@
namespace PhpOffice\PhpSpreadsheet\Chart;
+use PhpOffice\PhpSpreadsheet\RichText\RichText;
+
class Title
{
/**
* Title Caption.
*
- * @var string
+ * @var array|RichText|string
*/
- private $caption;
+ private $caption = '';
/**
* Title Layout.
@@ -21,9 +23,9 @@ class Title
/**
* Create a new Title.
*
- * @param null|mixed $caption
+ * @param array|RichText|string $caption
*/
- public function __construct($caption = null, ?Layout $layout = null)
+ public function __construct($caption = '', ?Layout $layout = null)
{
$this->caption = $caption;
$this->layout = $layout;
@@ -32,17 +34,40 @@ class Title
/**
* Get caption.
*
- * @return string
+ * @return array|RichText|string
*/
public function getCaption()
{
return $this->caption;
}
+ public function getCaptionText(): string
+ {
+ $caption = $this->caption;
+ if (is_string($caption)) {
+ return $caption;
+ }
+ if ($caption instanceof RichText) {
+ return $caption->getPlainText();
+ }
+ $retVal = '';
+ foreach ($caption as $textx) {
+ /** @var RichText|string */
+ $text = $textx;
+ if ($text instanceof RichText) {
+ $retVal .= $text->getPlainText();
+ } else {
+ $retVal .= $text;
+ }
+ }
+
+ return $retVal;
+ }
+
/**
* Set caption.
*
- * @param string $caption
+ * @param array|RichText|string $caption
*
* @return $this
*/
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php
index 48f34f41d24..e3d81cb44d1 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php
@@ -12,28 +12,28 @@ use Psr\SimpleCache\CacheInterface;
class Cells
{
/**
- * @var \Psr\SimpleCache\CacheInterface
+ * @var CacheInterface
*/
private $cache;
/**
* Parent worksheet.
*
- * @var Worksheet
+ * @var null|Worksheet
*/
private $parent;
/**
* The currently active Cell.
*
- * @var Cell
+ * @var null|Cell
*/
private $currentCell;
/**
* Coordinate of the currently active Cell.
*
- * @var string
+ * @var null|string
*/
private $currentCoordinate;
@@ -76,7 +76,7 @@ class Cells
/**
* Return the parent worksheet for this cell collection.
*
- * @return Worksheet
+ * @return null|Worksheet
*/
public function getParent()
{
@@ -86,18 +86,18 @@ class Cells
/**
* Whether the collection holds a cell for the given coordinate.
*
- * @param string $pCoord Coordinate of the cell to check
+ * @param string $cellCoordinate Coordinate of the cell to check
*
* @return bool
*/
- public function has($pCoord)
+ public function has($cellCoordinate)
{
- if ($pCoord === $this->currentCoordinate) {
+ if ($cellCoordinate === $this->currentCoordinate) {
return true;
}
// Check if the requested entry exists in the index
- return isset($this->index[$pCoord]);
+ return isset($this->index[$cellCoordinate]);
}
/**
@@ -115,21 +115,21 @@ class Cells
/**
* Delete a cell in cache identified by coordinate.
*
- * @param string $pCoord Coordinate of the cell to delete
+ * @param string $cellCoordinate Coordinate of the cell to delete
*/
- public function delete($pCoord): void
+ public function delete($cellCoordinate): void
{
- if ($pCoord === $this->currentCoordinate && $this->currentCell !== null) {
+ if ($cellCoordinate === $this->currentCoordinate && $this->currentCell !== null) {
$this->currentCell->detach();
$this->currentCoordinate = null;
$this->currentCell = null;
$this->currentCellIsDirty = false;
}
- unset($this->index[$pCoord]);
+ unset($this->index[$cellCoordinate]);
// Delete the entry from cache
- $this->cache->delete($this->cachePrefix . $pCoord);
+ $this->cache->delete($this->cachePrefix . $cellCoordinate);
}
/**
@@ -181,7 +181,7 @@ class Cells
// Determine highest column and row
$highestRow = max($row);
- $highestColumn = substr(max($col), 1);
+ $highestColumn = substr((string) @max($col), 1);
return [
'row' => $highestRow,
@@ -192,7 +192,7 @@ class Cells
/**
* Return the cell coordinate of the currently active cell object.
*
- * @return string
+ * @return null|string
*/
public function getCurrentCoordinate()
{
@@ -209,7 +209,7 @@ class Cells
$column = '';
$row = 0;
- sscanf($this->currentCoordinate, '%[A-Z]%d', $column, $row);
+ sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row);
return $column;
}
@@ -224,7 +224,7 @@ class Cells
$column = '';
$row = 0;
- sscanf($this->currentCoordinate, '%[A-Z]%d', $column, $row);
+ sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row);
return (int) $row;
}
@@ -232,7 +232,7 @@ class Cells
/**
* Get highest worksheet column.
*
- * @param string $row Return the highest column for the specified row,
+ * @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
@@ -257,13 +257,13 @@ class Cells
$columnList[] = Coordinate::columnIndexFromString($c);
}
- return Coordinate::stringFromColumnIndex(max($columnList));
+ return Coordinate::stringFromColumnIndex((int) @max($columnList));
}
/**
* Get highest worksheet row.
*
- * @param string $column Return the highest row for the specified column,
+ * @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
@@ -304,17 +304,15 @@ class Cells
/**
* Clone the cell collection.
*
- * @param Worksheet $parent The new worksheet that we're copying to
- *
* @return self
*/
- public function cloneCellCollection(Worksheet $parent)
+ public function cloneCellCollection(Worksheet $worksheet)
{
$this->storeCurrentCell();
$newCollection = clone $this;
- $newCollection->parent = $parent;
- if (($newCollection->currentCell !== null) && (is_object($newCollection->currentCell))) {
+ $newCollection->parent = $worksheet;
+ if (is_object($newCollection->currentCell)) {
$newCollection->currentCell->attach($this);
}
@@ -327,16 +325,14 @@ class Cells
// Change prefix
$newCollection->cachePrefix = $newCollection->getUniqueID();
foreach ($oldValues as $oldKey => $value) {
- $newValues[str_replace($oldCachePrefix, $newCollection->cachePrefix, $oldKey)] = clone $value;
+ /** @var string $newKey */
+ $newKey = str_replace($oldCachePrefix, $newCollection->cachePrefix, $oldKey);
+ $newValues[$newKey] = clone $value;
}
// Store new values
$stored = $newCollection->cache->setMultiple($newValues);
- if (!$stored) {
- $newCollection->__destruct();
-
- throw new PhpSpreadsheetException('Failed to copy cells in cache');
- }
+ $this->destructIfNeeded($stored, $newCollection, 'Failed to copy cells in cache');
return $newCollection;
}
@@ -383,15 +379,11 @@ class Cells
*/
private function storeCurrentCell(): void
{
- if ($this->currentCellIsDirty && !empty($this->currentCoordinate)) {
+ if ($this->currentCellIsDirty && isset($this->currentCoordinate, $this->currentCell)) {
$this->currentCell->detach();
$stored = $this->cache->set($this->cachePrefix . $this->currentCoordinate, $this->currentCell);
- if (!$stored) {
- $this->__destruct();
-
- throw new PhpSpreadsheetException("Failed to store cell {$this->currentCoordinate} in cache");
- }
+ $this->destructIfNeeded($stored, $this, "Failed to store cell {$this->currentCoordinate} in cache");
$this->currentCellIsDirty = false;
}
@@ -399,22 +391,31 @@ class Cells
$this->currentCell = null;
}
+ private function destructIfNeeded(bool $stored, self $cells, string $message): void
+ {
+ if (!$stored) {
+ $cells->__destruct();
+
+ throw new PhpSpreadsheetException($message);
+ }
+ }
+
/**
* Add or update a cell identified by its coordinate into the collection.
*
- * @param string $pCoord Coordinate of the cell to update
+ * @param string $cellCoordinate Coordinate of the cell to update
* @param Cell $cell Cell to update
*
- * @return \PhpOffice\PhpSpreadsheet\Cell\Cell
+ * @return Cell
*/
- public function add($pCoord, Cell $cell)
+ public function add($cellCoordinate, Cell $cell)
{
- if ($pCoord !== $this->currentCoordinate) {
+ if ($cellCoordinate !== $this->currentCoordinate) {
$this->storeCurrentCell();
}
- $this->index[$pCoord] = true;
+ $this->index[$cellCoordinate] = true;
- $this->currentCoordinate = $pCoord;
+ $this->currentCoordinate = $cellCoordinate;
$this->currentCell = $cell;
$this->currentCellIsDirty = true;
@@ -424,30 +425,30 @@ class Cells
/**
* Get cell at a specific coordinate.
*
- * @param string $pCoord Coordinate of the cell
+ * @param string $cellCoordinate Coordinate of the cell
*
- * @return null|\PhpOffice\PhpSpreadsheet\Cell\Cell Cell that was found, or null if not found
+ * @return null|Cell Cell that was found, or null if not found
*/
- public function get($pCoord)
+ public function get($cellCoordinate)
{
- if ($pCoord === $this->currentCoordinate) {
+ if ($cellCoordinate === $this->currentCoordinate) {
return $this->currentCell;
}
$this->storeCurrentCell();
// Return null if requested entry doesn't exist in collection
- if (!$this->has($pCoord)) {
+ if (!$this->has($cellCoordinate)) {
return null;
}
// Check if the entry that has been requested actually exists
- $cell = $this->cache->get($this->cachePrefix . $pCoord);
+ $cell = $this->cache->get($this->cachePrefix . $cellCoordinate);
if ($cell === null) {
- throw new PhpSpreadsheetException("Cell entry {$pCoord} no longer exists in cache. This probably means that the cache was cleared by someone else.");
+ 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 = $pCoord;
+ $this->currentCoordinate = $cellCoordinate;
$this->currentCell = $cell;
// Re-attach this as the cell's parent
$this->currentCell->attach($this);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php
index 7f34c2315c5..26f18dfc52c 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php
@@ -10,12 +10,12 @@ abstract class CellsFactory
/**
* Initialise the cache storage.
*
- * @param Worksheet $parent Enable cell caching for this worksheet
+ * @param Worksheet $worksheet Enable cell caching for this worksheet
*
* @return Cells
* */
- public static function getInstance(Worksheet $parent)
+ public static function getInstance(Worksheet $worksheet)
{
- return new Cells($parent, Settings::getCache());
+ return new Cells($worksheet, Settings::getCache());
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php
index a32551b0e5d..2690ab7d025 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php
@@ -2,6 +2,7 @@
namespace PhpOffice\PhpSpreadsheet\Collection;
+use DateInterval;
use Psr\SimpleCache\CacheInterface;
/**
@@ -14,6 +15,9 @@ class Memory implements CacheInterface
{
private $cache = [];
+ /**
+ * @return bool
+ */
public function clear()
{
$this->cache = [];
@@ -21,6 +25,11 @@ class Memory implements CacheInterface
return true;
}
+ /**
+ * @param string $key
+ *
+ * @return bool
+ */
public function delete($key)
{
unset($this->cache[$key]);
@@ -28,6 +37,11 @@ class Memory implements CacheInterface
return true;
}
+ /**
+ * @param iterable $keys
+ *
+ * @return bool
+ */
public function deleteMultiple($keys)
{
foreach ($keys as $key) {
@@ -37,6 +51,12 @@ class Memory implements CacheInterface
return true;
}
+ /**
+ * @param string $key
+ * @param mixed $default
+ *
+ * @return mixed
+ */
public function get($key, $default = null)
{
if ($this->has($key)) {
@@ -46,6 +66,12 @@ class Memory implements CacheInterface
return $default;
}
+ /**
+ * @param iterable $keys
+ * @param mixed $default
+ *
+ * @return iterable
+ */
public function getMultiple($keys, $default = null)
{
$results = [];
@@ -56,11 +82,23 @@ class Memory implements CacheInterface
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;
@@ -68,6 +106,12 @@ class Memory implements CacheInterface
return true;
}
+ /**
+ * @param iterable $values
+ * @param null|DateInterval|int $ttl
+ *
+ * @return bool
+ */
public function setMultiple($values, $ttl = null)
{
foreach ($values as $key => $value) {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php
index 31f7664053f..abadc7dfb88 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php
@@ -2,7 +2,13 @@
namespace PhpOffice\PhpSpreadsheet;
+use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
+use PhpOffice\PhpSpreadsheet\Helper\Size;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
+use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing;
+use PhpOffice\PhpSpreadsheet\Style\Alignment;
+use PhpOffice\PhpSpreadsheet\Style\Color;
+use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
class Comment implements IComparable
{
@@ -58,7 +64,7 @@ class Comment implements IComparable
/**
* Comment fill color.
*
- * @var Style\Color
+ * @var Color
*/
private $fillColor;
@@ -69,6 +75,13 @@ class Comment implements IComparable
*/
private $alignment;
+ /**
+ * Background image in comment.
+ *
+ * @var Drawing
+ */
+ private $backgroundImage;
+
/**
* Create a new Comment.
*/
@@ -77,28 +90,23 @@ class Comment implements IComparable
// Initialise variables
$this->author = 'Author';
$this->text = new RichText();
- $this->fillColor = new Style\Color('FFFFFFE1');
- $this->alignment = Style\Alignment::HORIZONTAL_GENERAL;
+ $this->fillColor = new Color('FFFFFFE1');
+ $this->alignment = Alignment::HORIZONTAL_GENERAL;
+ $this->backgroundImage = new Drawing();
}
/**
* Get Author.
- *
- * @return string
*/
- public function getAuthor()
+ public function getAuthor(): string
{
return $this->author;
}
/**
* Set Author.
- *
- * @param string $author
- *
- * @return $this
*/
- public function setAuthor($author)
+ public function setAuthor(string $author): self
{
$this->author = $author;
@@ -107,164 +115,146 @@ class Comment implements IComparable
/**
* Get Rich text comment.
- *
- * @return RichText
*/
- public function getText()
+ public function getText(): RichText
{
return $this->text;
}
/**
* Set Rich text comment.
- *
- * @return $this
*/
- public function setText(RichText $pValue)
+ public function setText(RichText $text): self
{
- $this->text = $pValue;
+ $this->text = $text;
return $this;
}
/**
* Get comment width (CSS style, i.e. XXpx or YYpt).
- *
- * @return string
*/
- public function getWidth()
+ public function getWidth(): string
{
return $this->width;
}
/**
- * Set comment width (CSS style, i.e. XXpx or YYpt).
- *
- * @param string $width
- *
- * @return $this
+ * Set comment width (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*/
- public function setWidth($width)
+ public function setWidth(string $width): self
{
- $this->width = $width;
+ $width = new Size($width);
+ if ($width->valid()) {
+ $this->width = (string) $width;
+ }
return $this;
}
/**
* Get comment height (CSS style, i.e. XXpx or YYpt).
- *
- * @return string
*/
- public function getHeight()
+ public function getHeight(): string
{
return $this->height;
}
/**
- * Set comment height (CSS style, i.e. XXpx or YYpt).
- *
- * @param string $value
- *
- * @return $this
+ * Set comment height (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*/
- public function setHeight($value)
+ public function setHeight(string $height): self
{
- $this->height = $value;
+ $height = new Size($height);
+ if ($height->valid()) {
+ $this->height = (string) $height;
+ }
return $this;
}
/**
* Get left margin (CSS style, i.e. XXpx or YYpt).
- *
- * @return string
*/
- public function getMarginLeft()
+ public function getMarginLeft(): string
{
return $this->marginLeft;
}
/**
- * Set left margin (CSS style, i.e. XXpx or YYpt).
- *
- * @param string $value
- *
- * @return $this
+ * Set left margin (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*/
- public function setMarginLeft($value)
+ public function setMarginLeft(string $margin): self
{
- $this->marginLeft = $value;
+ $margin = new Size($margin);
+ if ($margin->valid()) {
+ $this->marginLeft = (string) $margin;
+ }
return $this;
}
/**
* Get top margin (CSS style, i.e. XXpx or YYpt).
- *
- * @return string
*/
- public function getMarginTop()
+ public function getMarginTop(): string
{
return $this->marginTop;
}
/**
- * Set top margin (CSS style, i.e. XXpx or YYpt).
- *
- * @param string $value
- *
- * @return $this
+ * Set top margin (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*/
- public function setMarginTop($value)
+ public function setMarginTop(string $margin): self
{
- $this->marginTop = $value;
+ $margin = new Size($margin);
+ if ($margin->valid()) {
+ $this->marginTop = (string) $margin;
+ }
return $this;
}
/**
* Is the comment visible by default?
- *
- * @return bool
*/
- public function getVisible()
+ public function getVisible(): bool
{
return $this->visible;
}
/**
* Set comment default visibility.
- *
- * @param bool $value
- *
- * @return $this
*/
- public function setVisible($value)
+ public function setVisible(bool $visibility): self
{
- $this->visible = $value;
+ $this->visible = $visibility;
+
+ return $this;
+ }
+
+ /**
+ * Set fill color.
+ */
+ public function setFillColor(Color $color): self
+ {
+ $this->fillColor = $color;
return $this;
}
/**
* Get fill color.
- *
- * @return Style\Color
*/
- public function getFillColor()
+ public function getFillColor(): Color
{
return $this->fillColor;
}
/**
* Set Alignment.
- *
- * @param string $alignment see Style\Alignment::HORIZONTAL_*
- *
- * @return $this
*/
- public function setAlignment($alignment)
+ public function setAlignment(string $alignment): self
{
$this->alignment = $alignment;
@@ -273,20 +263,16 @@ class Comment implements IComparable
/**
* Get Alignment.
- *
- * @return string
*/
- public function getAlignment()
+ public function getAlignment(): string
{
return $this->alignment;
}
/**
* Get hash code.
- *
- * @return string Hash code
*/
- public function getHashCode()
+ public function getHashCode(): string
{
return md5(
$this->author .
@@ -298,6 +284,7 @@ class Comment implements IComparable
($this->visible ? 1 : 0) .
$this->fillColor->getHashCode() .
$this->alignment .
+ ($this->hasBackgroundImage() ? $this->backgroundImage->getHashCode() : '') .
__CLASS__
);
}
@@ -319,11 +306,57 @@ class Comment implements IComparable
/**
* Convert to string.
- *
- * @return string
*/
- public function __toString()
+ public function __toString(): string
{
return $this->text->getPlainText();
}
+
+ /**
+ * Check is background image exists.
+ */
+ public function hasBackgroundImage(): bool
+ {
+ $path = $this->backgroundImage->getPath();
+
+ if (empty($path)) {
+ return false;
+ }
+
+ return getimagesize($path) !== false;
+ }
+
+ /**
+ * Returns background image.
+ */
+ public function getBackgroundImage(): Drawing
+ {
+ return $this->backgroundImage;
+ }
+
+ /**
+ * Sets background image.
+ */
+ public function setBackgroundImage(Drawing $objDrawing): self
+ {
+ if (!array_key_exists($objDrawing->getType(), Drawing::IMAGE_TYPES_CONVERTION_MAP)) {
+ throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
+ }
+ $this->backgroundImage = $objDrawing;
+
+ return $this;
+ }
+
+ /**
+ * Sets size of comment as size of background image.
+ */
+ public function setSizeAsBackgroundImage(): self
+ {
+ if ($this->hasBackgroundImage()) {
+ $this->setWidth(SharedDrawing::pixelsToPoints($this->backgroundImage->getWidth()) . 'pt');
+ $this->setHeight(SharedDrawing::pixelsToPoints($this->backgroundImage->getHeight()) . 'pt');
+ }
+
+ return $this;
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DefinedName.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DefinedName.php
index dbadd4ced57..3b874b435b7 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DefinedName.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DefinedName.php
@@ -167,9 +167,9 @@ abstract class DefinedName
/**
* Set worksheet.
*/
- public function setWorksheet(?Worksheet $value): self
+ public function setWorksheet(?Worksheet $worksheet): self
{
- $this->worksheet = $value;
+ $this->worksheet = $worksheet;
return $this;
}
@@ -203,10 +203,10 @@ abstract class DefinedName
/**
* Set localOnly.
*/
- public function setLocalOnly(bool $value): self
+ public function setLocalOnly(bool $localScope): self
{
- $this->localOnly = $value;
- $this->scope = $value ? $this->worksheet : null;
+ $this->localOnly = $localScope;
+ $this->scope = $localScope ? $this->worksheet : null;
return $this;
}
@@ -222,10 +222,10 @@ abstract class DefinedName
/**
* Set scope.
*/
- public function setScope(?Worksheet $value): self
+ public function setScope(?Worksheet $worksheet): self
{
- $this->scope = $value;
- $this->localOnly = $value !== null;
+ $this->scope = $worksheet;
+ $this->localOnly = $worksheet !== null;
return $this;
}
@@ -241,9 +241,18 @@ abstract class DefinedName
/**
* Resolve a named range to a regular cell range or formula.
*/
- public static function resolveName(string $pDefinedName, Worksheet $pSheet): ?self
+ public static function resolveName(string $definedName, Worksheet $worksheet, string $sheetName = ''): ?self
{
- return $pSheet->getParent()->getDefinedName($pDefinedName, $pSheet);
+ if ($sheetName === '') {
+ $worksheet2 = $worksheet;
+ } else {
+ $worksheet2 = $worksheet->getParent()->getSheetByName($sheetName);
+ if ($worksheet2 === null) {
+ return null;
+ }
+ }
+
+ return $worksheet->getParent()->getDefinedName($definedName, $worksheet2);
}
/**
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php
index 0876a9ed486..3be5a67a855 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php
@@ -2,15 +2,26 @@
namespace PhpOffice\PhpSpreadsheet\Document;
+use DateTime;
+use PhpOffice\PhpSpreadsheet\Shared\IntOrFloat;
+
class Properties
{
/** constants */
- const PROPERTY_TYPE_BOOLEAN = 'b';
- const PROPERTY_TYPE_INTEGER = 'i';
- const PROPERTY_TYPE_FLOAT = 'f';
- const PROPERTY_TYPE_DATE = 'd';
- const PROPERTY_TYPE_STRING = 's';
- const PROPERTY_TYPE_UNKNOWN = 'u';
+ public const PROPERTY_TYPE_BOOLEAN = 'b';
+ public const PROPERTY_TYPE_INTEGER = 'i';
+ public const PROPERTY_TYPE_FLOAT = 'f';
+ public const PROPERTY_TYPE_DATE = 'd';
+ public const PROPERTY_TYPE_STRING = 's';
+ public const PROPERTY_TYPE_UNKNOWN = 'u';
+
+ private const VALID_PROPERTY_TYPE_LIST = [
+ self::PROPERTY_TYPE_BOOLEAN,
+ self::PROPERTY_TYPE_INTEGER,
+ self::PROPERTY_TYPE_FLOAT,
+ self::PROPERTY_TYPE_DATE,
+ self::PROPERTY_TYPE_STRING,
+ ];
/**
* Creator.
@@ -29,14 +40,14 @@ class Properties
/**
* Created.
*
- * @var int
+ * @var float|int
*/
private $created;
/**
* Modified.
*
- * @var int
+ * @var float|int
*/
private $modified;
@@ -87,12 +98,12 @@ class Properties
*
* @var string
*/
- private $company = 'Microsoft Corporation';
+ private $company = '';
/**
* Custom Properties.
*
- * @var string
+ * @var array{value: mixed, type: string}[]
*/
private $customProperties = [];
@@ -103,16 +114,14 @@ class Properties
{
// Initialise values
$this->lastModifiedBy = $this->creator;
- $this->created = time();
- $this->modified = time();
+ $this->created = self::intOrFloatTimestamp(null);
+ $this->modified = self::intOrFloatTimestamp(null);
}
/**
* Get Creator.
- *
- * @return string
*/
- public function getCreator()
+ public function getCreator(): string
{
return $this->creator;
}
@@ -120,11 +129,9 @@ class Properties
/**
* Set Creator.
*
- * @param string $creator
- *
* @return $this
*/
- public function setCreator($creator)
+ public function setCreator(string $creator): self
{
$this->creator = $creator;
@@ -133,10 +140,8 @@ class Properties
/**
* Get Last Modified By.
- *
- * @return string
*/
- public function getLastModifiedBy()
+ public function getLastModifiedBy(): string
{
return $this->lastModifiedBy;
}
@@ -144,21 +149,42 @@ class Properties
/**
* Set Last Modified By.
*
- * @param string $pValue
- *
* @return $this
*/
- public function setLastModifiedBy($pValue)
+ public function setLastModifiedBy(string $modifiedBy): self
{
- $this->lastModifiedBy = $pValue;
+ $this->lastModifiedBy = $modifiedBy;
return $this;
}
+ /**
+ * @param null|float|int|string $timestamp
+ *
+ * @return float|int
+ */
+ private static function intOrFloatTimestamp($timestamp)
+ {
+ if ($timestamp === null) {
+ $timestamp = (float) (new DateTime())->format('U');
+ } elseif (is_string($timestamp)) {
+ if (is_numeric($timestamp)) {
+ $timestamp = (float) $timestamp;
+ } else {
+ $timestamp = preg_replace('/[.][0-9]*$/', '', $timestamp) ?? '';
+ $timestamp = preg_replace('/^(\\d{4})- (\\d)/', '$1-0$2', $timestamp) ?? '';
+ $timestamp = preg_replace('/^(\\d{4}-\\d{2})- (\\d)/', '$1-0$2', $timestamp) ?? '';
+ $timestamp = (float) (new DateTime($timestamp))->format('U');
+ }
+ }
+
+ return IntOrFloat::evaluate($timestamp);
+ }
+
/**
* Get Created.
*
- * @return int
+ * @return float|int
*/
public function getCreated()
{
@@ -168,23 +194,13 @@ class Properties
/**
* Set Created.
*
- * @param int|string $time
+ * @param null|float|int|string $timestamp
*
* @return $this
*/
- public function setCreated($time)
+ public function setCreated($timestamp): self
{
- if ($time === null) {
- $time = time();
- } elseif (is_string($time)) {
- if (is_numeric($time)) {
- $time = (int) $time;
- } else {
- $time = strtotime($time);
- }
- }
-
- $this->created = $time;
+ $this->created = self::intOrFloatTimestamp($timestamp);
return $this;
}
@@ -192,7 +208,7 @@ class Properties
/**
* Get Modified.
*
- * @return int
+ * @return float|int
*/
public function getModified()
{
@@ -202,33 +218,21 @@ class Properties
/**
* Set Modified.
*
- * @param int|string $time
+ * @param null|float|int|string $timestamp
*
* @return $this
*/
- public function setModified($time)
+ public function setModified($timestamp): self
{
- if ($time === null) {
- $time = time();
- } elseif (is_string($time)) {
- if (is_numeric($time)) {
- $time = (int) $time;
- } else {
- $time = strtotime($time);
- }
- }
-
- $this->modified = $time;
+ $this->modified = self::intOrFloatTimestamp($timestamp);
return $this;
}
/**
* Get Title.
- *
- * @return string
*/
- public function getTitle()
+ public function getTitle(): string
{
return $this->title;
}
@@ -236,11 +240,9 @@ class Properties
/**
* Set Title.
*
- * @param string $title
- *
* @return $this
*/
- public function setTitle($title)
+ public function setTitle(string $title): self
{
$this->title = $title;
@@ -249,10 +251,8 @@ class Properties
/**
* Get Description.
- *
- * @return string
*/
- public function getDescription()
+ public function getDescription(): string
{
return $this->description;
}
@@ -260,11 +260,9 @@ class Properties
/**
* Set Description.
*
- * @param string $description
- *
* @return $this
*/
- public function setDescription($description)
+ public function setDescription(string $description): self
{
$this->description = $description;
@@ -273,10 +271,8 @@ class Properties
/**
* Get Subject.
- *
- * @return string
*/
- public function getSubject()
+ public function getSubject(): string
{
return $this->subject;
}
@@ -284,11 +280,9 @@ class Properties
/**
* Set Subject.
*
- * @param string $subject
- *
* @return $this
*/
- public function setSubject($subject)
+ public function setSubject(string $subject): self
{
$this->subject = $subject;
@@ -297,10 +291,8 @@ class Properties
/**
* Get Keywords.
- *
- * @return string
*/
- public function getKeywords()
+ public function getKeywords(): string
{
return $this->keywords;
}
@@ -308,11 +300,9 @@ class Properties
/**
* Set Keywords.
*
- * @param string $keywords
- *
* @return $this
*/
- public function setKeywords($keywords)
+ public function setKeywords(string $keywords): self
{
$this->keywords = $keywords;
@@ -321,10 +311,8 @@ class Properties
/**
* Get Category.
- *
- * @return string
*/
- public function getCategory()
+ public function getCategory(): string
{
return $this->category;
}
@@ -332,11 +320,9 @@ class Properties
/**
* Set Category.
*
- * @param string $category
- *
* @return $this
*/
- public function setCategory($category)
+ public function setCategory(string $category): self
{
$this->category = $category;
@@ -345,10 +331,8 @@ class Properties
/**
* Get Company.
- *
- * @return string
*/
- public function getCompany()
+ public function getCompany(): string
{
return $this->company;
}
@@ -356,11 +340,9 @@ class Properties
/**
* Set Company.
*
- * @param string $company
- *
* @return $this
*/
- public function setCompany($company)
+ public function setCompany(string $company): self
{
$this->company = $company;
@@ -369,10 +351,8 @@ class Properties
/**
* Get Manager.
- *
- * @return string
*/
- public function getManager()
+ public function getManager(): string
{
return $this->manager;
}
@@ -380,11 +360,9 @@ class Properties
/**
* Set Manager.
*
- * @param string $manager
- *
* @return $this
*/
- public function setManager($manager)
+ public function setManager(string $manager): self
{
$this->manager = $manager;
@@ -394,57 +372,66 @@ class Properties
/**
* Get a List of Custom Property Names.
*
- * @return array of string
+ * @return string[]
*/
- public function getCustomProperties()
+ public function getCustomProperties(): array
{
return array_keys($this->customProperties);
}
/**
* Check if a Custom Property is defined.
- *
- * @param string $propertyName
- *
- * @return bool
*/
- public function isCustomPropertySet($propertyName)
+ public function isCustomPropertySet(string $propertyName): bool
{
- return isset($this->customProperties[$propertyName]);
+ return array_key_exists($propertyName, $this->customProperties);
}
/**
* Get a Custom Property Value.
*
- * @param string $propertyName
- *
* @return mixed
*/
- public function getCustomPropertyValue($propertyName)
+ public function getCustomPropertyValue(string $propertyName)
{
if (isset($this->customProperties[$propertyName])) {
return $this->customProperties[$propertyName]['value'];
}
+
+ return null;
}
/**
* Get a Custom Property Type.
*
- * @param string $propertyName
- *
- * @return string
+ * @return null|string
*/
- public function getCustomPropertyType($propertyName)
+ public function getCustomPropertyType(string $propertyName)
{
- if (isset($this->customProperties[$propertyName])) {
- return $this->customProperties[$propertyName]['type'];
+ return $this->customProperties[$propertyName]['type'] ?? null;
+ }
+
+ /**
+ * @param mixed $propertyValue
+ */
+ private function identifyPropertyType($propertyValue): string
+ {
+ if (is_float($propertyValue)) {
+ return self::PROPERTY_TYPE_FLOAT;
}
+ if (is_int($propertyValue)) {
+ return self::PROPERTY_TYPE_INTEGER;
+ }
+ if (is_bool($propertyValue)) {
+ return self::PROPERTY_TYPE_BOOLEAN;
+ }
+
+ return self::PROPERTY_TYPE_STRING;
}
/**
* Set a Custom Property.
*
- * @param string $propertyName
* @param mixed $propertyValue
* @param string $propertyType
* 'i' : Integer
@@ -455,178 +442,96 @@ class Properties
*
* @return $this
*/
- public function setCustomProperty($propertyName, $propertyValue = '', $propertyType = null)
+ public function setCustomProperty(string $propertyName, $propertyValue = '', $propertyType = null): self
{
- if (
- ($propertyType === null) || (!in_array($propertyType, [self::PROPERTY_TYPE_INTEGER,
- self::PROPERTY_TYPE_FLOAT,
- self::PROPERTY_TYPE_STRING,
- self::PROPERTY_TYPE_DATE,
- self::PROPERTY_TYPE_BOOLEAN,
- ]))
- ) {
- if ($propertyValue === null) {
- $propertyType = self::PROPERTY_TYPE_STRING;
- } elseif (is_float($propertyValue)) {
- $propertyType = self::PROPERTY_TYPE_FLOAT;
- } elseif (is_int($propertyValue)) {
- $propertyType = self::PROPERTY_TYPE_INTEGER;
- } elseif (is_bool($propertyValue)) {
- $propertyType = self::PROPERTY_TYPE_BOOLEAN;
- } else {
- $propertyType = self::PROPERTY_TYPE_STRING;
- }
+ if (($propertyType === null) || (!in_array($propertyType, self::VALID_PROPERTY_TYPE_LIST))) {
+ $propertyType = $this->identifyPropertyType($propertyValue);
}
- $this->customProperties[$propertyName] = [
- 'value' => $propertyValue,
- 'type' => $propertyType,
- ];
+ if (!is_object($propertyValue)) {
+ $this->customProperties[$propertyName] = [
+ 'value' => self::convertProperty($propertyValue, $propertyType),
+ 'type' => $propertyType,
+ ];
+ }
return $this;
}
+ private const PROPERTY_TYPE_ARRAY = [
+ 'i' => self::PROPERTY_TYPE_INTEGER, // Integer
+ 'i1' => self::PROPERTY_TYPE_INTEGER, // 1-Byte Signed Integer
+ 'i2' => self::PROPERTY_TYPE_INTEGER, // 2-Byte Signed Integer
+ 'i4' => self::PROPERTY_TYPE_INTEGER, // 4-Byte Signed Integer
+ 'i8' => self::PROPERTY_TYPE_INTEGER, // 8-Byte Signed Integer
+ 'int' => self::PROPERTY_TYPE_INTEGER, // Integer
+ 'ui1' => self::PROPERTY_TYPE_INTEGER, // 1-Byte Unsigned Integer
+ 'ui2' => self::PROPERTY_TYPE_INTEGER, // 2-Byte Unsigned Integer
+ 'ui4' => self::PROPERTY_TYPE_INTEGER, // 4-Byte Unsigned Integer
+ 'ui8' => self::PROPERTY_TYPE_INTEGER, // 8-Byte Unsigned Integer
+ 'uint' => self::PROPERTY_TYPE_INTEGER, // Unsigned Integer
+ 'f' => self::PROPERTY_TYPE_FLOAT, // Real Number
+ 'r4' => self::PROPERTY_TYPE_FLOAT, // 4-Byte Real Number
+ 'r8' => self::PROPERTY_TYPE_FLOAT, // 8-Byte Real Number
+ 'decimal' => self::PROPERTY_TYPE_FLOAT, // Decimal
+ 's' => self::PROPERTY_TYPE_STRING, // String
+ 'empty' => self::PROPERTY_TYPE_STRING, // Empty
+ 'null' => self::PROPERTY_TYPE_STRING, // Null
+ 'lpstr' => self::PROPERTY_TYPE_STRING, // LPSTR
+ 'lpwstr' => self::PROPERTY_TYPE_STRING, // LPWSTR
+ 'bstr' => self::PROPERTY_TYPE_STRING, // Basic String
+ 'd' => self::PROPERTY_TYPE_DATE, // Date and Time
+ 'date' => self::PROPERTY_TYPE_DATE, // Date and Time
+ 'filetime' => self::PROPERTY_TYPE_DATE, // File Time
+ 'b' => self::PROPERTY_TYPE_BOOLEAN, // Boolean
+ 'bool' => self::PROPERTY_TYPE_BOOLEAN, // Boolean
+ ];
+
+ private const SPECIAL_TYPES = [
+ 'empty' => '',
+ 'null' => null,
+ ];
+
/**
- * Implement PHP __clone to create a deep clone, not just a shallow copy.
+ * Convert property to form desired by Excel.
+ *
+ * @param mixed $propertyValue
+ *
+ * @return mixed
*/
- public function __clone()
+ public static function convertProperty($propertyValue, string $propertyType)
{
- $vars = get_object_vars($this);
- foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
+ return self::SPECIAL_TYPES[$propertyType] ?? self::convertProperty2($propertyValue, $propertyType);
}
- public static function convertProperty($propertyValue, $propertyType)
+ /**
+ * Convert property to form desired by Excel.
+ *
+ * @param mixed $propertyValue
+ *
+ * @return mixed
+ */
+ private static function convertProperty2($propertyValue, string $type)
{
+ $propertyType = self::convertPropertyType($type);
switch ($propertyType) {
- case 'empty': // Empty
- return '';
+ case self::PROPERTY_TYPE_INTEGER:
+ $intValue = (int) $propertyValue;
- break;
- case 'null': // Null
- return null;
-
- break;
- case 'i1': // 1-Byte Signed Integer
- case 'i2': // 2-Byte Signed Integer
- case 'i4': // 4-Byte Signed Integer
- case 'i8': // 8-Byte Signed Integer
- case 'int': // Integer
- return (int) $propertyValue;
-
- break;
- case 'ui1': // 1-Byte Unsigned Integer
- case 'ui2': // 2-Byte Unsigned Integer
- case 'ui4': // 4-Byte Unsigned Integer
- case 'ui8': // 8-Byte Unsigned Integer
- case 'uint': // Unsigned Integer
- return abs((int) $propertyValue);
-
- break;
- case 'r4': // 4-Byte Real Number
- case 'r8': // 8-Byte Real Number
- case 'decimal': // Decimal
+ return ($type[0] === 'u') ? abs($intValue) : $intValue;
+ case self::PROPERTY_TYPE_FLOAT:
return (float) $propertyValue;
-
- break;
- case 'lpstr': // LPSTR
- case 'lpwstr': // LPWSTR
- case 'bstr': // Basic String
+ case self::PROPERTY_TYPE_DATE:
+ return self::intOrFloatTimestamp($propertyValue);
+ case self::PROPERTY_TYPE_BOOLEAN:
+ return is_bool($propertyValue) ? $propertyValue : ($propertyValue === 'true');
+ default: // includes string
return $propertyValue;
-
- break;
- case 'date': // Date and Time
- case 'filetime': // File Time
- return strtotime($propertyValue);
-
- break;
- case 'bool': // Boolean
- return $propertyValue == 'true';
-
- break;
- case 'cy': // Currency
- case 'error': // Error Status Code
- case 'vector': // Vector
- case 'array': // Array
- case 'blob': // Binary Blob
- case 'oblob': // Binary Blob Object
- case 'stream': // Binary Stream
- case 'ostream': // Binary Stream Object
- case 'storage': // Binary Storage
- case 'ostorage': // Binary Storage Object
- case 'vstream': // Binary Versioned Stream
- case 'clsid': // Class ID
- case 'cf': // Clipboard Data
- return $propertyValue;
-
- break;
}
-
- return $propertyValue;
}
- public static function convertPropertyType($propertyType)
+ public static function convertPropertyType(string $propertyType): string
{
- switch ($propertyType) {
- case 'i1': // 1-Byte Signed Integer
- case 'i2': // 2-Byte Signed Integer
- case 'i4': // 4-Byte Signed Integer
- case 'i8': // 8-Byte Signed Integer
- case 'int': // Integer
- case 'ui1': // 1-Byte Unsigned Integer
- case 'ui2': // 2-Byte Unsigned Integer
- case 'ui4': // 4-Byte Unsigned Integer
- case 'ui8': // 8-Byte Unsigned Integer
- case 'uint': // Unsigned Integer
- return self::PROPERTY_TYPE_INTEGER;
-
- break;
- case 'r4': // 4-Byte Real Number
- case 'r8': // 8-Byte Real Number
- case 'decimal': // Decimal
- return self::PROPERTY_TYPE_FLOAT;
-
- break;
- case 'empty': // Empty
- case 'null': // Null
- case 'lpstr': // LPSTR
- case 'lpwstr': // LPWSTR
- case 'bstr': // Basic String
- return self::PROPERTY_TYPE_STRING;
-
- break;
- case 'date': // Date and Time
- case 'filetime': // File Time
- return self::PROPERTY_TYPE_DATE;
-
- break;
- case 'bool': // Boolean
- return self::PROPERTY_TYPE_BOOLEAN;
-
- break;
- case 'cy': // Currency
- case 'error': // Error Status Code
- case 'vector': // Vector
- case 'array': // Array
- case 'blob': // Binary Blob
- case 'oblob': // Binary Blob Object
- case 'stream': // Binary Stream
- case 'ostream': // Binary Stream Object
- case 'storage': // Binary Storage
- case 'ostorage': // Binary Storage Object
- case 'vstream': // Binary Versioned Stream
- case 'clsid': // Class ID
- case 'cf': // Clipboard Data
- return self::PROPERTY_TYPE_UNKNOWN;
-
- break;
- }
-
- return self::PROPERTY_TYPE_UNKNOWN;
+ return self::PROPERTY_TYPE_ARRAY[$propertyType] ?? self::PROPERTY_TYPE_UNKNOWN;
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Security.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Security.php
index cef3db8c44c..279aed43725 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Security.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Security.php
@@ -50,94 +50,57 @@ class Security
/**
* Is some sort of document security enabled?
- *
- * @return bool
*/
- public function isSecurityEnabled()
+ public function isSecurityEnabled(): bool
{
return $this->lockRevision ||
$this->lockStructure ||
$this->lockWindows;
}
- /**
- * Get LockRevision.
- *
- * @return bool
- */
- public function getLockRevision()
+ public function getLockRevision(): bool
{
return $this->lockRevision;
}
- /**
- * Set LockRevision.
- *
- * @param bool $pValue
- *
- * @return $this
- */
- public function setLockRevision($pValue)
+ public function setLockRevision(?bool $locked): self
{
- $this->lockRevision = $pValue;
+ if ($locked !== null) {
+ $this->lockRevision = $locked;
+ }
return $this;
}
- /**
- * Get LockStructure.
- *
- * @return bool
- */
- public function getLockStructure()
+ public function getLockStructure(): bool
{
return $this->lockStructure;
}
- /**
- * Set LockStructure.
- *
- * @param bool $pValue
- *
- * @return $this
- */
- public function setLockStructure($pValue)
+ public function setLockStructure(?bool $locked): self
{
- $this->lockStructure = $pValue;
+ if ($locked !== null) {
+ $this->lockStructure = $locked;
+ }
return $this;
}
- /**
- * Get LockWindows.
- *
- * @return bool
- */
- public function getLockWindows()
+ public function getLockWindows(): bool
{
return $this->lockWindows;
}
- /**
- * Set LockWindows.
- *
- * @param bool $pValue
- *
- * @return $this
- */
- public function setLockWindows($pValue)
+ public function setLockWindows(?bool $locked): self
{
- $this->lockWindows = $pValue;
+ if ($locked !== null) {
+ $this->lockWindows = $locked;
+ }
return $this;
}
- /**
- * Get RevisionsPassword (hashed).
- *
- * @return string
- */
- public function getRevisionsPassword()
+ public function getRevisionsPassword(): string
{
return $this->revisionsPassword;
}
@@ -145,27 +108,24 @@ class Security
/**
* Set RevisionsPassword.
*
- * @param string $pValue
- * @param bool $pAlreadyHashed If the password has already been hashed, set this to true
+ * @param string $password
+ * @param bool $alreadyHashed If the password has already been hashed, set this to true
*
* @return $this
*/
- public function setRevisionsPassword($pValue, $pAlreadyHashed = false)
+ public function setRevisionsPassword(?string $password, bool $alreadyHashed = false)
{
- if (!$pAlreadyHashed) {
- $pValue = PasswordHasher::hashPassword($pValue);
+ if ($password !== null) {
+ if (!$alreadyHashed) {
+ $password = PasswordHasher::hashPassword($password);
+ }
+ $this->revisionsPassword = $password;
}
- $this->revisionsPassword = $pValue;
return $this;
}
- /**
- * Get WorkbookPassword (hashed).
- *
- * @return string
- */
- public function getWorkbookPassword()
+ public function getWorkbookPassword(): string
{
return $this->workbookPassword;
}
@@ -173,33 +133,20 @@ class Security
/**
* Set WorkbookPassword.
*
- * @param string $pValue
- * @param bool $pAlreadyHashed If the password has already been hashed, set this to true
+ * @param string $password
+ * @param bool $alreadyHashed If the password has already been hashed, set this to true
*
* @return $this
*/
- public function setWorkbookPassword($pValue, $pAlreadyHashed = false)
+ public function setWorkbookPassword(?string $password, bool $alreadyHashed = false)
{
- if (!$pAlreadyHashed) {
- $pValue = PasswordHasher::hashPassword($pValue);
+ if ($password !== null) {
+ if (!$alreadyHashed) {
+ $password = PasswordHasher::hashPassword($password);
+ }
+ $this->workbookPassword = $password;
}
- $this->workbookPassword = $pValue;
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)) {
- $this->$key = clone $value;
- } else {
- $this->$key = $value;
- }
- }
- }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DocumentGenerator.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DocumentGenerator.php
deleted file mode 100644
index 5e06af97f41..00000000000
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DocumentGenerator.php
+++ /dev/null
@@ -1,97 +0,0 @@
- $category) {
- $result .= "\n";
- $result .= "## {$categoryConstant}\n";
- $result .= "\n";
- $lengths = [20, 42];
- $result .= self::tableRow($lengths, ['Excel Function', 'PhpSpreadsheet Function']) . "\n";
- $result .= self::tableRow($lengths, null) . "\n";
- foreach ($phpSpreadsheetFunctions as $excelFunction => $functionInfo) {
- if ($category === $functionInfo['category']) {
- $phpFunction = self::getPhpSpreadsheetFunctionText($functionInfo['functionCall']);
- $result .= self::tableRow($lengths, [$excelFunction, $phpFunction]) . "\n";
- }
- }
- }
-
- return $result;
- }
-
- private static function getCategories(): array
- {
- return (new ReflectionClass(Category::class))->getConstants();
- }
-
- private static function tableRow(array $lengths, ?array $values = null): string
- {
- $result = '';
- foreach (array_map(null, $lengths, $values ?? []) as $i => [$length, $value]) {
- $pad = $value === null ? '-' : ' ';
- if ($i > 0) {
- $result .= '|' . $pad;
- }
- $result .= str_pad($value ?? '', $length, $pad);
- }
-
- return rtrim($result, ' ');
- }
-
- private static function getPhpSpreadsheetFunctionText($functionCall): string
- {
- if (is_string($functionCall)) {
- return $functionCall;
- }
- if ($functionCall === [Functions::class, 'DUMMY']) {
- return '**Not yet Implemented**';
- }
- if (is_array($functionCall)) {
- return "\\{$functionCall[0]}::{$functionCall[1]}";
- }
-
- throw new UnexpectedValueException(
- '$functionCall is of type ' . gettype($functionCall) . '. string or array expected'
- );
- }
-
- /**
- * @param array[] $phpSpreadsheetFunctions
- */
- public static function generateFunctionListByName(array $phpSpreadsheetFunctions): string
- {
- $categoryConstants = array_flip(self::getCategories());
- $result = "# Function list by name\n";
- $lastAlphabet = null;
- foreach ($phpSpreadsheetFunctions as $excelFunction => $functionInfo) {
- $lengths = [20, 31, 42];
- if ($lastAlphabet !== $excelFunction[0]) {
- $lastAlphabet = $excelFunction[0];
- $result .= "\n";
- $result .= "## {$lastAlphabet}\n";
- $result .= "\n";
- $result .= self::tableRow($lengths, ['Excel Function', 'Category', 'PhpSpreadsheet Function']) . "\n";
- $result .= self::tableRow($lengths, null) . "\n";
- }
- $category = $categoryConstants[$functionInfo['category']];
- $phpFunction = self::getPhpSpreadsheetFunctionText($functionInfo['functionCall']);
- $result .= self::tableRow($lengths, [$excelFunction, $category, $phpFunction]) . "\n";
- }
-
- return $result;
- }
-}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/HashTable.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/HashTable.php
index 90ea806bd8f..59209eed962 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/HashTable.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/HashTable.php
@@ -2,48 +2,51 @@
namespace PhpOffice\PhpSpreadsheet;
+/**
+ * @template T of IComparable
+ */
class HashTable
{
/**
* HashTable elements.
*
- * @var IComparable[]
+ * @var array
*/
protected $items = [];
/**
* HashTable key map.
*
- * @var string[]
+ * @var array
*/
protected $keyMap = [];
/**
- * Create a new \PhpOffice\PhpSpreadsheet\HashTable.
+ * Create a new HashTable.
*
- * @param IComparable[] $pSource Optional source array to create HashTable from
+ * @param T[] $source Optional source array to create HashTable from
*/
- public function __construct($pSource = null)
+ public function __construct($source = null)
{
- if ($pSource !== null) {
+ if ($source !== null) {
// Create HashTable
- $this->addFromSource($pSource);
+ $this->addFromSource($source);
}
}
/**
* Add HashTable items from source.
*
- * @param IComparable[] $pSource Source array to create HashTable from
+ * @param T[] $source Source array to create HashTable from
*/
- public function addFromSource(?array $pSource = null): void
+ public function addFromSource(?array $source = null): void
{
// Check if an array was passed
- if ($pSource == null) {
+ if ($source === null) {
return;
}
- foreach ($pSource as $item) {
+ foreach ($source as $item) {
$this->add($item);
}
}
@@ -51,13 +54,13 @@ class HashTable
/**
* Add HashTable item.
*
- * @param IComparable $pSource Item to add
+ * @param T $source Item to add
*/
- public function add(IComparable $pSource): void
+ public function add(IComparable $source): void
{
- $hash = $pSource->getHashCode();
+ $hash = $source->getHashCode();
if (!isset($this->items[$hash])) {
- $this->items[$hash] = $pSource;
+ $this->items[$hash] = $source;
$this->keyMap[count($this->items) - 1] = $hash;
}
}
@@ -65,11 +68,11 @@ class HashTable
/**
* Remove HashTable item.
*
- * @param IComparable $pSource Item to remove
+ * @param T $source Item to remove
*/
- public function remove(IComparable $pSource): void
+ public function remove(IComparable $source): void
{
- $hash = $pSource->getHashCode();
+ $hash = $source->getHashCode();
if (isset($this->items[$hash])) {
unset($this->items[$hash]);
@@ -109,26 +112,22 @@ class HashTable
/**
* Get index for hash code.
*
- * @param string $pHashCode
- *
- * @return int Index
+ * @return false|int Index
*/
- public function getIndexForHashCode($pHashCode)
+ public function getIndexForHashCode(string $hashCode)
{
- return array_search($pHashCode, $this->keyMap);
+ return array_search($hashCode, $this->keyMap, true);
}
/**
* Get by index.
*
- * @param int $pIndex
- *
- * @return IComparable
+ * @return null|T
*/
- public function getByIndex($pIndex)
+ public function getByIndex(int $index)
{
- if (isset($this->keyMap[$pIndex])) {
- return $this->getByHashCode($this->keyMap[$pIndex]);
+ if (isset($this->keyMap[$index])) {
+ return $this->getByHashCode($this->keyMap[$index]);
}
return null;
@@ -137,14 +136,12 @@ class HashTable
/**
* Get by hashcode.
*
- * @param string $pHashCode
- *
- * @return IComparable
+ * @return null|T
*/
- public function getByHashCode($pHashCode)
+ public function getByHashCode(string $hashCode)
{
- if (isset($this->items[$pHashCode])) {
- return $this->items[$pHashCode];
+ if (isset($this->items[$hashCode])) {
+ return $this->items[$hashCode];
}
return null;
@@ -153,7 +150,7 @@ class HashTable
/**
* HashTable to array.
*
- * @return IComparable[]
+ * @return T[]
*/
public function toArray()
{
@@ -167,8 +164,15 @@ class HashTable
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
- if (is_object($value)) {
- $this->$key = clone $value;
+ // each member of this class is an array
+ if (is_array($value)) {
+ $array1 = $value;
+ foreach ($array1 as $key1 => $value1) {
+ if (is_object($value1)) {
+ $array1[$key1] = clone $value1;
+ }
+ }
+ $this->$key = $array1;
}
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Dimension.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Dimension.php
new file mode 100644
index 00000000000..136ffd7fbfd
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Dimension.php
@@ -0,0 +1,103 @@
+ 96.0 / 2.54,
+ self::UOM_MILLIMETERS => 96.0 / 25.4,
+ self::UOM_INCHES => 96.0,
+ self::UOM_PIXELS => 1.0,
+ self::UOM_POINTS => 96.0 / 72,
+ self::UOM_PICA => 96.0 * 12 / 72,
+ ];
+
+ /**
+ * Based on a standard column width of 8.54 units in MS Excel.
+ */
+ const RELATIVE_UNITS = [
+ 'em' => 10.0 / 8.54,
+ 'ex' => 10.0 / 8.54,
+ 'ch' => 10.0 / 8.54,
+ 'rem' => 10.0 / 8.54,
+ 'vw' => 8.54,
+ 'vh' => 8.54,
+ 'vmin' => 8.54,
+ 'vmax' => 8.54,
+ '%' => 8.54 / 100,
+ ];
+
+ /**
+ * @var float|int If this is a width, then size is measured in pixels (if is set)
+ * or in Excel's default column width units if $unit is null.
+ * If this is a height, then size is measured in pixels ()
+ * or in points () if $unit is null.
+ */
+ protected $size;
+
+ /**
+ * @var null|string
+ */
+ protected $unit;
+
+ public function __construct(string $dimension)
+ {
+ [$size, $unit] = sscanf($dimension, '%[1234567890.]%s');
+ $unit = strtolower(trim($unit));
+
+ // If a UoM is specified, then convert the size to pixels for internal storage
+ if (isset(self::ABSOLUTE_UNITS[$unit])) {
+ $size *= self::ABSOLUTE_UNITS[$unit];
+ $this->unit = self::UOM_PIXELS;
+ } elseif (isset(self::RELATIVE_UNITS[$unit])) {
+ $size *= self::RELATIVE_UNITS[$unit];
+ $size = round($size, 4);
+ }
+
+ $this->size = $size;
+ }
+
+ public function width(): float
+ {
+ return (float) ($this->unit === null)
+ ? $this->size
+ : round(Drawing::pixelsToCellDimension((int) $this->size, new Font(false)), 4);
+ }
+
+ public function height(): float
+ {
+ return (float) ($this->unit === null)
+ ? $this->size
+ : $this->toUnit(self::UOM_POINTS);
+ }
+
+ public function toUnit(string $unitOfMeasure): float
+ {
+ $unitOfMeasure = strtolower($unitOfMeasure);
+ if (!array_key_exists($unitOfMeasure, self::ABSOLUTE_UNITS)) {
+ throw new Exception("{$unitOfMeasure} is not a vaid unit of measure");
+ }
+
+ $size = $this->size;
+ if ($this->unit === null) {
+ $size = Drawing::cellDimensionToPixels($size, new Font(false));
+ }
+
+ return $size / self::ABSOLUTE_UNITS[$unitOfMeasure];
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php
index 6c4cbf9bbb5..73a3308c249 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php
@@ -684,9 +684,9 @@ class Html
$this->stringData = '';
}
- protected function rgbToColour($rgb)
+ protected function rgbToColour(string $rgbValue): string
{
- preg_match_all('/\d+/', $rgb, $values);
+ preg_match_all('/\d+/', $rgbValue, $values);
foreach ($values[0] as &$value) {
$value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT);
}
@@ -694,9 +694,9 @@ class Html
return implode('', $values[0]);
}
- public static function colourNameLookup(string $rgb): string
+ public static function colourNameLookup(string $colorName): string
{
- return self::$colourMap[$rgb] ?? '';
+ return self::$colourMap[$colorName] ?? '';
}
protected function startFontTag($tag): void
@@ -711,7 +711,7 @@ class Html
} elseif (strpos(trim($attributeValue), '#') === 0) {
$this->$attributeName = ltrim($attributeValue, '#');
} else {
- $this->$attributeName = $this->colourNameLookup($attributeValue);
+ $this->$attributeName = static::colourNameLookup($attributeValue);
}
} else {
$this->$attributeName = $attributeValue;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php
index a91b195e24b..257a02a8273 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php
@@ -5,7 +5,6 @@ namespace PhpOffice\PhpSpreadsheet\Helper;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
-use PhpOffice\PhpSpreadsheet\Writer\Pdf;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RecursiveRegexIterator;
@@ -71,7 +70,7 @@ class Sample
/**
* Returns an array of all known samples.
*
- * @return string[] [$name => $path]
+ * @return string[][] [$name => $path]
*/
public function getSamples()
{
@@ -119,11 +118,6 @@ class Sample
foreach ($writers as $writerType) {
$path = $this->getFilename($filename, mb_strtolower($writerType));
$writer = IOFactory::createWriter($spreadsheet, $writerType);
- if ($writer instanceof Pdf) {
- // PDF writer needs temporary directory
- $tempDir = $this->getTemporaryFolder();
- $writer->setTempDir($tempDir);
- }
$callStartTime = microtime(true);
$writer->save($path);
$this->logWrite($writer, $path, $callStartTime);
@@ -132,6 +126,11 @@ class Sample
$this->logEndingNotes();
}
+ protected function isDirOrMkdir(string $folder): bool
+ {
+ return \is_dir($folder) || \mkdir($folder);
+ }
+
/**
* Returns the temporary directory and make sure it exists.
*
@@ -140,10 +139,8 @@ class Sample
private function getTemporaryFolder()
{
$tempFolder = sys_get_temp_dir() . '/phpspreadsheet';
- if (!is_dir($tempFolder)) {
- if (!mkdir($tempFolder) && !is_dir($tempFolder)) {
- throw new RuntimeException(sprintf('Directory "%s" was not created', $tempFolder));
- }
+ if (!$this->isDirOrMkdir($tempFolder)) {
+ throw new RuntimeException(sprintf('Directory "%s" was not created', $tempFolder));
}
return $tempFolder;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Size.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Size.php
new file mode 100644
index 00000000000..12ba4ef7325
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Size.php
@@ -0,0 +1,52 @@
+\d*\.?\d+)(?Ppt|px|em)?$/i';
+
+ /**
+ * @var bool
+ */
+ protected $valid;
+
+ /**
+ * @var string
+ */
+ protected $size = '';
+
+ /**
+ * @var string
+ */
+ protected $unit = '';
+
+ public function __construct(string $size)
+ {
+ $this->valid = (bool) preg_match(self::REGEXP_SIZE_VALIDATION, $size, $matches);
+ if ($this->valid) {
+ $this->size = $matches['size'];
+ $this->unit = $matches['unit'] ?? 'pt';
+ }
+ }
+
+ public function valid(): bool
+ {
+ return $this->valid;
+ }
+
+ public function size(): string
+ {
+ return $this->size;
+ }
+
+ public function unit(): string
+ {
+ return $this->unit;
+ }
+
+ public function __toString()
+ {
+ return $this->size . $this->unit;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php
index ab04e9698ef..91613cb440d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php
@@ -2,7 +2,9 @@
namespace PhpOffice\PhpSpreadsheet;
+use PhpOffice\PhpSpreadsheet\Reader\IReader;
use PhpOffice\PhpSpreadsheet\Shared\File;
+use PhpOffice\PhpSpreadsheet\Writer\IWriter;
/**
* Factory to create readers and writers easily.
@@ -36,12 +38,8 @@ abstract class IOFactory
/**
* Create Writer\IWriter.
- *
- * @param string $writerType Example: Xlsx
- *
- * @return Writer\IWriter
*/
- public static function createWriter(Spreadsheet $spreadsheet, $writerType)
+ public static function createWriter(Spreadsheet $spreadsheet, string $writerType): IWriter
{
if (!isset(self::$writers[$writerType])) {
throw new Writer\Exception("No writer found for type $writerType");
@@ -54,13 +52,9 @@ abstract class IOFactory
}
/**
- * Create Reader\IReader.
- *
- * @param string $readerType Example: Xlsx
- *
- * @return Reader\IReader
+ * Create IReader.
*/
- public static function createReader($readerType)
+ public static function createReader(string $readerType): IReader
{
if (!isset(self::$readers[$readerType])) {
throw new Reader\Exception("No reader found for type $readerType");
@@ -75,27 +69,21 @@ abstract class IOFactory
/**
* Loads Spreadsheet from file using automatic Reader\IReader resolution.
*
- * @param string $pFilename The name of the spreadsheet file
- *
- * @return Spreadsheet
+ * @param string $filename The name of the spreadsheet file
*/
- public static function load($pFilename)
+ public static function load(string $filename, int $flags = 0): Spreadsheet
{
- $reader = self::createReaderForFile($pFilename);
+ $reader = self::createReaderForFile($filename);
- return $reader->load($pFilename);
+ return $reader->load($filename, $flags);
}
/**
- * Identify file type using automatic Reader\IReader resolution.
- *
- * @param string $pFilename The name of the spreadsheet file to identify
- *
- * @return string
+ * Identify file type using automatic IReader resolution.
*/
- public static function identify($pFilename)
+ public static function identify(string $filename): string
{
- $reader = self::createReaderForFile($pFilename);
+ $reader = self::createReaderForFile($filename);
$className = get_class($reader);
$classType = explode('\\', $className);
unset($reader);
@@ -104,13 +92,9 @@ abstract class IOFactory
}
/**
- * Create Reader\IReader for file using automatic Reader\IReader resolution.
- *
- * @param string $filename The name of the spreadsheet file
- *
- * @return Reader\IReader
+ * Create Reader\IReader for file using automatic IReader resolution.
*/
- public static function createReaderForFile($filename)
+ public static function createReaderForFile(string $filename): IReader
{
File::assertFile($filename);
@@ -120,7 +104,7 @@ abstract class IOFactory
$reader = self::createReader($guessedReader);
// Let's see if we are lucky
- if (isset($reader) && $reader->canRead($filename)) {
+ if ($reader->canRead($filename)) {
return $reader;
}
}
@@ -142,12 +126,8 @@ abstract class IOFactory
/**
* Guess a reader type from the file extension, if any.
- *
- * @param string $filename
- *
- * @return null|string
*/
- private static function getReaderTypeFromExtension($filename)
+ private static function getReaderTypeFromExtension(string $filename): ?string
{
$pathinfo = pathinfo($filename);
if (!isset($pathinfo['extension'])) {
@@ -187,14 +167,11 @@ abstract class IOFactory
/**
* Register a writer with its type and class name.
- *
- * @param string $writerType
- * @param string $writerClass
*/
- public static function registerWriter($writerType, $writerClass): void
+ public static function registerWriter(string $writerType, string $writerClass): void
{
- if (!is_a($writerClass, Writer\IWriter::class, true)) {
- throw new Writer\Exception('Registered writers must implement ' . Writer\IWriter::class);
+ if (!is_a($writerClass, IWriter::class, true)) {
+ throw new Writer\Exception('Registered writers must implement ' . IWriter::class);
}
self::$writers[$writerType] = $writerClass;
@@ -202,14 +179,11 @@ abstract class IOFactory
/**
* Register a reader with its type and class name.
- *
- * @param string $readerType
- * @param string $readerClass
*/
- public static function registerReader($readerType, $readerClass): void
+ public static function registerReader(string $readerType, string $readerClass): void
{
- if (!is_a($readerClass, Reader\IReader::class, true)) {
- throw new Reader\Exception('Registered readers must implement ' . Reader\IReader::class);
+ if (!is_a($readerClass, IReader::class, true)) {
+ throw new Reader\Exception('Registered readers must implement ' . IReader::class);
}
self::$readers[$readerType] = $readerClass;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedFormula.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedFormula.php
index eeddbbcb99a..500151f0b8e 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedFormula.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedFormula.php
@@ -17,7 +17,7 @@ class NamedFormula extends DefinedName
?Worksheet $scope = null
) {
// Validate data
- if (empty($formula)) {
+ if (!isset($formula)) {
throw new Exception('You must specify a Formula value for a Named Formula');
}
parent::__construct($name, $worksheet, $formula, $localOnly, $scope);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php
index eb0e3ba223c..2ad8e6b20aa 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php
@@ -38,7 +38,7 @@ abstract class BaseReader implements IReader
* Restrict which sheets should be loaded?
* This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded.
*
- * @var array of string
+ * @var null|string[]
*/
protected $loadSheetsOnly;
@@ -66,9 +66,9 @@ abstract class BaseReader implements IReader
return $this->readDataOnly;
}
- public function setReadDataOnly($pValue)
+ public function setReadDataOnly($readCellValuesOnly)
{
- $this->readDataOnly = (bool) $pValue;
+ $this->readDataOnly = (bool) $readCellValuesOnly;
return $this;
}
@@ -78,9 +78,9 @@ abstract class BaseReader implements IReader
return $this->readEmptyCells;
}
- public function setReadEmptyCells($pValue)
+ public function setReadEmptyCells($readEmptyCells)
{
- $this->readEmptyCells = (bool) $pValue;
+ $this->readEmptyCells = (bool) $readEmptyCells;
return $this;
}
@@ -90,9 +90,9 @@ abstract class BaseReader implements IReader
return $this->includeCharts;
}
- public function setIncludeCharts($pValue)
+ public function setIncludeCharts($includeCharts)
{
- $this->includeCharts = (bool) $pValue;
+ $this->includeCharts = (bool) $includeCharts;
return $this;
}
@@ -102,13 +102,13 @@ abstract class BaseReader implements IReader
return $this->loadSheetsOnly;
}
- public function setLoadSheetsOnly($value)
+ public function setLoadSheetsOnly($sheetList)
{
- if ($value === null) {
+ if ($sheetList === null) {
return $this->setLoadAllSheets();
}
- $this->loadSheetsOnly = is_array($value) ? $value : [$value];
+ $this->loadSheetsOnly = is_array($sheetList) ? $sheetList : [$sheetList];
return $this;
}
@@ -125,9 +125,9 @@ abstract class BaseReader implements IReader
return $this->readFilter;
}
- public function setReadFilter(IReadFilter $pValue)
+ public function setReadFilter(IReadFilter $readFilter)
{
- $this->readFilter = $pValue;
+ $this->readFilter = $readFilter;
return $this;
}
@@ -137,25 +137,32 @@ abstract class BaseReader implements IReader
return $this->securityScanner;
}
+ protected function processFlags(int $flags): void
+ {
+ if (((bool) ($flags & self::LOAD_WITH_CHARTS)) === true) {
+ $this->setIncludeCharts(true);
+ }
+ }
+
/**
* Open file for reading.
*
- * @param string $pFilename
+ * @param string $filename
*/
- protected function openFile($pFilename): void
+ protected function openFile($filename): void
{
- if ($pFilename) {
- File::assertFile($pFilename);
+ if ($filename) {
+ File::assertFile($filename);
// Open file
- $fileHandle = fopen($pFilename, 'rb');
+ $fileHandle = fopen($filename, 'rb');
} else {
$fileHandle = false;
}
if ($fileHandle !== false) {
$this->fileHandle = $fileHandle;
} else {
- throw new ReaderException('Could not open file ' . $pFilename . ' for reading.');
+ throw new ReaderException('Could not open file ' . $filename . ' for reading.');
}
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php
index 1495d102c00..185f064c3f3 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php
@@ -2,13 +2,17 @@
namespace PhpOffice\PhpSpreadsheet\Reader;
-use InvalidArgumentException;
+use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
+use PhpOffice\PhpSpreadsheet\Reader\Csv\Delimiter;
+use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Csv extends BaseReader
{
+ const DEFAULT_FALLBACK_ENCODING = 'CP1252';
+ const GUESS_ENCODING = 'guess';
const UTF8_BOM = "\xEF\xBB\xBF";
const UTF8_BOM_LEN = 3;
const UTF16BE_BOM = "\xfe\xff";
@@ -32,10 +36,17 @@ class Csv extends BaseReader
private $inputEncoding = 'UTF-8';
/**
- * Delimiter.
+ * Fallback encoding if guess strikes out.
*
* @var string
*/
+ private $fallbackEncoding = self::DEFAULT_FALLBACK_ENCODING;
+
+ /**
+ * Delimiter.
+ *
+ * @var ?string
+ */
private $delimiter;
/**
@@ -66,38 +77,65 @@ class Csv extends BaseReader
*/
private $escapeCharacter = '\\';
+ /**
+ * Callback for setting defaults in construction.
+ *
+ * @var ?callable
+ */
+ private static $constructorCallback;
+
/**
* Create a new CSV Reader instance.
*/
public function __construct()
{
parent::__construct();
+ $callback = self::$constructorCallback;
+ if ($callback !== null) {
+ $callback($this);
+ }
}
/**
- * Set input encoding.
+ * Set a callback to change the defaults.
*
- * @param string $pValue Input encoding, eg: 'UTF-8'
- *
- * @return $this
+ * The callback must accept the Csv Reader object as the first parameter,
+ * and it should return void.
*/
- public function setInputEncoding($pValue)
+ public static function setConstructorCallback(?callable $callback): void
{
- $this->inputEncoding = $pValue;
+ self::$constructorCallback = $callback;
+ }
+
+ public static function getConstructorCallback(): ?callable
+ {
+ return self::$constructorCallback;
+ }
+
+ public function setInputEncoding(string $encoding): self
+ {
+ $this->inputEncoding = $encoding;
return $this;
}
- /**
- * Get input encoding.
- *
- * @return string
- */
- public function getInputEncoding()
+ public function getInputEncoding(): string
{
return $this->inputEncoding;
}
+ public function setFallbackEncoding(string $fallbackEncoding): self
+ {
+ $this->fallbackEncoding = $fallbackEncoding;
+
+ return $this;
+ }
+
+ public function getFallbackEncoding(): string
+ {
+ return $this->fallbackEncoding;
+ }
+
/**
* Move filepointer past any BOM marker.
*/
@@ -138,129 +176,33 @@ class Csv extends BaseReader
return;
}
- $potentialDelimiters = [',', ';', "\t", '|', ':', ' ', '~'];
- $counts = [];
- foreach ($potentialDelimiters as $delimiter) {
- $counts[$delimiter] = [];
- }
-
- // Count how many times each of the potential delimiters appears in each line
- $numberLines = 0;
- while (($line = $this->getNextLine()) !== false && (++$numberLines < 1000)) {
- $countLine = [];
- for ($i = strlen($line) - 1; $i >= 0; --$i) {
- $char = $line[$i];
- if (isset($counts[$char])) {
- if (!isset($countLine[$char])) {
- $countLine[$char] = 0;
- }
- ++$countLine[$char];
- }
- }
- foreach ($potentialDelimiters as $delimiter) {
- $counts[$delimiter][] = $countLine[$delimiter]
- ?? 0;
- }
- }
+ $inferenceEngine = new Delimiter($this->fileHandle, $this->escapeCharacter, $this->enclosure);
// If number of lines is 0, nothing to infer : fall back to the default
- if ($numberLines === 0) {
- $this->delimiter = reset($potentialDelimiters);
+ if ($inferenceEngine->linesCounted() === 0) {
+ $this->delimiter = $inferenceEngine->getDefaultDelimiter();
$this->skipBOM();
return;
}
- // Calculate the mean square deviations for each delimiter (ignoring delimiters that haven't been found consistently)
- $meanSquareDeviations = [];
- $middleIdx = floor(($numberLines - 1) / 2);
-
- foreach ($potentialDelimiters as $delimiter) {
- $series = $counts[$delimiter];
- sort($series);
-
- $median = ($numberLines % 2)
- ? $series[$middleIdx]
- : ($series[$middleIdx] + $series[$middleIdx + 1]) / 2;
-
- if ($median === 0) {
- continue;
- }
-
- $meanSquareDeviations[$delimiter] = array_reduce(
- $series,
- function ($sum, $value) use ($median) {
- return $sum + ($value - $median) ** 2;
- }
- ) / count($series);
- }
-
- // ... and pick the delimiter with the smallest mean square deviation (in case of ties, the order in potentialDelimiters is respected)
- $min = INF;
- foreach ($potentialDelimiters as $delimiter) {
- if (!isset($meanSquareDeviations[$delimiter])) {
- continue;
- }
-
- if ($meanSquareDeviations[$delimiter] < $min) {
- $min = $meanSquareDeviations[$delimiter];
- $this->delimiter = $delimiter;
- }
- }
+ $this->delimiter = $inferenceEngine->infer();
// If no delimiter could be detected, fall back to the default
if ($this->delimiter === null) {
- $this->delimiter = reset($potentialDelimiters);
+ $this->delimiter = $inferenceEngine->getDefaultDelimiter();
}
$this->skipBOM();
}
- /**
- * Get the next full line from the file.
- *
- * @return false|string
- */
- private function getNextLine()
- {
- $line = '';
- $enclosure = ($this->escapeCharacter === '' ? ''
- : ('(?escapeCharacter, '/') . ')'))
- . preg_quote($this->enclosure, '/');
-
- do {
- // Get the next line in the file
- $newLine = fgets($this->fileHandle);
-
- // Return false if there is no next line
- if ($newLine === false) {
- return false;
- }
-
- // Add the new line to the line passed in
- $line = $line . $newLine;
-
- // Drop everything that is enclosed to avoid counting false positives in enclosures
- $line = preg_replace('/(' . $enclosure . '.*' . $enclosure . ')/Us', '', $line);
-
- // See if we have any enclosures left in the line
- // if we still have an enclosure then we need to read the next line as well
- } while (preg_match('/(' . $enclosure . ')/', $line) > 0);
-
- return $line;
- }
-
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
- *
- * @param string $pFilename
- *
- * @return array
*/
- public function listWorksheetInfo($pFilename)
+ public function listWorksheetInfo(string $filename): array
{
// Open file
- $this->openFileOrMemory($pFilename);
+ $this->openFileOrMemory($filename);
$fileHandle = $this->fileHandle;
// Skip BOM, if any
@@ -276,9 +218,11 @@ class Csv extends BaseReader
$worksheetInfo[0]['totalColumns'] = 0;
// Loop through each line of the file in turn
- while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure, $this->escapeCharacter)) !== false) {
+ $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter);
+ while (is_array($rowData)) {
++$worksheetInfo[0]['totalRows'];
$worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1);
+ $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter);
}
$worksheetInfo[0]['lastColumnLetter'] = Coordinate::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex'] + 1);
@@ -293,51 +237,65 @@ class Csv extends BaseReader
/**
* Loads Spreadsheet from file.
*
- * @param string $pFilename
- *
* @return Spreadsheet
*/
- public function load($pFilename)
+ public function load(string $filename, int $flags = 0)
{
+ $this->processFlags($flags);
+
// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
// Load into this instance
- return $this->loadIntoExisting($pFilename, $spreadsheet);
+ return $this->loadIntoExisting($filename, $spreadsheet);
}
- private function openFileOrMemory($pFilename): void
+ private function openFileOrMemory(string $filename): void
{
// Open file
- $fhandle = $this->canRead($pFilename);
+ $fhandle = $this->canRead($filename);
if (!$fhandle) {
- throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
+ throw new Exception($filename . ' is an Invalid Spreadsheet file.');
}
- $this->openFile($pFilename);
+ if ($this->inputEncoding === self::GUESS_ENCODING) {
+ $this->inputEncoding = self::guessEncoding($filename, $this->fallbackEncoding);
+ }
+ $this->openFile($filename);
if ($this->inputEncoding !== 'UTF-8') {
fclose($this->fileHandle);
- $entireFile = file_get_contents($pFilename);
+ $entireFile = file_get_contents($filename);
$this->fileHandle = fopen('php://memory', 'r+b');
- $data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding);
- fwrite($this->fileHandle, $data);
- $this->skipBOM();
+ if ($this->fileHandle !== false && $entireFile !== false) {
+ $data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding);
+ fwrite($this->fileHandle, $data);
+ $this->skipBOM();
+ }
}
}
+ private static function setAutoDetect(?string $value): ?string
+ {
+ $retVal = null;
+ if ($value !== null) {
+ $retVal2 = @ini_set('auto_detect_line_endings', $value);
+ if (is_string($retVal2)) {
+ $retVal = $retVal2;
+ }
+ }
+
+ return $retVal;
+ }
+
/**
* Loads PhpSpreadsheet from file into PhpSpreadsheet instance.
- *
- * @param string $pFilename
- *
- * @return Spreadsheet
*/
- public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet)
+ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet
{
- $lineEnding = ini_get('auto_detect_line_endings');
- ini_set('auto_detect_line_endings', true);
+ // Deprecated in Php8.1
+ $iniset = self::setAutoDetect('1');
// Open file
- $this->openFileOrMemory($pFilename);
+ $this->openFileOrMemory($filename);
$fileHandle = $this->fileHandle;
// Skip BOM, if any
@@ -356,11 +314,15 @@ class Csv extends BaseReader
$outRow = 0;
// Loop through each line of the file in turn
- while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure, $this->escapeCharacter)) !== false) {
+ $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter);
+ $valueBinder = Cell::getValueBinder();
+ $preserveBooleanString = method_exists($valueBinder, 'getBooleanConversion') && $valueBinder->getBooleanConversion();
+ while (is_array($rowData)) {
$noOutputYet = true;
$columnLetter = 'A';
foreach ($rowData as $rowDatum) {
- if ($rowDatum != '' && $this->readFilter->readCell($columnLetter, $currentRow)) {
+ $this->convertBoolean($rowDatum, $preserveBooleanString);
+ if ($rowDatum !== '' && $this->readFilter->readCell($columnLetter, $currentRow)) {
if ($this->contiguous) {
if ($noOutputYet) {
$noOutputYet = false;
@@ -374,60 +336,55 @@ class Csv extends BaseReader
}
++$columnLetter;
}
+ $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter);
++$currentRow;
}
// Close file
fclose($fileHandle);
- ini_set('auto_detect_line_endings', $lineEnding);
+ self::setAutoDetect($iniset);
// Return
return $spreadsheet;
}
/**
- * Get delimiter.
+ * Convert string true/false to boolean, and null to null-string.
*
- * @return string
+ * @param mixed $rowDatum
*/
- public function getDelimiter()
+ private function convertBoolean(&$rowDatum, bool $preserveBooleanString): void
+ {
+ if (is_string($rowDatum) && !$preserveBooleanString) {
+ if (strcasecmp('true', $rowDatum) === 0) {
+ $rowDatum = true;
+ } elseif (strcasecmp('false', $rowDatum) === 0) {
+ $rowDatum = false;
+ }
+ } elseif ($rowDatum === null) {
+ $rowDatum = '';
+ }
+ }
+
+ public function getDelimiter(): ?string
{
return $this->delimiter;
}
- /**
- * Set delimiter.
- *
- * @param string $delimiter Delimiter, eg: ','
- *
- * @return $this
- */
- public function setDelimiter($delimiter)
+ public function setDelimiter(?string $delimiter): self
{
$this->delimiter = $delimiter;
return $this;
}
- /**
- * Get enclosure.
- *
- * @return string
- */
- public function getEnclosure()
+ public function getEnclosure(): string
{
return $this->enclosure;
}
- /**
- * Set enclosure.
- *
- * @param string $enclosure Enclosure, defaults to "
- *
- * @return $this
- */
- public function setEnclosure($enclosure)
+ public function setEnclosure(string $enclosure): self
{
if ($enclosure == '') {
$enclosure = '"';
@@ -437,104 +394,64 @@ class Csv extends BaseReader
return $this;
}
- /**
- * Get sheet index.
- *
- * @return int
- */
- public function getSheetIndex()
+ public function getSheetIndex(): int
{
return $this->sheetIndex;
}
- /**
- * Set sheet index.
- *
- * @param int $pValue Sheet index
- *
- * @return $this
- */
- public function setSheetIndex($pValue)
+ public function setSheetIndex(int $indexValue): self
{
- $this->sheetIndex = $pValue;
+ $this->sheetIndex = $indexValue;
return $this;
}
- /**
- * Set Contiguous.
- *
- * @param bool $contiguous
- *
- * @return $this
- */
- public function setContiguous($contiguous)
+ public function setContiguous(bool $contiguous): self
{
- $this->contiguous = (bool) $contiguous;
+ $this->contiguous = $contiguous;
return $this;
}
- /**
- * Get Contiguous.
- *
- * @return bool
- */
- public function getContiguous()
+ public function getContiguous(): bool
{
return $this->contiguous;
}
- /**
- * Set escape backslashes.
- *
- * @param string $escapeCharacter
- *
- * @return $this
- */
- public function setEscapeCharacter($escapeCharacter)
+ public function setEscapeCharacter(string $escapeCharacter): self
{
$this->escapeCharacter = $escapeCharacter;
return $this;
}
- /**
- * Get escape backslashes.
- *
- * @return string
- */
- public function getEscapeCharacter()
+ public function getEscapeCharacter(): string
{
return $this->escapeCharacter;
}
/**
* Can the current IReader read the file?
- *
- * @param string $pFilename
- *
- * @return bool
*/
- public function canRead($pFilename)
+ public function canRead(string $filename): bool
{
// Check if file exists
try {
- $this->openFile($pFilename);
- } catch (InvalidArgumentException $e) {
+ $this->openFile($filename);
+ } catch (ReaderException $e) {
return false;
}
fclose($this->fileHandle);
// Trust file extension if any
- $extension = strtolower(pathinfo($pFilename, PATHINFO_EXTENSION));
+ $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (in_array($extension, ['csv', 'tsv'])) {
return true;
}
// Attempt to guess mimetype
- $type = mime_content_type($pFilename);
+ $type = mime_content_type($filename);
$supportedTypes = [
'application/csv',
'text/csv',
@@ -594,7 +511,7 @@ class Csv extends BaseReader
return $encoding;
}
- public static function guessEncoding(string $filename, string $dflt = 'CP1252'): string
+ public static function guessEncoding(string $filename, string $dflt = self::DEFAULT_FALLBACK_ENCODING): string
{
$encoding = self::guessEncodingBom($filename);
if ($encoding === '') {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv/Delimiter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv/Delimiter.php
new file mode 100644
index 00000000000..fc298957b83
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv/Delimiter.php
@@ -0,0 +1,151 @@
+fileHandle = $fileHandle;
+ $this->escapeCharacter = $escapeCharacter;
+ $this->enclosure = $enclosure;
+
+ $this->countPotentialDelimiters();
+ }
+
+ public function getDefaultDelimiter(): string
+ {
+ return self::POTENTIAL_DELIMETERS[0];
+ }
+
+ public function linesCounted(): int
+ {
+ return $this->numberLines;
+ }
+
+ protected function countPotentialDelimiters(): void
+ {
+ $this->counts = array_fill_keys(self::POTENTIAL_DELIMETERS, []);
+ $delimiterKeys = array_flip(self::POTENTIAL_DELIMETERS);
+
+ // Count how many times each of the potential delimiters appears in each line
+ $this->numberLines = 0;
+ while (($line = $this->getNextLine()) !== false && (++$this->numberLines < 1000)) {
+ $this->countDelimiterValues($line, $delimiterKeys);
+ }
+ }
+
+ protected function countDelimiterValues(string $line, array $delimiterKeys): void
+ {
+ $splitString = str_split($line, 1);
+ if (is_array($splitString)) {
+ $distribution = array_count_values($splitString);
+ $countLine = array_intersect_key($distribution, $delimiterKeys);
+
+ foreach (self::POTENTIAL_DELIMETERS as $delimiter) {
+ $this->counts[$delimiter][] = $countLine[$delimiter] ?? 0;
+ }
+ }
+ }
+
+ public function infer(): ?string
+ {
+ // Calculate the mean square deviations for each delimiter
+ // (ignoring delimiters that haven't been found consistently)
+ $meanSquareDeviations = [];
+ $middleIdx = floor(($this->numberLines - 1) / 2);
+
+ foreach (self::POTENTIAL_DELIMETERS as $delimiter) {
+ $series = $this->counts[$delimiter];
+ sort($series);
+
+ $median = ($this->numberLines % 2)
+ ? $series[$middleIdx]
+ : ($series[$middleIdx] + $series[$middleIdx + 1]) / 2;
+
+ if ($median === 0) {
+ continue;
+ }
+
+ $meanSquareDeviations[$delimiter] = array_reduce(
+ $series,
+ function ($sum, $value) use ($median) {
+ return $sum + ($value - $median) ** 2;
+ }
+ ) / count($series);
+ }
+
+ // ... and pick the delimiter with the smallest mean square deviation
+ // (in case of ties, the order in potentialDelimiters is respected)
+ $min = INF;
+ foreach (self::POTENTIAL_DELIMETERS as $delimiter) {
+ if (!isset($meanSquareDeviations[$delimiter])) {
+ continue;
+ }
+
+ if ($meanSquareDeviations[$delimiter] < $min) {
+ $min = $meanSquareDeviations[$delimiter];
+ $this->delimiter = $delimiter;
+ }
+ }
+
+ return $this->delimiter;
+ }
+
+ /**
+ * Get the next full line from the file.
+ *
+ * @return false|string
+ */
+ public function getNextLine()
+ {
+ $line = '';
+ $enclosure = ($this->escapeCharacter === '' ? ''
+ : ('(?escapeCharacter, '/') . ')'))
+ . preg_quote($this->enclosure, '/');
+
+ do {
+ // Get the next line in the file
+ $newLine = fgets($this->fileHandle);
+
+ // Return false if there is no next line
+ if ($newLine === false) {
+ return false;
+ }
+
+ // Add the new line to the line passed in
+ $line = $line . $newLine;
+
+ // Drop everything that is enclosed to avoid counting false positives in enclosures
+ $line = preg_replace('/(' . $enclosure . '.*' . $enclosure . ')/Us', '', $line);
+
+ // See if we have any enclosures left in the line
+ // if we still have an enclosure then we need to read the next line as well
+ } while (preg_match('/(' . $enclosure . ')/', $line ?? '') > 0);
+
+ return $line ?? false;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/DefaultReadFilter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/DefaultReadFilter.php
index e104186abbb..8fdb162b4c7 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/DefaultReadFilter.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/DefaultReadFilter.php
@@ -7,13 +7,13 @@ class DefaultReadFilter implements IReadFilter
/**
* Should this cell be read?
*
- * @param string $column Column address (as a string value like "A", or "IV")
+ * @param string $columnAddress Column address (as a string value like "A", or "IV")
* @param int $row Row number
* @param string $worksheetName Optional worksheet name
*
* @return bool
*/
- public function readCell($column, $row, $worksheetName = '')
+ public function readCell($columnAddress, $row, $worksheetName = '')
{
return true;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php
index dc921c1e446..9b03cdc9a80 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php
@@ -6,25 +6,33 @@ use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Reader\Gnumeric\PageSetup;
+use PhpOffice\PhpSpreadsheet\Reader\Gnumeric\Properties;
+use PhpOffice\PhpSpreadsheet\Reader\Gnumeric\Styles;
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Settings;
-use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\File;
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\Worksheet\Worksheet;
use SimpleXMLElement;
use XMLReader;
class Gnumeric extends BaseReader
{
- private const UOM_CONVERSION_POINTS_TO_CENTIMETERS = 0.03527777778;
+ const NAMESPACE_GNM = 'http://www.gnumeric.org/v10.dtd'; // gmr in old sheets
+
+ const NAMESPACE_XSI = 'http://www.w3.org/2001/XMLSchema-instance';
+
+ const NAMESPACE_OFFICE = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0';
+
+ const NAMESPACE_XLINK = 'http://www.w3.org/1999/xlink';
+
+ const NAMESPACE_DC = 'http://purl.org/dc/elements/1.1/';
+
+ const NAMESPACE_META = 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0';
+
+ const NAMESPACE_OOO = 'http://openoffice.org/2004/office';
/**
* Shared Expressions.
@@ -40,15 +48,22 @@ class Gnumeric extends BaseReader
*/
private $spreadsheet;
+ /** @var ReferenceHelper */
private $referenceHelper;
- /**
- * Namespace shared across all functions.
- * It is 'gnm', except for really old sheets which use 'gmr'.
- *
- * @var string
- */
- private $gnm = 'gnm';
+ /** @var array */
+ public static $mappings = [
+ 'dataType' => [
+ '10' => DataType::TYPE_NULL,
+ '20' => DataType::TYPE_BOOL,
+ '30' => DataType::TYPE_NUMERIC, // Integer doesn't exist in Excel
+ '40' => DataType::TYPE_NUMERIC, // Float
+ '50' => DataType::TYPE_ERROR,
+ '60' => DataType::TYPE_STRING,
+ //'70': // Cell Range
+ //'80': // Array
+ ],
+ ];
/**
* Create a new Gnumeric.
@@ -62,53 +77,50 @@ class Gnumeric extends BaseReader
/**
* Can the current IReader read the file?
- *
- * @param string $pFilename
- *
- * @return bool
*/
- public function canRead($pFilename)
+ public function canRead(string $filename): bool
{
- File::assertFile($pFilename);
-
// Check if gzlib functions are available
- $data = '';
- if (function_exists('gzread')) {
+ if (File::testFileNoThrow($filename) && function_exists('gzread')) {
// Read signature data (first 3 bytes)
- $fh = fopen($pFilename, 'rb');
- $data = fread($fh, 2);
- fclose($fh);
+ $fh = fopen($filename, 'rb');
+ if ($fh !== false) {
+ $data = fread($fh, 2);
+ fclose($fh);
+ }
}
- return $data == chr(0x1F) . chr(0x8B);
+ return isset($data) && $data === chr(0x1F) . chr(0x8B);
}
- private static function matchXml(string $name, string $field): bool
+ private static function matchXml(XMLReader $xml, string $expectedLocalName): bool
{
- return 1 === preg_match("/^(gnm|gmr):$field$/", $name);
+ return $xml->namespaceURI === self::NAMESPACE_GNM
+ && $xml->localName === $expectedLocalName
+ && $xml->nodeType === XMLReader::ELEMENT;
}
/**
* Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
*
- * @param string $pFilename
+ * @param string $filename
*
* @return array
*/
- public function listWorksheetNames($pFilename)
+ public function listWorksheetNames($filename)
{
- File::assertFile($pFilename);
+ File::assertFile($filename);
$xml = new XMLReader();
- $xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($pFilename)), null, Settings::getLibXmlLoaderOptions());
+ $xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($filename)), null, Settings::getLibXmlLoaderOptions());
$xml->setParserProperty(2, true);
$worksheetNames = [];
while ($xml->read()) {
- if (self::matchXml($xml->name, 'SheetName') && $xml->nodeType == XMLReader::ELEMENT) {
+ if (self::matchXml($xml, 'SheetName')) {
$xml->read(); // Move onto the value node
$worksheetNames[] = (string) $xml->value;
- } elseif (self::matchXml($xml->name, 'Sheets')) {
+ } elseif (self::matchXml($xml, 'Sheets')) {
// break out of the loop once we've got our sheet names rather than parse the entire file
break;
}
@@ -120,21 +132,21 @@ class Gnumeric extends BaseReader
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
- * @param string $pFilename
+ * @param string $filename
*
* @return array
*/
- public function listWorksheetInfo($pFilename)
+ public function listWorksheetInfo($filename)
{
- File::assertFile($pFilename);
+ File::assertFile($filename);
$xml = new XMLReader();
- $xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($pFilename)), null, Settings::getLibXmlLoaderOptions());
+ $xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($filename)), null, Settings::getLibXmlLoaderOptions());
$xml->setParserProperty(2, true);
$worksheetInfo = [];
while ($xml->read()) {
- if (self::matchXml($xml->name, 'Sheet') && $xml->nodeType == XMLReader::ELEMENT) {
+ if (self::matchXml($xml, 'Sheet')) {
$tmpInfo = [
'worksheetName' => '',
'lastColumnLetter' => 'A',
@@ -144,20 +156,18 @@ class Gnumeric extends BaseReader
];
while ($xml->read()) {
- if ($xml->nodeType == XMLReader::ELEMENT) {
- if (self::matchXml($xml->name, 'Name')) {
- $xml->read(); // Move onto the value node
- $tmpInfo['worksheetName'] = (string) $xml->value;
- } elseif (self::matchXml($xml->name, 'MaxCol')) {
- $xml->read(); // Move onto the value node
- $tmpInfo['lastColumnIndex'] = (int) $xml->value;
- $tmpInfo['totalColumns'] = (int) $xml->value + 1;
- } elseif (self::matchXml($xml->name, 'MaxRow')) {
- $xml->read(); // Move onto the value node
- $tmpInfo['totalRows'] = (int) $xml->value + 1;
+ if (self::matchXml($xml, 'Name')) {
+ $xml->read(); // Move onto the value node
+ $tmpInfo['worksheetName'] = (string) $xml->value;
+ } elseif (self::matchXml($xml, 'MaxCol')) {
+ $xml->read(); // Move onto the value node
+ $tmpInfo['lastColumnIndex'] = (int) $xml->value;
+ $tmpInfo['totalColumns'] = (int) $xml->value + 1;
+ } elseif (self::matchXml($xml, 'MaxRow')) {
+ $xml->read(); // Move onto the value node
+ $tmpInfo['totalRows'] = (int) $xml->value + 1;
- break;
- }
+ break;
}
}
$tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
@@ -187,275 +197,72 @@ class Gnumeric extends BaseReader
return $data;
}
- private static $mappings = [
- 'borderStyle' => [
- '0' => Border::BORDER_NONE,
- '1' => Border::BORDER_THIN,
- '2' => Border::BORDER_MEDIUM,
- '3' => Border::BORDER_SLANTDASHDOT,
- '4' => Border::BORDER_DASHED,
- '5' => Border::BORDER_THICK,
- '6' => Border::BORDER_DOUBLE,
- '7' => Border::BORDER_DOTTED,
- '8' => Border::BORDER_MEDIUMDASHED,
- '9' => Border::BORDER_DASHDOT,
- '10' => Border::BORDER_MEDIUMDASHDOT,
- '11' => Border::BORDER_DASHDOTDOT,
- '12' => Border::BORDER_MEDIUMDASHDOTDOT,
- '13' => Border::BORDER_MEDIUMDASHDOTDOT,
- ],
- 'dataType' => [
- '10' => DataType::TYPE_NULL,
- '20' => DataType::TYPE_BOOL,
- '30' => DataType::TYPE_NUMERIC, // Integer doesn't exist in Excel
- '40' => DataType::TYPE_NUMERIC, // Float
- '50' => DataType::TYPE_ERROR,
- '60' => DataType::TYPE_STRING,
- //'70': // Cell Range
- //'80': // Array
- ],
- 'fillType' => [
- '1' => Fill::FILL_SOLID,
- '2' => Fill::FILL_PATTERN_DARKGRAY,
- '3' => Fill::FILL_PATTERN_MEDIUMGRAY,
- '4' => Fill::FILL_PATTERN_LIGHTGRAY,
- '5' => Fill::FILL_PATTERN_GRAY125,
- '6' => Fill::FILL_PATTERN_GRAY0625,
- '7' => Fill::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe
- '8' => Fill::FILL_PATTERN_DARKVERTICAL, // vertical stripe
- '9' => Fill::FILL_PATTERN_DARKDOWN, // diagonal stripe
- '10' => Fill::FILL_PATTERN_DARKUP, // reverse diagonal stripe
- '11' => Fill::FILL_PATTERN_DARKGRID, // diagoanl crosshatch
- '12' => Fill::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch
- '13' => Fill::FILL_PATTERN_LIGHTHORIZONTAL,
- '14' => Fill::FILL_PATTERN_LIGHTVERTICAL,
- '15' => Fill::FILL_PATTERN_LIGHTUP,
- '16' => Fill::FILL_PATTERN_LIGHTDOWN,
- '17' => Fill::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch
- '18' => Fill::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch
- ],
- 'horizontal' => [
- '1' => Alignment::HORIZONTAL_GENERAL,
- '2' => Alignment::HORIZONTAL_LEFT,
- '4' => Alignment::HORIZONTAL_RIGHT,
- '8' => Alignment::HORIZONTAL_CENTER,
- '16' => Alignment::HORIZONTAL_CENTER_CONTINUOUS,
- '32' => Alignment::HORIZONTAL_JUSTIFY,
- '64' => Alignment::HORIZONTAL_CENTER_CONTINUOUS,
- ],
- 'underline' => [
- '1' => Font::UNDERLINE_SINGLE,
- '2' => Font::UNDERLINE_DOUBLE,
- '3' => Font::UNDERLINE_SINGLEACCOUNTING,
- '4' => Font::UNDERLINE_DOUBLEACCOUNTING,
- ],
- 'vertical' => [
- '1' => Alignment::VERTICAL_TOP,
- '2' => Alignment::VERTICAL_BOTTOM,
- '4' => Alignment::VERTICAL_CENTER,
- '8' => Alignment::VERTICAL_JUSTIFY,
- ],
- ];
-
public static function gnumericMappings(): array
{
- return self::$mappings;
- }
-
- private function docPropertiesOld(SimpleXMLElement $gnmXML): void
- {
- $docProps = $this->spreadsheet->getProperties();
- foreach ($gnmXML->Summary->Item as $summaryItem) {
- $propertyName = $summaryItem->name;
- $propertyValue = $summaryItem->{'val-string'};
- switch ($propertyName) {
- case 'title':
- $docProps->setTitle(trim($propertyValue));
-
- break;
- case 'comments':
- $docProps->setDescription(trim($propertyValue));
-
- break;
- case 'keywords':
- $docProps->setKeywords(trim($propertyValue));
-
- break;
- case 'category':
- $docProps->setCategory(trim($propertyValue));
-
- break;
- case 'manager':
- $docProps->setManager(trim($propertyValue));
-
- break;
- case 'author':
- $docProps->setCreator(trim($propertyValue));
- $docProps->setLastModifiedBy(trim($propertyValue));
-
- break;
- case 'company':
- $docProps->setCompany(trim($propertyValue));
-
- break;
- }
- }
- }
-
- private function docPropertiesDC(SimpleXMLElement $officePropertyDC): void
- {
- $docProps = $this->spreadsheet->getProperties();
- foreach ($officePropertyDC as $propertyName => $propertyValue) {
- $propertyValue = trim((string) $propertyValue);
- switch ($propertyName) {
- case 'title':
- $docProps->setTitle($propertyValue);
-
- break;
- case 'subject':
- $docProps->setSubject($propertyValue);
-
- break;
- case 'creator':
- $docProps->setCreator($propertyValue);
- $docProps->setLastModifiedBy($propertyValue);
-
- break;
- case 'date':
- $creationDate = strtotime($propertyValue);
- $docProps->setCreated($creationDate);
- $docProps->setModified($creationDate);
-
- break;
- case 'description':
- $docProps->setDescription($propertyValue);
-
- break;
- }
- }
- }
-
- private function docPropertiesMeta(SimpleXMLElement $officePropertyMeta, array $namespacesMeta): void
- {
- $docProps = $this->spreadsheet->getProperties();
- foreach ($officePropertyMeta as $propertyName => $propertyValue) {
- $attributes = $propertyValue->attributes($namespacesMeta['meta']);
- $propertyValue = trim((string) $propertyValue);
- switch ($propertyName) {
- case 'keyword':
- $docProps->setKeywords($propertyValue);
-
- break;
- case 'initial-creator':
- $docProps->setCreator($propertyValue);
- $docProps->setLastModifiedBy($propertyValue);
-
- break;
- case 'creation-date':
- $creationDate = strtotime($propertyValue);
- $docProps->setCreated($creationDate);
- $docProps->setModified($creationDate);
-
- break;
- case 'user-defined':
- [, $attrName] = explode(':', $attributes['name']);
- switch ($attrName) {
- case 'publisher':
- $docProps->setCompany($propertyValue);
-
- break;
- case 'category':
- $docProps->setCategory($propertyValue);
-
- break;
- case 'manager':
- $docProps->setManager($propertyValue);
-
- break;
- }
-
- break;
- }
- }
- }
-
- private function docProperties(SimpleXMLElement $xml, SimpleXMLElement $gnmXML, array $namespacesMeta): void
- {
- if (isset($namespacesMeta['office'])) {
- $officeXML = $xml->children($namespacesMeta['office']);
- $officeDocXML = $officeXML->{'document-meta'};
- $officeDocMetaXML = $officeDocXML->meta;
-
- foreach ($officeDocMetaXML as $officePropertyData) {
- $officePropertyDC = [];
- if (isset($namespacesMeta['dc'])) {
- $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']);
- }
- $this->docPropertiesDC($officePropertyDC);
-
- $officePropertyMeta = [];
- if (isset($namespacesMeta['meta'])) {
- $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
- }
- $this->docPropertiesMeta($officePropertyMeta, $namespacesMeta);
- }
- } elseif (isset($gnmXML->Summary)) {
- $this->docPropertiesOld($gnmXML);
- }
+ return array_merge(self::$mappings, Styles::$mappings);
}
private function processComments(SimpleXMLElement $sheet): void
{
if ((!$this->readDataOnly) && (isset($sheet->Objects))) {
- foreach ($sheet->Objects->children($this->gnm, true) as $key => $comment) {
+ foreach ($sheet->Objects->children(self::NAMESPACE_GNM) as $key => $comment) {
$commentAttributes = $comment->attributes();
// Only comment objects are handled at the moment
- if ($commentAttributes->Text) {
- $this->spreadsheet->getActiveSheet()->getComment((string) $commentAttributes->ObjectBound)->setAuthor((string) $commentAttributes->Author)->setText($this->parseRichText((string) $commentAttributes->Text));
+ if ($commentAttributes && $commentAttributes->Text) {
+ $this->spreadsheet->getActiveSheet()->getComment((string) $commentAttributes->ObjectBound)
+ ->setAuthor((string) $commentAttributes->Author)
+ ->setText($this->parseRichText((string) $commentAttributes->Text));
}
}
}
}
+ /**
+ * @param mixed $value
+ */
+ private static function testSimpleXml($value): SimpleXMLElement
+ {
+ return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement('');
+ }
+
/**
* Loads Spreadsheet from file.
*
- * @param string $pFilename
- *
* @return Spreadsheet
*/
- public function load($pFilename)
+ public function load(string $filename, int $flags = 0)
{
+ $this->processFlags($flags);
+
// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
$spreadsheet->removeSheetByIndex(0);
// Load into this instance
- return $this->loadIntoExisting($pFilename, $spreadsheet);
+ return $this->loadIntoExisting($filename, $spreadsheet);
}
/**
* Loads from file into Spreadsheet instance.
*/
- public function loadIntoExisting(string $pFilename, Spreadsheet $spreadsheet): Spreadsheet
+ public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet
{
$this->spreadsheet = $spreadsheet;
- File::assertFile($pFilename);
+ File::assertFile($filename);
- $gFileData = $this->gzfileGetContents($pFilename);
+ $gFileData = $this->gzfileGetContents($filename);
$xml2 = simplexml_load_string($this->securityScanner->scan($gFileData), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions());
- $xml = ($xml2 !== false) ? $xml2 : new SimpleXMLElement('');
- $namespacesMeta = $xml->getNamespaces(true);
- $this->gnm = array_key_exists('gmr', $namespacesMeta) ? 'gmr' : 'gnm';
+ $xml = self::testSimpleXml($xml2);
- $gnmXML = $xml->children($namespacesMeta[$this->gnm]);
- $this->docProperties($xml, $gnmXML, $namespacesMeta);
+ $gnmXML = $xml->children(self::NAMESPACE_GNM);
+ (new Properties($this->spreadsheet))->readProperties($xml, $gnmXML);
$worksheetID = 0;
- foreach ($gnmXML->Sheets->Sheet as $sheet) {
+ foreach ($gnmXML->Sheets->Sheet as $sheetOrNull) {
+ $sheet = self::testSimpleXml($sheetOrNull);
$worksheetName = (string) $sheet->Name;
- if ((isset($this->loadSheetsOnly)) && (!in_array($worksheetName, $this->loadSheetsOnly))) {
+ if (is_array($this->loadSheetsOnly) && !in_array($worksheetName, $this->loadSheetsOnly, true)) {
continue;
}
@@ -470,13 +277,14 @@ class Gnumeric extends BaseReader
$this->spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false);
if (!$this->readDataOnly) {
- (new PageSetup($this->spreadsheet, $this->gnm))
+ (new PageSetup($this->spreadsheet))
->printInformation($sheet)
->sheetMargins($sheet);
}
- foreach ($sheet->Cells->Cell as $cell) {
- $cellAttributes = $cell->attributes();
+ foreach ($sheet->Cells->Cell as $cellOrNull) {
+ $cell = self::testSimpleXml($cellOrNull);
+ $cellAttributes = self::testSimpleXml($cell->attributes());
$row = (int) $cellAttributes->Row + 1;
$column = (int) $cellAttributes->Col;
@@ -523,90 +331,22 @@ class Gnumeric extends BaseReader
if (array_key_exists($vtype, self::$mappings['dataType'])) {
$type = self::$mappings['dataType'][$vtype];
}
- if ($vtype == '20') { // Boolean
+ if ($vtype === '20') { // Boolean
$cell = $cell == 'TRUE';
}
}
$this->spreadsheet->getActiveSheet()->getCell($column . $row)->setValueExplicit((string) $cell, $type);
}
- $this->processComments($sheet);
-
- foreach ($sheet->Styles->StyleRegion as $styleRegion) {
- $styleAttributes = $styleRegion->attributes();
- if (
- ($styleAttributes['startRow'] <= $maxRow) &&
- ($styleAttributes['startCol'] <= $maxCol)
- ) {
- $startColumn = Coordinate::stringFromColumnIndex((int) $styleAttributes['startCol'] + 1);
- $startRow = $styleAttributes['startRow'] + 1;
-
- $endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol'];
- $endColumn = Coordinate::stringFromColumnIndex($endColumn + 1);
-
- $endRow = 1 + (($styleAttributes['endRow'] > $maxRow) ? $maxRow : (int) $styleAttributes['endRow']);
- $cellRange = $startColumn . $startRow . ':' . $endColumn . $endRow;
-
- $styleAttributes = $styleRegion->Style->attributes();
-
- $styleArray = [];
- // We still set the number format mask for date/time values, even if readDataOnly is true
- $formatCode = (string) $styleAttributes['Format'];
- if (Date::isDateTimeFormatCode($formatCode)) {
- $styleArray['numberFormat']['formatCode'] = $formatCode;
- }
- if (!$this->readDataOnly) {
- // If readDataOnly is false, we set all formatting information
- $styleArray['numberFormat']['formatCode'] = $formatCode;
-
- self::addStyle2($styleArray, 'alignment', 'horizontal', $styleAttributes['HAlign']);
- self::addStyle2($styleArray, 'alignment', 'vertical', $styleAttributes['VAlign']);
- $styleArray['alignment']['wrapText'] = $styleAttributes['WrapText'] == '1';
- $styleArray['alignment']['textRotation'] = $this->calcRotation($styleAttributes);
- $styleArray['alignment']['shrinkToFit'] = $styleAttributes['ShrinkToFit'] == '1';
- $styleArray['alignment']['indent'] = ((int) ($styleAttributes['Indent']) > 0) ? $styleAttributes['indent'] : 0;
-
- $this->addColors($styleArray, $styleAttributes);
-
- $fontAttributes = $styleRegion->Style->Font->attributes();
- $styleArray['font']['name'] = (string) $styleRegion->Style->Font;
- $styleArray['font']['size'] = (int) ($fontAttributes['Unit']);
- $styleArray['font']['bold'] = $fontAttributes['Bold'] == '1';
- $styleArray['font']['italic'] = $fontAttributes['Italic'] == '1';
- $styleArray['font']['strikethrough'] = $fontAttributes['StrikeThrough'] == '1';
- self::addStyle2($styleArray, 'font', 'underline', $fontAttributes['Underline']);
-
- switch ($fontAttributes['Script']) {
- case '1':
- $styleArray['font']['superscript'] = true;
-
- break;
- case '-1':
- $styleArray['font']['subscript'] = true;
-
- break;
- }
-
- if (isset($styleRegion->Style->StyleBorder)) {
- $srssb = $styleRegion->Style->StyleBorder;
- $this->addBorderStyle($srssb, $styleArray, 'top');
- $this->addBorderStyle($srssb, $styleArray, 'bottom');
- $this->addBorderStyle($srssb, $styleArray, 'left');
- $this->addBorderStyle($srssb, $styleArray, 'right');
- $this->addBorderDiagonal($srssb, $styleArray);
- }
- if (isset($styleRegion->Style->HyperLink)) {
- // TO DO
- $hyperlink = $styleRegion->Style->HyperLink->attributes();
- }
- }
- $this->spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray);
- }
+ if ($sheet->Styles !== null) {
+ (new Styles($this->spreadsheet, $this->readDataOnly))->read($sheet, $maxRow, $maxCol);
}
+ $this->processComments($sheet);
$this->processColumnWidths($sheet, $maxCol);
$this->processRowHeights($sheet, $maxRow);
$this->processMergedCells($sheet);
+ $this->processAutofilter($sheet);
++$worksheetID;
}
@@ -617,126 +357,158 @@ class Gnumeric extends BaseReader
return $this->spreadsheet;
}
- private function addBorderDiagonal(SimpleXMLElement $srssb, array &$styleArray): void
- {
- if (isset($srssb->Diagonal, $srssb->{'Rev-Diagonal'})) {
- $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes());
- $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_BOTH;
- } elseif (isset($srssb->Diagonal)) {
- $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes());
- $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_UP;
- } elseif (isset($srssb->{'Rev-Diagonal'})) {
- $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->{'Rev-Diagonal'}->attributes());
- $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_DOWN;
- }
- }
-
- private function addBorderStyle(SimpleXMLElement $srssb, array &$styleArray, string $direction): void
- {
- $ucDirection = ucfirst($direction);
- if (isset($srssb->$ucDirection)) {
- $styleArray['borders'][$direction] = self::parseBorderAttributes($srssb->$ucDirection->attributes());
- }
- }
-
- private function processMergedCells(SimpleXMLElement $sheet): void
+ private function processMergedCells(?SimpleXMLElement $sheet): void
{
// Handle Merged Cells in this worksheet
- if (isset($sheet->MergedRegions)) {
+ if ($sheet !== null && isset($sheet->MergedRegions)) {
foreach ($sheet->MergedRegions->Merge as $mergeCells) {
- if (strpos($mergeCells, ':') !== false) {
+ if (strpos((string) $mergeCells, ':') !== false) {
$this->spreadsheet->getActiveSheet()->mergeCells($mergeCells);
}
}
}
}
- private function processColumnLoop(int $c, int $maxCol, SimpleXMLElement $columnOverride, float $defaultWidth): int
+ private function processAutofilter(?SimpleXMLElement $sheet): void
{
- $columnAttributes = $columnOverride->attributes();
+ if ($sheet !== null && isset($sheet->Filters)) {
+ foreach ($sheet->Filters->Filter as $autofilter) {
+ if ($autofilter !== null) {
+ $attributes = $autofilter->attributes();
+ if (isset($attributes['Area'])) {
+ $this->spreadsheet->getActiveSheet()->setAutoFilter((string) $attributes['Area']);
+ }
+ }
+ }
+ }
+ }
+
+ private function setColumnWidth(int $whichColumn, float $defaultWidth): void
+ {
+ $columnDimension = $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($whichColumn + 1));
+ if ($columnDimension !== null) {
+ $columnDimension->setWidth($defaultWidth);
+ }
+ }
+
+ private function setColumnInvisible(int $whichColumn): void
+ {
+ $columnDimension = $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($whichColumn + 1));
+ if ($columnDimension !== null) {
+ $columnDimension->setVisible(false);
+ }
+ }
+
+ private function processColumnLoop(int $whichColumn, int $maxCol, ?SimpleXMLElement $columnOverride, float $defaultWidth): int
+ {
+ $columnOverride = self::testSimpleXml($columnOverride);
+ $columnAttributes = self::testSimpleXml($columnOverride->attributes());
$column = $columnAttributes['No'];
$columnWidth = ((float) $columnAttributes['Unit']) / 5.4;
$hidden = (isset($columnAttributes['Hidden'])) && ((string) $columnAttributes['Hidden'] == '1');
- $columnCount = (isset($columnAttributes['Count'])) ? $columnAttributes['Count'] : 1;
- while ($c < $column) {
- $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($defaultWidth);
- ++$c;
+ $columnCount = (int) ($columnAttributes['Count'] ?? 1);
+ while ($whichColumn < $column) {
+ $this->setColumnWidth($whichColumn, $defaultWidth);
+ ++$whichColumn;
}
- while (($c < ($column + $columnCount)) && ($c <= $maxCol)) {
- $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($columnWidth);
+ while (($whichColumn < ($column + $columnCount)) && ($whichColumn <= $maxCol)) {
+ $this->setColumnWidth($whichColumn, $columnWidth);
if ($hidden) {
- $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setVisible(false);
+ $this->setColumnInvisible($whichColumn);
}
- ++$c;
+ ++$whichColumn;
}
- return $c;
+ return $whichColumn;
}
- private function processColumnWidths(SimpleXMLElement $sheet, int $maxCol): void
+ private function processColumnWidths(?SimpleXMLElement $sheet, int $maxCol): void
{
- if ((!$this->readDataOnly) && (isset($sheet->Cols))) {
+ if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Cols))) {
// Column Widths
+ $defaultWidth = 0;
$columnAttributes = $sheet->Cols->attributes();
- $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4;
- $c = 0;
- foreach ($sheet->Cols->ColInfo as $columnOverride) {
- $c = $this->processColumnLoop($c, $maxCol, $columnOverride, $defaultWidth);
+ if ($columnAttributes !== null) {
+ $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4;
}
- while ($c <= $maxCol) {
- $this->spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($defaultWidth);
- ++$c;
+ $whichColumn = 0;
+ foreach ($sheet->Cols->ColInfo as $columnOverride) {
+ $whichColumn = $this->processColumnLoop($whichColumn, $maxCol, $columnOverride, $defaultWidth);
+ }
+ while ($whichColumn <= $maxCol) {
+ $this->setColumnWidth($whichColumn, $defaultWidth);
+ ++$whichColumn;
}
}
}
- private function processRowLoop(int $r, int $maxRow, SimpleXMLElement $rowOverride, float $defaultHeight): int
+ private function setRowHeight(int $whichRow, float $defaultHeight): void
{
- $rowAttributes = $rowOverride->attributes();
+ $rowDimension = $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow);
+ if ($rowDimension !== null) {
+ $rowDimension->setRowHeight($defaultHeight);
+ }
+ }
+
+ private function setRowInvisible(int $whichRow): void
+ {
+ $rowDimension = $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow);
+ if ($rowDimension !== null) {
+ $rowDimension->setVisible(false);
+ }
+ }
+
+ private function processRowLoop(int $whichRow, int $maxRow, ?SimpleXMLElement $rowOverride, float $defaultHeight): int
+ {
+ $rowOverride = self::testSimpleXml($rowOverride);
+ $rowAttributes = self::testSimpleXml($rowOverride->attributes());
$row = $rowAttributes['No'];
$rowHeight = (float) $rowAttributes['Unit'];
$hidden = (isset($rowAttributes['Hidden'])) && ((string) $rowAttributes['Hidden'] == '1');
- $rowCount = (isset($rowAttributes['Count'])) ? $rowAttributes['Count'] : 1;
- while ($r < $row) {
- ++$r;
- $this->spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight);
+ $rowCount = (int) ($rowAttributes['Count'] ?? 1);
+ while ($whichRow < $row) {
+ ++$whichRow;
+ $this->setRowHeight($whichRow, $defaultHeight);
}
- while (($r < ($row + $rowCount)) && ($r < $maxRow)) {
- ++$r;
- $this->spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($rowHeight);
+ while (($whichRow < ($row + $rowCount)) && ($whichRow < $maxRow)) {
+ ++$whichRow;
+ $this->setRowHeight($whichRow, $rowHeight);
if ($hidden) {
- $this->spreadsheet->getActiveSheet()->getRowDimension($r)->setVisible(false);
+ $this->setRowInvisible($whichRow);
}
}
- return $r;
+ return $whichRow;
}
- private function processRowHeights(SimpleXMLElement $sheet, int $maxRow): void
+ private function processRowHeights(?SimpleXMLElement $sheet, int $maxRow): void
{
- if ((!$this->readDataOnly) && (isset($sheet->Rows))) {
+ if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Rows))) {
// Row Heights
+ $defaultHeight = 0;
$rowAttributes = $sheet->Rows->attributes();
- $defaultHeight = (float) $rowAttributes['DefaultSizePts'];
- $r = 0;
+ if ($rowAttributes !== null) {
+ $defaultHeight = (float) $rowAttributes['DefaultSizePts'];
+ }
+ $whichRow = 0;
foreach ($sheet->Rows->RowInfo as $rowOverride) {
- $r = $this->processRowLoop($r, $maxRow, $rowOverride, $defaultHeight);
+ $whichRow = $this->processRowLoop($whichRow, $maxRow, $rowOverride, $defaultHeight);
}
// never executed, I can't figure out any circumstances
// under which it would be executed, and, even if
// such exist, I'm not convinced this is needed.
- //while ($r < $maxRow) {
- // ++$r;
- // $this->spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight);
+ //while ($whichRow < $maxRow) {
+ // ++$whichRow;
+ // $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow)->setRowHeight($defaultHeight);
//}
}
}
- private function processDefinedNames(SimpleXMLElement $gnmXML): void
+ private function processDefinedNames(?SimpleXMLElement $gnmXML): void
{
// Loop through definedNames (global named ranges)
- if (isset($gnmXML->Names)) {
+ if ($gnmXML !== null && isset($gnmXML->Names)) {
foreach ($gnmXML->Names->Name as $definedName) {
$name = (string) $definedName->name;
$value = (string) $definedName->value;
@@ -755,77 +527,11 @@ class Gnumeric extends BaseReader
}
}
- private function calcRotation(SimpleXMLElement $styleAttributes): int
- {
- $rotation = (int) $styleAttributes->Rotation;
- if ($rotation >= 270 && $rotation <= 360) {
- $rotation -= 360;
- }
- $rotation = (abs($rotation) > 90) ? 0 : $rotation;
-
- return $rotation;
- }
-
- private static function addStyle(array &$styleArray, string $key, string $value): void
- {
- if (array_key_exists($value, self::$mappings[$key])) {
- $styleArray[$key] = self::$mappings[$key][$value];
- }
- }
-
- private static function addStyle2(array &$styleArray, string $key1, string $key, string $value): void
- {
- if (array_key_exists($value, self::$mappings[$key])) {
- $styleArray[$key1][$key] = self::$mappings[$key][$value];
- }
- }
-
- private static function parseBorderAttributes($borderAttributes)
- {
- $styleArray = [];
- if (isset($borderAttributes['Color'])) {
- $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']);
- }
-
- self::addStyle($styleArray, 'borderStyle', $borderAttributes['Style']);
-
- return $styleArray;
- }
-
- private function parseRichText($is)
+ private function parseRichText(string $is): RichText
{
$value = new RichText();
$value->createText($is);
return $value;
}
-
- private static function parseGnumericColour($gnmColour)
- {
- [$gnmR, $gnmG, $gnmB] = explode(':', $gnmColour);
- $gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2);
- $gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2);
- $gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2);
-
- return $gnmR . $gnmG . $gnmB;
- }
-
- private function addColors(array &$styleArray, SimpleXMLElement $styleAttributes): void
- {
- $RGB = self::parseGnumericColour($styleAttributes['Fore']);
- $styleArray['font']['color']['rgb'] = $RGB;
- $RGB = self::parseGnumericColour($styleAttributes['Back']);
- $shade = (string) $styleAttributes['Shade'];
- if (($RGB != '000000') || ($shade != '0')) {
- $RGB2 = self::parseGnumericColour($styleAttributes['PatternColor']);
- if ($shade == '1') {
- $styleArray['fill']['startColor']['rgb'] = $RGB;
- $styleArray['fill']['endColor']['rgb'] = $RGB2;
- } else {
- $styleArray['fill']['endColor']['rgb'] = $RGB;
- $styleArray['fill']['startColor']['rgb'] = $RGB2;
- }
- self::addStyle2($styleArray, 'fill', 'fillType', $shade);
- }
- }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php
index 0fe73005939..5b501e0fa7c 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php
@@ -2,6 +2,7 @@
namespace PhpOffice\PhpSpreadsheet\Reader\Gnumeric;
+use PhpOffice\PhpSpreadsheet\Reader\Gnumeric;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageMargins;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup as WorksheetPageSetup;
@@ -14,21 +15,19 @@ class PageSetup
*/
private $spreadsheet;
- /**
- * @var string
- */
- private $gnm;
-
- public function __construct(Spreadsheet $spreadsheet, string $gnm)
+ public function __construct(Spreadsheet $spreadsheet)
{
$this->spreadsheet = $spreadsheet;
- $this->gnm = $gnm;
}
public function printInformation(SimpleXMLElement $sheet): self
{
if (isset($sheet->PrintInformation)) {
$printInformation = $sheet->PrintInformation[0];
+ if (!$printInformation) {
+ return $this;
+ }
+
$scale = (string) $printInformation->Scale->attributes()['percentage'];
$pageOrder = (string) $printInformation->order;
$orientation = (string) $printInformation->orientation;
@@ -68,7 +67,7 @@ class PageSetup
private function buildMarginSet(SimpleXMLElement $sheet, array $marginSet): array
{
- foreach ($sheet->PrintInformation->Margins->children($this->gnm, true) as $key => $margin) {
+ foreach ($sheet->PrintInformation->Margins->children(Gnumeric::NAMESPACE_GNM) as $key => $margin) {
$marginAttributes = $margin->attributes();
$marginSize = ($marginAttributes['Points']) ?? 72; // Default is 72pt
// Convert value in points to inches
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php
new file mode 100644
index 00000000000..23d4067b9d0
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php
@@ -0,0 +1,164 @@
+spreadsheet = $spreadsheet;
+ }
+
+ private function docPropertiesOld(SimpleXMLElement $gnmXML): void
+ {
+ $docProps = $this->spreadsheet->getProperties();
+ foreach ($gnmXML->Summary->Item as $summaryItem) {
+ $propertyName = $summaryItem->name;
+ $propertyValue = $summaryItem->{'val-string'};
+ switch ($propertyName) {
+ case 'title':
+ $docProps->setTitle(trim($propertyValue));
+
+ break;
+ case 'comments':
+ $docProps->setDescription(trim($propertyValue));
+
+ break;
+ case 'keywords':
+ $docProps->setKeywords(trim($propertyValue));
+
+ break;
+ case 'category':
+ $docProps->setCategory(trim($propertyValue));
+
+ break;
+ case 'manager':
+ $docProps->setManager(trim($propertyValue));
+
+ break;
+ case 'author':
+ $docProps->setCreator(trim($propertyValue));
+ $docProps->setLastModifiedBy(trim($propertyValue));
+
+ break;
+ case 'company':
+ $docProps->setCompany(trim($propertyValue));
+
+ break;
+ }
+ }
+ }
+
+ private function docPropertiesDC(SimpleXMLElement $officePropertyDC): void
+ {
+ $docProps = $this->spreadsheet->getProperties();
+ foreach ($officePropertyDC as $propertyName => $propertyValue) {
+ $propertyValue = trim((string) $propertyValue);
+ switch ($propertyName) {
+ case 'title':
+ $docProps->setTitle($propertyValue);
+
+ break;
+ case 'subject':
+ $docProps->setSubject($propertyValue);
+
+ break;
+ case 'creator':
+ $docProps->setCreator($propertyValue);
+ $docProps->setLastModifiedBy($propertyValue);
+
+ break;
+ case 'date':
+ $creationDate = $propertyValue;
+ $docProps->setModified($creationDate);
+
+ break;
+ case 'description':
+ $docProps->setDescription($propertyValue);
+
+ break;
+ }
+ }
+ }
+
+ private function docPropertiesMeta(SimpleXMLElement $officePropertyMeta): void
+ {
+ $docProps = $this->spreadsheet->getProperties();
+ foreach ($officePropertyMeta as $propertyName => $propertyValue) {
+ if ($propertyValue !== null) {
+ $attributes = $propertyValue->attributes(Gnumeric::NAMESPACE_META);
+ $propertyValue = trim((string) $propertyValue);
+ switch ($propertyName) {
+ case 'keyword':
+ $docProps->setKeywords($propertyValue);
+
+ break;
+ case 'initial-creator':
+ $docProps->setCreator($propertyValue);
+ $docProps->setLastModifiedBy($propertyValue);
+
+ break;
+ case 'creation-date':
+ $creationDate = $propertyValue;
+ $docProps->setCreated($creationDate);
+
+ break;
+ case 'user-defined':
+ if ($attributes) {
+ [, $attrName] = explode(':', (string) $attributes['name']);
+ $this->userDefinedProperties($attrName, $propertyValue);
+ }
+
+ break;
+ }
+ }
+ }
+ }
+
+ private function userDefinedProperties(string $attrName, string $propertyValue): void
+ {
+ $docProps = $this->spreadsheet->getProperties();
+ switch ($attrName) {
+ case 'publisher':
+ $docProps->setCompany($propertyValue);
+
+ break;
+ case 'category':
+ $docProps->setCategory($propertyValue);
+
+ break;
+ case 'manager':
+ $docProps->setManager($propertyValue);
+
+ break;
+ }
+ }
+
+ public function readProperties(SimpleXMLElement $xml, SimpleXMLElement $gnmXML): void
+ {
+ $officeXML = $xml->children(Gnumeric::NAMESPACE_OFFICE);
+ if (!empty($officeXML)) {
+ $officeDocXML = $officeXML->{'document-meta'};
+ $officeDocMetaXML = $officeDocXML->meta;
+
+ foreach ($officeDocMetaXML as $officePropertyData) {
+ $officePropertyDC = $officePropertyData->children(Gnumeric::NAMESPACE_DC);
+ $this->docPropertiesDC($officePropertyDC);
+
+ $officePropertyMeta = $officePropertyData->children(Gnumeric::NAMESPACE_META);
+ $this->docPropertiesMeta($officePropertyMeta);
+ }
+ } elseif (isset($gnmXML->Summary)) {
+ $this->docPropertiesOld($gnmXML);
+ }
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php
new file mode 100644
index 00000000000..e2e9d561c49
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php
@@ -0,0 +1,278 @@
+ [
+ '0' => Border::BORDER_NONE,
+ '1' => Border::BORDER_THIN,
+ '2' => Border::BORDER_MEDIUM,
+ '3' => Border::BORDER_SLANTDASHDOT,
+ '4' => Border::BORDER_DASHED,
+ '5' => Border::BORDER_THICK,
+ '6' => Border::BORDER_DOUBLE,
+ '7' => Border::BORDER_DOTTED,
+ '8' => Border::BORDER_MEDIUMDASHED,
+ '9' => Border::BORDER_DASHDOT,
+ '10' => Border::BORDER_MEDIUMDASHDOT,
+ '11' => Border::BORDER_DASHDOTDOT,
+ '12' => Border::BORDER_MEDIUMDASHDOTDOT,
+ '13' => Border::BORDER_MEDIUMDASHDOTDOT,
+ ],
+ 'fillType' => [
+ '1' => Fill::FILL_SOLID,
+ '2' => Fill::FILL_PATTERN_DARKGRAY,
+ '3' => Fill::FILL_PATTERN_MEDIUMGRAY,
+ '4' => Fill::FILL_PATTERN_LIGHTGRAY,
+ '5' => Fill::FILL_PATTERN_GRAY125,
+ '6' => Fill::FILL_PATTERN_GRAY0625,
+ '7' => Fill::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe
+ '8' => Fill::FILL_PATTERN_DARKVERTICAL, // vertical stripe
+ '9' => Fill::FILL_PATTERN_DARKDOWN, // diagonal stripe
+ '10' => Fill::FILL_PATTERN_DARKUP, // reverse diagonal stripe
+ '11' => Fill::FILL_PATTERN_DARKGRID, // diagoanl crosshatch
+ '12' => Fill::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch
+ '13' => Fill::FILL_PATTERN_LIGHTHORIZONTAL,
+ '14' => Fill::FILL_PATTERN_LIGHTVERTICAL,
+ '15' => Fill::FILL_PATTERN_LIGHTUP,
+ '16' => Fill::FILL_PATTERN_LIGHTDOWN,
+ '17' => Fill::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch
+ '18' => Fill::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch
+ ],
+ 'horizontal' => [
+ '1' => Alignment::HORIZONTAL_GENERAL,
+ '2' => Alignment::HORIZONTAL_LEFT,
+ '4' => Alignment::HORIZONTAL_RIGHT,
+ '8' => Alignment::HORIZONTAL_CENTER,
+ '16' => Alignment::HORIZONTAL_CENTER_CONTINUOUS,
+ '32' => Alignment::HORIZONTAL_JUSTIFY,
+ '64' => Alignment::HORIZONTAL_CENTER_CONTINUOUS,
+ ],
+ 'underline' => [
+ '1' => Font::UNDERLINE_SINGLE,
+ '2' => Font::UNDERLINE_DOUBLE,
+ '3' => Font::UNDERLINE_SINGLEACCOUNTING,
+ '4' => Font::UNDERLINE_DOUBLEACCOUNTING,
+ ],
+ 'vertical' => [
+ '1' => Alignment::VERTICAL_TOP,
+ '2' => Alignment::VERTICAL_BOTTOM,
+ '4' => Alignment::VERTICAL_CENTER,
+ '8' => Alignment::VERTICAL_JUSTIFY,
+ ],
+ ];
+
+ public function __construct(Spreadsheet $spreadsheet, bool $readDataOnly)
+ {
+ $this->spreadsheet = $spreadsheet;
+ $this->readDataOnly = $readDataOnly;
+ }
+
+ public function read(SimpleXMLElement $sheet, int $maxRow, int $maxCol): void
+ {
+ if ($sheet->Styles->StyleRegion !== null) {
+ $this->readStyles($sheet->Styles->StyleRegion, $maxRow, $maxCol);
+ }
+ }
+
+ private function readStyles(SimpleXMLElement $styleRegion, int $maxRow, int $maxCol): void
+ {
+ foreach ($styleRegion as $style) {
+ $styleAttributes = $style->attributes();
+ if ($styleAttributes !== null && ($styleAttributes['startRow'] <= $maxRow) && ($styleAttributes['startCol'] <= $maxCol)) {
+ $cellRange = $this->readStyleRange($styleAttributes, $maxCol, $maxRow);
+
+ $styleAttributes = $style->Style->attributes();
+
+ $styleArray = [];
+ // We still set the number format mask for date/time values, even if readDataOnly is true
+ // so that we can identify whether a float is a float or a date value
+ $formatCode = $styleAttributes ? (string) $styleAttributes['Format'] : null;
+ if ($formatCode && Date::isDateTimeFormatCode($formatCode)) {
+ $styleArray['numberFormat']['formatCode'] = $formatCode;
+ }
+ if ($this->readDataOnly === false && $styleAttributes !== null) {
+ // If readDataOnly is false, we set all formatting information
+ $styleArray['numberFormat']['formatCode'] = $formatCode;
+ $styleArray = $this->readStyle($styleArray, $styleAttributes, $style);
+ }
+ $this->spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray);
+ }
+ }
+ }
+
+ private function addBorderDiagonal(SimpleXMLElement $srssb, array &$styleArray): void
+ {
+ if (isset($srssb->Diagonal, $srssb->{'Rev-Diagonal'})) {
+ $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes());
+ $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_BOTH;
+ } elseif (isset($srssb->Diagonal)) {
+ $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes());
+ $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_UP;
+ } elseif (isset($srssb->{'Rev-Diagonal'})) {
+ $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->{'Rev-Diagonal'}->attributes());
+ $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_DOWN;
+ }
+ }
+
+ private function addBorderStyle(SimpleXMLElement $srssb, array &$styleArray, string $direction): void
+ {
+ $ucDirection = ucfirst($direction);
+ if (isset($srssb->$ucDirection)) {
+ $styleArray['borders'][$direction] = self::parseBorderAttributes($srssb->$ucDirection->attributes());
+ }
+ }
+
+ private function calcRotation(SimpleXMLElement $styleAttributes): int
+ {
+ $rotation = (int) $styleAttributes->Rotation;
+ if ($rotation >= 270 && $rotation <= 360) {
+ $rotation -= 360;
+ }
+ $rotation = (abs($rotation) > 90) ? 0 : $rotation;
+
+ return $rotation;
+ }
+
+ private static function addStyle(array &$styleArray, string $key, string $value): void
+ {
+ if (array_key_exists($value, self::$mappings[$key])) {
+ $styleArray[$key] = self::$mappings[$key][$value];
+ }
+ }
+
+ private static function addStyle2(array &$styleArray, string $key1, string $key, string $value): void
+ {
+ if (array_key_exists($value, self::$mappings[$key])) {
+ $styleArray[$key1][$key] = self::$mappings[$key][$value];
+ }
+ }
+
+ private static function parseBorderAttributes(?SimpleXMLElement $borderAttributes): array
+ {
+ $styleArray = [];
+ if ($borderAttributes !== null) {
+ if (isset($borderAttributes['Color'])) {
+ $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']);
+ }
+
+ self::addStyle($styleArray, 'borderStyle', (string) $borderAttributes['Style']);
+ }
+
+ return $styleArray;
+ }
+
+ private static function parseGnumericColour(string $gnmColour): string
+ {
+ [$gnmR, $gnmG, $gnmB] = explode(':', $gnmColour);
+ $gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2);
+ $gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2);
+ $gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2);
+
+ return $gnmR . $gnmG . $gnmB;
+ }
+
+ private function addColors(array &$styleArray, SimpleXMLElement $styleAttributes): void
+ {
+ $RGB = self::parseGnumericColour((string) $styleAttributes['Fore']);
+ $styleArray['font']['color']['rgb'] = $RGB;
+ $RGB = self::parseGnumericColour((string) $styleAttributes['Back']);
+ $shade = (string) $styleAttributes['Shade'];
+ if (($RGB !== '000000') || ($shade !== '0')) {
+ $RGB2 = self::parseGnumericColour((string) $styleAttributes['PatternColor']);
+ if ($shade === '1') {
+ $styleArray['fill']['startColor']['rgb'] = $RGB;
+ $styleArray['fill']['endColor']['rgb'] = $RGB2;
+ } else {
+ $styleArray['fill']['endColor']['rgb'] = $RGB;
+ $styleArray['fill']['startColor']['rgb'] = $RGB2;
+ }
+ self::addStyle2($styleArray, 'fill', 'fillType', $shade);
+ }
+ }
+
+ private function readStyleRange(SimpleXMLElement $styleAttributes, int $maxCol, int $maxRow): string
+ {
+ $startColumn = Coordinate::stringFromColumnIndex((int) $styleAttributes['startCol'] + 1);
+ $startRow = $styleAttributes['startRow'] + 1;
+
+ $endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol'];
+ $endColumn = Coordinate::stringFromColumnIndex($endColumn + 1);
+
+ $endRow = 1 + (($styleAttributes['endRow'] > $maxRow) ? $maxRow : (int) $styleAttributes['endRow']);
+ $cellRange = $startColumn . $startRow . ':' . $endColumn . $endRow;
+
+ return $cellRange;
+ }
+
+ private function readStyle(array $styleArray, SimpleXMLElement $styleAttributes, SimpleXMLElement $style): array
+ {
+ self::addStyle2($styleArray, 'alignment', 'horizontal', (string) $styleAttributes['HAlign']);
+ self::addStyle2($styleArray, 'alignment', 'vertical', (string) $styleAttributes['VAlign']);
+ $styleArray['alignment']['wrapText'] = $styleAttributes['WrapText'] == '1';
+ $styleArray['alignment']['textRotation'] = $this->calcRotation($styleAttributes);
+ $styleArray['alignment']['shrinkToFit'] = $styleAttributes['ShrinkToFit'] == '1';
+ $styleArray['alignment']['indent'] = ((int) ($styleAttributes['Indent']) > 0) ? $styleAttributes['indent'] : 0;
+
+ $this->addColors($styleArray, $styleAttributes);
+
+ $fontAttributes = $style->Style->Font->attributes();
+ if ($fontAttributes !== null) {
+ $styleArray['font']['name'] = (string) $style->Style->Font;
+ $styleArray['font']['size'] = (int) ($fontAttributes['Unit']);
+ $styleArray['font']['bold'] = $fontAttributes['Bold'] == '1';
+ $styleArray['font']['italic'] = $fontAttributes['Italic'] == '1';
+ $styleArray['font']['strikethrough'] = $fontAttributes['StrikeThrough'] == '1';
+ self::addStyle2($styleArray, 'font', 'underline', (string) $fontAttributes['Underline']);
+
+ switch ($fontAttributes['Script']) {
+ case '1':
+ $styleArray['font']['superscript'] = true;
+
+ break;
+ case '-1':
+ $styleArray['font']['subscript'] = true;
+
+ break;
+ }
+ }
+
+ if (isset($style->Style->StyleBorder)) {
+ $srssb = $style->Style->StyleBorder;
+ $this->addBorderStyle($srssb, $styleArray, 'top');
+ $this->addBorderStyle($srssb, $styleArray, 'bottom');
+ $this->addBorderStyle($srssb, $styleArray, 'left');
+ $this->addBorderStyle($srssb, $styleArray, 'right');
+ $this->addBorderDiagonal($srssb, $styleArray);
+ }
+ if (isset($style->Style->HyperLink)) {
+ // TO DO
+ $hyperlink = $style->Style->HyperLink->attributes();
+ }
+
+ return $styleArray;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php
index 73f4591e7f1..c37f1c1af18 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php
@@ -7,6 +7,7 @@ use DOMElement;
use DOMNode;
use DOMText;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
+use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension;
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Border;
@@ -122,6 +123,7 @@ class Html extends BaseReader
], // Italic
];
+ /** @var array */
protected $rowspan = [];
/**
@@ -135,16 +137,12 @@ class Html extends BaseReader
/**
* Validate that the current file is an HTML file.
- *
- * @param string $pFilename
- *
- * @return bool
*/
- public function canRead($pFilename)
+ public function canRead(string $filename): bool
{
// Check if file exists
try {
- $this->openFile($pFilename);
+ $this->openFile($filename);
} catch (Exception $e) {
return false;
}
@@ -159,19 +157,19 @@ class Html extends BaseReader
return $startWithTag && $containsTags && $endsWithTag;
}
- private function readBeginning()
+ private function readBeginning(): string
{
fseek($this->fileHandle, 0);
- return fread($this->fileHandle, self::TEST_SAMPLE_SIZE);
+ return (string) fread($this->fileHandle, self::TEST_SAMPLE_SIZE);
}
- private function readEnding()
+ private function readEnding(): string
{
$meta = stream_get_meta_data($this->fileHandle);
$filename = $meta['uri'];
- $size = filesize($filename);
+ $size = (int) filesize($filename);
if ($size === 0) {
return '';
}
@@ -183,20 +181,20 @@ class Html extends BaseReader
fseek($this->fileHandle, $size - $blockSize);
- return fread($this->fileHandle, $blockSize);
+ return (string) fread($this->fileHandle, $blockSize);
}
- private static function startsWithTag($data)
+ private static function startsWithTag(string $data): bool
{
return '<' === substr(trim($data), 0, 1);
}
- private static function endsWithTag($data)
+ private static function endsWithTag(string $data): bool
{
return '>' === substr(trim($data), -1, 1);
}
- private static function containsTags($data)
+ private static function containsTags(string $data): bool
{
return strlen($data) !== strlen(strip_tags($data));
}
@@ -204,33 +202,33 @@ class Html extends BaseReader
/**
* Loads Spreadsheet from file.
*
- * @param string $pFilename
- *
* @return Spreadsheet
*/
- public function load($pFilename)
+ public function load(string $filename, int $flags = 0)
{
+ $this->processFlags($flags);
+
// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
// Load into this instance
- return $this->loadIntoExisting($pFilename, $spreadsheet);
+ return $this->loadIntoExisting($filename, $spreadsheet);
}
/**
* Set input encoding.
*
- * @deprecated no use is made of this property
- *
- * @param string $pValue Input encoding, eg: 'ANSI'
+ * @param string $inputEncoding Input encoding, eg: 'ANSI'
*
* @return $this
*
* @codeCoverageIgnore
+ *
+ * @deprecated no use is made of this property
*/
- public function setInputEncoding($pValue)
+ public function setInputEncoding($inputEncoding)
{
- $this->inputEncoding = $pValue;
+ $this->inputEncoding = $inputEncoding;
return $this;
}
@@ -238,11 +236,11 @@ class Html extends BaseReader
/**
* Get input encoding.
*
- * @deprecated no use is made of this property
- *
* @return string
*
* @codeCoverageIgnore
+ *
+ * @deprecated no use is made of this property
*/
public function getInputEncoding()
{
@@ -250,13 +248,17 @@ class Html extends BaseReader
}
// Data Array used for testing only, should write to Spreadsheet object on completion of tests
+
+ /** @var array */
protected $dataArray = [];
+ /** @var int */
protected $tableLevel = 0;
+ /** @var array */
protected $nestedColumn = ['A'];
- protected function setTableStartColumn($column)
+ protected function setTableStartColumn(string $column): string
{
if ($this->tableLevel == 0) {
$column = 'A';
@@ -267,18 +269,25 @@ class Html extends BaseReader
return $this->nestedColumn[$this->tableLevel];
}
- protected function getTableStartColumn()
+ protected function getTableStartColumn(): string
{
return $this->nestedColumn[$this->tableLevel];
}
- protected function releaseTableStartColumn()
+ protected function releaseTableStartColumn(): string
{
--$this->tableLevel;
return array_pop($this->nestedColumn);
}
+ /**
+ * Flush cell.
+ *
+ * @param string $column
+ * @param int|string $row
+ * @param mixed $cellContent
+ */
protected function flushCell(Worksheet $sheet, $column, $row, &$cellContent): void
{
if (is_string($cellContent)) {
@@ -301,7 +310,7 @@ class Html extends BaseReader
private function processDomElementBody(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child): void
{
$attributeArray = [];
- foreach ($child->attributes as $attribute) {
+ foreach (($child->attributes ?? []) as $attribute) {
$attributeArray[$attribute->name] = $attribute->value;
}
@@ -320,24 +329,25 @@ class Html extends BaseReader
{
if ($child->nodeName === 'title') {
$this->processDomElement($child, $sheet, $row, $column, $cellContent);
- $sheet->setTitle($cellContent, true, false);
+ $sheet->setTitle($cellContent, true, true);
$cellContent = '';
} else {
$this->processDomElementSpanEtc($sheet, $row, $column, $cellContent, $child, $attributeArray);
}
}
- private static $spanEtc = ['span', 'div', 'font', 'i', 'em', 'strong', 'b'];
+ private const SPAN_ETC = ['span', 'div', 'font', 'i', 'em', 'strong', 'b'];
private function processDomElementSpanEtc(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void
{
- if (in_array($child->nodeName, self::$spanEtc)) {
+ if (in_array((string) $child->nodeName, self::SPAN_ETC, true)) {
if (isset($attributeArray['class']) && $attributeArray['class'] === 'comment') {
$sheet->getComment($column . $row)
->getText()
->createTextRun($child->textContent);
+ } else {
+ $this->processDomElement($child, $sheet, $row, $column, $cellContent);
}
- $this->processDomElement($child, $sheet, $row, $column, $cellContent);
if (isset($this->formats[$child->nodeName])) {
$sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]);
@@ -404,11 +414,11 @@ class Html extends BaseReader
}
}
- private static $h1Etc = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'p'];
+ private const H1_ETC = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'p'];
private function processDomElementH1Etc(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void
{
- if (in_array($child->nodeName, self::$h1Etc)) {
+ if (in_array((string) $child->nodeName, self::H1_ETC, true)) {
if ($this->tableLevel > 0) {
// If we're inside a table, replace with a \n
$cellContent .= $cellContent ? "\n" : '';
@@ -469,7 +479,7 @@ class Html extends BaseReader
if ($child->nodeName === 'table') {
$this->flushCell($sheet, $column, $row, $cellContent);
$column = $this->setTableStartColumn($column);
- if ($this->tableLevel > 1) {
+ if ($this->tableLevel > 1 && $row > 1) {
--$row;
}
$this->processDomElement($child, $sheet, $row, $column, $cellContent);
@@ -527,14 +537,14 @@ class Html extends BaseReader
private function processDomElementWidth(Worksheet $sheet, string $column, array $attributeArray): void
{
if (isset($attributeArray['width'])) {
- $sheet->getColumnDimension($column)->setWidth($attributeArray['width']);
+ $sheet->getColumnDimension($column)->setWidth((new CssDimension($attributeArray['width']))->width());
}
}
private function processDomElementHeight(Worksheet $sheet, int $row, array $attributeArray): void
{
if (isset($attributeArray['height'])) {
- $sheet->getRowDimension($row)->setRowHeight($attributeArray['height']);
+ $sheet->getRowDimension($row)->setRowHeight((new CssDimension($attributeArray['height']))->height());
}
}
@@ -627,30 +637,41 @@ class Html extends BaseReader
}
}
+ /**
+ * Make sure mb_convert_encoding returns string.
+ *
+ * @param mixed $result
+ */
+ private static function ensureString($result): string
+ {
+ return is_string($result) ? $result : '';
+ }
+
/**
* Loads PhpSpreadsheet from file into PhpSpreadsheet instance.
*
- * @param string $pFilename
+ * @param string $filename
*
* @return Spreadsheet
*/
- public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet)
+ public function loadIntoExisting($filename, Spreadsheet $spreadsheet)
{
// Validate
- if (!$this->canRead($pFilename)) {
- throw new Exception($pFilename . ' is an Invalid HTML file.');
+ if (!$this->canRead($filename)) {
+ throw new Exception($filename . ' is an Invalid HTML file.');
}
// Create a new DOM object
$dom = new DOMDocument();
// Reload the HTML file into the DOM object
try {
- $loaded = $dom->loadHTML(mb_convert_encoding($this->securityScanner->scanFile($pFilename), 'HTML-ENTITIES', 'UTF-8'));
+ $convert = mb_convert_encoding($this->securityScanner->scanFile($filename), 'HTML-ENTITIES', 'UTF-8');
+ $loaded = $dom->loadHTML(self::ensureString($convert));
} catch (Throwable $e) {
$loaded = false;
}
if ($loaded === false) {
- throw new Exception('Failed to load ' . $pFilename . ' as a DOM Document');
+ throw new Exception('Failed to load ' . $filename . ' as a DOM Document', 0, $e ?? null);
}
return $this->loadDocument($dom, $spreadsheet);
@@ -667,12 +688,13 @@ class Html extends BaseReader
$dom = new DOMDocument();
// Reload the HTML file into the DOM object
try {
- $loaded = $dom->loadHTML(mb_convert_encoding($this->securityScanner->scan($content), 'HTML-ENTITIES', 'UTF-8'));
+ $convert = mb_convert_encoding($this->securityScanner->scan($content), 'HTML-ENTITIES', 'UTF-8');
+ $loaded = $dom->loadHTML(self::ensureString($convert));
} catch (Throwable $e) {
$loaded = false;
}
if ($loaded === false) {
- throw new Exception('Failed to load content as a DOM Document');
+ throw new Exception('Failed to load content as a DOM Document', 0, $e ?? null);
}
return $this->loadDocument($dom, $spreadsheet ?? new Spreadsheet());
@@ -714,13 +736,13 @@ class Html extends BaseReader
/**
* Set sheet index.
*
- * @param int $pValue Sheet index
+ * @param int $sheetIndex Sheet index
*
* @return $this
*/
- public function setSheetIndex($pValue)
+ public function setSheetIndex($sheetIndex)
{
- $this->sheetIndex = $pValue;
+ $this->sheetIndex = $sheetIndex;
return $this;
}
@@ -735,12 +757,11 @@ class Html extends BaseReader
* TODO :
* - Implement to other propertie, such as border
*
- * @param Worksheet $sheet
* @param int $row
* @param string $column
* @param array $attributeArray
*/
- private function applyInlineStyle(&$sheet, $row, $column, $attributeArray): void
+ private function applyInlineStyle(Worksheet &$sheet, $row, $column, $attributeArray): void
{
if (!isset($attributeArray['style'])) {
return;
@@ -773,6 +794,7 @@ class Html extends BaseReader
$value = explode(':', $st);
$styleName = isset($value[0]) ? trim($value[0]) : null;
$styleValue = isset($value[1]) ? trim($value[1]) : null;
+ $styleValueString = (string) $styleValue;
if (!$styleName) {
continue;
@@ -781,7 +803,7 @@ class Html extends BaseReader
switch ($styleName) {
case 'background':
case 'background-color':
- $styleColor = $this->getStyleColor($styleValue);
+ $styleColor = $this->getStyleColor($styleValueString);
if (!$styleColor) {
continue 2;
@@ -791,7 +813,7 @@ class Html extends BaseReader
break;
case 'color':
- $styleColor = $this->getStyleColor($styleValue);
+ $styleColor = $this->getStyleColor($styleValueString);
if (!$styleColor) {
continue 2;
@@ -802,27 +824,27 @@ class Html extends BaseReader
break;
case 'border':
- $this->setBorderStyle($cellStyle, $styleValue, 'allBorders');
+ $this->setBorderStyle($cellStyle, $styleValueString, 'allBorders');
break;
case 'border-top':
- $this->setBorderStyle($cellStyle, $styleValue, 'top');
+ $this->setBorderStyle($cellStyle, $styleValueString, 'top');
break;
case 'border-bottom':
- $this->setBorderStyle($cellStyle, $styleValue, 'bottom');
+ $this->setBorderStyle($cellStyle, $styleValueString, 'bottom');
break;
case 'border-left':
- $this->setBorderStyle($cellStyle, $styleValue, 'left');
+ $this->setBorderStyle($cellStyle, $styleValueString, 'left');
break;
case 'border-right':
- $this->setBorderStyle($cellStyle, $styleValue, 'right');
+ $this->setBorderStyle($cellStyle, $styleValueString, 'right');
break;
@@ -848,7 +870,7 @@ class Html extends BaseReader
break;
case 'font-family':
- $cellStyle->getFont()->setName(str_replace('\'', '', $styleValue));
+ $cellStyle->getFont()->setName(str_replace('\'', '', $styleValueString));
break;
@@ -867,25 +889,25 @@ class Html extends BaseReader
break;
case 'text-align':
- $cellStyle->getAlignment()->setHorizontal($styleValue);
+ $cellStyle->getAlignment()->setHorizontal($styleValueString);
break;
case 'vertical-align':
- $cellStyle->getAlignment()->setVertical($styleValue);
+ $cellStyle->getAlignment()->setVertical($styleValueString);
break;
case 'width':
$sheet->getColumnDimension($column)->setWidth(
- str_replace('px', '', $styleValue)
+ (new CssDimension($styleValue ?? ''))->width()
);
break;
case 'height':
$sheet->getRowDimension($row)->setRowHeight(
- str_replace('px', '', $styleValue)
+ (new CssDimension($styleValue ?? ''))->height()
);
break;
@@ -899,7 +921,7 @@ class Html extends BaseReader
case 'text-indent':
$cellStyle->getAlignment()->setIndent(
- (int) str_replace(['px'], '', $styleValue)
+ (int) str_replace(['px'], '', $styleValueString)
);
break;
@@ -910,17 +932,18 @@ class Html extends BaseReader
/**
* Check if has #, so we can get clean hex.
*
- * @param $value
+ * @param mixed $value
*
* @return null|string
*/
public function getStyleColor($value)
{
- if (strpos($value, '#') === 0) {
+ $value = (string) $value;
+ if (strpos($value ?? '', '#') === 0) {
return substr($value, 1);
}
- return \PhpOffice\PhpSpreadsheet\Helper\Html::colourNameLookup((string) $value);
+ return \PhpOffice\PhpSpreadsheet\Helper\Html::colourNameLookup($value);
}
/**
@@ -967,7 +990,7 @@ class Html extends BaseReader
);
}
- private static $borderMappings = [
+ private const BORDER_MAPPINGS = [
'dash-dot' => Border::BORDER_DASHDOT,
'dash-dot-dot' => Border::BORDER_DASHDOTDOT,
'dashed' => Border::BORDER_DASHED,
@@ -986,7 +1009,7 @@ class Html extends BaseReader
public static function getBorderMappings(): array
{
- return self::$borderMappings;
+ return self::BORDER_MAPPINGS;
}
/**
@@ -998,7 +1021,7 @@ class Html extends BaseReader
*/
public function getBorderStyle($style)
{
- return (array_key_exists($style, self::$borderMappings)) ? self::$borderMappings[$style] : null;
+ return self::BORDER_MAPPINGS[$style] ?? null;
}
/**
@@ -1011,7 +1034,15 @@ class Html extends BaseReader
$borderStyle = Border::BORDER_NONE;
$color = null;
} else {
- [, $borderStyle, $color] = explode(' ', $styleValue);
+ $borderArray = explode(' ', $styleValue);
+ $borderCount = count($borderArray);
+ if ($borderCount >= 3) {
+ $borderStyle = $borderArray[1];
+ $color = $borderArray[2];
+ } else {
+ $borderStyle = $borderArray[0];
+ $color = $borderArray[1] ?? null;
+ }
}
$cellStyle->applyFromArray([
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReadFilter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReadFilter.php
index ccfe05ada6c..9f68a7f360f 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReadFilter.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReadFilter.php
@@ -7,11 +7,11 @@ interface IReadFilter
/**
* Should this cell be read?
*
- * @param string $column Column address (as a string value like "A", or "IV")
+ * @param string $columnAddress Column address (as a string value like "A", or "IV")
* @param int $row Row number
* @param string $worksheetName Optional worksheet name
*
* @return bool
*/
- public function readCell($column, $row, $worksheetName = '');
+ public function readCell($columnAddress, $row, $worksheetName = '');
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php
index a8bd3606596..d73662b4262 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php
@@ -4,6 +4,8 @@ namespace PhpOffice\PhpSpreadsheet\Reader;
interface IReader
{
+ public const LOAD_WITH_CHARTS = 1;
+
/**
* IReader constructor.
*/
@@ -11,12 +13,8 @@ interface IReader
/**
* Can the current IReader read the file?
- *
- * @param string $pFilename
- *
- * @return bool
*/
- public function canRead($pFilename);
+ public function canRead(string $filename): bool;
/**
* Read data only?
@@ -32,11 +30,11 @@ interface IReader
* Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
* Set to false (the default) to advise the Reader to read both data and formatting for cells.
*
- * @param bool $pValue
+ * @param bool $readDataOnly
*
* @return IReader
*/
- public function setReadDataOnly($pValue);
+ public function setReadDataOnly($readDataOnly);
/**
* Read empty cells?
@@ -52,11 +50,11 @@ interface IReader
* Set to true (the default) to advise the Reader read data values for all cells, irrespective of value.
* Set to false to advise the Reader to ignore cells containing a null value or an empty string.
*
- * @param bool $pValue
+ * @param bool $readEmptyCells
*
* @return IReader
*/
- public function setReadEmptyCells($pValue);
+ public function setReadEmptyCells($readEmptyCells);
/**
* Read charts in workbook?
@@ -74,11 +72,11 @@ interface IReader
* Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
* Set to false (the default) to discard charts.
*
- * @param bool $pValue
+ * @param bool $includeCharts
*
* @return IReader
*/
- public function setIncludeCharts($pValue);
+ public function setIncludeCharts($includeCharts);
/**
* Get which sheets to load
@@ -120,14 +118,12 @@ interface IReader
*
* @return IReader
*/
- public function setReadFilter(IReadFilter $pValue);
+ public function setReadFilter(IReadFilter $readFilter);
/**
* Loads PhpSpreadsheet from file.
*
- * @param string $pFilename
- *
* @return \PhpOffice\PhpSpreadsheet\Spreadsheet
*/
- public function load($pFilename);
+ public function load(string $filename, int $flags = 0);
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php
index 4ceac65301d..86b3ee38199 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php
@@ -3,7 +3,6 @@
namespace PhpOffice\PhpSpreadsheet\Reader;
use DateTime;
-use DateTimeZone;
use DOMAttr;
use DOMDocument;
use DOMElement;
@@ -11,8 +10,8 @@ use DOMNode;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
-use PhpOffice\PhpSpreadsheet\DefinedName;
-use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
+use PhpOffice\PhpSpreadsheet\Reader\Ods\AutoFilter;
+use PhpOffice\PhpSpreadsheet\Reader\Ods\DefinedNames;
use PhpOffice\PhpSpreadsheet\Reader\Ods\PageSettings;
use PhpOffice\PhpSpreadsheet\Reader\Ods\Properties as DocumentProperties;
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
@@ -22,12 +21,14 @@ use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
-use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
+use Throwable;
use XMLReader;
use ZipArchive;
class Ods extends BaseReader
{
+ const INITIAL_FILE = 'content.xml';
+
/**
* Create a new Ods Reader instance.
*/
@@ -39,46 +40,42 @@ class Ods extends BaseReader
/**
* Can the current IReader read the file?
- *
- * @param string $pFilename
- *
- * @return bool
*/
- public function canRead($pFilename)
+ public function canRead(string $filename): bool
{
- File::assertFile($pFilename);
-
$mimeType = 'UNKNOWN';
// Load file
- $zip = new ZipArchive();
- if ($zip->open($pFilename) === true) {
- // check if it is an OOXML archive
- $stat = $zip->statName('mimetype');
- if ($stat && ($stat['size'] <= 255)) {
- $mimeType = $zip->getFromName($stat['name']);
- } elseif ($zip->statName('META-INF/manifest.xml')) {
- $xml = simplexml_load_string(
- $this->securityScanner->scan($zip->getFromName('META-INF/manifest.xml')),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- $namespacesContent = $xml->getNamespaces(true);
- if (isset($namespacesContent['manifest'])) {
- $manifest = $xml->children($namespacesContent['manifest']);
- foreach ($manifest as $manifestDataSet) {
- $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']);
- if ($manifestAttributes->{'full-path'} == '/') {
- $mimeType = (string) $manifestAttributes->{'media-type'};
+ if (File::testFileNoThrow($filename, '')) {
+ $zip = new ZipArchive();
+ if ($zip->open($filename) === true) {
+ // check if it is an OOXML archive
+ $stat = $zip->statName('mimetype');
+ if ($stat && ($stat['size'] <= 255)) {
+ $mimeType = $zip->getFromName($stat['name']);
+ } elseif ($zip->statName('META-INF/manifest.xml')) {
+ $xml = simplexml_load_string(
+ $this->securityScanner->scan($zip->getFromName('META-INF/manifest.xml')),
+ 'SimpleXMLElement',
+ Settings::getLibXmlLoaderOptions()
+ );
+ $namespacesContent = $xml->getNamespaces(true);
+ if (isset($namespacesContent['manifest'])) {
+ $manifest = $xml->children($namespacesContent['manifest']);
+ foreach ($manifest as $manifestDataSet) {
+ $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']);
+ if ($manifestAttributes && $manifestAttributes->{'full-path'} == '/') {
+ $mimeType = (string) $manifestAttributes->{'media-type'};
- break;
+ break;
+ }
}
}
}
- }
- $zip->close();
+ $zip->close();
+ }
}
return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet';
@@ -87,24 +84,19 @@ class Ods extends BaseReader
/**
* Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object.
*
- * @param string $pFilename
+ * @param string $filename
*
* @return string[]
*/
- public function listWorksheetNames($pFilename)
+ public function listWorksheetNames($filename)
{
- File::assertFile($pFilename);
-
- $zip = new ZipArchive();
- if ($zip->open($pFilename) !== true) {
- throw new ReaderException('Could not open ' . $pFilename . ' for reading! Error opening file.');
- }
+ File::assertFile($filename, self::INITIAL_FILE);
$worksheetNames = [];
$xml = new XMLReader();
$xml->xml(
- $this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#content.xml'),
+ $this->securityScanner->scanFile('zip://' . realpath($filename) . '#' . self::INITIAL_FILE),
null,
Settings::getLibXmlLoaderOptions()
);
@@ -139,24 +131,19 @@ class Ods extends BaseReader
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
- * @param string $pFilename
+ * @param string $filename
*
* @return array
*/
- public function listWorksheetInfo($pFilename)
+ public function listWorksheetInfo($filename)
{
- File::assertFile($pFilename);
+ File::assertFile($filename, self::INITIAL_FILE);
$worksheetInfo = [];
- $zip = new ZipArchive();
- if ($zip->open($pFilename) !== true) {
- throw new ReaderException('Could not open ' . $pFilename . ' for reading! Error opening file.');
- }
-
$xml = new XMLReader();
$xml->xml(
- $this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#content.xml'),
+ $this->securityScanner->scanFile('zip://' . realpath($filename) . '#' . self::INITIAL_FILE),
null,
Settings::getLibXmlLoaderOptions()
);
@@ -231,37 +218,32 @@ class Ods extends BaseReader
/**
* Loads PhpSpreadsheet from file.
*
- * @param string $pFilename
- *
* @return Spreadsheet
*/
- public function load($pFilename)
+ public function load(string $filename, int $flags = 0)
{
+ $this->processFlags($flags);
+
// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
// Load into this instance
- return $this->loadIntoExisting($pFilename, $spreadsheet);
+ return $this->loadIntoExisting($filename, $spreadsheet);
}
/**
* Loads PhpSpreadsheet from file into PhpSpreadsheet instance.
*
- * @param string $pFilename
+ * @param string $filename
*
* @return Spreadsheet
*/
- public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet)
+ public function loadIntoExisting($filename, Spreadsheet $spreadsheet)
{
- File::assertFile($pFilename);
-
- $timezoneObj = new DateTimeZone('Europe/London');
- $GMT = new DateTimeZone('UTC');
+ File::assertFile($filename, self::INITIAL_FILE);
$zip = new ZipArchive();
- if ($zip->open($pFilename) !== true) {
- throw new Exception("Could not open {$pFilename} for reading! Error opening file.");
- }
+ $zip->open($filename);
// Meta
@@ -292,7 +274,7 @@ class Ods extends BaseReader
$dom = new DOMDocument('1.01', 'UTF-8');
$dom->loadXML(
- $this->securityScanner->scan($zip->getFromName('content.xml')),
+ $this->securityScanner->scan($zip->getFromName(self::INITIAL_FILE)),
Settings::getLibXmlLoaderOptions()
);
@@ -303,8 +285,10 @@ class Ods extends BaseReader
$pageSettings->readStyleCrossReferences($dom);
- // Content
+ $autoFilterReader = new AutoFilter($spreadsheet, $tableNs);
+ $definedNameReader = new DefinedNames($spreadsheet, $tableNs);
+ // Content
$spreadsheets = $dom->getElementsByTagNameNS($officeNs, 'body')
->item(0)
->getElementsByTagNameNS($officeNs, 'spreadsheet');
@@ -373,15 +357,14 @@ class Ods extends BaseReader
break;
case 'table-row':
if ($childNode->hasAttributeNS($tableNs, 'number-rows-repeated')) {
- $rowRepeats = $childNode->getAttributeNS($tableNs, 'number-rows-repeated');
+ $rowRepeats = (int) $childNode->getAttributeNS($tableNs, 'number-rows-repeated');
} else {
$rowRepeats = 1;
}
$columnID = 'A';
- foreach ($childNode->childNodes as $key => $cellData) {
- // @var \DOMElement $cellData
-
+ /** @var DOMElement $cellData */
+ foreach ($childNode->childNodes as $cellData) {
if ($this->getReadFilter() !== null) {
if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
++$columnID;
@@ -500,8 +483,7 @@ class Ods extends BaseReader
$type = DataType::TYPE_NUMERIC;
$value = $cellData->getAttributeNS($officeNs, 'date-value');
- $dateObj = new DateTime($value, $GMT);
- $dateObj->setTimeZone($timezoneObj);
+ $dateObj = new DateTime($value);
[$year, $month, $day, $hour, $minute, $second] = explode(
' ',
$dateObj->format('Y m d H i s')
@@ -532,7 +514,7 @@ class Ods extends BaseReader
$dataValue = Date::PHPToExcel(
strtotime(
- '01-01-1970 ' . implode(':', sscanf($timeValue, 'PT%dH%dM%dS'))
+ '01-01-1970 ' . implode(':', sscanf($timeValue, 'PT%dH%dM%dS') ?? [])
)
);
$formatting = NumberFormat::FORMAT_DATE_TIME4;
@@ -642,14 +624,88 @@ class Ods extends BaseReader
++$worksheetID;
}
- $this->readDefinedRanges($spreadsheet, $workbookData, $tableNs);
- $this->readDefinedExpressions($spreadsheet, $workbookData, $tableNs);
+ $autoFilterReader->read($workbookData);
+ $definedNameReader->read($workbookData);
}
$spreadsheet->setActiveSheetIndex(0);
+
+ if ($zip->locateName('settings.xml') !== false) {
+ $this->processSettings($zip, $spreadsheet);
+ }
+
// Return
return $spreadsheet;
}
+ private function processSettings(ZipArchive $zip, Spreadsheet $spreadsheet): void
+ {
+ $dom = new DOMDocument('1.01', 'UTF-8');
+ $dom->loadXML(
+ $this->securityScanner->scan($zip->getFromName('settings.xml')),
+ Settings::getLibXmlLoaderOptions()
+ );
+ //$xlinkNs = $dom->lookupNamespaceUri('xlink');
+ $configNs = $dom->lookupNamespaceUri('config');
+ //$oooNs = $dom->lookupNamespaceUri('ooo');
+ $officeNs = $dom->lookupNamespaceUri('office');
+ $settings = $dom->getElementsByTagNameNS($officeNs, 'settings')
+ ->item(0);
+ $this->lookForActiveSheet($settings, $spreadsheet, $configNs);
+ $this->lookForSelectedCells($settings, $spreadsheet, $configNs);
+ }
+
+ private function lookForActiveSheet(DOMElement $settings, Spreadsheet $spreadsheet, string $configNs): void
+ {
+ /** @var DOMElement $t */
+ foreach ($settings->getElementsByTagNameNS($configNs, 'config-item') as $t) {
+ if ($t->getAttributeNs($configNs, 'name') === 'ActiveTable') {
+ try {
+ $spreadsheet->setActiveSheetIndexByName($t->nodeValue);
+ } catch (Throwable $e) {
+ // do nothing
+ }
+
+ break;
+ }
+ }
+ }
+
+ private function lookForSelectedCells(DOMElement $settings, Spreadsheet $spreadsheet, string $configNs): void
+ {
+ /** @var DOMElement $t */
+ foreach ($settings->getElementsByTagNameNS($configNs, 'config-item-map-named') as $t) {
+ if ($t->getAttributeNs($configNs, 'name') === 'Tables') {
+ foreach ($t->getElementsByTagNameNS($configNs, 'config-item-map-entry') as $ws) {
+ $setRow = $setCol = '';
+ $wsname = $ws->getAttributeNs($configNs, 'name');
+ foreach ($ws->getElementsByTagNameNS($configNs, 'config-item') as $configItem) {
+ $attrName = $configItem->getAttributeNs($configNs, 'name');
+ if ($attrName === 'CursorPositionX') {
+ $setCol = $configItem->nodeValue;
+ }
+ if ($attrName === 'CursorPositionY') {
+ $setRow = $configItem->nodeValue;
+ }
+ }
+ $this->setSelected($spreadsheet, $wsname, $setCol, $setRow);
+ }
+
+ break;
+ }
+ }
+ }
+
+ private function setSelected(Spreadsheet $spreadsheet, string $wsname, string $setCol, string $setRow): void
+ {
+ if (is_numeric($setCol) && is_numeric($setRow)) {
+ try {
+ $spreadsheet->getSheetByName($wsname)->setSelectedCellByColumnAndRow($setCol + 1, $setRow + 1);
+ } catch (Throwable $e) {
+ // do nothing
+ }
+ }
+ }
+
/**
* Recursively scan element.
*
@@ -698,26 +754,6 @@ class Ods extends BaseReader
return $value;
}
- private function convertToExcelAddressValue(string $openOfficeAddress): string
- {
- $excelAddress = $openOfficeAddress;
-
- // Cell range 3-d reference
- // As we don't support 3-d ranges, we're just going to take a quick and dirty approach
- // and assume that the second worksheet reference is the same as the first
- $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+):\$?([^\.]+)\.([^\.]+)/miu', '$1!$2:$4', $excelAddress);
- // Cell range reference in another sheet
- $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+):\.([^\.]+)/miu', '$1!$2:$3', $excelAddress);
- // Cell reference in another sheet
- $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+)/miu', '$1!$2', $excelAddress);
- // Cell range reference
- $excelAddress = preg_replace('/\.([^\.]+):\.([^\.]+)/miu', '$1:$2', $excelAddress);
- // Simple cell reference
- $excelAddress = preg_replace('/\.([^\.]+)/miu', '$1', $excelAddress);
-
- return $excelAddress;
- }
-
private function convertToExcelFormulaValue(string $openOfficeFormula): string
{
$temp = explode('"', $openOfficeFormula);
@@ -728,11 +764,13 @@ class Ods extends BaseReader
// Cell range reference in another sheet
$value = preg_replace('/\[\$?([^\.]+)\.([^\.]+):\.([^\.]+)\]/miu', '$1!$2:$3', $value);
// Cell reference in another sheet
- $value = preg_replace('/\[\$?([^\.]+)\.([^\.]+)\]/miu', '$1!$2', $value);
+ $value = preg_replace('/\[\$?([^\.]+)\.([^\.]+)\]/miu', '$1!$2', $value ?? '');
// Cell range reference
- $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/miu', '$1:$2', $value);
+ $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/miu', '$1:$2', $value ?? '');
// Simple cell reference
- $value = preg_replace('/\[\.([^\.]+)\]/miu', '$1', $value);
+ $value = preg_replace('/\[\.([^\.]+)\]/miu', '$1', $value ?? '');
+ // Convert references to defined names/formulae
+ $value = str_replace('$$', '', $value ?? '');
$value = Calculation::translateSeparator(';', ',', $value, $inBraces);
}
@@ -743,53 +781,4 @@ class Ods extends BaseReader
return $excelFormula;
}
-
- /**
- * Read any Named Ranges that are defined in this spreadsheet.
- */
- private function readDefinedRanges(Spreadsheet $spreadsheet, DOMElement $workbookData, string $tableNs): void
- {
- $namedRanges = $workbookData->getElementsByTagNameNS($tableNs, 'named-range');
- foreach ($namedRanges as $definedNameElement) {
- $definedName = $definedNameElement->getAttributeNS($tableNs, 'name');
- $baseAddress = $definedNameElement->getAttributeNS($tableNs, 'base-cell-address');
- $range = $definedNameElement->getAttributeNS($tableNs, 'cell-range-address');
-
- $baseAddress = $this->convertToExcelAddressValue($baseAddress);
- $range = $this->convertToExcelAddressValue($range);
-
- $this->addDefinedName($spreadsheet, $baseAddress, $definedName, $range);
- }
- }
-
- /**
- * Read any Named Formulae that are defined in this spreadsheet.
- */
- private function readDefinedExpressions(Spreadsheet $spreadsheet, DOMElement $workbookData, string $tableNs): void
- {
- $namedExpressions = $workbookData->getElementsByTagNameNS($tableNs, 'named-expression');
- foreach ($namedExpressions as $definedNameElement) {
- $definedName = $definedNameElement->getAttributeNS($tableNs, 'name');
- $baseAddress = $definedNameElement->getAttributeNS($tableNs, 'base-cell-address');
- $expression = $definedNameElement->getAttributeNS($tableNs, 'expression');
-
- $baseAddress = $this->convertToExcelAddressValue($baseAddress);
- $expression = $this->convertToExcelFormulaValue($expression);
-
- $this->addDefinedName($spreadsheet, $baseAddress, $definedName, $expression);
- }
- }
-
- /**
- * Assess scope and store the Defined Name.
- */
- private function addDefinedName(Spreadsheet $spreadsheet, string $baseAddress, string $definedName, string $value): void
- {
- [$sheetReference] = Worksheet::extractSheetTitle($baseAddress, true);
- $worksheet = $spreadsheet->getSheetByName($sheetReference);
- // Worksheet might still be null if we're only loading selected sheets rather than the full spreadsheet
- if ($worksheet !== null) {
- $spreadsheet->addDefinedName(DefinedName::createInstance((string) $definedName, $worksheet, $value));
- }
- }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php
new file mode 100644
index 00000000000..bdc8b3ffc37
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php
@@ -0,0 +1,45 @@
+readAutoFilters($workbookData);
+ }
+
+ protected function readAutoFilters(DOMElement $workbookData): void
+ {
+ $databases = $workbookData->getElementsByTagNameNS($this->tableNs, 'database-ranges');
+
+ foreach ($databases as $autofilters) {
+ foreach ($autofilters->childNodes as $autofilter) {
+ $autofilterRange = $this->getAttributeValue($autofilter, 'target-range-address');
+ if ($autofilterRange !== null) {
+ $baseAddress = $this->convertToExcelAddressValue($autofilterRange);
+ $this->spreadsheet->getActiveSheet()->setAutoFilter($baseAddress);
+ }
+ }
+ }
+ }
+
+ protected function getAttributeValue(?DOMNode $node, string $attributeName): ?string
+ {
+ if ($node !== null && $node->attributes !== null) {
+ $attribute = $node->attributes->getNamedItemNS(
+ $this->tableNs,
+ $attributeName
+ );
+
+ if ($attribute !== null) {
+ return $attribute->nodeValue;
+ }
+ }
+
+ return null;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/BaseReader.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/BaseReader.php
new file mode 100644
index 00000000000..17e2d4d573b
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/BaseReader.php
@@ -0,0 +1,77 @@
+spreadsheet = $spreadsheet;
+ $this->tableNs = $tableNs;
+ }
+
+ abstract public function read(DOMElement $workbookData): void;
+
+ protected function convertToExcelAddressValue(string $openOfficeAddress): string
+ {
+ $excelAddress = $openOfficeAddress;
+
+ // Cell range 3-d reference
+ // As we don't support 3-d ranges, we're just going to take a quick and dirty approach
+ // and assume that the second worksheet reference is the same as the first
+ $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+):\$?([^\.]+)\.([^\.]+)/miu', '$1!$2:$4', $excelAddress);
+ // Cell range reference in another sheet
+ $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+):\.([^\.]+)/miu', '$1!$2:$3', $excelAddress ?? '');
+ // Cell reference in another sheet
+ $excelAddress = preg_replace('/\$?([^\.]+)\.([^\.]+)/miu', '$1!$2', $excelAddress ?? '');
+ // Cell range reference
+ $excelAddress = preg_replace('/\.([^\.]+):\.([^\.]+)/miu', '$1:$2', $excelAddress ?? '');
+ // Simple cell reference
+ $excelAddress = preg_replace('/\.([^\.]+)/miu', '$1', $excelAddress ?? '');
+
+ return $excelAddress ?? '';
+ }
+
+ protected function convertToExcelFormulaValue(string $openOfficeFormula): string
+ {
+ $temp = explode('"', $openOfficeFormula);
+ $tKey = false;
+ foreach ($temp as &$value) {
+ // @var string $value
+ // Only replace in alternate array entries (i.e. non-quoted blocks)
+ if ($tKey = !$tKey) {
+ // Cell range reference in another sheet
+ $value = preg_replace('/\[\$?([^\.]+)\.([^\.]+):\.([^\.]+)\]/miu', '$1!$2:$3', $value);
+ // Cell reference in another sheet
+ $value = preg_replace('/\[\$?([^\.]+)\.([^\.]+)\]/miu', '$1!$2', $value ?? '');
+ // Cell range reference
+ $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/miu', '$1:$2', $value ?? '');
+ // Simple cell reference
+ $value = preg_replace('/\[\.([^\.]+)\]/miu', '$1', $value ?? '');
+ // Convert references to defined names/formulae
+ $value = str_replace('$$', '', $value ?? '');
+
+ $value = Calculation::translateSeparator(';', ',', $value, $inBraces);
+ }
+ }
+
+ // Then rebuild the formula string
+ $excelFormula = implode('"', $temp);
+
+ return $excelFormula;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php
new file mode 100644
index 00000000000..6810a3c7268
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php
@@ -0,0 +1,66 @@
+readDefinedRanges($workbookData);
+ $this->readDefinedExpressions($workbookData);
+ }
+
+ /**
+ * Read any Named Ranges that are defined in this spreadsheet.
+ */
+ protected function readDefinedRanges(DOMElement $workbookData): void
+ {
+ $namedRanges = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-range');
+ foreach ($namedRanges as $definedNameElement) {
+ $definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name');
+ $baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address');
+ $range = $definedNameElement->getAttributeNS($this->tableNs, 'cell-range-address');
+
+ $baseAddress = $this->convertToExcelAddressValue($baseAddress);
+ $range = $this->convertToExcelAddressValue($range);
+
+ $this->addDefinedName($baseAddress, $definedName, $range);
+ }
+ }
+
+ /**
+ * Read any Named Formulae that are defined in this spreadsheet.
+ */
+ protected function readDefinedExpressions(DOMElement $workbookData): void
+ {
+ $namedExpressions = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-expression');
+ foreach ($namedExpressions as $definedNameElement) {
+ $definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name');
+ $baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address');
+ $expression = $definedNameElement->getAttributeNS($this->tableNs, 'expression');
+
+ $baseAddress = $this->convertToExcelAddressValue($baseAddress);
+ $expression = substr($expression, strpos($expression, ':=') + 1);
+ $expression = $this->convertToExcelFormulaValue($expression);
+
+ $this->addDefinedName($baseAddress, $definedName, $expression);
+ }
+ }
+
+ /**
+ * Assess scope and store the Defined Name.
+ */
+ private function addDefinedName(string $baseAddress, string $definedName, string $value): void
+ {
+ [$sheetReference] = Worksheet::extractSheetTitle($baseAddress, true);
+ $worksheet = $this->spreadsheet->getSheetByName($sheetReference);
+ // Worksheet might still be null if we're only loading selected sheets rather than the full spreadsheet
+ if ($worksheet !== null) {
+ $this->spreadsheet->addDefinedName(DefinedName::createInstance((string) $definedName, $worksheet, $value));
+ }
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/PageSettings.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/PageSettings.php
index 77341aab856..8d24fd0c247 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/PageSettings.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/PageSettings.php
@@ -54,10 +54,10 @@ class PageSettings
$marginBottom = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-bottom');
$header = $styleSet->getElementsByTagNameNS($this->stylesNs, 'header-style')[0];
$headerProperties = $header->getElementsByTagNameNS($this->stylesNs, 'header-footer-properties')[0];
- $marginHeader = $headerProperties->getAttributeNS($this->stylesFo, 'min-height');
+ $marginHeader = isset($headerProperties) ? $headerProperties->getAttributeNS($this->stylesFo, 'min-height') : null;
$footer = $styleSet->getElementsByTagNameNS($this->stylesNs, 'footer-style')[0];
$footerProperties = $footer->getElementsByTagNameNS($this->stylesNs, 'header-footer-properties')[0];
- $marginFooter = $footerProperties->getAttributeNS($this->stylesFo, 'min-height');
+ $marginFooter = isset($footerProperties) ? $footerProperties->getAttributeNS($this->stylesFo, 'min-height') : null;
$this->pageLayoutStyles[$styleName] = (object) [
'orientation' => $styleOrientation ?: PageSetup::ORIENTATION_DEFAULT,
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php
index d0a45e6adb7..fc78936735d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php
@@ -26,7 +26,7 @@ class Properties
$this->setCoreProperties($docProps, $officePropertiesDC);
}
- $officePropertyMeta = (object) [];
+ $officePropertyMeta = [];
if (isset($namespacesMeta['dc'])) {
$officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
}
@@ -55,9 +55,7 @@ class Properties
break;
case 'date':
- $creationDate = strtotime($propertyValue);
- $docProps->setCreated($creationDate);
- $docProps->setModified($creationDate);
+ $docProps->setModified($propertyValue);
break;
case 'description':
@@ -86,8 +84,7 @@ class Properties
break;
case 'creation-date':
- $creationDate = strtotime($propertyValue);
- $docProps->setCreated($creationDate);
+ $docProps->setCreated($propertyValue);
break;
case 'user-defined':
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php
index a65797c1565..8155b838fa6 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php
@@ -3,7 +3,6 @@
namespace PhpOffice\PhpSpreadsheet\Reader\Security;
use PhpOffice\PhpSpreadsheet\Reader;
-use PhpOffice\PhpSpreadsheet\Settings;
class XmlScanner
{
@@ -18,6 +17,11 @@ class XmlScanner
private static $libxmlDisableEntityLoaderValue;
+ /**
+ * @var bool
+ */
+ private static $shutdownRegistered = false;
+
public function __construct($pattern = 'pattern = $pattern;
@@ -25,7 +29,10 @@ class XmlScanner
$this->disableEntityLoaderCheck();
// A fatal error will bypass the destructor, so we register a shutdown here
- register_shutdown_function([__CLASS__, 'shutdown']);
+ if (!self::$shutdownRegistered) {
+ self::$shutdownRegistered = true;
+ register_shutdown_function([__CLASS__, 'shutdown']);
+ }
}
public static function getInstance(Reader\IReader $reader)
@@ -63,7 +70,7 @@ class XmlScanner
private function disableEntityLoaderCheck(): void
{
- if (Settings::getLibXmlDisableEntityLoader() && \PHP_VERSION_ID < 80000) {
+ if (\PHP_VERSION_ID < 80000) {
$libxmlDisableEntityLoaderValue = libxml_disable_entity_loader(true);
if (self::$libxmlDisableEntityLoaderValue === null) {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Slk.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Slk.php
index e58ff2f6c5d..de3c6ce5a09 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Slk.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Slk.php
@@ -2,7 +2,6 @@
namespace PhpOffice\PhpSpreadsheet\Reader;
-use InvalidArgumentException;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
@@ -65,21 +64,17 @@ class Slk extends BaseReader
/**
* Validate that the current file is a SYLK file.
- *
- * @param string $pFilename
- *
- * @return bool
*/
- public function canRead($pFilename)
+ public function canRead(string $filename): bool
{
try {
- $this->openFile($pFilename);
- } catch (InvalidArgumentException $e) {
+ $this->openFile($filename);
+ } catch (ReaderException $e) {
return false;
}
// Read sample data (first 2 KB will do)
- $data = fread($this->fileHandle, 2048);
+ $data = (string) fread($this->fileHandle, 2048);
// Count delimiters in file
$delimiterCount = substr_count($data, ';');
@@ -94,12 +89,12 @@ class Slk extends BaseReader
return $hasDelimiter && $hasId;
}
- private function canReadOrBust(string $pFilename): void
+ private function canReadOrBust(string $filename): void
{
- if (!$this->canRead($pFilename)) {
- throw new ReaderException($pFilename . ' is an Invalid SYLK file.');
+ if (!$this->canRead($filename)) {
+ throw new ReaderException($filename . ' is an Invalid SYLK file.');
}
- $this->openFile($pFilename);
+ $this->openFile($filename);
}
/**
@@ -107,15 +102,15 @@ class Slk extends BaseReader
*
* @deprecated no use is made of this property
*
- * @param string $pValue Input encoding, eg: 'ANSI'
+ * @param string $inputEncoding Input encoding, eg: 'ANSI'
*
* @return $this
*
* @codeCoverageIgnore
*/
- public function setInputEncoding($pValue)
+ public function setInputEncoding($inputEncoding)
{
- $this->inputEncoding = $pValue;
+ $this->inputEncoding = $inputEncoding;
return $this;
}
@@ -137,19 +132,19 @@ class Slk extends BaseReader
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
- * @param string $pFilename
+ * @param string $filename
*
* @return array
*/
- public function listWorksheetInfo($pFilename)
+ public function listWorksheetInfo($filename)
{
// Open file
- $this->canReadOrBust($pFilename);
+ $this->canReadOrBust($filename);
$fileHandle = $this->fileHandle;
rewind($fileHandle);
$worksheetInfo = [];
- $worksheetInfo[0]['worksheetName'] = basename($pFilename, '.slk');
+ $worksheetInfo[0]['worksheetName'] = basename($filename, '.slk');
// loop through one row (line) at a time in the file
$rowIndex = 0;
@@ -169,7 +164,7 @@ class Slk extends BaseReader
foreach ($rowData as $rowDatum) {
switch ($rowDatum[0]) {
case 'X':
- $columnIndex = substr($rowDatum, 1) - 1;
+ $columnIndex = (int) substr($rowDatum, 1) - 1;
break;
case 'Y':
@@ -197,20 +192,20 @@ class Slk extends BaseReader
/**
* Loads PhpSpreadsheet from file.
*
- * @param string $pFilename
- *
* @return Spreadsheet
*/
- public function load($pFilename)
+ public function load(string $filename, int $flags = 0)
{
+ $this->processFlags($flags);
+
// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
// Load into this instance
- return $this->loadIntoExisting($pFilename, $spreadsheet);
+ return $this->loadIntoExisting($filename, $spreadsheet);
}
- private $colorArray = [
+ private const COLOR_ARRAY = [
'FF00FFFF', // 0 - cyan
'FF000000', // 1 - black
'FFFFFFFF', // 2 - white
@@ -221,7 +216,7 @@ class Slk extends BaseReader
'FFFF00FF', // 7 - magenta
];
- private $fontStyleMappings = [
+ private const FONT_STYLE_MAPPINGS = [
'B' => 'bold',
'I' => 'italic',
'U' => 'underline',
@@ -235,7 +230,8 @@ class Slk extends BaseReader
$key = false;
foreach ($temp as &$value) {
// Only count/replace in alternate array entries
- if ($key = !$key) {
+ $key = !$key;
+ if ($key) {
preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
// Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
// through the formula from left to right. Reversing means that we work right to left.through
@@ -251,7 +247,7 @@ class Slk extends BaseReader
}
// Bracketed R references are relative to the current row
if ($rowReference[0] == '[') {
- $rowReference = $row + trim($rowReference, '[]');
+ $rowReference = (int) $row + (int) trim($rowReference, '[]');
}
$columnReference = $cellReference[4][0];
// Empty C reference is the current column
@@ -260,7 +256,7 @@ class Slk extends BaseReader
}
// Bracketed C references are relative to the current column
if ($columnReference[0] == '[') {
- $columnReference = $column + trim($columnReference, '[]');
+ $columnReference = (int) $column + (int) trim($columnReference, '[]');
}
$A1CellReference = Coordinate::stringFromColumnIndex($columnReference) . $rowReference;
@@ -298,6 +294,15 @@ class Slk extends BaseReader
case 'E':
$this->processFormula($rowDatum, $hasCalculatedValue, $cellDataFormula, $row, $column);
+ break;
+ case 'A':
+ $comment = substr($rowDatum, 1);
+ $columnLetter = Coordinate::stringFromColumnIndex((int) $column);
+ $spreadsheet->getActiveSheet()
+ ->getComment("$columnLetter$row")
+ ->getText()
+ ->createText($comment);
+
break;
}
}
@@ -357,9 +362,9 @@ class Slk extends BaseReader
$this->addWidth($spreadsheet, $columnWidth, $startCol, $endCol);
}
- private $styleSettingsFont = ['D' => 'bold', 'I' => 'italic'];
+ private const STYLE_SETTINGS_FONT = ['D' => 'bold', 'I' => 'italic'];
- private $styleSettingsBorder = [
+ private const STYLE_SETTINGS_BORDER = [
'B' => 'bottom',
'L' => 'left',
'R' => 'right',
@@ -372,10 +377,10 @@ class Slk extends BaseReader
$iMax = strlen($styleSettings);
for ($i = 0; $i < $iMax; ++$i) {
$char = $styleSettings[$i];
- if (array_key_exists($char, $this->styleSettingsFont)) {
- $styleData['font'][$this->styleSettingsFont[$char]] = true;
- } elseif (array_key_exists($char, $this->styleSettingsBorder)) {
- $styleData['borders'][$this->styleSettingsBorder[$char]]['borderStyle'] = Border::BORDER_THIN;
+ if (array_key_exists($char, self::STYLE_SETTINGS_FONT)) {
+ $styleData['font'][self::STYLE_SETTINGS_FONT[$char]] = true;
+ } elseif (array_key_exists($char, self::STYLE_SETTINGS_BORDER)) {
+ $styleData['borders'][self::STYLE_SETTINGS_BORDER[$char]]['borderStyle'] = Border::BORDER_THIN;
} elseif ($char == 'S') {
$styleData['fill']['fillType'] = \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_PATTERN_GRAY125;
} elseif ($char == 'M') {
@@ -409,7 +414,7 @@ class Slk extends BaseReader
private function addStyle(Spreadsheet &$spreadsheet, array $styleData, string $row, string $column): void
{
if ((!empty($styleData)) && $column > '' && $row > '') {
- $columnLetter = Coordinate::stringFromColumnIndex($column);
+ $columnLetter = Coordinate::stringFromColumnIndex((int) $column);
$spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($styleData);
}
}
@@ -419,14 +424,14 @@ class Slk extends BaseReader
if ($columnWidth > '') {
if ($startCol == $endCol) {
$startCol = Coordinate::stringFromColumnIndex((int) $startCol);
- $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
+ $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth);
} else {
- $startCol = Coordinate::stringFromColumnIndex($startCol);
- $endCol = Coordinate::stringFromColumnIndex($endCol);
+ $startCol = Coordinate::stringFromColumnIndex((int) $startCol);
+ $endCol = Coordinate::stringFromColumnIndex((int) $endCol);
$spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth);
do {
- $spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth);
- } while ($startCol != $endCol);
+ $spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth((float) $columnWidth);
+ } while ($startCol !== $endCol);
}
}
}
@@ -469,7 +474,7 @@ class Slk extends BaseReader
{
if (preg_match('/L([1-9]\\d*)/', $rowDatum, $matches)) {
$fontColor = $matches[1] % 8;
- $formatArray['font']['color']['argb'] = $this->colorArray[$fontColor];
+ $formatArray['font']['color']['argb'] = self::COLOR_ARRAY[$fontColor];
}
}
@@ -478,8 +483,8 @@ class Slk extends BaseReader
$styleSettings = substr($rowDatum, 1);
$iMax = strlen($styleSettings);
for ($i = 0; $i < $iMax; ++$i) {
- if (array_key_exists($styleSettings[$i], $this->fontStyleMappings)) {
- $formatArray['font'][$this->fontStyleMappings[$styleSettings[$i]]] = true;
+ if (array_key_exists($styleSettings[$i], self::FONT_STYLE_MAPPINGS)) {
+ $formatArray['font'][self::FONT_STYLE_MAPPINGS[$styleSettings[$i]]] = true;
}
}
}
@@ -501,14 +506,14 @@ class Slk extends BaseReader
/**
* Loads PhpSpreadsheet from file into PhpSpreadsheet instance.
*
- * @param string $pFilename
+ * @param string $filename
*
* @return Spreadsheet
*/
- public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet)
+ public function loadIntoExisting($filename, Spreadsheet $spreadsheet)
{
// Open file
- $this->canReadOrBust($pFilename);
+ $this->canReadOrBust($filename);
$fileHandle = $this->fileHandle;
rewind($fileHandle);
@@ -517,7 +522,7 @@ class Slk extends BaseReader
$spreadsheet->createSheet();
}
$spreadsheet->setActiveSheetIndex($this->sheetIndex);
- $spreadsheet->getActiveSheet()->setTitle(substr(basename($pFilename, '.slk'), 0, Worksheet::SHEET_TITLE_MAXIMUM_LENGTH));
+ $spreadsheet->getActiveSheet()->setTitle(substr(basename($filename, '.slk'), 0, Worksheet::SHEET_TITLE_MAXIMUM_LENGTH));
// Loop through file
$column = $row = '';
@@ -578,13 +583,13 @@ class Slk extends BaseReader
/**
* Set sheet index.
*
- * @param int $pValue Sheet index
+ * @param int $sheetIndex Sheet index
*
* @return $this
*/
- public function setSheetIndex($pValue)
+ public function setSheetIndex($sheetIndex)
{
- $this->sheetIndex = $pValue;
+ $this->sheetIndex = $sheetIndex;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php
index 124cc3b252f..6b2c2fd6e77 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php
@@ -3,6 +3,7 @@
namespace PhpOffice\PhpSpreadsheet\Reader;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
+use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
@@ -12,11 +13,13 @@ use PhpOffice\PhpSpreadsheet\Reader\Xlsx\ColumnAndRowAttributes;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\ConditionalStyles;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\DataValidations;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Hyperlinks;
+use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\PageSetup;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Properties as PropertyReader;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViewOptions;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViews;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Styles;
+use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Theme;
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Settings;
@@ -26,22 +29,20 @@ use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Shared\Font;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
-use PhpOffice\PhpSpreadsheet\Style\Border;
-use PhpOffice\PhpSpreadsheet\Style\Borders;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
-use PhpOffice\PhpSpreadsheet\Style\Protection;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
-use stdClass;
use Throwable;
use XMLReader;
use ZipArchive;
class Xlsx extends BaseReader
{
+ const INITIAL_FILE = '_rels/.rels';
+
/**
* ReferenceHelper instance.
*
@@ -50,11 +51,12 @@ class Xlsx extends BaseReader
private $referenceHelper;
/**
- * Xlsx\Theme instance.
- *
- * @var Xlsx\Theme
+ * @var ZipArchive
*/
- private static $theme = null;
+ private $zip;
+
+ /** @var Styles */
+ private $styleReader;
/**
* Create a new Xlsx Reader instance.
@@ -68,20 +70,18 @@ class Xlsx extends BaseReader
/**
* Can the current IReader read the file?
- *
- * @param string $pFilename
- *
- * @return bool
*/
- public function canRead($pFilename)
+ public function canRead(string $filename): bool
{
- File::assertFile($pFilename);
+ if (!File::testFileNoThrow($filename, self::INITIAL_FILE)) {
+ return false;
+ }
$result = false;
- $zip = new ZipArchive();
+ $this->zip = $zip = new ZipArchive();
- if ($zip->open($pFilename) === true) {
- $workbookBasename = $this->getWorkbookBaseName($zip);
+ if ($zip->open($filename) === true) {
+ [$workbookBasename] = $this->getWorkbookBaseName();
$result = !empty($workbookBasename);
$zip->close();
@@ -90,41 +90,102 @@ class Xlsx extends BaseReader
return $result;
}
+ /**
+ * @param mixed $value
+ */
+ public static function testSimpleXml($value): SimpleXMLElement
+ {
+ return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement('');
+ }
+
+ public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement
+ {
+ return self::testSimpleXml($value === null ? $value : $value->attributes($ns));
+ }
+
+ // Phpstan thinks, correctly, that xpath can return false.
+ // Scrutinizer thinks it can't.
+ // Sigh.
+ private static function xpathNoFalse(SimpleXmlElement $sxml, string $path): array
+ {
+ return self::falseToArray($sxml->xpath($path));
+ }
+
+ /**
+ * @param mixed $value
+ */
+ public static function falseToArray($value): array
+ {
+ return is_array($value) ? $value : [];
+ }
+
+ private function loadZip(string $filename, string $ns = ''): SimpleXMLElement
+ {
+ $contents = $this->getFromZipArchive($this->zip, $filename);
+ $rels = simplexml_load_string(
+ $this->securityScanner->scan($contents),
+ 'SimpleXMLElement',
+ Settings::getLibXmlLoaderOptions(),
+ $ns
+ );
+
+ return self::testSimpleXml($rels);
+ }
+
+ // This function is just to identify cases where I'm not sure
+ // why empty namespace is required.
+ private function loadZipNonamespace(string $filename, string $ns): SimpleXMLElement
+ {
+ $contents = $this->getFromZipArchive($this->zip, $filename);
+ $rels = simplexml_load_string(
+ $this->securityScanner->scan($contents),
+ 'SimpleXMLElement',
+ Settings::getLibXmlLoaderOptions(),
+ ($ns === '' ? $ns : '')
+ );
+
+ return self::testSimpleXml($rels);
+ }
+
+ private const REL_TO_MAIN = [
+ Namespaces::PURL_OFFICE_DOCUMENT => Namespaces::PURL_MAIN,
+ ];
+
+ private const REL_TO_DRAWING = [
+ Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_DRAWING,
+ ];
+
/**
* Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
*
- * @param string $pFilename
+ * @param string $filename
*
* @return array
*/
- public function listWorksheetNames($pFilename)
+ public function listWorksheetNames($filename)
{
- File::assertFile($pFilename);
+ File::assertFile($filename, self::INITIAL_FILE);
$worksheetNames = [];
- $zip = new ZipArchive();
- $zip->open($pFilename);
+ $this->zip = $zip = new ZipArchive();
+ $zip->open($filename);
// The files we're looking at here are small enough that simpleXML is more efficient than XMLReader
- //~ http://schemas.openxmlformats.org/package/2006/relationships");
- $rels = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels'))
- );
- foreach ($rels->Relationship as $rel) {
- switch ($rel['Type']) {
- case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
- //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
- $xmlWorkbook = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}"))
- );
+ $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
+ foreach ($rels->Relationship as $relx) {
+ $rel = self::getAttributes($relx);
+ $relType = (string) $rel['Type'];
+ $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN;
+ if ($mainNS !== '') {
+ $xmlWorkbook = $this->loadZip((string) $rel['Target'], $mainNS);
- if ($xmlWorkbook->sheets) {
- foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
- // Check if sheet should be skipped
- $worksheetNames[] = (string) $eleSheet['name'];
- }
+ if ($xmlWorkbook->sheets) {
+ foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
+ // Check if sheet should be skipped
+ $worksheetNames[] = (string) self::getAttributes($eleSheet)['name'];
}
+ }
}
}
@@ -136,72 +197,58 @@ class Xlsx extends BaseReader
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
- * @param string $pFilename
+ * @param string $filename
*
* @return array
*/
- public function listWorksheetInfo($pFilename)
+ public function listWorksheetInfo($filename)
{
- File::assertFile($pFilename);
+ File::assertFile($filename, self::INITIAL_FILE);
$worksheetInfo = [];
- $zip = new ZipArchive();
- $zip->open($pFilename);
+ $this->zip = $zip = new ZipArchive();
+ $zip->open($filename);
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $rels = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- foreach ($rels->Relationship as $rel) {
- if ($rel['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument') {
- $dir = dirname($rel['Target']);
-
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $relsWorkbook = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
+ $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
+ foreach ($rels->Relationship as $relx) {
+ $rel = self::getAttributes($relx);
+ $relType = (string) $rel['Type'];
+ $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN;
+ if ($mainNS !== '') {
+ $relTarget = (string) $rel['Target'];
+ $dir = dirname($relTarget);
+ $namespace = dirname($relType);
+ $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', '');
$worksheets = [];
- foreach ($relsWorkbook->Relationship as $ele) {
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet') {
+ foreach ($relsWorkbook->Relationship as $elex) {
+ $ele = self::getAttributes($elex);
+ if ((string) $ele['Type'] === "$namespace/worksheet") {
$worksheets[(string) $ele['Id']] = $ele['Target'];
}
}
- //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
- $xmlWorkbook = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, "{$rel['Target']}")
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $xmlWorkbook = $this->loadZip($relTarget, $mainNS);
if ($xmlWorkbook->sheets) {
- $dir = dirname($rel['Target']);
+ $dir = dirname($relTarget);
/** @var SimpleXMLElement $eleSheet */
foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
$tmpInfo = [
- 'worksheetName' => (string) $eleSheet['name'],
+ 'worksheetName' => (string) self::getAttributes($eleSheet)['name'],
'lastColumnLetter' => 'A',
'lastColumnIndex' => 0,
'totalRows' => 0,
'totalColumns' => 0,
];
- $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
+ $fileWorksheet = (string) $worksheets[(string) self::getArrayItem(self::getAttributes($eleSheet, $namespace), 'id')];
+ $fileWorksheetPath = strpos($fileWorksheet, '/') === 0 ? substr($fileWorksheet, 1) : "$dir/$fileWorksheet";
$xml = new XMLReader();
$xml->xml(
$this->securityScanner->scanFile(
- 'zip://' . File::realpath($pFilename) . '#' . "$dir/$fileWorksheet"
+ 'zip://' . File::realpath($filename) . '#' . $fileWorksheetPath
),
null,
Settings::getLibXmlLoaderOptions()
@@ -210,13 +257,14 @@ class Xlsx extends BaseReader
$currCells = 0;
while ($xml->read()) {
- if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) {
+ if ($xml->localName == 'row' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) {
$row = $xml->getAttribute('r');
$tmpInfo['totalRows'] = $row;
$tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
$currCells = 0;
- } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) {
- ++$currCells;
+ } elseif ($xml->localName == 'c' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) {
+ $cell = $xml->getAttribute('r');
+ $currCells = $cell ? max($currCells, Coordinate::indexesFromString($cell)[0]) : ($currCells + 1);
}
}
$tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
@@ -260,22 +308,23 @@ class Xlsx extends BaseReader
private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType): void
{
+ $attr = $c->f->attributes();
$cellDataType = 'f';
$value = "={$c->f}";
$calculatedValue = self::$castBaseType($c);
// Shared formula?
- if (isset($c->f['t']) && strtolower((string) $c->f['t']) == 'shared') {
- $instance = (string) $c->f['si'];
+ if (isset($attr['t']) && strtolower((string) $attr['t']) == 'shared') {
+ $instance = (string) $attr['si'];
- if (!isset($sharedFormulas[(string) $c->f['si']])) {
+ if (!isset($sharedFormulas[(string) $attr['si']])) {
$sharedFormulas[$instance] = ['master' => $r, 'formula' => $value];
} else {
- $master = Coordinate::coordinateFromString($sharedFormulas[$instance]['master']);
- $current = Coordinate::coordinateFromString($r);
+ $master = Coordinate::indexesFromString($sharedFormulas[$instance]['master']);
+ $current = Coordinate::indexesFromString($r);
$difference = [0, 0];
- $difference[0] = Coordinate::columnIndexFromString($current[0]) - Coordinate::columnIndexFromString($master[0]);
+ $difference[0] = $current[0] - $master[0];
$difference[1] = $current[1] - $master[1];
$value = $this->referenceHelper->updateFormulaReferences($sharedFormulas[$instance]['formula'], 'A1', $difference[0], $difference[1]);
@@ -283,6 +332,29 @@ class Xlsx extends BaseReader
}
}
+ /**
+ * @param string $fileName
+ */
+ private function fileExistsInArchive(ZipArchive $archive, $fileName = ''): bool
+ {
+ // Root-relative paths
+ if (strpos($fileName, '//') !== false) {
+ $fileName = substr($fileName, strpos($fileName, '//') + 1);
+ }
+ $fileName = File::realpath($fileName);
+
+ // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming
+ // so we need to load case-insensitively from the zip file
+
+ // Apache POI fixes
+ $contents = $archive->locateName($fileName, ZipArchive::FL_NOCASE);
+ if ($contents === false) {
+ $contents = $archive->locateName(substr($fileName, 1), ZipArchive::FL_NOCASE);
+ }
+
+ return $contents !== false;
+ }
+
/**
* @param string $fileName
*
@@ -310,126 +382,113 @@ class Xlsx extends BaseReader
/**
* Loads Spreadsheet from file.
- *
- * @param string $pFilename
- *
- * @return Spreadsheet
*/
- public function load($pFilename)
+ public function load(string $filename, int $flags = 0): Spreadsheet
{
- File::assertFile($pFilename);
+ File::assertFile($filename, self::INITIAL_FILE);
+ $this->processFlags($flags);
// Initialisations
$excel = new Spreadsheet();
$excel->removeSheetByIndex(0);
- if (!$this->readDataOnly) {
- $excel->removeCellStyleXfByIndex(0); // remove the default style
- $excel->removeCellXfByIndex(0); // remove the default style
- }
+ $addingFirstCellStyleXf = true;
+ $addingFirstCellXf = true;
+
$unparsedLoadedData = [];
- $zip = new ZipArchive();
- $zip->open($pFilename);
+ $this->zip = $zip = new ZipArchive();
+ $zip->open($filename);
// Read the theme first, because we need the colour scheme when reading the styles
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $workbookBasename = $this->getWorkbookBaseName($zip);
- $wbRels = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, "xl/_rels/${workbookBasename}.rels")),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- foreach ($wbRels->Relationship as $rel) {
+ [$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName();
+ $wbRels = $this->loadZip("xl/_rels/${workbookBasename}.rels", Namespaces::RELATIONSHIPS);
+ $theme = null;
+ $this->styleReader = new Styles();
+ foreach ($wbRels->Relationship as $relx) {
+ $rel = self::getAttributes($relx);
+ $relTarget = (string) $rel['Target'];
switch ($rel['Type']) {
- case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme':
+ case "$xmlNamespaceBase/theme":
$themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2'];
$themeOrderAdditional = count($themeOrderArray);
+ $drawingNS = self::REL_TO_DRAWING[$xmlNamespaceBase] ?? Namespaces::DRAWINGML;
- $xmlTheme = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, "xl/{$rel['Target']}")),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- if (is_object($xmlTheme)) {
- $xmlThemeName = $xmlTheme->attributes();
- $xmlTheme = $xmlTheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
- $themeName = (string) $xmlThemeName['name'];
+ $xmlTheme = $this->loadZip("xl/{$relTarget}", $drawingNS);
+ $xmlThemeName = self::getAttributes($xmlTheme);
+ $xmlTheme = $xmlTheme->children($drawingNS);
+ $themeName = (string) $xmlThemeName['name'];
- $colourScheme = $xmlTheme->themeElements->clrScheme->attributes();
- $colourSchemeName = (string) $colourScheme['name'];
- $colourScheme = $xmlTheme->themeElements->clrScheme->children('http://schemas.openxmlformats.org/drawingml/2006/main');
+ $colourScheme = self::getAttributes($xmlTheme->themeElements->clrScheme);
+ $colourSchemeName = (string) $colourScheme['name'];
+ $colourScheme = $xmlTheme->themeElements->clrScheme->children($drawingNS);
- $themeColours = [];
- foreach ($colourScheme as $k => $xmlColour) {
- $themePos = array_search($k, $themeOrderArray);
- if ($themePos === false) {
- $themePos = $themeOrderAdditional++;
- }
- if (isset($xmlColour->sysClr)) {
- $xmlColourData = $xmlColour->sysClr->attributes();
- $themeColours[$themePos] = $xmlColourData['lastClr'];
- } elseif (isset($xmlColour->srgbClr)) {
- $xmlColourData = $xmlColour->srgbClr->attributes();
- $themeColours[$themePos] = $xmlColourData['val'];
- }
+ $themeColours = [];
+ foreach ($colourScheme as $k => $xmlColour) {
+ $themePos = array_search($k, $themeOrderArray);
+ if ($themePos === false) {
+ $themePos = $themeOrderAdditional++;
+ }
+ if (isset($xmlColour->sysClr)) {
+ $xmlColourData = self::getAttributes($xmlColour->sysClr);
+ $themeColours[$themePos] = (string) $xmlColourData['lastClr'];
+ } elseif (isset($xmlColour->srgbClr)) {
+ $xmlColourData = self::getAttributes($xmlColour->srgbClr);
+ $themeColours[$themePos] = (string) $xmlColourData['val'];
}
- self::$theme = new Xlsx\Theme($themeName, $colourSchemeName, $themeColours);
}
+ $theme = new Theme($themeName, $colourSchemeName, $themeColours);
+ $this->styleReader->setTheme($theme);
break;
}
}
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $rels = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
$propertyReader = new PropertyReader($this->securityScanner, $excel->getProperties());
- foreach ($rels->Relationship as $rel) {
- switch ($rel['Type']) {
- case 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties':
- $propertyReader->readCoreProperties($this->getFromZipArchive($zip, "{$rel['Target']}"));
+ foreach ($rels->Relationship as $relx) {
+ $rel = self::getAttributes($relx);
+ $relTarget = (string) $rel['Target'];
+ $relType = (string) $rel['Type'];
+ $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN;
+ switch ($relType) {
+ case Namespaces::CORE_PROPERTIES:
+ $propertyReader->readCoreProperties($this->getFromZipArchive($zip, $relTarget));
break;
- case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties':
- $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, "{$rel['Target']}"));
+ case "$xmlNamespaceBase/extended-properties":
+ $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, $relTarget));
break;
- case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties':
- $propertyReader->readCustomProperties($this->getFromZipArchive($zip, "{$rel['Target']}"));
+ case "$xmlNamespaceBase/custom-properties":
+ $propertyReader->readCustomProperties($this->getFromZipArchive($zip, $relTarget));
break;
//Ribbon
- case 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility':
- $customUI = $rel['Target'];
- if ($customUI !== null) {
+ case Namespaces::EXTENSIBILITY:
+ $customUI = $relTarget;
+ if ($customUI) {
$this->readRibbon($excel, $customUI, $zip);
}
break;
- case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
- $dir = dirname($rel['Target']);
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $relsWorkbook = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships');
+ case "$xmlNamespaceBase/officeDocument":
+ $dir = dirname($relTarget);
+
+ // Do not specify namespace in next stmt - do it in Xpath
+ $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', '');
+ $relsWorkbook->registerXPathNamespace('rel', Namespaces::RELATIONSHIPS);
$sharedStrings = [];
- $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']"));
+ $relType = "rel:Relationship[@Type='"
+ //. Namespaces::SHARED_STRINGS
+ . "$xmlNamespaceBase/sharedStrings"
+ . "']";
+ $xpath = self::getArrayItem($relsWorkbook->xpath($relType));
+
if ($xpath) {
- //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
- $xmlStrings = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- if (isset($xmlStrings, $xmlStrings->si)) {
+ $xmlStrings = $this->loadZip("$dir/$xpath[Target]", $mainNS);
+ if (isset($xmlStrings->si)) {
foreach ($xmlStrings->si as $val) {
if (isset($val->t)) {
$sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t);
@@ -442,14 +501,16 @@ class Xlsx extends BaseReader
$worksheets = [];
$macros = $customUI = null;
- foreach ($relsWorkbook->Relationship as $ele) {
+ foreach ($relsWorkbook->Relationship as $elex) {
+ $ele = self::getAttributes($elex);
switch ($ele['Type']) {
- case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet':
+ case Namespaces::WORKSHEET:
+ case Namespaces::PURL_WORKSHEET:
$worksheets[(string) $ele['Id']] = $ele['Target'];
break;
// a vbaProject ? (: some macros)
- case 'http://schemas.microsoft.com/office/2006/relationships/vbaProject':
+ case Namespaces::VBA:
$macros = $ele['Target'];
break;
@@ -469,26 +530,38 @@ class Xlsx extends BaseReader
}
}
- $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']"));
- //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
- $xmlStyles = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $relType = "rel:Relationship[@Type='"
+ . "$xmlNamespaceBase/styles"
+ . "']";
+ $xpath = self::getArrayItem(self::xpathNoFalse($relsWorkbook, $relType));
+
+ if ($xpath === null) {
+ $xmlStyles = self::testSimpleXml(null);
+ } else {
+ // I think Nonamespace is okay because I'm using xpath.
+ $xmlStyles = $this->loadZipNonamespace("$dir/$xpath[Target]", $mainNS);
+ }
+
+ $xmlStyles->registerXPathNamespace('smm', Namespaces::MAIN);
+ $fills = self::xpathNoFalse($xmlStyles, 'smm:fills/smm:fill');
+ $fonts = self::xpathNoFalse($xmlStyles, 'smm:fonts/smm:font');
+ $borders = self::xpathNoFalse($xmlStyles, 'smm:borders/smm:border');
+ $xfTags = self::xpathNoFalse($xmlStyles, 'smm:cellXfs/smm:xf');
+ $cellXfTags = self::xpathNoFalse($xmlStyles, 'smm:cellStyleXfs/smm:xf');
$styles = [];
$cellStyles = [];
$numFmts = null;
- if ($xmlStyles && $xmlStyles->numFmts[0]) {
+ if (/*$xmlStyles && */ $xmlStyles->numFmts[0]) {
$numFmts = $xmlStyles->numFmts[0];
}
if (isset($numFmts) && ($numFmts !== null)) {
- $numFmts->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
+ $numFmts->registerXPathNamespace('sml', $mainNS);
}
- if (!$this->readDataOnly && $xmlStyles) {
- foreach ($xmlStyles->cellXfs->xf as $xf) {
- $numFmt = NumberFormat::FORMAT_GENERAL;
+ if (!$this->readDataOnly/* && $xmlStyles*/) {
+ foreach ($xfTags as $xfTag) {
+ $xf = self::getAttributes($xfTag);
+ $numFmt = null;
if ($xf['numFmtId']) {
if (isset($numFmts)) {
@@ -503,35 +576,38 @@ class Xlsx extends BaseReader
// But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used
// So we make allowance for them rather than lose formatting masks
if (
+ $numFmt === null &&
(int) $xf['numFmtId'] < 164 &&
NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== ''
) {
$numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']);
}
}
- $quotePrefix = false;
- if (isset($xf['quotePrefix'])) {
- $quotePrefix = (bool) $xf['quotePrefix'];
- }
+ $quotePrefix = (bool) ($xf['quotePrefix'] ?? false);
$style = (object) [
- 'numFmt' => $numFmt,
- 'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
- 'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
- 'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
- 'alignment' => $xf->alignment,
- 'protection' => $xf->protection,
+ 'numFmt' => $numFmt ?? NumberFormat::FORMAT_GENERAL,
+ 'font' => $fonts[(int) ($xf['fontId'])],
+ 'fill' => $fills[(int) ($xf['fillId'])],
+ 'border' => $borders[(int) ($xf['borderId'])],
+ 'alignment' => $xfTag->alignment,
+ 'protection' => $xfTag->protection,
'quotePrefix' => $quotePrefix,
];
$styles[] = $style;
// add style to cellXf collection
$objStyle = new Style();
- self::readStyle($objStyle, $style);
+ $this->styleReader->readStyle($objStyle, $style);
+ if ($addingFirstCellXf) {
+ $excel->removeCellXfByIndex(0); // remove the default style
+ $addingFirstCellXf = false;
+ }
$excel->addCellXf($objStyle);
}
- foreach (isset($xmlStyles->cellStyleXfs->xf) ? $xmlStyles->cellStyleXfs->xf : [] as $xf) {
+ foreach ($cellXfTags as $xfTag) {
+ $xf = self::getAttributes($xfTag);
$numFmt = NumberFormat::FORMAT_GENERAL;
if ($numFmts && $xf['numFmtId']) {
$tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]"));
@@ -542,41 +618,43 @@ class Xlsx extends BaseReader
}
}
+ $quotePrefix = (bool) ($xf['quotePrefix'] ?? false);
+
$cellStyle = (object) [
'numFmt' => $numFmt,
- 'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])],
- 'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])],
- 'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])],
- 'alignment' => $xf->alignment,
- 'protection' => $xf->protection,
+ 'font' => $fonts[(int) ($xf['fontId'])],
+ 'fill' => $fills[((int) $xf['fillId'])],
+ 'border' => $borders[(int) ($xf['borderId'])],
+ 'alignment' => $xfTag->alignment,
+ 'protection' => $xfTag->protection,
'quotePrefix' => $quotePrefix,
];
$cellStyles[] = $cellStyle;
// add style to cellStyleXf collection
$objStyle = new Style();
- self::readStyle($objStyle, $cellStyle);
+ $this->styleReader->readStyle($objStyle, $cellStyle);
+ if ($addingFirstCellStyleXf) {
+ $excel->removeCellStyleXfByIndex(0); // remove the default style
+ $addingFirstCellStyleXf = false;
+ }
$excel->addCellStyleXf($objStyle);
}
}
+ $this->styleReader->setStyleXml($xmlStyles);
+ $this->styleReader->setStyleBaseData($theme, $styles, $cellStyles);
+ $dxfs = $this->styleReader->dxfs($this->readDataOnly);
+ $styles = $this->styleReader->styles();
- $styleReader = new Styles($xmlStyles);
- $styleReader->setStyleBaseData(self::$theme, $styles, $cellStyles);
- $dxfs = $styleReader->dxfs($this->readDataOnly);
- $styles = $styleReader->styles();
-
- //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
- $xmlWorkbook = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}")),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $xmlWorkbook = $this->loadZipNoNamespace($relTarget, $mainNS);
+ $xmlWorkbookNS = $this->loadZip($relTarget, $mainNS);
// Set base date
- if ($xmlWorkbook->workbookPr) {
+ if ($xmlWorkbookNS->workbookPr) {
Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900);
- if (isset($xmlWorkbook->workbookPr['date1904'])) {
- if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) {
+ $attrs1904 = self::getAttributes($xmlWorkbookNS->workbookPr);
+ if (isset($attrs1904['date1904'])) {
+ if (self::boolean((string) $attrs1904['date1904'])) {
Date::setExcelCalendar(Date::CALENDAR_MAC_1904);
}
}
@@ -592,13 +670,14 @@ class Xlsx extends BaseReader
$charts = $chartDetails = [];
- if ($xmlWorkbook->sheets) {
+ if ($xmlWorkbookNS->sheets) {
/** @var SimpleXMLElement $eleSheet */
- foreach ($xmlWorkbook->sheets->sheet as $eleSheet) {
+ foreach ($xmlWorkbookNS->sheets->sheet as $eleSheet) {
+ $eleSheetAttr = self::getAttributes($eleSheet);
++$oldSheetId;
// Check if sheet should be skipped
- if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet['name'], $this->loadSheetsOnly)) {
+ if (is_array($this->loadSheetsOnly) && !in_array((string) $eleSheetAttr['name'], $this->loadSheetsOnly)) {
++$countSkippedSheets;
$mapSheetId[$oldSheetId] = null;
@@ -615,44 +694,46 @@ class Xlsx extends BaseReader
// references in formula cells... during the load, all formulae should be correct,
// and we're simply bringing the worksheet name in line with the formula, not the
// reverse
- $docSheet->setTitle((string) $eleSheet['name'], false, false);
- $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')];
- //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"
- $xmlSheet = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $docSheet->setTitle((string) $eleSheetAttr['name'], false, false);
+ $fileWorksheet = (string) $worksheets[(string) self::getArrayItem(self::getAttributes($eleSheet, $xmlNamespaceBase), 'id')];
+ $xmlSheet = $this->loadZipNoNamespace("$dir/$fileWorksheet", $mainNS);
+ $xmlSheetNS = $this->loadZip("$dir/$fileWorksheet", $mainNS);
$sharedFormulas = [];
- if (isset($eleSheet['state']) && (string) $eleSheet['state'] != '') {
- $docSheet->setSheetState((string) $eleSheet['state']);
+ if (isset($eleSheetAttr['state']) && (string) $eleSheetAttr['state'] != '') {
+ $docSheet->setSheetState((string) $eleSheetAttr['state']);
}
-
- if ($xmlSheet) {
- if (isset($xmlSheet->sheetViews, $xmlSheet->sheetViews->sheetView)) {
- $sheetViews = new SheetViews($xmlSheet->sheetViews->sheetView, $docSheet);
+ if ($xmlSheetNS) {
+ $xmlSheetMain = $xmlSheetNS->children($mainNS);
+ // Setting Conditional Styles adjusts selected cells, so we need to execute this
+ // before reading the sheet view data to get the actual selected cells
+ if (!$this->readDataOnly && $xmlSheet->conditionalFormatting) {
+ (new ConditionalStyles($docSheet, $xmlSheet, $dxfs))->load();
+ }
+ if (isset($xmlSheetMain->sheetViews, $xmlSheetMain->sheetViews->sheetView)) {
+ $sheetViews = new SheetViews($xmlSheetMain->sheetViews->sheetView, $docSheet);
$sheetViews->load();
}
$sheetViewOptions = new SheetViewOptions($docSheet, $xmlSheet);
- $sheetViewOptions->load($this->getReadDataOnly());
+ $sheetViewOptions->load($this->getReadDataOnly(), $this->styleReader);
(new ColumnAndRowAttributes($docSheet, $xmlSheet))
->load($this->getReadFilter(), $this->getReadDataOnly());
}
- if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) {
+ if ($xmlSheetNS && $xmlSheetNS->sheetData && $xmlSheetNS->sheetData->row) {
$cIndex = 1; // Cell Start from 1
- foreach ($xmlSheet->sheetData->row as $row) {
+ foreach ($xmlSheetNS->sheetData->row as $row) {
$rowIndex = 1;
foreach ($row->c as $c) {
- $r = (string) $c['r'];
+ $cAttr = self::getAttributes($c);
+ $r = (string) $cAttr['r'];
if ($r == '') {
$r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex;
}
- $cellDataType = (string) $c['t'];
+ $cellDataType = (string) $cAttr['t'];
$value = null;
$calculatedValue = null;
@@ -661,7 +742,7 @@ class Xlsx extends BaseReader
$coordinates = Coordinate::coordinateFromString($r);
if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) {
- if (isset($c->f)) {
+ if (isset($cAttr->f)) {
$this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError');
}
++$rowIndex;
@@ -720,6 +801,10 @@ class Xlsx extends BaseReader
} else {
// Formula
$this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString');
+ if (isset($c->f['t'])) {
+ $attributes = $c->f['t'];
+ $docSheet->getCell($r)->setFormulaAttributes(['t' => (string) $attributes]);
+ }
}
break;
@@ -735,6 +820,10 @@ class Xlsx extends BaseReader
$cell = $docSheet->getCell($r);
// Assign value
if ($cellDataType != '') {
+ // it is possible, that datatype is numeric but with an empty string, which result in an error
+ if ($cellDataType === DataType::TYPE_NUMERIC && $value === '') {
+ $cellDataType = DataType::TYPE_STRING;
+ }
$cell->setValueExplicit($value, $cellDataType);
} else {
$cell->setValue($value);
@@ -744,10 +833,10 @@ class Xlsx extends BaseReader
}
// Style information?
- if ($c['s'] && !$this->readDataOnly) {
+ if ($cAttr['s'] && !$this->readDataOnly) {
// no style index means 0, it seems
- $cell->setXfIndex(isset($styles[(int) ($c['s'])]) ?
- (int) ($c['s']) : 0);
+ $cell->setXfIndex(isset($styles[(int) ($cAttr['s'])]) ?
+ (int) ($cAttr['s']) : 0);
}
}
++$rowIndex;
@@ -756,10 +845,6 @@ class Xlsx extends BaseReader
}
}
- if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) {
- (new ConditionalStyles($docSheet, $xmlSheet, $dxfs))->load();
- }
-
$aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells'];
if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) {
foreach ($aKeys as $key) {
@@ -772,8 +857,8 @@ class Xlsx extends BaseReader
$this->readSheetProtection($docSheet, $xmlSheet);
}
- if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) {
- (new AutoFilter($docSheet, $xmlSheet))->load();
+ if ($this->readDataOnly === false) {
+ $this->readAutoFilterTables($xmlSheet, $docSheet, $dir, $fileWorksheet, $zip);
}
if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) {
@@ -789,15 +874,32 @@ class Xlsx extends BaseReader
$unparsedLoadedData = (new PageSetup($docSheet, $xmlSheet))->load($unparsedLoadedData);
}
+ if ($xmlSheet !== false && isset($xmlSheet->extLst, $xmlSheet->extLst->ext, $xmlSheet->extLst->ext['uri']) && ($xmlSheet->extLst->ext['uri'] == '{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}')) {
+ // Create dataValidations node if does not exists, maybe is better inside the foreach ?
+ if (!$xmlSheet->dataValidations) {
+ $xmlSheet->addChild('dataValidations');
+ }
+
+ foreach ($xmlSheet->extLst->ext->children('x14', true)->dataValidations->dataValidation as $item) {
+ $node = $xmlSheet->dataValidations->addChild('dataValidation');
+ foreach ($item->attributes() ?? [] as $attr) {
+ $node->addAttribute($attr->getName(), $attr);
+ }
+ $node->addAttribute('sqref', $item->children('xm', true)->sqref);
+ $node->addChild('formula1', $item->formula1->children('xm', true)->f);
+ }
+ }
+
if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) {
(new DataValidations($docSheet, $xmlSheet))->load();
}
// unparsed sheet AlternateContent
if ($xmlSheet && !$this->readDataOnly) {
- $mc = $xmlSheet->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
+ $mc = $xmlSheet->children(Namespaces::COMPATIBILITY);
if ($mc->AlternateContent) {
foreach ($mc->AlternateContent as $alternateContent) {
+ $alternateContent = self::testSimpleXml($alternateContent);
$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML();
}
}
@@ -809,20 +911,13 @@ class Xlsx extends BaseReader
// Locate hyperlink relations
$relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
if ($zip->locateName($relationsFileName)) {
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $relsWorksheet = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, $relationsFileName)
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $relsWorksheet = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS);
$hyperlinkReader->readHyperlinks($relsWorksheet);
}
// Loop through hyperlinks
- if ($xmlSheet && $xmlSheet->hyperlinks) {
- $hyperlinkReader->setHyperlinks($xmlSheet->hyperlinks);
+ if ($xmlSheetNS && $xmlSheetNS->children($mainNS)->hyperlinks) {
+ $hyperlinkReader->setHyperlinks($xmlSheetNS->children($mainNS)->hyperlinks);
}
}
@@ -831,20 +926,15 @@ class Xlsx extends BaseReader
$vmlComments = [];
if (!$this->readDataOnly) {
// Locate comment relations
- if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $relsWorksheet = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- foreach ($relsWorksheet->Relationship as $ele) {
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') {
+ $commentRelations = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
+ if ($zip->locateName($commentRelations)) {
+ $relsWorksheet = $this->loadZip($commentRelations, Namespaces::RELATIONSHIPS);
+ foreach ($relsWorksheet->Relationship as $elex) {
+ $ele = self::getAttributes($elex);
+ if ($ele['Type'] == Namespaces::COMMENTS) {
$comments[(string) $ele['Id']] = (string) $ele['Target'];
}
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
+ if ($ele['Type'] == Namespaces::VML) {
$vmlComments[(string) $ele['Id']] = (string) $ele['Target'];
}
}
@@ -854,26 +944,26 @@ class Xlsx extends BaseReader
foreach ($comments as $relName => $relPath) {
// Load comments file
$relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
- $commentsFile = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ // okay to ignore namespace - using xpath
+ $commentsFile = $this->loadZip($relPath, '');
// Utility variables
$authors = [];
-
- // Loop through authors
- foreach ($commentsFile->authors->author as $author) {
+ $commentsFile->registerXpathNamespace('com', $mainNS);
+ $authorPath = self::xpathNoFalse($commentsFile, 'com:authors/com:author');
+ foreach ($authorPath as $author) {
$authors[] = (string) $author;
}
// Loop through contents
- foreach ($commentsFile->commentList->comment as $comment) {
- if (!empty($comment['authorId'])) {
- $docSheet->getComment((string) $comment['ref'])->setAuthor($authors[(string) $comment['authorId']]);
+ $contentPath = self::xpathNoFalse($commentsFile, 'com:commentList/com:comment');
+ foreach ($contentPath as $comment) {
+ $commentx = $comment->attributes();
+ $commentModel = $docSheet->getComment((string) $commentx['ref']);
+ if (isset($commentx['authorId'])) {
+ $commentModel->setAuthor($authors[(int) $commentx['authorId']]);
}
- $docSheet->getComment((string) $comment['ref'])->setText($this->parseRichText($comment->text));
+ $commentModel->setText($this->parseRichText($comment->children($mainNS)->text));
}
}
@@ -886,26 +976,38 @@ class Xlsx extends BaseReader
$relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath);
try {
- $vmlCommentsFile = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
+ // no namespace okay - processed with Xpath
+ $vmlCommentsFile = $this->loadZip($relPath, '');
+ $vmlCommentsFile->registerXPathNamespace('v', Namespaces::URN_VML);
} catch (Throwable $ex) {
//Ignore unparsable vmlDrawings. Later they will be moved from $unparsedVmlDrawings to $unparsedLoadedData
continue;
}
- $shapes = $vmlCommentsFile->xpath('//v:shape');
+ // Locate VML drawings image relations
+ $drowingImages = [];
+ $VMLDrawingsRelations = dirname($relPath) . '/_rels/' . basename($relPath) . '.rels';
+ if ($zip->locateName($VMLDrawingsRelations)) {
+ $relsVMLDrawing = $this->loadZip($VMLDrawingsRelations, Namespaces::RELATIONSHIPS);
+ foreach ($relsVMLDrawing->Relationship as $elex) {
+ $ele = self::getAttributes($elex);
+ if ($ele['Type'] == Namespaces::IMAGE) {
+ $drowingImages[(string) $ele['Id']] = (string) $ele['Target'];
+ }
+ }
+ }
+
+ $shapes = self::xpathNoFalse($vmlCommentsFile, '//v:shape');
foreach ($shapes as $shape) {
- $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
+ $shape->registerXPathNamespace('v', Namespaces::URN_VML);
if (isset($shape['style'])) {
$style = (string) $shape['style'];
$fillColor = strtoupper(substr((string) $shape['fillcolor'], 1));
$column = null;
$row = null;
+ $fillImageRelId = null;
+ $fillImageTitle = '';
$clientData = $shape->xpath('.//x:ClientData');
if (is_array($clientData) && !empty($clientData)) {
@@ -924,10 +1026,39 @@ class Xlsx extends BaseReader
}
}
+ $fillImageRelNode = $shape->xpath('.//v:fill/@o:relid');
+ if (is_array($fillImageRelNode) && !empty($fillImageRelNode)) {
+ $fillImageRelNode = $fillImageRelNode[0];
+
+ if (isset($fillImageRelNode['relid'])) {
+ $fillImageRelId = (string) $fillImageRelNode['relid'];
+ }
+ }
+
+ $fillImageTitleNode = $shape->xpath('.//v:fill/@o:title');
+ if (is_array($fillImageTitleNode) && !empty($fillImageTitleNode)) {
+ $fillImageTitleNode = $fillImageTitleNode[0];
+
+ if (isset($fillImageTitleNode['title'])) {
+ $fillImageTitle = (string) $fillImageTitleNode['title'];
+ }
+ }
+
if (($column !== null) && ($row !== null)) {
// Set comment properties
$comment = $docSheet->getCommentByColumnAndRow($column + 1, $row + 1);
$comment->getFillColor()->setRGB($fillColor);
+ if (isset($drowingImages[$fillImageRelId])) {
+ $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
+ $objDrawing->setName($fillImageTitle);
+ $imagePath = str_replace('../', 'xl/', $drowingImages[$fillImageRelId]);
+ $objDrawing->setPath(
+ 'zip://' . File::realpath($filename) . '#' . $imagePath,
+ true,
+ $zip
+ );
+ $comment->setBackgroundImage($objDrawing);
+ }
// Parse style
$styleArray = explode(';', str_replace(' ', '', $style));
@@ -973,62 +1104,44 @@ class Xlsx extends BaseReader
// Header/footer images
if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) {
if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $relsWorksheet = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $relsWorksheet = $this->loadZipNoNamespace(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels', Namespaces::RELATIONSHIPS);
$vmlRelationship = '';
foreach ($relsWorksheet->Relationship as $ele) {
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') {
+ if ($ele['Type'] == Namespaces::VML) {
$vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
}
}
if ($vmlRelationship != '') {
// Fetch linked images
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $relsVML = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels')
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $relsVML = $this->loadZipNoNamespace(dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels', Namespaces::RELATIONSHIPS);
$drawings = [];
if (isset($relsVML->Relationship)) {
foreach ($relsVML->Relationship as $ele) {
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
+ if ($ele['Type'] == Namespaces::IMAGE) {
$drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']);
}
}
}
// Fetch VML document
- $vmlDrawing = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, $vmlRelationship)),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
+ $vmlDrawing = $this->loadZipNoNamespace($vmlRelationship, '');
+ $vmlDrawing->registerXPathNamespace('v', Namespaces::URN_VML);
$hfImages = [];
- $shapes = $vmlDrawing->xpath('//v:shape');
+ $shapes = self::xpathNoFalse($vmlDrawing, '//v:shape');
foreach ($shapes as $idx => $shape) {
- $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml');
+ $shape->registerXPathNamespace('v', Namespaces::URN_VML);
$imageData = $shape->xpath('//v:imagedata');
- if (!$imageData) {
+ if (empty($imageData)) {
continue;
}
$imageData = $imageData[$idx];
- $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office');
+ $imageData = self::getAttributes($imageData, Namespaces::URN_MSOFFICE);
$style = self::toCSSArray((string) $shape['style']);
$hfImages[(string) $shape['id']] = new HeaderFooterDrawing();
@@ -1036,7 +1149,7 @@ class Xlsx extends BaseReader
$hfImages[(string) $shape['id']]->setName((string) $imageData['title']);
}
- $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false);
+ $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($filename) . '#' . $drawings[(string) $imageData['relid']], false);
$hfImages[(string) $shape['id']]->setResizeProportional(false);
$hfImages[(string) $shape['id']]->setWidth($style['width']);
$hfImages[(string) $shape['id']]->setHeight($style['height']);
@@ -1054,44 +1167,37 @@ class Xlsx extends BaseReader
}
// TODO: Autoshapes from twoCellAnchors!
- if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $relsWorksheet = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $drawingFilename = dirname("$dir/$fileWorksheet")
+ . '/_rels/'
+ . basename($fileWorksheet)
+ . '.rels';
+ if ($zip->locateName($drawingFilename)) {
+ $relsWorksheet = $this->loadZipNoNamespace($drawingFilename, Namespaces::RELATIONSHIPS);
$drawings = [];
foreach ($relsWorksheet->Relationship as $ele) {
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
+ if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") {
$drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']);
}
}
if ($xmlSheet->drawing && !$this->readDataOnly) {
$unparsedDrawings = [];
+ $fileDrawing = null;
foreach ($xmlSheet->drawing as $drawing) {
- $drawingRelId = (string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id');
+ $drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id');
$fileDrawing = $drawings[$drawingRelId];
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $relsDrawing = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels')
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $drawingFilename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels';
+ $relsDrawing = $this->loadZipNoNamespace($drawingFilename, $xmlNamespaceBase);
$images = [];
$hyperlinks = [];
if ($relsDrawing && $relsDrawing->Relationship) {
foreach ($relsDrawing->Relationship as $ele) {
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
+ $eleType = (string) $ele['Type'];
+ if ($eleType === Namespaces::HYPERLINK) {
$hyperlinks[(string) $ele['Id']] = (string) $ele['Target'];
}
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
+ if ($eleType === "$xmlNamespaceBase/image") {
$images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']);
- } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') {
+ } elseif ($eleType === "$xmlNamespaceBase/chart") {
if ($this->includeCharts) {
$charts[self::dirAdd($fileDrawing, $ele['Target'])] = [
'id' => (string) $ele['Id'],
@@ -1101,124 +1207,160 @@ class Xlsx extends BaseReader
}
}
}
- $xmlDrawing = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- $xmlDrawingChildren = $xmlDrawing->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
+ $xmlDrawing = $this->loadZipNoNamespace($fileDrawing, '');
+ $xmlDrawingChildren = $xmlDrawing->children(Namespaces::SPREADSHEET_DRAWING);
if ($xmlDrawingChildren->oneCellAnchor) {
foreach ($xmlDrawingChildren->oneCellAnchor as $oneCellAnchor) {
if ($oneCellAnchor->pic->blipFill) {
/** @var SimpleXMLElement $blip */
- $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
+ $blip = $oneCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip;
/** @var SimpleXMLElement $xfrm */
- $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
+ $xfrm = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm;
/** @var SimpleXMLElement $outerShdw */
- $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
+ $outerShdw = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw;
/** @var SimpleXMLElement $hlinkClick */
- $hlinkClick = $oneCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
+ $hlinkClick = $oneCellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick;
$objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
- $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
- $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
- $objDrawing->setPath(
- 'zip://' . File::realpath($pFilename) . '#' .
- $images[(string) self::getArrayItem(
- $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
- 'embed'
- )],
- false
+ $objDrawing->setName((string) self::getArrayItem(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'name'));
+ $objDrawing->setDescription((string) self::getArrayItem(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'descr'));
+ $embedImageKey = (string) self::getArrayItem(
+ self::getAttributes($blip, $xmlNamespaceBase),
+ 'embed'
);
- $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
- $objDrawing->setOffsetX(Drawing::EMUToPixels($oneCellAnchor->from->colOff));
+ if (isset($images[$embedImageKey])) {
+ $objDrawing->setPath(
+ 'zip://' . File::realpath($filename) . '#' .
+ $images[$embedImageKey],
+ false
+ );
+ } else {
+ $linkImageKey = (string) self::getArrayItem(
+ $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
+ 'link'
+ );
+ if (isset($images[$linkImageKey])) {
+ $url = str_replace('xl/drawings/', '', $images[$linkImageKey]);
+ $objDrawing->setPath($url);
+ }
+ }
+ $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
+
+ $objDrawing->setOffsetX((int) Drawing::EMUToPixels($oneCellAnchor->from->colOff));
$objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff));
$objDrawing->setResizeProportional(false);
- $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')));
- $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')));
+ $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem((int) self::getAttributes($oneCellAnchor->ext), 'cx')));
+ $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem((int) self::getAttributes($oneCellAnchor->ext), 'cy')));
if ($xfrm) {
- $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
+ $objDrawing->setRotation((int) Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($xfrm), 'rot')));
}
if ($outerShdw) {
$shadow = $objDrawing->getShadow();
$shadow->setVisible(true);
- $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'blurRad')));
- $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
- $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
- $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn'));
- $clr = isset($outerShdw->srgbClr) ? $outerShdw->srgbClr : $outerShdw->prstClr;
- $shadow->getColor()->setRGB(self::getArrayItem($clr->attributes(), 'val'));
- $shadow->setAlpha(self::getArrayItem($clr->alpha->attributes(), 'val') / 1000);
+ $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'blurRad')));
+ $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'dist')));
+ $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($outerShdw), 'dir')));
+ $shadow->setAlignment((string) self::getArrayItem(self::getAttributes($outerShdw), 'algn'));
+ $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr;
+ $shadow->getColor()->setRGB(self::getArrayItem(self::getAttributes($clr), 'val'));
+ $shadow->setAlpha(self::getArrayItem(self::getAttributes($clr->alpha), 'val') / 1000);
}
$this->readHyperLinkDrawing($objDrawing, $oneCellAnchor, $hyperlinks);
$objDrawing->setWorksheet($docSheet);
- } else {
- // ? Can charts be positioned with a oneCellAnchor ?
- $coordinates = Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1);
+ } elseif ($this->includeCharts && $oneCellAnchor->graphicFrame) {
+ // Exported XLSX from Google Sheets positions charts with a oneCellAnchor
+ $coordinates = Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1);
$offsetX = Drawing::EMUToPixels($oneCellAnchor->from->colOff);
$offsetY = Drawing::EMUToPixels($oneCellAnchor->from->rowOff);
- $width = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx'));
- $height = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy'));
+ $width = Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cx'));
+ $height = Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cy'));
+
+ $graphic = $oneCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic;
+ /** @var SimpleXMLElement $chartRef */
+ $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart;
+ $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase);
+
+ $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
+ 'fromCoordinate' => $coordinates,
+ 'fromOffsetX' => $offsetX,
+ 'fromOffsetY' => $offsetY,
+ 'width' => $width,
+ 'height' => $height,
+ 'worksheetTitle' => $docSheet->getTitle(),
+ ];
}
}
}
if ($xmlDrawingChildren->twoCellAnchor) {
foreach ($xmlDrawingChildren->twoCellAnchor as $twoCellAnchor) {
if ($twoCellAnchor->pic->blipFill) {
- $blip = $twoCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip;
- $xfrm = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm;
- $outerShdw = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw;
- $hlinkClick = $twoCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
+ $blip = $twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip;
+ $xfrm = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm;
+ $outerShdw = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw;
+ $hlinkClick = $twoCellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick;
$objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
- $objDrawing->setName((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name'));
- $objDrawing->setDescription((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr'));
- $objDrawing->setPath(
- 'zip://' . File::realpath($pFilename) . '#' .
- $images[(string) self::getArrayItem(
- $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
- 'embed'
- )],
- false
+ $objDrawing->setName((string) self::getArrayItem(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'name'));
+ $objDrawing->setDescription((string) self::getArrayItem(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'descr'));
+ $embedImageKey = (string) self::getArrayItem(
+ self::getAttributes($blip, $xmlNamespaceBase),
+ 'embed'
);
- $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1));
+ if (isset($images[$embedImageKey])) {
+ $objDrawing->setPath(
+ 'zip://' . File::realpath($filename) . '#' .
+ $images[$embedImageKey],
+ false
+ );
+ } else {
+ $linkImageKey = (string) self::getArrayItem(
+ $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'),
+ 'link'
+ );
+ if (isset($images[$linkImageKey])) {
+ $url = str_replace('xl/drawings/', '', $images[$linkImageKey]);
+ $objDrawing->setPath($url);
+ }
+ }
+ $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1));
+
$objDrawing->setOffsetX(Drawing::EMUToPixels($twoCellAnchor->from->colOff));
$objDrawing->setOffsetY(Drawing::EMUToPixels($twoCellAnchor->from->rowOff));
$objDrawing->setResizeProportional(false);
if ($xfrm) {
- $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cx')));
- $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cy')));
- $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot')));
+ $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($xfrm->ext), 'cx')));
+ $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($xfrm->ext), 'cy')));
+ $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($xfrm), 'rot')));
}
if ($outerShdw) {
$shadow = $objDrawing->getShadow();
$shadow->setVisible(true);
- $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'blurRad')));
- $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'dist')));
- $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir')));
- $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn'));
- $clr = isset($outerShdw->srgbClr) ? $outerShdw->srgbClr : $outerShdw->prstClr;
- $shadow->getColor()->setRGB(self::getArrayItem($clr->attributes(), 'val'));
- $shadow->setAlpha(self::getArrayItem($clr->alpha->attributes(), 'val') / 1000);
+ $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'blurRad')));
+ $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'dist')));
+ $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($outerShdw), 'dir')));
+ $shadow->setAlignment((string) self::getArrayItem(self::getAttributes($outerShdw), 'algn'));
+ $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr;
+ $shadow->getColor()->setRGB(self::getArrayItem(self::getAttributes($clr), 'val'));
+ $shadow->setAlpha(self::getArrayItem(self::getAttributes($clr->alpha), 'val') / 1000);
}
$this->readHyperLinkDrawing($objDrawing, $twoCellAnchor, $hyperlinks);
$objDrawing->setWorksheet($docSheet);
} elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) {
- $fromCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1);
+ $fromCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1);
$fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff);
$fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff);
- $toCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1);
+ $toCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1);
$toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff);
$toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff);
- $graphic = $twoCellAnchor->graphicFrame->children('http://schemas.openxmlformats.org/drawingml/2006/main')->graphic;
+ $graphic = $twoCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic;
/** @var SimpleXMLElement $chartRef */
- $chartRef = $graphic->graphicData->children('http://schemas.openxmlformats.org/drawingml/2006/chart')->chart;
- $thisChart = (string) $chartRef->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+ $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart;
+ $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase);
$chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [
'fromCoordinate' => $fromCoordinate,
@@ -1232,7 +1374,7 @@ class Xlsx extends BaseReader
}
}
}
- if ($relsDrawing === false && $xmlDrawing->count() == 0) {
+ if (empty($relsDrawing) && $xmlDrawing->count() == 0) {
// Save Drawing without rels and children as unparsed
$unparsedDrawings[$drawingRelId] = $xmlDrawing->asXML();
}
@@ -1241,7 +1383,7 @@ class Xlsx extends BaseReader
// store original rId of drawing files
$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = [];
foreach ($relsWorksheet->Relationship as $ele) {
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') {
+ if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") {
$drawingRelId = (string) $ele['Id'];
$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'][(string) $ele['Target']] = $drawingRelId;
if (isset($unparsedDrawings[$drawingRelId])) {
@@ -1251,22 +1393,19 @@ class Xlsx extends BaseReader
}
// unparsed drawing AlternateContent
- $xmlAltDrawing = simplexml_load_string(
- $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- )->children('http://schemas.openxmlformats.org/markup-compatibility/2006');
+ $xmlAltDrawing = $this->loadZip($fileDrawing, Namespaces::COMPATIBILITY);
if ($xmlAltDrawing->AlternateContent) {
foreach ($xmlAltDrawing->AlternateContent as $alternateContent) {
+ $alternateContent = self::testSimpleXml($alternateContent);
$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingAlternateContents'][] = $alternateContent->asXML();
}
}
}
}
- $this->readFormControlProperties($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
- $this->readPrinterSettings($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
+ $this->readFormControlProperties($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
+ $this->readPrinterSettings($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData);
// Loop through definedNames
if ($xmlWorkbook->definedNames) {
@@ -1407,11 +1546,11 @@ class Xlsx extends BaseReader
}
}
- if ((!$this->readDataOnly || !empty($this->loadSheetsOnly)) && isset($xmlWorkbook->bookViews->workbookView)) {
- $workbookView = $xmlWorkbook->bookViews->workbookView;
-
+ $workbookView = $xmlWorkbook->children($mainNS)->bookViews->workbookView;
+ if ((!$this->readDataOnly || !empty($this->loadSheetsOnly)) && !empty($workbookView)) {
+ $workbookViewAttributes = self::testSimpleXml(self::getAttributes($workbookView));
// active sheet index
- $activeTab = (int) ($workbookView['activeTab']); // refers to old sheet index
+ $activeTab = (int) $workbookViewAttributes->activeTab; // refers to old sheet index
// keep active sheet index if sheet is still loaded, else first sheet is set as the active
if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) {
@@ -1423,43 +1562,43 @@ class Xlsx extends BaseReader
$excel->setActiveSheetIndex(0);
}
- if (isset($workbookView['showHorizontalScroll'])) {
- $showHorizontalScroll = (string) $workbookView['showHorizontalScroll'];
+ if (isset($workbookViewAttributes->showHorizontalScroll)) {
+ $showHorizontalScroll = (string) $workbookViewAttributes->showHorizontalScroll;
$excel->setShowHorizontalScroll($this->castXsdBooleanToBool($showHorizontalScroll));
}
- if (isset($workbookView['showVerticalScroll'])) {
- $showVerticalScroll = (string) $workbookView['showVerticalScroll'];
+ if (isset($workbookViewAttributes->showVerticalScroll)) {
+ $showVerticalScroll = (string) $workbookViewAttributes->showVerticalScroll;
$excel->setShowVerticalScroll($this->castXsdBooleanToBool($showVerticalScroll));
}
- if (isset($workbookView['showSheetTabs'])) {
- $showSheetTabs = (string) $workbookView['showSheetTabs'];
+ if (isset($workbookViewAttributes->showSheetTabs)) {
+ $showSheetTabs = (string) $workbookViewAttributes->showSheetTabs;
$excel->setShowSheetTabs($this->castXsdBooleanToBool($showSheetTabs));
}
- if (isset($workbookView['minimized'])) {
- $minimized = (string) $workbookView['minimized'];
+ if (isset($workbookViewAttributes->minimized)) {
+ $minimized = (string) $workbookViewAttributes->minimized;
$excel->setMinimized($this->castXsdBooleanToBool($minimized));
}
- if (isset($workbookView['autoFilterDateGrouping'])) {
- $autoFilterDateGrouping = (string) $workbookView['autoFilterDateGrouping'];
+ if (isset($workbookViewAttributes->autoFilterDateGrouping)) {
+ $autoFilterDateGrouping = (string) $workbookViewAttributes->autoFilterDateGrouping;
$excel->setAutoFilterDateGrouping($this->castXsdBooleanToBool($autoFilterDateGrouping));
}
- if (isset($workbookView['firstSheet'])) {
- $firstSheet = (string) $workbookView['firstSheet'];
+ if (isset($workbookViewAttributes->firstSheet)) {
+ $firstSheet = (string) $workbookViewAttributes->firstSheet;
$excel->setFirstSheetIndex((int) $firstSheet);
}
- if (isset($workbookView['visibility'])) {
- $visibility = (string) $workbookView['visibility'];
+ if (isset($workbookViewAttributes->visibility)) {
+ $visibility = (string) $workbookViewAttributes->visibility;
$excel->setVisibility($visibility);
}
- if (isset($workbookView['tabRatio'])) {
- $tabRatio = (string) $workbookView['tabRatio'];
+ if (isset($workbookViewAttributes->tabRatio)) {
+ $tabRatio = (string) $workbookViewAttributes->tabRatio;
$excel->setTabRatio((int) $tabRatio);
}
}
@@ -1469,13 +1608,7 @@ class Xlsx extends BaseReader
}
if (!$this->readDataOnly) {
- $contentTypes = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, '[Content_Types].xml')
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $contentTypes = $this->loadZip('[Content_Types].xml');
// Default content types
foreach ($contentTypes->Default as $contentType) {
@@ -1492,14 +1625,8 @@ class Xlsx extends BaseReader
switch ($contentType['ContentType']) {
case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml':
if ($this->includeCharts) {
- $chartEntryRef = ltrim($contentType['PartName'], '/');
- $chartElements = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, $chartEntryRef)
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $chartEntryRef = ltrim((string) $contentType['PartName'], '/');
+ $chartElements = $this->loadZip($chartEntryRef);
$objChart = Chart::readChart($chartElements, basename($chartEntryRef, '.xml'));
if (isset($charts[$chartEntryRef])) {
@@ -1508,7 +1635,10 @@ class Xlsx extends BaseReader
$excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
$objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
$objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']);
- $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
+ if (array_key_exists('toCoordinate', $chartDetails[$chartPositionRef])) {
+ // For oneCellAnchor positioned charts, toCoordinate is not in the data. Does it need to be calculated?
+ $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']);
+ }
}
}
}
@@ -1531,177 +1661,10 @@ class Xlsx extends BaseReader
return $excel;
}
- private static function readColor($color, $background = false)
- {
- if (isset($color['rgb'])) {
- return (string) $color['rgb'];
- } elseif (isset($color['indexed'])) {
- return Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
- } elseif (isset($color['theme'])) {
- if (self::$theme !== null) {
- $returnColour = self::$theme->getColourByIndex((int) $color['theme']);
- if (isset($color['tint'])) {
- $tintAdjust = (float) $color['tint'];
- $returnColour = Color::changeBrightness($returnColour, $tintAdjust);
- }
-
- return 'FF' . $returnColour;
- }
- }
-
- if ($background) {
- return 'FFFFFFFF';
- }
-
- return 'FF000000';
- }
-
/**
- * @param SimpleXMLElement|stdClass $style
- */
- private static function readStyle(Style $docStyle, $style): void
- {
- $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
-
- // font
- if (isset($style->font)) {
- $docStyle->getFont()->setName((string) $style->font->name['val']);
- $docStyle->getFont()->setSize((string) $style->font->sz['val']);
- if (isset($style->font->b)) {
- $docStyle->getFont()->setBold(!isset($style->font->b['val']) || self::boolean((string) $style->font->b['val']));
- }
- if (isset($style->font->i)) {
- $docStyle->getFont()->setItalic(!isset($style->font->i['val']) || self::boolean((string) $style->font->i['val']));
- }
- if (isset($style->font->strike)) {
- $docStyle->getFont()->setStrikethrough(!isset($style->font->strike['val']) || self::boolean((string) $style->font->strike['val']));
- }
- $docStyle->getFont()->getColor()->setARGB(self::readColor($style->font->color));
-
- if (isset($style->font->u) && !isset($style->font->u['val'])) {
- $docStyle->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
- } elseif (isset($style->font->u, $style->font->u['val'])) {
- $docStyle->getFont()->setUnderline((string) $style->font->u['val']);
- }
-
- if (isset($style->font->vertAlign, $style->font->vertAlign['val'])) {
- $vertAlign = strtolower((string) $style->font->vertAlign['val']);
- if ($vertAlign == 'superscript') {
- $docStyle->getFont()->setSuperscript(true);
- }
- if ($vertAlign == 'subscript') {
- $docStyle->getFont()->setSubscript(true);
- }
- }
- }
-
- // fill
- if (isset($style->fill)) {
- if ($style->fill->gradientFill) {
- /** @var SimpleXMLElement $gradientFill */
- $gradientFill = $style->fill->gradientFill[0];
- if (!empty($gradientFill['type'])) {
- $docStyle->getFill()->setFillType((string) $gradientFill['type']);
- }
- $docStyle->getFill()->setRotation((float) ($gradientFill['degree']));
- $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
- $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color));
- $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color));
- } elseif ($style->fill->patternFill) {
- $patternType = (string) $style->fill->patternFill['patternType'] != '' ? (string) $style->fill->patternFill['patternType'] : 'solid';
- $docStyle->getFill()->setFillType($patternType);
- if ($style->fill->patternFill->fgColor) {
- $docStyle->getFill()->getStartColor()->setARGB(self::readColor($style->fill->patternFill->fgColor, true));
- }
- if ($style->fill->patternFill->bgColor) {
- $docStyle->getFill()->getEndColor()->setARGB(self::readColor($style->fill->patternFill->bgColor, true));
- }
- }
- }
-
- // border
- if (isset($style->border)) {
- $diagonalUp = self::boolean((string) $style->border['diagonalUp']);
- $diagonalDown = self::boolean((string) $style->border['diagonalDown']);
- if (!$diagonalUp && !$diagonalDown) {
- $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE);
- } elseif ($diagonalUp && !$diagonalDown) {
- $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP);
- } elseif (!$diagonalUp && $diagonalDown) {
- $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN);
- } else {
- $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH);
- }
- self::readBorder($docStyle->getBorders()->getLeft(), $style->border->left);
- self::readBorder($docStyle->getBorders()->getRight(), $style->border->right);
- self::readBorder($docStyle->getBorders()->getTop(), $style->border->top);
- self::readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom);
- self::readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal);
- }
-
- // alignment
- if (isset($style->alignment)) {
- $docStyle->getAlignment()->setHorizontal((string) $style->alignment['horizontal']);
- $docStyle->getAlignment()->setVertical((string) $style->alignment['vertical']);
-
- $textRotation = 0;
- if ((int) $style->alignment['textRotation'] <= 90) {
- $textRotation = (int) $style->alignment['textRotation'];
- } elseif ((int) $style->alignment['textRotation'] > 90) {
- $textRotation = 90 - (int) $style->alignment['textRotation'];
- }
-
- $docStyle->getAlignment()->setTextRotation((int) $textRotation);
- $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment['wrapText']));
- $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment['shrinkToFit']));
- $docStyle->getAlignment()->setIndent((int) ((string) $style->alignment['indent']) > 0 ? (int) ((string) $style->alignment['indent']) : 0);
- $docStyle->getAlignment()->setReadOrder((int) ((string) $style->alignment['readingOrder']) > 0 ? (int) ((string) $style->alignment['readingOrder']) : 0);
- }
-
- // protection
- if (isset($style->protection)) {
- if (isset($style->protection['locked'])) {
- if (self::boolean((string) $style->protection['locked'])) {
- $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED);
- } else {
- $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED);
- }
- }
-
- if (isset($style->protection['hidden'])) {
- if (self::boolean((string) $style->protection['hidden'])) {
- $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED);
- } else {
- $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED);
- }
- }
- }
-
- // top-level style settings
- if (isset($style->quotePrefix)) {
- $docStyle->setQuotePrefix($style->quotePrefix);
- }
- }
-
- /**
- * @param SimpleXMLElement $eleBorder
- */
- private static function readBorder(Border $docBorder, $eleBorder): void
- {
- if (isset($eleBorder['style'])) {
- $docBorder->setBorderStyle((string) $eleBorder['style']);
- }
- if (isset($eleBorder->color)) {
- $docBorder->getColor()->setARGB(self::readColor($eleBorder->color));
- }
- }
-
- /**
- * @param SimpleXMLElement | null $is
- *
* @return RichText
*/
- private function parseRichText($is)
+ private function parseRichText(?SimpleXMLElement $is)
{
$value = new RichText();
@@ -1709,52 +1672,71 @@ class Xlsx extends BaseReader
$value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t));
} else {
if (is_object($is->r)) {
+
+ /** @var SimpleXMLElement $run */
foreach ($is->r as $run) {
if (!isset($run->rPr)) {
$value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
} else {
$objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t));
- if (isset($run->rPr->rFont['val'])) {
- $objText->getFont()->setName((string) $run->rPr->rFont['val']);
+ $attr = $run->rPr->rFont->attributes();
+ if (isset($attr['val'])) {
+ $objText->getFont()->setName((string) $attr['val']);
}
- if (isset($run->rPr->sz['val'])) {
- $objText->getFont()->setSize((float) $run->rPr->sz['val']);
+ $attr = $run->rPr->sz->attributes();
+ if (isset($attr['val'])) {
+ $objText->getFont()->setSize((float) $attr['val']);
}
if (isset($run->rPr->color)) {
- $objText->getFont()->setColor(new Color(self::readColor($run->rPr->color)));
+ $objText->getFont()->setColor(new Color($this->styleReader->readColor($run->rPr->color)));
}
- if (
- (isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) ||
- (isset($run->rPr->b) && !isset($run->rPr->b['val']))
- ) {
- $objText->getFont()->setBold(true);
- }
- if (
- (isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) ||
- (isset($run->rPr->i) && !isset($run->rPr->i['val']))
- ) {
- $objText->getFont()->setItalic(true);
- }
- if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) {
- $vertAlign = strtolower((string) $run->rPr->vertAlign['val']);
- if ($vertAlign == 'superscript') {
- $objText->getFont()->setSuperscript(true);
- }
- if ($vertAlign == 'subscript') {
- $objText->getFont()->setSubscript(true);
+ if (isset($run->rPr->b)) {
+ $attr = $run->rPr->b->attributes();
+ if (
+ (isset($attr['val']) && self::boolean((string) $attr['val'])) ||
+ (!isset($attr['val']))
+ ) {
+ $objText->getFont()->setBold(true);
}
}
- if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) {
- $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
- } elseif (isset($run->rPr->u, $run->rPr->u['val'])) {
- $objText->getFont()->setUnderline((string) $run->rPr->u['val']);
+ if (isset($run->rPr->i)) {
+ $attr = $run->rPr->i->attributes();
+ if (
+ (isset($attr['val']) && self::boolean((string) $attr['val'])) ||
+ (!isset($attr['val']))
+ ) {
+ $objText->getFont()->setItalic(true);
+ }
}
- if (
- (isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) ||
- (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))
- ) {
- $objText->getFont()->setStrikethrough(true);
+ if (isset($run->rPr->vertAlign)) {
+ $attr = $run->rPr->vertAlign->attributes();
+ if (isset($attr['val'])) {
+ $vertAlign = strtolower((string) $attr['val']);
+ if ($vertAlign == 'superscript') {
+ $objText->getFont()->setSuperscript(true);
+ }
+ if ($vertAlign == 'subscript') {
+ $objText->getFont()->setSubscript(true);
+ }
+ }
+ }
+ if (isset($run->rPr->u)) {
+ $attr = $run->rPr->u->attributes();
+ if (!isset($attr['val'])) {
+ $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE);
+ } else {
+ $objText->getFont()->setUnderline((string) $attr['val']);
+ }
+ }
+ if (isset($run->rPr->strike)) {
+ $attr = $run->rPr->strike->attributes();
+ if (
+ (isset($attr['val']) && self::boolean((string) $attr['val'])) ||
+ (!isset($attr['val']))
+ ) {
+ $objText->getFont()->setStrikethrough(true);
+ }
}
}
}
@@ -1764,11 +1746,7 @@ class Xlsx extends BaseReader
return $value;
}
- /**
- * @param mixed $customUITarget
- * @param mixed $zip
- */
- private function readRibbon(Spreadsheet $excel, $customUITarget, $zip): void
+ private function readRibbon(Spreadsheet $excel, string $customUITarget, ZipArchive $zip): void
{
$baseDir = dirname($customUITarget);
$nameCustomUI = basename($customUITarget);
@@ -1789,7 +1767,7 @@ class Xlsx extends BaseReader
if (false !== $UIRels) {
// we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image
foreach ($UIRels->Relationship as $ele) {
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') {
+ if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/image') {
// an image ?
$customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target'];
$customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']);
@@ -1869,22 +1847,20 @@ class Xlsx extends BaseReader
}
/**
- * @param \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing
- * @param SimpleXMLElement $cellAnchor
* @param array $hyperlinks
*/
- private function readHyperLinkDrawing($objDrawing, $cellAnchor, $hyperlinks): void
+ private function readHyperLinkDrawing(\PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing, SimpleXMLElement $cellAnchor, $hyperlinks): void
{
- $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick;
+ $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick;
if ($hlinkClick->count() === 0) {
return;
}
- $hlinkId = (string) $hlinkClick->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships')['id'];
+ $hlinkId = (string) self::getAttributes($hlinkClick, Namespaces::SCHEMA_OFFICE_DOCUMENT)['id'];
$hyperlink = new Hyperlink(
$hyperlinks[$hlinkId],
- (string) self::getArrayItem($cellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name')
+ (string) self::getArrayItem(self::getAttributes($cellAnchor->pic->nvPicPr->cNvPr), 'name')
);
$objDrawing->setHyperlink($hyperlink);
}
@@ -1895,44 +1871,49 @@ class Xlsx extends BaseReader
return;
}
- if ($xmlWorkbook->workbookProtection['lockRevision']) {
- $excel->getSecurity()->setLockRevision((bool) $xmlWorkbook->workbookProtection['lockRevision']);
- }
-
- if ($xmlWorkbook->workbookProtection['lockStructure']) {
- $excel->getSecurity()->setLockStructure((bool) $xmlWorkbook->workbookProtection['lockStructure']);
- }
-
- if ($xmlWorkbook->workbookProtection['lockWindows']) {
- $excel->getSecurity()->setLockWindows((bool) $xmlWorkbook->workbookProtection['lockWindows']);
- }
+ $excel->getSecurity()->setLockRevision(self::getLockValue($xmlWorkbook->workbookProtection, 'lockRevision'));
+ $excel->getSecurity()->setLockStructure(self::getLockValue($xmlWorkbook->workbookProtection, 'lockStructure'));
+ $excel->getSecurity()->setLockWindows(self::getLockValue($xmlWorkbook->workbookProtection, 'lockWindows'));
if ($xmlWorkbook->workbookProtection['revisionsPassword']) {
- $excel->getSecurity()->setRevisionsPassword((string) $xmlWorkbook->workbookProtection['revisionsPassword'], true);
+ $excel->getSecurity()->setRevisionsPassword(
+ (string) $xmlWorkbook->workbookProtection['revisionsPassword'],
+ true
+ );
}
if ($xmlWorkbook->workbookProtection['workbookPassword']) {
- $excel->getSecurity()->setWorkbookPassword((string) $xmlWorkbook->workbookProtection['workbookPassword'], true);
+ $excel->getSecurity()->setWorkbookPassword(
+ (string) $xmlWorkbook->workbookProtection['workbookPassword'],
+ true
+ );
}
}
- private function readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void
+ private static function getLockValue(SimpleXmlElement $protection, string $key): ?bool
{
+ $returnValue = null;
+ $protectKey = $protection[$key];
+ if (!empty($protectKey)) {
+ $protectKey = (string) $protectKey;
+ $returnValue = $protectKey !== 'false' && (bool) $protectKey;
+ }
+
+ return $returnValue;
+ }
+
+ private function readFormControlProperties(Spreadsheet $excel, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void
+ {
+ $zip = $this->zip;
if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
return;
}
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $relsWorksheet = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
+ $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS);
$ctrlProps = [];
foreach ($relsWorksheet->Relationship as $ele) {
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp') {
+ if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/ctrlProp') {
$ctrlProps[(string) $ele['Id']] = $ele;
}
}
@@ -1948,23 +1929,18 @@ class Xlsx extends BaseReader
unset($unparsedCtrlProps);
}
- private function readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void
+ private function readPrinterSettings(Spreadsheet $excel, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void
{
+ $zip = $this->zip;
if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) {
return;
}
- //~ http://schemas.openxmlformats.org/package/2006/relationships"
- $relsWorksheet = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
+ $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
+ $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS);
$sheetPrinterSettings = [];
foreach ($relsWorksheet->Relationship as $ele) {
- if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings') {
+ if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/printerSettings') {
$sheetPrinterSettings[(string) $ele['Id']] = $ele;
}
}
@@ -2003,38 +1979,30 @@ class Xlsx extends BaseReader
return (bool) $xsdBoolean;
}
- /**
- * @param ZipArchive $zip Opened zip archive
- *
- * @return string basename of the used excel workbook
- */
- private function getWorkbookBaseName(ZipArchive $zip)
+ private function getWorkbookBaseName(): array
{
$workbookBasename = '';
+ $xmlNamespaceBase = '';
// check if it is an OOXML archive
- $rels = simplexml_load_string(
- $this->securityScanner->scan(
- $this->getFromZipArchive($zip, '_rels/.rels')
- ),
- 'SimpleXMLElement',
- Settings::getLibXmlLoaderOptions()
- );
- if ($rels !== false) {
- foreach ($rels->Relationship as $rel) {
- switch ($rel['Type']) {
- case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument':
- $basename = basename($rel['Target']);
- if (preg_match('/workbook.*\.xml/', $basename)) {
- $workbookBasename = $basename;
- }
+ $rels = $this->loadZip(self::INITIAL_FILE);
+ foreach ($rels->children(Namespaces::RELATIONSHIPS)->Relationship as $rel) {
+ $rel = self::getAttributes($rel);
+ $type = (string) $rel['Type'];
+ switch ($type) {
+ case Namespaces::OFFICE_DOCUMENT:
+ case Namespaces::PURL_OFFICE_DOCUMENT:
+ $basename = basename((string) $rel['Target']);
+ $xmlNamespaceBase = dirname($type);
+ if (preg_match('/workbook.*\.xml/', $basename)) {
+ $workbookBasename = $basename;
+ }
- break;
- }
+ break;
}
}
- return $workbookBasename;
+ return [$workbookBasename, $xmlNamespaceBase];
}
private function readSheetProtection(Worksheet $docSheet, SimpleXMLElement $xmlSheet): void
@@ -2061,4 +2029,52 @@ class Xlsx extends BaseReader
}
}
}
+
+ private function readAutoFilterTables(
+ SimpleXMLElement $xmlSheet,
+ Worksheet $docSheet,
+ string $dir,
+ string $fileWorksheet,
+ ZipArchive $zip
+ ): void {
+ if ($xmlSheet && $xmlSheet->autoFilter) {
+ // In older files, autofilter structure is defined in the worksheet file
+ (new AutoFilter($docSheet, $xmlSheet))->load();
+ } elseif ($xmlSheet && $xmlSheet->tableParts && $xmlSheet->tableParts['count'] > 0) {
+ // But for Office365, MS decided to make it all just a bit more complicated
+ $this->readAutoFilterTablesInTablesFile($xmlSheet, $dir, $fileWorksheet, $zip, $docSheet);
+ }
+ }
+
+ private function readAutoFilterTablesInTablesFile(
+ SimpleXMLElement $xmlSheet,
+ string $dir,
+ string $fileWorksheet,
+ ZipArchive $zip,
+ Worksheet $docSheet
+ ): void {
+ foreach ($xmlSheet->tableParts->tablePart as $tablePart) {
+ $relation = self::getAttributes($tablePart, Namespaces::SCHEMA_OFFICE_DOCUMENT);
+ $tablePartRel = (string) $relation['id'];
+ $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels';
+
+ if ($zip->locateName($relationsFileName)) {
+ $relsTableReferences = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS);
+ foreach ($relsTableReferences->Relationship as $relationship) {
+ $relationshipAttributes = self::getAttributes($relationship, '');
+
+ if ((string) $relationshipAttributes['Id'] === $tablePartRel) {
+ $relationshipFileName = (string) $relationshipAttributes['Target'];
+ $relationshipFilePath = dirname("$dir/$fileWorksheet") . '/' . $relationshipFileName;
+ $relationshipFilePath = File::realpath($relationshipFilePath);
+
+ if ($this->fileExistsInArchive($this->zip, $relationshipFilePath)) {
+ $autoFilter = $this->loadZip($relationshipFilePath);
+ (new AutoFilter($docSheet, $autoFilter))->load();
+ }
+ }
+ }
+ }
+ }
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php
index f52bfd41a8c..b88f9056749 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php
@@ -61,6 +61,7 @@ class AutoFilter
// Check for dynamic filters
$this->readTopTenAutoFilter($filterColumn, $column);
}
+ $autoFilter->setEvaluated(true);
}
private function readDateRangeAutoFilter(SimpleXMLElement $filters, Column $column): void
@@ -89,7 +90,7 @@ class AutoFilter
$customFilters = $filterColumn->customFilters;
// Custom filters can an AND or an OR join;
// and there should only ever be one or two entries
- if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) {
+ if ((isset($customFilters['and'])) && ((string) $customFilters['and'] === '1')) {
$column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND);
}
foreach ($customFilters->customFilter as $filterRule) {
@@ -130,12 +131,14 @@ class AutoFilter
// We should only ever have one top10 filter
foreach ($filterColumn->top10 as $filterRule) {
$column->createRule()->setRule(
- (((isset($filterRule['percent'])) && ($filterRule['percent'] == 1))
+ (
+ ((isset($filterRule['percent'])) && ((string) $filterRule['percent'] === '1'))
? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT
: Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE
),
(string) $filterRule['val'],
- (((isset($filterRule['top'])) && ($filterRule['top'] == 1))
+ (
+ ((isset($filterRule['top'])) && ((string) $filterRule['top'] === '1'))
? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
: Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
)
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php
index c9a230c215d..667e3674bac 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php
@@ -31,7 +31,9 @@ class Chart
} elseif ($format == 'integer') {
return (int) $attributes[$name];
} elseif ($format == 'boolean') {
- return (bool) ($attributes[$name] === '0' || $attributes[$name] !== 'true') ? false : true;
+ $value = (string) $attributes[$name];
+
+ return $value === 'true' || $value === '1';
}
return (float) $attributes[$name];
@@ -61,7 +63,7 @@ class Chart
$XaxisLabel = $YaxisLabel = $legend = $title = null;
$dispBlanksAs = $plotVisOnly = null;
-
+ $plotArea = null;
foreach ($chartElementsC as $chartElementKey => $chartElement) {
switch ($chartElementKey) {
case 'chart':
@@ -90,8 +92,22 @@ class Chart
break;
case 'valAx':
- if (isset($chartDetail->title)) {
- $YaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta);
+ if (isset($chartDetail->title, $chartDetail->axPos)) {
+ $axisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta);
+ $axPos = self::getAttribute($chartDetail->axPos, 'val', 'string');
+
+ switch ($axPos) {
+ case 't':
+ case 'b':
+ $XaxisLabel = $axisLabel;
+
+ break;
+ case 'r':
+ case 'l':
+ $YaxisLabel = $axisLabel;
+
+ break;
+ }
}
break;
@@ -328,26 +344,51 @@ class Chart
{
if (isset($seriesDetail->strRef)) {
$seriesSource = (string) $seriesDetail->strRef->f;
- $seriesData = self::chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']), 's');
+ $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker);
- return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker);
+ if (isset($seriesDetail->strRef->strCache)) {
+ $seriesData = self::chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']), 's');
+ $seriesValues
+ ->setFormatCode($seriesData['formatCode'])
+ ->setDataValues($seriesData['dataValues']);
+ }
+
+ return $seriesValues;
} elseif (isset($seriesDetail->numRef)) {
$seriesSource = (string) $seriesDetail->numRef->f;
- $seriesData = self::chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c']));
+ $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, $seriesSource, null, null, null, $marker);
+ if (isset($seriesDetail->numRef->numCache)) {
+ $seriesData = self::chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c']));
+ $seriesValues
+ ->setFormatCode($seriesData['formatCode'])
+ ->setDataValues($seriesData['dataValues']);
+ }
- return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker);
+ return $seriesValues;
} elseif (isset($seriesDetail->multiLvlStrRef)) {
$seriesSource = (string) $seriesDetail->multiLvlStrRef->f;
- $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']), 's');
- $seriesData['pointCount'] = count($seriesData['dataValues']);
+ $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker);
- return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker);
+ if (isset($seriesDetail->multiLvlStrRef->multiLvlStrCache)) {
+ $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']), 's');
+ $seriesValues
+ ->setFormatCode($seriesData['formatCode'])
+ ->setDataValues($seriesData['dataValues']);
+ }
+
+ return $seriesValues;
} elseif (isset($seriesDetail->multiLvlNumRef)) {
$seriesSource = (string) $seriesDetail->multiLvlNumRef->f;
- $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']), 's');
- $seriesData['pointCount'] = count($seriesData['dataValues']);
+ $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker);
- return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker);
+ if (isset($seriesDetail->multiLvlNumRef->multiLvlNumCache)) {
+ $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']), 's');
+ $seriesValues
+ ->setFormatCode($seriesData['formatCode'])
+ ->setDataValues($seriesData['dataValues']);
+ }
+
+ return $seriesValues;
}
return null;
@@ -443,7 +484,7 @@ class Chart
}
$fontSize = (self::getAttribute($titleDetailElement->rPr, 'sz', 'integer'));
- if ($fontSize !== null) {
+ if (is_int($fontSize)) {
$objText->getFont()->setSize(floor($fontSize / 100));
}
@@ -500,7 +541,7 @@ class Chart
{
$plotAttributes = [];
if (isset($chartDetail->dLbls)) {
- if (isset($chartDetail->dLbls->howLegendKey)) {
+ if (isset($chartDetail->dLbls->showLegendKey)) {
$plotAttributes['showLegendKey'] = self::getAttribute($chartDetail->dLbls->showLegendKey, 'val', 'string');
}
if (isset($chartDetail->dLbls->showVal)) {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php
index 4134b2f1843..2a1e2afd8da 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php
@@ -3,6 +3,7 @@
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
+use PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter;
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
@@ -71,11 +72,7 @@ class ColumnAndRowAttributes extends BaseParserClass
}
}
- /**
- * @param IReadFilter $readFilter
- * @param bool $readDataOnly
- */
- public function load(?IReadFilter $readFilter = null, $readDataOnly = false): void
+ public function load(?IReadFilter $readFilter = null, bool $readDataOnly = false): void
{
if ($this->worksheetXml === null) {
return;
@@ -91,6 +88,10 @@ class ColumnAndRowAttributes extends BaseParserClass
$rowsAttributes = $this->readRowAttributes($this->worksheetXml->sheetData->row, $readDataOnly);
}
+ if ($readFilter !== null && get_class($readFilter) === DefaultReadFilter::class) {
+ $readFilter = null;
+ }
+
// set columns/rows attributes
$columnsAttributesAreSet = [];
foreach ($columnsAttributes as $columnCoordinate => $columnAttributes) {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php
index 4aa48e17cef..dcd7ad12cb5 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php
@@ -3,6 +3,9 @@
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
+use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar;
+use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension;
+use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormatValueObject;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
@@ -25,7 +28,8 @@ class ConditionalStyles
{
$this->setConditionalStyles(
$this->worksheet,
- $this->readConditionalStyles($this->worksheetXml)
+ $this->readConditionalStyles($this->worksheetXml),
+ $this->worksheetXml->extLst
);
}
@@ -34,15 +38,9 @@ class ConditionalStyles
$conditionals = [];
foreach ($xmlSheet->conditionalFormatting as $conditional) {
foreach ($conditional->cfRule as $cfRule) {
- if (
- ((string) $cfRule['type'] == Conditional::CONDITION_NONE
- || (string) $cfRule['type'] == Conditional::CONDITION_CELLIS
- || (string) $cfRule['type'] == Conditional::CONDITION_CONTAINSTEXT
- || (string) $cfRule['type'] == Conditional::CONDITION_CONTAINSBLANKS
- || (string) $cfRule['type'] == Conditional::CONDITION_NOTCONTAINSBLANKS
- || (string) $cfRule['type'] == Conditional::CONDITION_EXPRESSION)
- && isset($this->dxfs[(int) ($cfRule['dxfId'])])
- ) {
+ if (Conditional::isValidConditionType((string) $cfRule['type']) && isset($this->dxfs[(int) ($cfRule['dxfId'])])) {
+ $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
+ } elseif ((string) $cfRule['type'] == Conditional::CONDITION_DATABAR) {
$conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule;
}
}
@@ -51,11 +49,11 @@ class ConditionalStyles
return $conditionals;
}
- private function setConditionalStyles(Worksheet $worksheet, array $conditionals): void
+ private function setConditionalStyles(Worksheet $worksheet, array $conditionals, $xmlExtLst): void
{
foreach ($conditionals as $ref => $cfRules) {
ksort($cfRules);
- $conditionalStyles = $this->readStyleRules($cfRules);
+ $conditionalStyles = $this->readStyleRules($cfRules, $xmlExtLst);
// Extract all cell references in $ref
$cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref)));
@@ -65,8 +63,9 @@ class ConditionalStyles
}
}
- private function readStyleRules($cfRules)
+ private function readStyleRules($cfRules, $extLst)
{
+ $conditionalFormattingRuleExtensions = ConditionalFormattingRuleExtension::parseExtLstXml($extLst);
$conditionalStyles = [];
foreach ($cfRules as $cfRule) {
$objConditional = new Conditional();
@@ -88,10 +87,63 @@ class ConditionalStyles
} else {
$objConditional->addCondition((string) $cfRule->formula);
}
- $objConditional->setStyle(clone $this->dxfs[(int) ($cfRule['dxfId'])]);
+
+ if (isset($cfRule->dataBar)) {
+ $objConditional->setDataBar(
+ $this->readDataBarOfConditionalRule($cfRule, $conditionalFormattingRuleExtensions)
+ );
+ } else {
+ $objConditional->setStyle(clone $this->dxfs[(int) ($cfRule['dxfId'])]);
+ }
+
$conditionalStyles[] = $objConditional;
}
return $conditionalStyles;
}
+
+ private function readDataBarOfConditionalRule($cfRule, $conditionalFormattingRuleExtensions): ConditionalDataBar
+ {
+ $dataBar = new ConditionalDataBar();
+ //dataBar attribute
+ if (isset($cfRule->dataBar['showValue'])) {
+ $dataBar->setShowValue((bool) $cfRule->dataBar['showValue']);
+ }
+
+ //dataBar children
+ //conditionalFormatValueObjects
+ $cfvoXml = $cfRule->dataBar->cfvo;
+ $cfvoIndex = 0;
+ foreach ((count($cfvoXml) > 1 ? $cfvoXml : [$cfvoXml]) as $cfvo) {
+ if ($cfvoIndex === 0) {
+ $dataBar->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val']));
+ }
+ if ($cfvoIndex === 1) {
+ $dataBar->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val']));
+ }
+ ++$cfvoIndex;
+ }
+
+ //color
+ if (isset($cfRule->dataBar->color)) {
+ $dataBar->setColor((string) $cfRule->dataBar->color['rgb']);
+ }
+ //extLst
+ $this->readDataBarExtLstOfConditionalRule($dataBar, $cfRule, $conditionalFormattingRuleExtensions);
+
+ return $dataBar;
+ }
+
+ private function readDataBarExtLstOfConditionalRule(ConditionalDataBar $dataBar, $cfRule, $conditionalFormattingRuleExtensions): void
+ {
+ if (isset($cfRule->extLst)) {
+ $ns = $cfRule->extLst->getNamespaces(true);
+ foreach ((count($cfRule->extLst) > 0 ? $cfRule->extLst->ext : [$cfRule->extLst->ext]) as $ext) {
+ $extId = (string) $ext->children($ns['x14'])->id;
+ if (isset($conditionalFormattingRuleExtensions[$extId]) && (string) $ext['uri'] === '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}') {
+ $dataBar->setConditionalFormattingRuleExt($conditionalFormattingRuleExtensions[$extId]);
+ }
+ }
+ }
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php
index 41a8c9fb57c..b699cb57412 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php
@@ -34,16 +34,18 @@ class DataValidations
$docValidation->setType((string) $dataValidation['type']);
$docValidation->setErrorStyle((string) $dataValidation['errorStyle']);
$docValidation->setOperator((string) $dataValidation['operator']);
- $docValidation->setAllowBlank($dataValidation['allowBlank'] != 0);
- $docValidation->setShowDropDown($dataValidation['showDropDown'] == 0);
- $docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0);
- $docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0);
+ $docValidation->setAllowBlank(filter_var($dataValidation['allowBlank'], FILTER_VALIDATE_BOOLEAN));
+ // showDropDown is inverted (works as hideDropDown if true)
+ $docValidation->setShowDropDown(!filter_var($dataValidation['showDropDown'], FILTER_VALIDATE_BOOLEAN));
+ $docValidation->setShowInputMessage(filter_var($dataValidation['showInputMessage'], FILTER_VALIDATE_BOOLEAN));
+ $docValidation->setShowErrorMessage(filter_var($dataValidation['showErrorMessage'], FILTER_VALIDATE_BOOLEAN));
$docValidation->setErrorTitle((string) $dataValidation['errorTitle']);
$docValidation->setError((string) $dataValidation['error']);
$docValidation->setPromptTitle((string) $dataValidation['promptTitle']);
$docValidation->setPrompt((string) $dataValidation['prompt']);
$docValidation->setFormula1((string) $dataValidation->formula1);
$docValidation->setFormula2((string) $dataValidation->formula2);
+ $docValidation->setSqref($range);
}
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php
index 106fd44efc1..8488499629b 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php
@@ -3,6 +3,7 @@
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
+use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
@@ -19,40 +20,44 @@ class Hyperlinks
public function readHyperlinks(SimpleXMLElement $relsWorksheet): void
{
- foreach ($relsWorksheet->Relationship as $element) {
- if ($element['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') {
- $this->hyperlinks[(string) $element['Id']] = (string) $element['Target'];
+ foreach ($relsWorksheet->children(Namespaces::RELATIONSHIPS)->Relationship as $elementx) {
+ $element = Xlsx::getAttributes($elementx);
+ if ($element->Type == Namespaces::HYPERLINK) {
+ $this->hyperlinks[(string) $element->Id] = (string) $element->Target;
}
}
}
public function setHyperlinks(SimpleXMLElement $worksheetXml): void
{
- foreach ($worksheetXml->hyperlink as $hyperlink) {
- $this->setHyperlink($hyperlink, $this->worksheet);
+ foreach ($worksheetXml->children(Namespaces::MAIN)->hyperlink as $hyperlink) {
+ if ($hyperlink !== null) {
+ $this->setHyperlink($hyperlink, $this->worksheet);
+ }
}
}
private function setHyperlink(SimpleXMLElement $hyperlink, Worksheet $worksheet): void
{
// Link url
- $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+ $linkRel = Xlsx::getAttributes($hyperlink, Namespaces::SCHEMA_OFFICE_DOCUMENT);
- foreach (Coordinate::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) {
+ $attributes = Xlsx::getAttributes($hyperlink);
+ foreach (Coordinate::extractAllCellReferencesInRange($attributes->ref) as $cellReference) {
$cell = $worksheet->getCell($cellReference);
if (isset($linkRel['id'])) {
$hyperlinkUrl = $this->hyperlinks[(string) $linkRel['id']] ?? null;
- if (isset($hyperlink['location'])) {
- $hyperlinkUrl .= '#' . (string) $hyperlink['location'];
+ if (isset($attributes['location'])) {
+ $hyperlinkUrl .= '#' . (string) $attributes['location'];
}
$cell->getHyperlink()->setUrl($hyperlinkUrl);
- } elseif (isset($hyperlink['location'])) {
- $cell->getHyperlink()->setUrl('sheet://' . (string) $hyperlink['location']);
+ } elseif (isset($attributes['location'])) {
+ $cell->getHyperlink()->setUrl('sheet://' . (string) $attributes['location']);
}
// Tooltip
- if (isset($hyperlink['tooltip'])) {
- $cell->getHyperlink()->setTooltip((string) $hyperlink['tooltip']);
+ if (isset($attributes['tooltip'])) {
+ $cell->getHyperlink()->setTooltip((string) $attributes['tooltip']);
}
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php
new file mode 100644
index 00000000000..54f56d7247b
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php
@@ -0,0 +1,76 @@
+setPageOrder((string) $xmlSheet->pageSetup['pageOrder']);
}
- $relAttributes = $xmlSheet->pageSetup->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships');
+ $relAttributes = $xmlSheet->pageSetup->attributes(Namespaces::SCHEMA_OFFICE_DOCUMENT);
if (isset($relAttributes['id'])) {
$unparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'] = (string) $relAttributes['id'];
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php
index b6f3c61fc3a..82b5172b58d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php
@@ -9,8 +9,10 @@ use SimpleXMLElement;
class Properties
{
+ /** @var XmlScanner */
private $securityScanner;
+ /** @var DocumentProperties */
private $docProps;
public function __construct(XmlScanner $securityScanner, DocumentProperties $docProps)
@@ -19,28 +21,39 @@ class Properties
$this->docProps = $docProps;
}
- private function extractPropertyData($propertyData)
+ /**
+ * @param mixed $obj
+ */
+ private static function nullOrSimple($obj): ?SimpleXMLElement
{
- return simplexml_load_string(
+ return ($obj instanceof SimpleXMLElement) ? $obj : null;
+ }
+
+ private function extractPropertyData(string $propertyData): ?SimpleXMLElement
+ {
+ // okay to omit namespace because everything will be processed by xpath
+ $obj = simplexml_load_string(
$this->securityScanner->scan($propertyData),
'SimpleXMLElement',
Settings::getLibXmlLoaderOptions()
);
+
+ return self::nullOrSimple($obj);
}
- public function readCoreProperties($propertyData): void
+ public function readCoreProperties(string $propertyData): void
{
$xmlCore = $this->extractPropertyData($propertyData);
if (is_object($xmlCore)) {
- $xmlCore->registerXPathNamespace('dc', 'http://purl.org/dc/elements/1.1/');
- $xmlCore->registerXPathNamespace('dcterms', 'http://purl.org/dc/terms/');
- $xmlCore->registerXPathNamespace('cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties');
+ $xmlCore->registerXPathNamespace('dc', Namespaces::DC_ELEMENTS);
+ $xmlCore->registerXPathNamespace('dcterms', Namespaces::DC_TERMS);
+ $xmlCore->registerXPathNamespace('cp', Namespaces::CORE_PROPERTIES2);
$this->docProps->setCreator((string) self::getArrayItem($xmlCore->xpath('dc:creator')));
$this->docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath('cp:lastModifiedBy')));
- $this->docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:created')))); //! respect xsi:type
- $this->docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:modified')))); //! respect xsi:type
+ $this->docProps->setCreated((string) self::getArrayItem($xmlCore->xpath('dcterms:created'))); //! respect xsi:type
+ $this->docProps->setModified((string) self::getArrayItem($xmlCore->xpath('dcterms:modified'))); //! respect xsi:type
$this->docProps->setTitle((string) self::getArrayItem($xmlCore->xpath('dc:title')));
$this->docProps->setDescription((string) self::getArrayItem($xmlCore->xpath('dc:description')));
$this->docProps->setSubject((string) self::getArrayItem($xmlCore->xpath('dc:subject')));
@@ -49,7 +62,7 @@ class Properties
}
}
- public function readExtendedProperties($propertyData): void
+ public function readExtendedProperties(string $propertyData): void
{
$xmlCore = $this->extractPropertyData($propertyData);
@@ -63,7 +76,7 @@ class Properties
}
}
- public function readCustomProperties($propertyData): void
+ public function readCustomProperties(string $propertyData): void
{
$xmlCore = $this->extractPropertyData($propertyData);
@@ -85,8 +98,12 @@ class Properties
}
}
- private static function getArrayItem(array $array, $key = 0)
+ /**
+ * @param array|false $array
+ * @param mixed $key
+ */
+ private static function getArrayItem($array, $key = 0): ?SimpleXMLElement
{
- return $array[$key] ?? null;
+ return is_array($array) ? ($array[$key] ?? null) : null;
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php
index 123588182be..a302cc5692b 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php
@@ -17,17 +17,14 @@ class SheetViewOptions extends BaseParserClass
$this->worksheetXml = $worksheetXml;
}
- /**
- * @param bool $readDataOnly
- */
- public function load($readDataOnly = false): void
+ public function load(bool $readDataOnly, Styles $styleReader): void
{
if ($this->worksheetXml === null) {
return;
}
if (isset($this->worksheetXml->sheetPr)) {
- $this->tabColor($this->worksheetXml->sheetPr);
+ $this->tabColor($this->worksheetXml->sheetPr, $styleReader);
$this->codeName($this->worksheetXml->sheetPr);
$this->outlines($this->worksheetXml->sheetPr);
$this->pageSetup($this->worksheetXml->sheetPr);
@@ -42,10 +39,10 @@ class SheetViewOptions extends BaseParserClass
}
}
- private function tabColor(SimpleXMLElement $sheetPr): void
+ private function tabColor(SimpleXMLElement $sheetPr, Styles $styleReader): void
{
- if (isset($sheetPr->tabColor, $sheetPr->tabColor['rgb'])) {
- $this->worksheet->getTabColor()->setARGB((string) $sheetPr->tabColor['rgb']);
+ if (isset($sheetPr->tabColor)) {
+ $this->worksheet->getTabColor()->setARGB($styleReader->readColor($sheetPr->tabColor));
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php
index f6c47929067..b2bc99f0529 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php
@@ -3,23 +3,31 @@
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
+use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use SimpleXMLElement;
class SheetViews extends BaseParserClass
{
+ /** @var SimpleXMLElement */
private $sheetViewXml;
+ /** @var SimpleXMLElement */
+ private $sheetViewAttributes;
+
+ /** @var Worksheet */
private $worksheet;
public function __construct(SimpleXMLElement $sheetViewXml, Worksheet $workSheet)
{
$this->sheetViewXml = $sheetViewXml;
+ $this->sheetViewAttributes = Xlsx::testSimpleXml($sheetViewXml->attributes());
$this->worksheet = $workSheet;
}
public function load(): void
{
+ $this->topLeft();
$this->zoomScale();
$this->view();
$this->gridLines();
@@ -30,15 +38,15 @@ class SheetViews extends BaseParserClass
if (isset($this->sheetViewXml->pane)) {
$this->pane();
}
- if (isset($this->sheetViewXml->selection, $this->sheetViewXml->selection['sqref'])) {
+ if (isset($this->sheetViewXml->selection, $this->sheetViewXml->selection->attributes()->sqref)) {
$this->selection();
}
}
private function zoomScale(): void
{
- if (isset($this->sheetViewXml['zoomScale'])) {
- $zoomScale = (int) ($this->sheetViewXml['zoomScale']);
+ if (isset($this->sheetViewAttributes->zoomScale)) {
+ $zoomScale = (int) ($this->sheetViewAttributes->zoomScale);
if ($zoomScale <= 0) {
// setZoomScale will throw an Exception if the scale is less than or equals 0
// that is OK when manually creating documents, but we should be able to read all documents
@@ -48,8 +56,8 @@ class SheetViews extends BaseParserClass
$this->worksheet->getSheetView()->setZoomScale($zoomScale);
}
- if (isset($this->sheetViewXml['zoomScaleNormal'])) {
- $zoomScaleNormal = (int) ($this->sheetViewXml['zoomScaleNormal']);
+ if (isset($this->sheetViewAttributes->zoomScaleNormal)) {
+ $zoomScaleNormal = (int) ($this->sheetViewAttributes->zoomScaleNormal);
if ($zoomScaleNormal <= 0) {
// setZoomScaleNormal will throw an Exception if the scale is less than or equals 0
// that is OK when manually creating documents, but we should be able to read all documents
@@ -62,43 +70,50 @@ class SheetViews extends BaseParserClass
private function view(): void
{
- if (isset($this->sheetViewXml['view'])) {
- $this->worksheet->getSheetView()->setView((string) $this->sheetViewXml['view']);
+ if (isset($this->sheetViewAttributes->view)) {
+ $this->worksheet->getSheetView()->setView((string) $this->sheetViewAttributes->view);
+ }
+ }
+
+ private function topLeft(): void
+ {
+ if (isset($this->sheetViewAttributes->topLeftCell)) {
+ $this->worksheet->setTopLeftCell($this->sheetViewAttributes->topLeftCell);
}
}
private function gridLines(): void
{
- if (isset($this->sheetViewXml['showGridLines'])) {
+ if (isset($this->sheetViewAttributes->showGridLines)) {
$this->worksheet->setShowGridLines(
- self::boolean((string) $this->sheetViewXml['showGridLines'])
+ self::boolean((string) $this->sheetViewAttributes->showGridLines)
);
}
}
private function headers(): void
{
- if (isset($this->sheetViewXml['showRowColHeaders'])) {
+ if (isset($this->sheetViewAttributes->showRowColHeaders)) {
$this->worksheet->setShowRowColHeaders(
- self::boolean((string) $this->sheetViewXml['showRowColHeaders'])
+ self::boolean((string) $this->sheetViewAttributes->showRowColHeaders)
);
}
}
private function direction(): void
{
- if (isset($this->sheetViewXml['rightToLeft'])) {
+ if (isset($this->sheetViewAttributes->rightToLeft)) {
$this->worksheet->setRightToLeft(
- self::boolean((string) $this->sheetViewXml['rightToLeft'])
+ self::boolean((string) $this->sheetViewAttributes->rightToLeft)
);
}
}
private function showZeros(): void
{
- if (isset($this->sheetViewXml['showZeros'])) {
+ if (isset($this->sheetViewAttributes->showZeros)) {
$this->worksheet->getSheetView()->setShowZeros(
- self::boolean((string) $this->sheetViewXml['showZeros'])
+ self::boolean((string) $this->sheetViewAttributes->showZeros)
);
}
}
@@ -108,17 +123,18 @@ class SheetViews extends BaseParserClass
$xSplit = 0;
$ySplit = 0;
$topLeftCell = null;
+ $paneAttributes = $this->sheetViewXml->pane->attributes();
- if (isset($this->sheetViewXml->pane['xSplit'])) {
- $xSplit = (int) ($this->sheetViewXml->pane['xSplit']);
+ if (isset($paneAttributes->xSplit)) {
+ $xSplit = (int) ($paneAttributes->xSplit);
}
- if (isset($this->sheetViewXml->pane['ySplit'])) {
- $ySplit = (int) ($this->sheetViewXml->pane['ySplit']);
+ if (isset($paneAttributes->ySplit)) {
+ $ySplit = (int) ($paneAttributes->ySplit);
}
- if (isset($this->sheetViewXml->pane['topLeftCell'])) {
- $topLeftCell = (string) $this->sheetViewXml->pane['topLeftCell'];
+ if (isset($paneAttributes->topLeftCell)) {
+ $topLeftCell = (string) $paneAttributes->topLeftCell;
}
$this->worksheet->freezePane(
@@ -129,10 +145,12 @@ class SheetViews extends BaseParserClass
private function selection(): void
{
- $sqref = (string) $this->sheetViewXml->selection['sqref'];
- $sqref = explode(' ', $sqref);
- $sqref = $sqref[0];
-
- $this->worksheet->setSelectedCells($sqref);
+ $attributes = $this->sheetViewXml->selection->attributes();
+ if ($attributes !== null) {
+ $sqref = (string) $attributes->sqref;
+ $sqref = explode(' ', $sqref);
+ $sqref = $sqref[0];
+ $this->worksheet->setSelectedCells($sqref);
+ }
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php
index 43de87875e1..6f01c7457d1 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php
@@ -2,6 +2,7 @@
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
+use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Borders;
@@ -12,39 +13,51 @@ use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Protection;
use PhpOffice\PhpSpreadsheet\Style\Style;
use SimpleXMLElement;
+use stdClass;
class Styles extends BaseParserClass
{
/**
* Theme instance.
*
- * @var Theme
+ * @var ?Theme
*/
- private static $theme = null;
+ private $theme;
+ /** @var array */
private $styles = [];
+ /** @var array */
private $cellStyles = [];
+ /** @var SimpleXMLElement */
private $styleXml;
- public function __construct(SimpleXMLElement $styleXml)
+ public function setStyleXml(SimpleXmlElement $styleXml): void
{
$this->styleXml = $styleXml;
}
- public function setStyleBaseData(?Theme $theme = null, $styles = [], $cellStyles = []): void
+ public function setTheme(Theme $theme): void
{
- self::$theme = $theme;
+ $this->theme = $theme;
+ }
+
+ public function setStyleBaseData(?Theme $theme = null, array $styles = [], array $cellStyles = []): void
+ {
+ $this->theme = $theme;
$this->styles = $styles;
$this->cellStyles = $cellStyles;
}
- private static function readFontStyle(Font $fontStyle, SimpleXMLElement $fontStyleXml): void
+ public function readFontStyle(Font $fontStyle, SimpleXMLElement $fontStyleXml): void
{
- $fontStyle->setName((string) $fontStyleXml->name['val']);
- $fontStyle->setSize((float) $fontStyleXml->sz['val']);
-
+ if (isset($fontStyleXml->name, $fontStyleXml->name['val'])) {
+ $fontStyle->setName((string) $fontStyleXml->name['val']);
+ }
+ if (isset($fontStyleXml->sz, $fontStyleXml->sz['val'])) {
+ $fontStyle->setSize((float) $fontStyleXml->sz['val']);
+ }
if (isset($fontStyleXml->b)) {
$fontStyle->setBold(!isset($fontStyleXml->b['val']) || self::boolean((string) $fontStyleXml->b['val']));
}
@@ -52,9 +65,11 @@ class Styles extends BaseParserClass
$fontStyle->setItalic(!isset($fontStyleXml->i['val']) || self::boolean((string) $fontStyleXml->i['val']));
}
if (isset($fontStyleXml->strike)) {
- $fontStyle->setStrikethrough(!isset($fontStyleXml->strike['val']) || self::boolean((string) $fontStyleXml->strike['val']));
+ $fontStyle->setStrikethrough(
+ !isset($fontStyleXml->strike['val']) || self::boolean((string) $fontStyleXml->strike['val'])
+ );
}
- $fontStyle->getColor()->setARGB(self::readColor($fontStyleXml->color));
+ $fontStyle->getColor()->setARGB($this->readColor($fontStyleXml->color));
if (isset($fontStyleXml->u) && !isset($fontStyleXml->u['val'])) {
$fontStyle->setUnderline(Font::UNDERLINE_SINGLE);
@@ -66,25 +81,24 @@ class Styles extends BaseParserClass
$verticalAlign = strtolower((string) $fontStyleXml->vertAlign['val']);
if ($verticalAlign === 'superscript') {
$fontStyle->setSuperscript(true);
- }
- if ($verticalAlign === 'subscript') {
+ } elseif ($verticalAlign === 'subscript') {
$fontStyle->setSubscript(true);
}
}
}
- private static function readNumberFormat(NumberFormat $numfmtStyle, SimpleXMLElement $numfmtStyleXml): void
+ private function readNumberFormat(NumberFormat $numfmtStyle, SimpleXMLElement $numfmtStyleXml): void
{
if ($numfmtStyleXml->count() === 0) {
return;
}
- $numfmt = $numfmtStyleXml->attributes();
+ $numfmt = Xlsx::getAttributes($numfmtStyleXml);
if ($numfmt->count() > 0 && isset($numfmt['formatCode'])) {
- $numfmtStyle->setFormatCode((string) $numfmt['formatCode']);
+ $numfmtStyle->setFormatCode(self::formatGeneral((string) $numfmt['formatCode']));
}
}
- private static function readFillStyle(Fill $fillStyle, SimpleXMLElement $fillStyleXml): void
+ public function readFillStyle(Fill $fillStyle, SimpleXMLElement $fillStyleXml): void
{
if ($fillStyleXml->gradientFill) {
/** @var SimpleXMLElement $gradientFill */
@@ -93,24 +107,29 @@ class Styles extends BaseParserClass
$fillStyle->setFillType((string) $gradientFill['type']);
}
$fillStyle->setRotation((float) ($gradientFill['degree']));
- $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
- $fillStyle->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color));
- $fillStyle->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color));
+ $gradientFill->registerXPathNamespace('sml', Namespaces::MAIN);
+ $fillStyle->getStartColor()->setARGB($this->readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color));
+ $fillStyle->getEndColor()->setARGB($this->readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color));
} elseif ($fillStyleXml->patternFill) {
- $patternType = (string) $fillStyleXml->patternFill['patternType'] != '' ? (string) $fillStyleXml->patternFill['patternType'] : 'solid';
- $fillStyle->setFillType($patternType);
+ $defaultFillStyle = Fill::FILL_NONE;
if ($fillStyleXml->patternFill->fgColor) {
- $fillStyle->getStartColor()->setARGB(self::readColor($fillStyleXml->patternFill->fgColor, true));
- } else {
- $fillStyle->getStartColor()->setARGB('FF000000');
+ $fillStyle->getStartColor()->setARGB($this->readColor($fillStyleXml->patternFill->fgColor, true));
+ $defaultFillStyle = Fill::FILL_SOLID;
}
if ($fillStyleXml->patternFill->bgColor) {
- $fillStyle->getEndColor()->setARGB(self::readColor($fillStyleXml->patternFill->bgColor, true));
+ $fillStyle->getEndColor()->setARGB($this->readColor($fillStyleXml->patternFill->bgColor, true));
+ $defaultFillStyle = Fill::FILL_SOLID;
}
+
+ $patternType = (string) $fillStyleXml->patternFill['patternType'] != ''
+ ? (string) $fillStyleXml->patternFill['patternType']
+ : $defaultFillStyle;
+
+ $fillStyle->setFillType($patternType);
}
}
- private static function readBorderStyle(Borders $borderStyle, SimpleXMLElement $borderStyleXml): void
+ public function readBorderStyle(Borders $borderStyle, SimpleXMLElement $borderStyleXml): void
{
$diagonalUp = self::boolean((string) $borderStyleXml['diagonalUp']);
$diagonalDown = self::boolean((string) $borderStyleXml['diagonalDown']);
@@ -124,64 +143,82 @@ class Styles extends BaseParserClass
$borderStyle->setDiagonalDirection(Borders::DIAGONAL_BOTH);
}
- self::readBorder($borderStyle->getLeft(), $borderStyleXml->left);
- self::readBorder($borderStyle->getRight(), $borderStyleXml->right);
- self::readBorder($borderStyle->getTop(), $borderStyleXml->top);
- self::readBorder($borderStyle->getBottom(), $borderStyleXml->bottom);
- self::readBorder($borderStyle->getDiagonal(), $borderStyleXml->diagonal);
+ $this->readBorder($borderStyle->getLeft(), $borderStyleXml->left);
+ $this->readBorder($borderStyle->getRight(), $borderStyleXml->right);
+ $this->readBorder($borderStyle->getTop(), $borderStyleXml->top);
+ $this->readBorder($borderStyle->getBottom(), $borderStyleXml->bottom);
+ $this->readBorder($borderStyle->getDiagonal(), $borderStyleXml->diagonal);
}
- private static function readBorder(Border $border, SimpleXMLElement $borderXml): void
+ private function readBorder(Border $border, SimpleXMLElement $borderXml): void
{
if (isset($borderXml['style'])) {
$border->setBorderStyle((string) $borderXml['style']);
}
if (isset($borderXml->color)) {
- $border->getColor()->setARGB(self::readColor($borderXml->color));
+ $border->getColor()->setARGB($this->readColor($borderXml->color));
}
}
- private static function readAlignmentStyle(Alignment $alignment, SimpleXMLElement $alignmentXml): void
+ public function readAlignmentStyle(Alignment $alignment, SimpleXMLElement $alignmentXml): void
{
- $alignment->setHorizontal((string) $alignmentXml->alignment['horizontal']);
- $alignment->setVertical((string) $alignmentXml->alignment['vertical']);
+ $alignment->setHorizontal((string) $alignmentXml['horizontal']);
+ $alignment->setVertical((string) $alignmentXml['vertical']);
$textRotation = 0;
- if ((int) $alignmentXml->alignment['textRotation'] <= 90) {
- $textRotation = (int) $alignmentXml->alignment['textRotation'];
- } elseif ((int) $alignmentXml->alignment['textRotation'] > 90) {
- $textRotation = 90 - (int) $alignmentXml->alignment['textRotation'];
+ if ((int) $alignmentXml['textRotation'] <= 90) {
+ $textRotation = (int) $alignmentXml['textRotation'];
+ } elseif ((int) $alignmentXml['textRotation'] > 90) {
+ $textRotation = 90 - (int) $alignmentXml['textRotation'];
}
$alignment->setTextRotation((int) $textRotation);
- $alignment->setWrapText(self::boolean((string) $alignmentXml->alignment['wrapText']));
- $alignment->setShrinkToFit(self::boolean((string) $alignmentXml->alignment['shrinkToFit']));
- $alignment->setIndent((int) ((string) $alignmentXml->alignment['indent']) > 0 ? (int) ((string) $alignmentXml->alignment['indent']) : 0);
- $alignment->setReadOrder((int) ((string) $alignmentXml->alignment['readingOrder']) > 0 ? (int) ((string) $alignmentXml->alignment['readingOrder']) : 0);
+ $alignment->setWrapText(self::boolean((string) $alignmentXml['wrapText']));
+ $alignment->setShrinkToFit(self::boolean((string) $alignmentXml['shrinkToFit']));
+ $alignment->setIndent(
+ (int) ((string) $alignmentXml['indent']) > 0 ? (int) ((string) $alignmentXml['indent']) : 0
+ );
+ $alignment->setReadOrder(
+ (int) ((string) $alignmentXml['readingOrder']) > 0 ? (int) ((string) $alignmentXml['readingOrder']) : 0
+ );
}
- private function readStyle(Style $docStyle, $style): void
+ private static function formatGeneral(string $formatString): string
+ {
+ if ($formatString === 'GENERAL') {
+ $formatString = NumberFormat::FORMAT_GENERAL;
+ }
+
+ return $formatString;
+ }
+
+ /**
+ * Read style.
+ *
+ * @param SimpleXMLElement|stdClass $style
+ */
+ public function readStyle(Style $docStyle, $style): void
{
if ($style->numFmt instanceof SimpleXMLElement) {
- self::readNumberFormat($docStyle->getNumberFormat(), $style->numFmt);
+ $this->readNumberFormat($docStyle->getNumberFormat(), $style->numFmt);
} else {
- $docStyle->getNumberFormat()->setFormatCode($style->numFmt);
+ $docStyle->getNumberFormat()->setFormatCode(self::formatGeneral((string) $style->numFmt));
}
if (isset($style->font)) {
- self::readFontStyle($docStyle->getFont(), $style->font);
+ $this->readFontStyle($docStyle->getFont(), $style->font);
}
if (isset($style->fill)) {
- self::readFillStyle($docStyle->getFill(), $style->fill);
+ $this->readFillStyle($docStyle->getFill(), $style->fill);
}
if (isset($style->border)) {
- self::readBorderStyle($docStyle->getBorders(), $style->border);
+ $this->readBorderStyle($docStyle->getBorders(), $style->border);
}
- if (isset($style->alignment->alignment)) {
- self::readAlignmentStyle($docStyle->getAlignment(), $style->alignment);
+ if (isset($style->alignment)) {
+ $this->readAlignmentStyle($docStyle->getAlignment(), $style->alignment);
}
// protection
@@ -192,11 +229,16 @@ class Styles extends BaseParserClass
// top-level style settings
if (isset($style->quotePrefix)) {
- $docStyle->setQuotePrefix(true);
+ $docStyle->setQuotePrefix((bool) $style->quotePrefix);
}
}
- private function readProtectionLocked(Style $docStyle, $style): void
+ /**
+ * Read protection locked attribute.
+ *
+ * @param SimpleXMLElement|stdClass $style
+ */
+ public function readProtectionLocked(Style $docStyle, $style): void
{
if (isset($style->protection['locked'])) {
if (self::boolean((string) $style->protection['locked'])) {
@@ -207,7 +249,12 @@ class Styles extends BaseParserClass
}
}
- private function readProtectionHidden(Style $docStyle, $style): void
+ /**
+ * Read protection hidden attribute.
+ *
+ * @param SimpleXMLElement|stdClass $style
+ */
+ public function readProtectionHidden(Style $docStyle, $style): void
{
if (isset($style->protection['hidden'])) {
if (self::boolean((string) $style->protection['hidden'])) {
@@ -218,18 +265,18 @@ class Styles extends BaseParserClass
}
}
- private static function readColor($color, $background = false)
+ public function readColor(SimpleXMLElement $color, bool $background = false): string
{
if (isset($color['rgb'])) {
return (string) $color['rgb'];
} elseif (isset($color['indexed'])) {
- return Color::indexedColor($color['indexed'] - 7, $background)->getARGB();
+ return Color::indexedColor((int) ($color['indexed'] - 7), $background)->getARGB() ?? '';
} elseif (isset($color['theme'])) {
- if (self::$theme !== null) {
- $returnColour = self::$theme->getColourByIndex((int) $color['theme']);
+ if ($this->theme !== null) {
+ $returnColour = $this->theme->getColourByIndex((int) $color['theme']);
if (isset($color['tint'])) {
$tintAdjust = (float) $color['tint'];
- $returnColour = Color::changeBrightness($returnColour, $tintAdjust);
+ $returnColour = Color::changeBrightness($returnColour ?? '', $tintAdjust);
}
return 'FF' . $returnColour;
@@ -239,7 +286,7 @@ class Styles extends BaseParserClass
return ($background) ? 'FFFFFFFF' : 'FF000000';
}
- public function dxfs($readDataOnly = false)
+ public function dxfs(bool $readDataOnly = false): array
{
$dxfs = [];
if (!$readDataOnly && $this->styleXml) {
@@ -253,7 +300,8 @@ class Styles extends BaseParserClass
}
// Cell Styles
if ($this->styleXml->cellStyles) {
- foreach ($this->styleXml->cellStyles->cellStyle as $cellStyle) {
+ foreach ($this->styleXml->cellStyles->cellStyle as $cellStylex) {
+ $cellStyle = Xlsx::getAttributes($cellStylex);
if ((int) ($cellStyle['builtinId']) == 0) {
if (isset($this->cellStyles[(int) ($cellStyle['xfId'])])) {
// Set default style
@@ -270,13 +318,20 @@ class Styles extends BaseParserClass
return $dxfs;
}
- public function styles()
+ public function styles(): array
{
return $this->styles;
}
- private static function getArrayItem($array, $key = 0)
+ /**
+ * Get array item.
+ *
+ * @param mixed $array (usually array, in theory can be false)
+ *
+ * @return stdClass
+ */
+ private static function getArrayItem($array, int $key = 0)
{
- return $array[$key] ?? null;
+ return is_array($array) ? ($array[$key] ?? null) : null;
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Theme.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Theme.php
index c105f3c1a66..1f2b863c782 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Theme.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Theme.php
@@ -21,16 +21,16 @@ class Theme
/**
* Colour Map.
*
- * @var array of string
+ * @var string[]
*/
private $colourMap;
/**
* Create a new Theme.
*
- * @param mixed $themeName
- * @param mixed $colourSchemeName
- * @param mixed $colourMap
+ * @param string $themeName
+ * @param string $colourSchemeName
+ * @param string[] $colourMap
*/
public function __construct($themeName, $colourSchemeName, $colourMap)
{
@@ -63,9 +63,9 @@ class Theme
/**
* Get colour Map Value by Position.
*
- * @param mixed $index
+ * @param int $index
*
- * @return string
+ * @return null|string
*/
public function getColourByIndex($index)
{
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php
index 11aa1df3bdf..8552509e4d9 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php
@@ -2,24 +2,22 @@
namespace PhpOffice\PhpSpreadsheet\Reader;
+use DateTime;
+use DateTimeZone;
use PhpOffice\PhpSpreadsheet\Cell\AddressHelper;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\DefinedName;
-use PhpOffice\PhpSpreadsheet\Document\Properties;
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
use PhpOffice\PhpSpreadsheet\Reader\Xml\PageSettings;
+use PhpOffice\PhpSpreadsheet\Reader\Xml\Properties;
+use PhpOffice\PhpSpreadsheet\Reader\Xml\Style;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Settings;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\File;
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 SimpleXMLElement;
/**
@@ -45,62 +43,18 @@ class Xml extends BaseReader
private $fileContents = '';
- private static $mappings = [
- 'borderStyle' => [
- '1continuous' => Border::BORDER_THIN,
- '1dash' => Border::BORDER_DASHED,
- '1dashdot' => Border::BORDER_DASHDOT,
- '1dashdotdot' => Border::BORDER_DASHDOTDOT,
- '1dot' => Border::BORDER_DOTTED,
- '1double' => Border::BORDER_DOUBLE,
- '2continuous' => Border::BORDER_MEDIUM,
- '2dash' => Border::BORDER_MEDIUMDASHED,
- '2dashdot' => Border::BORDER_MEDIUMDASHDOT,
- '2dashdotdot' => Border::BORDER_MEDIUMDASHDOTDOT,
- '2dot' => Border::BORDER_DOTTED,
- '2double' => Border::BORDER_DOUBLE,
- '3continuous' => Border::BORDER_THICK,
- '3dash' => Border::BORDER_MEDIUMDASHED,
- '3dashdot' => Border::BORDER_MEDIUMDASHDOT,
- '3dashdotdot' => Border::BORDER_MEDIUMDASHDOTDOT,
- '3dot' => Border::BORDER_DOTTED,
- '3double' => Border::BORDER_DOUBLE,
- ],
- 'fillType' => [
- 'solid' => Fill::FILL_SOLID,
- 'gray75' => Fill::FILL_PATTERN_DARKGRAY,
- 'gray50' => Fill::FILL_PATTERN_MEDIUMGRAY,
- 'gray25' => Fill::FILL_PATTERN_LIGHTGRAY,
- 'gray125' => Fill::FILL_PATTERN_GRAY125,
- 'gray0625' => Fill::FILL_PATTERN_GRAY0625,
- 'horzstripe' => Fill::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe
- 'vertstripe' => Fill::FILL_PATTERN_DARKVERTICAL, // vertical stripe
- 'reversediagstripe' => Fill::FILL_PATTERN_DARKUP, // reverse diagonal stripe
- 'diagstripe' => Fill::FILL_PATTERN_DARKDOWN, // diagonal stripe
- 'diagcross' => Fill::FILL_PATTERN_DARKGRID, // diagoanl crosshatch
- 'thickdiagcross' => Fill::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch
- 'thinhorzstripe' => Fill::FILL_PATTERN_LIGHTHORIZONTAL,
- 'thinvertstripe' => Fill::FILL_PATTERN_LIGHTVERTICAL,
- 'thinreversediagstripe' => Fill::FILL_PATTERN_LIGHTUP,
- 'thindiagstripe' => Fill::FILL_PATTERN_LIGHTDOWN,
- 'thinhorzcross' => Fill::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch
- 'thindiagcross' => Fill::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch
- ],
- ];
-
public static function xmlMappings(): array
{
- return self::$mappings;
+ return array_merge(
+ Style\Fill::FILL_MAPPINGS,
+ Style\Border::BORDER_MAPPINGS
+ );
}
/**
* Can the current IReader read the file?
- *
- * @param string $pFilename
- *
- * @return bool
*/
- public function canRead($pFilename)
+ public function canRead(string $filename): bool
{
// Office xmlns:o="urn:schemas-microsoft-com:office:office"
// Excel xmlns:x="urn:schemas-microsoft-com:office:excel"
@@ -114,11 +68,11 @@ class Xml extends BaseReader
$signature = [
'',
+ 'xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet',
];
// Open file
- $data = file_get_contents($pFilename);
+ $data = file_get_contents($filename);
// Why?
//$data = str_replace("'", '"', $data); // fix headers with single quote
@@ -149,20 +103,20 @@ class Xml extends BaseReader
/**
* Check if the file is a valid SimpleXML.
*
- * @param string $pFilename
+ * @param string $filename
*
* @return false|SimpleXMLElement
*/
- public function trySimpleXMLLoadString($pFilename)
+ public function trySimpleXMLLoadString($filename)
{
try {
$xml = simplexml_load_string(
- $this->securityScanner->scan($this->fileContents ?: file_get_contents($pFilename)),
+ $this->securityScanner->scan($this->fileContents ?: file_get_contents($filename)),
'SimpleXMLElement',
Settings::getLibXmlLoaderOptions()
);
} catch (\Exception $e) {
- throw new Exception('Cannot load invalid XML file: ' . $pFilename, 0, $e);
+ throw new Exception('Cannot load invalid XML file: ' . $filename, 0, $e);
}
$this->fileContents = '';
@@ -172,26 +126,29 @@ class Xml extends BaseReader
/**
* Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object.
*
- * @param string $pFilename
+ * @param string $filename
*
* @return array
*/
- public function listWorksheetNames($pFilename)
+ public function listWorksheetNames($filename)
{
- File::assertFile($pFilename);
- if (!$this->canRead($pFilename)) {
- throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
+ File::assertFile($filename);
+ if (!$this->canRead($filename)) {
+ throw new Exception($filename . ' is an Invalid Spreadsheet file.');
}
$worksheetNames = [];
- $xml = $this->trySimpleXMLLoadString($pFilename);
+ $xml = $this->trySimpleXMLLoadString($filename);
+ if ($xml === false) {
+ throw new Exception("Problem reading {$filename}");
+ }
$namespaces = $xml->getNamespaces(true);
$xml_ss = $xml->children($namespaces['ss']);
foreach ($xml_ss->Worksheet as $worksheet) {
- $worksheet_ss = $worksheet->attributes($namespaces['ss']);
+ $worksheet_ss = self::getAttributes($worksheet, $namespaces['ss']);
$worksheetNames[] = (string) $worksheet_ss['Name'];
}
@@ -201,27 +158,30 @@ class Xml extends BaseReader
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
*
- * @param string $pFilename
+ * @param string $filename
*
* @return array
*/
- public function listWorksheetInfo($pFilename)
+ public function listWorksheetInfo($filename)
{
- File::assertFile($pFilename);
- if (!$this->canRead($pFilename)) {
- throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
+ File::assertFile($filename);
+ if (!$this->canRead($filename)) {
+ throw new Exception($filename . ' is an Invalid Spreadsheet file.');
}
$worksheetInfo = [];
- $xml = $this->trySimpleXMLLoadString($pFilename);
+ $xml = $this->trySimpleXMLLoadString($filename);
+ if ($xml === false) {
+ throw new Exception("Problem reading {$filename}");
+ }
$namespaces = $xml->getNamespaces(true);
$worksheetID = 1;
$xml_ss = $xml->children($namespaces['ss']);
foreach ($xml_ss->Worksheet as $worksheet) {
- $worksheet_ss = $worksheet->attributes($namespaces['ss']);
+ $worksheet_ss = self::getAttributes($worksheet, $namespaces['ss']);
$tmpInfo = [];
$tmpInfo['worksheetName'] = '';
@@ -272,159 +232,55 @@ class Xml extends BaseReader
/**
* Loads Spreadsheet from file.
*
- * @param string $pFilename
- *
* @return Spreadsheet
*/
- public function load($pFilename)
+ public function load(string $filename, int $flags = 0)
{
+ $this->processFlags($flags);
+
// Create new Spreadsheet
$spreadsheet = new Spreadsheet();
$spreadsheet->removeSheetByIndex(0);
// Load into this instance
- return $this->loadIntoExisting($pFilename, $spreadsheet);
- }
-
- private static function identifyFixedStyleValue($styleList, &$styleAttributeValue)
- {
- $returnValue = false;
- $styleAttributeValue = strtolower($styleAttributeValue);
- foreach ($styleList as $style) {
- if ($styleAttributeValue == strtolower($style)) {
- $styleAttributeValue = $style;
- $returnValue = true;
-
- break;
- }
- }
-
- return $returnValue;
- }
-
- protected static function hex2str($hex)
- {
- return mb_chr((int) hexdec($hex[1]), 'UTF-8');
+ return $this->loadIntoExisting($filename, $spreadsheet);
}
/**
* Loads from file into Spreadsheet instance.
*
- * @param string $pFilename
+ * @param string $filename
*
* @return Spreadsheet
*/
- public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet)
+ public function loadIntoExisting($filename, Spreadsheet $spreadsheet)
{
- File::assertFile($pFilename);
- if (!$this->canRead($pFilename)) {
- throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
+ File::assertFile($filename);
+ if (!$this->canRead($filename)) {
+ throw new Exception($filename . ' is an Invalid Spreadsheet file.');
}
- $xml = $this->trySimpleXMLLoadString($pFilename);
+ $xml = $this->trySimpleXMLLoadString($filename);
+ if ($xml === false) {
+ throw new Exception("Problem reading {$filename}");
+ }
$namespaces = $xml->getNamespaces(true);
- $docProps = $spreadsheet->getProperties();
- if (isset($xml->DocumentProperties[0])) {
- foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) {
- $stringValue = (string) $propertyValue;
- switch ($propertyName) {
- case 'Title':
- $docProps->setTitle($stringValue);
+ (new Properties($spreadsheet))->readProperties($xml, $namespaces);
- break;
- case 'Subject':
- $docProps->setSubject($stringValue);
-
- break;
- case 'Author':
- $docProps->setCreator($stringValue);
-
- break;
- case 'Created':
- $creationDate = strtotime($stringValue);
- $docProps->setCreated($creationDate);
-
- break;
- case 'LastAuthor':
- $docProps->setLastModifiedBy($stringValue);
-
- break;
- case 'LastSaved':
- $lastSaveDate = strtotime($stringValue);
- $docProps->setModified($lastSaveDate);
-
- break;
- case 'Company':
- $docProps->setCompany($stringValue);
-
- break;
- case 'Category':
- $docProps->setCategory($stringValue);
-
- break;
- case 'Manager':
- $docProps->setManager($stringValue);
-
- break;
- case 'Keywords':
- $docProps->setKeywords($stringValue);
-
- break;
- case 'Description':
- $docProps->setDescription($stringValue);
-
- break;
- }
- }
- }
- if (isset($xml->CustomDocumentProperties)) {
- foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) {
- $propertyAttributes = $propertyValue->attributes($namespaces['dt']);
- $propertyName = preg_replace_callback('/_x([0-9a-f]{4})_/i', ['self', 'hex2str'], $propertyName);
- $propertyType = Properties::PROPERTY_TYPE_UNKNOWN;
- switch ((string) $propertyAttributes) {
- case 'string':
- $propertyType = Properties::PROPERTY_TYPE_STRING;
- $propertyValue = trim($propertyValue);
-
- break;
- case 'boolean':
- $propertyType = Properties::PROPERTY_TYPE_BOOLEAN;
- $propertyValue = (bool) $propertyValue;
-
- break;
- case 'integer':
- $propertyType = Properties::PROPERTY_TYPE_INTEGER;
- $propertyValue = (int) $propertyValue;
-
- break;
- case 'float':
- $propertyType = Properties::PROPERTY_TYPE_FLOAT;
- $propertyValue = (float) $propertyValue;
-
- break;
- case 'dateTime.tz':
- $propertyType = Properties::PROPERTY_TYPE_DATE;
- $propertyValue = strtotime(trim($propertyValue));
-
- break;
- }
- $docProps->setCustomProperty($propertyName, $propertyValue, $propertyType);
- }
- }
-
- $this->parseStyles($xml, $namespaces);
+ $this->styles = (new Style())->parseStyles($xml, $namespaces);
$worksheetID = 0;
$xml_ss = $xml->children($namespaces['ss']);
- foreach ($xml_ss->Worksheet as $worksheet) {
- $worksheet_ss = $worksheet->attributes($namespaces['ss']);
+ /** @var null|SimpleXMLElement $worksheetx */
+ foreach ($xml_ss->Worksheet as $worksheetx) {
+ $worksheet = $worksheetx ?? new SimpleXMLElement('');
+ $worksheet_ss = self::getAttributes($worksheet, $namespaces['ss']);
if (
- (isset($this->loadSheetsOnly)) && (isset($worksheet_ss['Name'])) &&
+ isset($this->loadSheetsOnly, $worksheet_ss['Name']) &&
(!in_array($worksheet_ss['Name'], $this->loadSheetsOnly))
) {
continue;
@@ -433,6 +289,7 @@ class Xml extends BaseReader
// Create new Worksheet
$spreadsheet->createSheet();
$spreadsheet->setActiveSheetIndex($worksheetID);
+ $worksheetName = '';
if (isset($worksheet_ss['Name'])) {
$worksheetName = (string) $worksheet_ss['Name'];
// Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in
@@ -444,7 +301,7 @@ class Xml extends BaseReader
// locally scoped defined names
if (isset($worksheet->Names[0])) {
foreach ($worksheet->Names[0] as $definedName) {
- $definedName_ss = $definedName->attributes($namespaces['ss']);
+ $definedName_ss = self::getAttributes($definedName, $namespaces['ss']);
$name = (string) $definedName_ss['Name'];
$definedValue = (string) $definedName_ss['RefersTo'];
$convertedValue = AddressHelper::convertFormulaToA1($definedValue);
@@ -458,7 +315,7 @@ class Xml extends BaseReader
$columnID = 'A';
if (isset($worksheet->Table->Column)) {
foreach ($worksheet->Table->Column as $columnData) {
- $columnData_ss = $columnData->attributes($namespaces['ss']);
+ $columnData_ss = self::getAttributes($columnData, $namespaces['ss']);
if (isset($columnData_ss['Index'])) {
$columnID = Coordinate::stringFromColumnIndex((int) $columnData_ss['Index']);
}
@@ -475,14 +332,14 @@ class Xml extends BaseReader
$additionalMergedCells = 0;
foreach ($worksheet->Table->Row as $rowData) {
$rowHasData = false;
- $row_ss = $rowData->attributes($namespaces['ss']);
+ $row_ss = self::getAttributes($rowData, $namespaces['ss']);
if (isset($row_ss['Index'])) {
$rowID = (int) $row_ss['Index'];
}
$columnID = 'A';
foreach ($rowData->Cell as $cell) {
- $cell_ss = $cell->attributes($namespaces['ss']);
+ $cell_ss = self::getAttributes($cell, $namespaces['ss']);
if (isset($cell_ss['Index'])) {
$columnID = Coordinate::stringFromColumnIndex((int) $cell_ss['Index']);
}
@@ -504,7 +361,7 @@ class Xml extends BaseReader
$columnTo = $columnID;
if (isset($cell_ss['MergeAcross'])) {
$additionalMergedCells += (int) $cell_ss['MergeAcross'];
- $columnTo = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($columnID) + $cell_ss['MergeAcross']);
+ $columnTo = Coordinate::stringFromColumnIndex((int) (Coordinate::columnIndexFromString($columnID) + $cell_ss['MergeAcross']));
}
$rowTo = $rowID;
if (isset($cell_ss['MergeDown'])) {
@@ -524,7 +381,7 @@ class Xml extends BaseReader
$cellData = $cell->Data;
$cellValue = (string) $cellData;
$type = DataType::TYPE_NULL;
- $cellData_ss = $cellData->attributes($namespaces['ss']);
+ $cellData_ss = self::getAttributes($cellData, $namespaces['ss']);
if (isset($cellData_ss['Type'])) {
$cellDataType = $cellData_ss['Type'];
switch ($cellDataType) {
@@ -556,7 +413,8 @@ class Xml extends BaseReader
break;
case 'DateTime':
$type = DataType::TYPE_NUMERIC;
- $cellValue = Date::PHPToExcel(strtotime($cellValue . ' UTC'));
+ $dateTime = new DateTime($cellValue, new DateTimeZone('UTC'));
+ $cellValue = Date::PHPToExcel($dateTime);
break;
case 'Error':
@@ -581,14 +439,7 @@ class Xml extends BaseReader
}
if (isset($cell->Comment)) {
- $commentAttributes = $cell->Comment->attributes($namespaces['ss']);
- $author = 'unknown';
- if (isset($commentAttributes->Author)) {
- $author = (string) $commentAttributes->Author;
- }
- $node = $cell->Comment->Data->asXML();
- $annotation = strip_tags($node);
- $spreadsheet->getActiveSheet()->getComment($columnID . $rowID)->setAuthor($author)->setText($this->parseRichText($annotation));
+ $this->parseCellComment($cell->Comment, $namespaces, $spreadsheet, $columnID, $rowID);
}
if (isset($cell_ss['StyleID'])) {
@@ -597,7 +448,8 @@ class Xml extends BaseReader
//if (!$spreadsheet->getActiveSheet()->cellExists($columnID . $rowID)) {
// $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValue(null);
//}
- $spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->styles[$style]);
+ $spreadsheet->getActiveSheet()->getStyle($cellRange)
+ ->applyFromArray($this->styles[$style]);
}
}
++$columnID;
@@ -610,7 +462,7 @@ class Xml extends BaseReader
if ($rowHasData) {
if (isset($row_ss['Height'])) {
$rowHeight = $row_ss['Height'];
- $spreadsheet->getActiveSheet()->getRowDimension($rowID)->setRowHeight($rowHeight);
+ $spreadsheet->getActiveSheet()->getRowDimension($rowID)->setRowHeight((float) $rowHeight);
}
}
@@ -631,7 +483,7 @@ class Xml extends BaseReader
$activeWorksheet = $spreadsheet->setActiveSheetIndex(0);
if (isset($xml->Names[0])) {
foreach ($xml->Names[0] as $definedName) {
- $definedName_ss = $definedName->attributes($namespaces['ss']);
+ $definedName_ss = self::getAttributes($definedName, $namespaces['ss']);
$name = (string) $definedName_ss['Name'];
$definedValue = (string) $definedName_ss['RefersTo'];
$convertedValue = AddressHelper::convertFormulaToA1($definedValue);
@@ -646,254 +498,39 @@ class Xml extends BaseReader
return $spreadsheet;
}
- protected function parseRichText($is)
+ protected function parseCellComment(
+ SimpleXMLElement $comment,
+ array $namespaces,
+ Spreadsheet $spreadsheet,
+ string $columnID,
+ int $rowID
+ ): void {
+ $commentAttributes = $comment->attributes($namespaces['ss']);
+ $author = 'unknown';
+ if (isset($commentAttributes->Author)) {
+ $author = (string) $commentAttributes->Author;
+ }
+
+ $node = $comment->Data->asXML();
+ $annotation = strip_tags((string) $node);
+ $spreadsheet->getActiveSheet()->getComment($columnID . $rowID)
+ ->setAuthor($author)
+ ->setText($this->parseRichText($annotation));
+ }
+
+ protected function parseRichText(string $annotation): RichText
{
$value = new RichText();
- $value->createText($is);
+ $value->createText($annotation);
return $value;
}
- private function parseStyles(SimpleXMLElement $xml, array $namespaces): void
+ private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement
{
- if (!isset($xml->Styles)) {
- return;
- }
-
- foreach ($xml->Styles[0] as $style) {
- $style_ss = $style->attributes($namespaces['ss']);
- $styleID = (string) $style_ss['ID'];
- $this->styles[$styleID] = (isset($this->styles['Default'])) ? $this->styles['Default'] : [];
- foreach ($style as $styleType => $styleData) {
- $styleAttributes = $styleData->attributes($namespaces['ss']);
- switch ($styleType) {
- case 'Alignment':
- $this->parseStyleAlignment($styleID, $styleAttributes);
-
- break;
- case 'Borders':
- $this->parseStyleBorders($styleID, $styleData, $namespaces);
-
- break;
- case 'Font':
- $this->parseStyleFont($styleID, $styleAttributes);
-
- break;
- case 'Interior':
- $this->parseStyleInterior($styleID, $styleAttributes);
-
- break;
- case 'NumberFormat':
- $this->parseStyleNumberFormat($styleID, $styleAttributes);
-
- break;
- }
- }
- }
- }
-
- /**
- * @param string $styleID
- */
- private function parseStyleAlignment($styleID, SimpleXMLElement $styleAttributes): void
- {
- $verticalAlignmentStyles = [
- Alignment::VERTICAL_BOTTOM,
- Alignment::VERTICAL_TOP,
- Alignment::VERTICAL_CENTER,
- Alignment::VERTICAL_JUSTIFY,
- ];
- $horizontalAlignmentStyles = [
- Alignment::HORIZONTAL_GENERAL,
- Alignment::HORIZONTAL_LEFT,
- Alignment::HORIZONTAL_RIGHT,
- Alignment::HORIZONTAL_CENTER,
- Alignment::HORIZONTAL_CENTER_CONTINUOUS,
- Alignment::HORIZONTAL_JUSTIFY,
- ];
-
- foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
- $styleAttributeValue = (string) $styleAttributeValue;
- switch ($styleAttributeKey) {
- case 'Vertical':
- if (self::identifyFixedStyleValue($verticalAlignmentStyles, $styleAttributeValue)) {
- $this->styles[$styleID]['alignment']['vertical'] = $styleAttributeValue;
- }
-
- break;
- case 'Horizontal':
- if (self::identifyFixedStyleValue($horizontalAlignmentStyles, $styleAttributeValue)) {
- $this->styles[$styleID]['alignment']['horizontal'] = $styleAttributeValue;
- }
-
- break;
- case 'WrapText':
- $this->styles[$styleID]['alignment']['wrapText'] = true;
-
- break;
- case 'Rotate':
- $this->styles[$styleID]['alignment']['textRotation'] = $styleAttributeValue;
-
- break;
- }
- }
- }
-
- private static $borderPositions = ['top', 'left', 'bottom', 'right'];
-
- /**
- * @param $styleID
- */
- private function parseStyleBorders($styleID, SimpleXMLElement $styleData, array $namespaces): void
- {
- $diagonalDirection = '';
- $borderPosition = '';
- foreach ($styleData->Border as $borderStyle) {
- $borderAttributes = $borderStyle->attributes($namespaces['ss']);
- $thisBorder = [];
- $style = (string) $borderAttributes->Weight;
- $style .= strtolower((string) $borderAttributes->LineStyle);
- $thisBorder['borderStyle'] = self::$mappings['borderStyle'][$style] ?? Border::BORDER_NONE;
- foreach ($borderAttributes as $borderStyleKey => $borderStyleValue) {
- switch ($borderStyleKey) {
- case 'Position':
- $borderStyleValue = strtolower((string) $borderStyleValue);
- if (in_array($borderStyleValue, self::$borderPositions)) {
- $borderPosition = $borderStyleValue;
- } elseif ($borderStyleValue == 'diagonalleft') {
- $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_DOWN;
- } elseif ($borderStyleValue == 'diagonalright') {
- $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_UP;
- }
-
- break;
- case 'Color':
- $borderColour = substr($borderStyleValue, 1);
- $thisBorder['color']['rgb'] = $borderColour;
-
- break;
- }
- }
- if ($borderPosition) {
- $this->styles[$styleID]['borders'][$borderPosition] = $thisBorder;
- } elseif ($diagonalDirection) {
- $this->styles[$styleID]['borders']['diagonalDirection'] = $diagonalDirection;
- $this->styles[$styleID]['borders']['diagonal'] = $thisBorder;
- }
- }
- }
-
- private static $underlineStyles = [
- Font::UNDERLINE_NONE,
- Font::UNDERLINE_DOUBLE,
- Font::UNDERLINE_DOUBLEACCOUNTING,
- Font::UNDERLINE_SINGLE,
- Font::UNDERLINE_SINGLEACCOUNTING,
- ];
-
- private function parseStyleFontUnderline(string $styleID, string $styleAttributeValue): void
- {
- if (self::identifyFixedStyleValue(self::$underlineStyles, $styleAttributeValue)) {
- $this->styles[$styleID]['font']['underline'] = $styleAttributeValue;
- }
- }
-
- private function parseStyleFontVerticalAlign(string $styleID, string $styleAttributeValue): void
- {
- if ($styleAttributeValue == 'Superscript') {
- $this->styles[$styleID]['font']['superscript'] = true;
- }
- if ($styleAttributeValue == 'Subscript') {
- $this->styles[$styleID]['font']['subscript'] = true;
- }
- }
-
- /**
- * @param $styleID
- */
- private function parseStyleFont(string $styleID, SimpleXMLElement $styleAttributes): void
- {
- foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
- $styleAttributeValue = (string) $styleAttributeValue;
- switch ($styleAttributeKey) {
- case 'FontName':
- $this->styles[$styleID]['font']['name'] = $styleAttributeValue;
-
- break;
- case 'Size':
- $this->styles[$styleID]['font']['size'] = $styleAttributeValue;
-
- break;
- case 'Color':
- $this->styles[$styleID]['font']['color']['rgb'] = substr($styleAttributeValue, 1);
-
- break;
- case 'Bold':
- $this->styles[$styleID]['font']['bold'] = true;
-
- break;
- case 'Italic':
- $this->styles[$styleID]['font']['italic'] = true;
-
- break;
- case 'Underline':
- $this->parseStyleFontUnderline($styleID, $styleAttributeValue);
-
- break;
- case 'VerticalAlign':
- $this->parseStyleFontVerticalAlign($styleID, $styleAttributeValue);
-
- break;
- }
- }
- }
-
- /**
- * @param $styleID
- */
- private function parseStyleInterior($styleID, SimpleXMLElement $styleAttributes): void
- {
- foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
- switch ($styleAttributeKey) {
- case 'Color':
- $this->styles[$styleID]['fill']['endColor']['rgb'] = substr($styleAttributeValue, 1);
- $this->styles[$styleID]['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1);
-
- break;
- case 'PatternColor':
- $this->styles[$styleID]['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1);
-
- break;
- case 'Pattern':
- $lcStyleAttributeValue = strtolower((string) $styleAttributeValue);
- $this->styles[$styleID]['fill']['fillType'] = self::$mappings['fillType'][$lcStyleAttributeValue] ?? Fill::FILL_NONE;
-
- break;
- }
- }
- }
-
- /**
- * @param $styleID
- */
- private function parseStyleNumberFormat($styleID, SimpleXMLElement $styleAttributes): void
- {
- $fromFormats = ['\-', '\ '];
- $toFormats = ['-', ' '];
-
- foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) {
- $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue);
- switch ($styleAttributeValue) {
- case 'Short Date':
- $styleAttributeValue = 'dd/mm/yyyy';
-
- break;
- }
-
- if ($styleAttributeValue > '') {
- $this->styles[$styleID]['numberFormat']['formatCode'] = $styleAttributeValue;
- }
- }
+ return ($simple === null)
+ ? new SimpleXMLElement('')
+ : ($simple->attributes($node) ?? new SimpleXMLElement(''));
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/PageSettings.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/PageSettings.php
index e56ac331f37..c0caca3ba2d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/PageSettings.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/PageSettings.php
@@ -62,6 +62,10 @@ class PageSettings
foreach ($xmlX->WorksheetOptions->PageSetup as $pageSetupData) {
foreach ($pageSetupData as $pageSetupKey => $pageSetupValue) {
$pageSetupAttributes = $pageSetupValue->attributes($namespaces['x']);
+ if (!$pageSetupAttributes) {
+ continue;
+ }
+
switch ($pageSetupKey) {
case 'Layout':
$this->setLayout($printDefaults, $pageSetupAttributes);
@@ -115,7 +119,7 @@ class PageSettings
private function setLayout(stdClass $printDefaults, SimpleXMLElement $pageSetupAttributes): void
{
- $printDefaults->orientation = (string) strtolower($pageSetupAttributes->Orientation) ?: PageSetup::ORIENTATION_PORTRAIT;
+ $printDefaults->orientation = (string) strtolower($pageSetupAttributes->Orientation ?? '') ?: PageSetup::ORIENTATION_PORTRAIT;
$printDefaults->horizontalCentered = (bool) $pageSetupAttributes->CenterHorizontal ?: false;
$printDefaults->verticalCentered = (bool) $pageSetupAttributes->CenterVertical ?: false;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Properties.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Properties.php
new file mode 100644
index 00000000000..1c3e421ae7e
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Properties.php
@@ -0,0 +1,157 @@
+spreadsheet = $spreadsheet;
+ }
+
+ public function readProperties(SimpleXMLElement $xml, array $namespaces): void
+ {
+ $this->readStandardProperties($xml);
+ $this->readCustomProperties($xml, $namespaces);
+ }
+
+ protected function readStandardProperties(SimpleXMLElement $xml): void
+ {
+ if (isset($xml->DocumentProperties[0])) {
+ $docProps = $this->spreadsheet->getProperties();
+
+ foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) {
+ $propertyValue = (string) $propertyValue;
+
+ $this->processStandardProperty($docProps, $propertyName, $propertyValue);
+ }
+ }
+ }
+
+ protected function readCustomProperties(SimpleXMLElement $xml, array $namespaces): void
+ {
+ if (isset($xml->CustomDocumentProperties)) {
+ $docProps = $this->spreadsheet->getProperties();
+
+ foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) {
+ $propertyAttributes = self::getAttributes($propertyValue, $namespaces['dt']);
+ $propertyName = preg_replace_callback('/_x([0-9a-f]{4})_/i', [$this, 'hex2str'], $propertyName);
+
+ $this->processCustomProperty($docProps, $propertyName, $propertyValue, $propertyAttributes);
+ }
+ }
+ }
+
+ protected function processStandardProperty(
+ DocumentProperties $docProps,
+ string $propertyName,
+ string $stringValue
+ ): void {
+ switch ($propertyName) {
+ case 'Title':
+ $docProps->setTitle($stringValue);
+
+ break;
+ case 'Subject':
+ $docProps->setSubject($stringValue);
+
+ break;
+ case 'Author':
+ $docProps->setCreator($stringValue);
+
+ break;
+ case 'Created':
+ $docProps->setCreated($stringValue);
+
+ break;
+ case 'LastAuthor':
+ $docProps->setLastModifiedBy($stringValue);
+
+ break;
+ case 'LastSaved':
+ $docProps->setModified($stringValue);
+
+ break;
+ case 'Company':
+ $docProps->setCompany($stringValue);
+
+ break;
+ case 'Category':
+ $docProps->setCategory($stringValue);
+
+ break;
+ case 'Manager':
+ $docProps->setManager($stringValue);
+
+ break;
+ case 'Keywords':
+ $docProps->setKeywords($stringValue);
+
+ break;
+ case 'Description':
+ $docProps->setDescription($stringValue);
+
+ break;
+ }
+ }
+
+ protected function processCustomProperty(
+ DocumentProperties $docProps,
+ string $propertyName,
+ ?SimpleXMLElement $propertyValue,
+ SimpleXMLElement $propertyAttributes
+ ): void {
+ $propertyType = DocumentProperties::PROPERTY_TYPE_UNKNOWN;
+
+ switch ((string) $propertyAttributes) {
+ case 'string':
+ $propertyType = DocumentProperties::PROPERTY_TYPE_STRING;
+ $propertyValue = trim((string) $propertyValue);
+
+ break;
+ case 'boolean':
+ $propertyType = DocumentProperties::PROPERTY_TYPE_BOOLEAN;
+ $propertyValue = (bool) $propertyValue;
+
+ break;
+ case 'integer':
+ $propertyType = DocumentProperties::PROPERTY_TYPE_INTEGER;
+ $propertyValue = (int) $propertyValue;
+
+ break;
+ case 'float':
+ $propertyType = DocumentProperties::PROPERTY_TYPE_FLOAT;
+ $propertyValue = (float) $propertyValue;
+
+ break;
+ case 'dateTime.tz':
+ $propertyType = DocumentProperties::PROPERTY_TYPE_DATE;
+ $propertyValue = trim((string) $propertyValue);
+
+ break;
+ }
+
+ $docProps->setCustomProperty($propertyName, $propertyValue, $propertyType);
+ }
+
+ protected function hex2str(array $hex): string
+ {
+ return mb_chr((int) hexdec($hex[1]), 'UTF-8');
+ }
+
+ private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement
+ {
+ return ($simple === null)
+ ? new SimpleXMLElement('')
+ : ($simple->attributes($node) ?? new SimpleXMLElement(''));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php
new file mode 100644
index 00000000000..0e3cd16de17
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php
@@ -0,0 +1,83 @@
+Styles)) {
+ return [];
+ }
+
+ $alignmentStyleParser = new Style\Alignment();
+ $borderStyleParser = new Style\Border();
+ $fontStyleParser = new Style\Font();
+ $fillStyleParser = new Style\Fill();
+ $numberFormatStyleParser = new Style\NumberFormat();
+
+ foreach ($xml->Styles[0] as $style) {
+ $style_ss = self::getAttributes($style, $namespaces['ss']);
+ $styleID = (string) $style_ss['ID'];
+ $this->styles[$styleID] = $this->styles['Default'] ?? [];
+
+ $alignment = $border = $font = $fill = $numberFormat = [];
+
+ foreach ($style as $styleType => $styleDatax) {
+ $styleData = $styleDatax ?? new SimpleXMLElement('');
+ $styleAttributes = $styleData->attributes($namespaces['ss']);
+
+ switch ($styleType) {
+ case 'Alignment':
+ if ($styleAttributes) {
+ $alignment = $alignmentStyleParser->parseStyle($styleAttributes);
+ }
+
+ break;
+ case 'Borders':
+ $border = $borderStyleParser->parseStyle($styleData, $namespaces);
+
+ break;
+ case 'Font':
+ if ($styleAttributes) {
+ $font = $fontStyleParser->parseStyle($styleAttributes);
+ }
+
+ break;
+ case 'Interior':
+ if ($styleAttributes) {
+ $fill = $fillStyleParser->parseStyle($styleAttributes);
+ }
+
+ break;
+ case 'NumberFormat':
+ if ($styleAttributes) {
+ $numberFormat = $numberFormatStyleParser->parseStyle($styleAttributes);
+ }
+
+ break;
+ }
+ }
+
+ $this->styles[$styleID] = array_merge($alignment, $border, $font, $fill, $numberFormat);
+ }
+
+ return $this->styles;
+ }
+
+ protected static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement
+ {
+ return ($simple === null)
+ ? new SimpleXMLElement('')
+ : ($simple->attributes($node) ?? new SimpleXMLElement(''));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php
new file mode 100644
index 00000000000..d1363548b81
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php
@@ -0,0 +1,58 @@
+ $styleAttributeValue) {
+ $styleAttributeValue = (string) $styleAttributeValue;
+ switch ($styleAttributeKey) {
+ case 'Vertical':
+ if (self::identifyFixedStyleValue(self::VERTICAL_ALIGNMENT_STYLES, $styleAttributeValue)) {
+ $style['alignment']['vertical'] = $styleAttributeValue;
+ }
+
+ break;
+ case 'Horizontal':
+ if (self::identifyFixedStyleValue(self::HORIZONTAL_ALIGNMENT_STYLES, $styleAttributeValue)) {
+ $style['alignment']['horizontal'] = $styleAttributeValue;
+ }
+
+ break;
+ case 'WrapText':
+ $style['alignment']['wrapText'] = true;
+
+ break;
+ case 'Rotate':
+ $style['alignment']['textRotation'] = $styleAttributeValue;
+
+ break;
+ }
+ }
+
+ return $style;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Border.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Border.php
new file mode 100644
index 00000000000..8aefd9c9e97
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Border.php
@@ -0,0 +1,98 @@
+ [
+ '1continuous' => BorderStyle::BORDER_THIN,
+ '1dash' => BorderStyle::BORDER_DASHED,
+ '1dashdot' => BorderStyle::BORDER_DASHDOT,
+ '1dashdotdot' => BorderStyle::BORDER_DASHDOTDOT,
+ '1dot' => BorderStyle::BORDER_DOTTED,
+ '1double' => BorderStyle::BORDER_DOUBLE,
+ '2continuous' => BorderStyle::BORDER_MEDIUM,
+ '2dash' => BorderStyle::BORDER_MEDIUMDASHED,
+ '2dashdot' => BorderStyle::BORDER_MEDIUMDASHDOT,
+ '2dashdotdot' => BorderStyle::BORDER_MEDIUMDASHDOTDOT,
+ '2dot' => BorderStyle::BORDER_DOTTED,
+ '2double' => BorderStyle::BORDER_DOUBLE,
+ '3continuous' => BorderStyle::BORDER_THICK,
+ '3dash' => BorderStyle::BORDER_MEDIUMDASHED,
+ '3dashdot' => BorderStyle::BORDER_MEDIUMDASHDOT,
+ '3dashdotdot' => BorderStyle::BORDER_MEDIUMDASHDOTDOT,
+ '3dot' => BorderStyle::BORDER_DOTTED,
+ '3double' => BorderStyle::BORDER_DOUBLE,
+ ],
+ ];
+
+ public function parseStyle(SimpleXMLElement $styleData, array $namespaces): array
+ {
+ $style = [];
+
+ $diagonalDirection = '';
+ $borderPosition = '';
+ foreach ($styleData->Border as $borderStyle) {
+ $borderAttributes = self::getAttributes($borderStyle, $namespaces['ss']);
+ $thisBorder = [];
+ $styleType = (string) $borderAttributes->Weight;
+ $styleType .= strtolower((string) $borderAttributes->LineStyle);
+ $thisBorder['borderStyle'] = self::BORDER_MAPPINGS['borderStyle'][$styleType] ?? BorderStyle::BORDER_NONE;
+
+ foreach ($borderAttributes as $borderStyleKey => $borderStyleValuex) {
+ $borderStyleValue = (string) $borderStyleValuex;
+ switch ($borderStyleKey) {
+ case 'Position':
+ [$borderPosition, $diagonalDirection] =
+ $this->parsePosition($borderStyleValue, $diagonalDirection);
+
+ break;
+ case 'Color':
+ $borderColour = substr($borderStyleValue, 1);
+ $thisBorder['color']['rgb'] = $borderColour;
+
+ break;
+ }
+ }
+
+ if ($borderPosition) {
+ $style['borders'][$borderPosition] = $thisBorder;
+ } elseif ($diagonalDirection) {
+ $style['borders']['diagonalDirection'] = $diagonalDirection;
+ $style['borders']['diagonal'] = $thisBorder;
+ }
+ }
+
+ return $style;
+ }
+
+ protected function parsePosition(string $borderStyleValue, string $diagonalDirection): array
+ {
+ $borderStyleValue = strtolower($borderStyleValue);
+
+ if (in_array($borderStyleValue, self::BORDER_POSITIONS)) {
+ $borderPosition = $borderStyleValue;
+ } elseif ($borderStyleValue === 'diagonalleft') {
+ $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_DOWN;
+ } elseif ($borderStyleValue === 'diagonalright') {
+ $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_UP;
+ }
+
+ return [$borderPosition ?? null, $diagonalDirection];
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php
new file mode 100644
index 00000000000..9a61215258e
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php
@@ -0,0 +1,63 @@
+ [
+ 'solid' => FillStyles::FILL_SOLID,
+ 'gray75' => FillStyles::FILL_PATTERN_DARKGRAY,
+ 'gray50' => FillStyles::FILL_PATTERN_MEDIUMGRAY,
+ 'gray25' => FillStyles::FILL_PATTERN_LIGHTGRAY,
+ 'gray125' => FillStyles::FILL_PATTERN_GRAY125,
+ 'gray0625' => FillStyles::FILL_PATTERN_GRAY0625,
+ 'horzstripe' => FillStyles::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe
+ 'vertstripe' => FillStyles::FILL_PATTERN_DARKVERTICAL, // vertical stripe
+ 'reversediagstripe' => FillStyles::FILL_PATTERN_DARKUP, // reverse diagonal stripe
+ 'diagstripe' => FillStyles::FILL_PATTERN_DARKDOWN, // diagonal stripe
+ 'diagcross' => FillStyles::FILL_PATTERN_DARKGRID, // diagoanl crosshatch
+ 'thickdiagcross' => FillStyles::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch
+ 'thinhorzstripe' => FillStyles::FILL_PATTERN_LIGHTHORIZONTAL,
+ 'thinvertstripe' => FillStyles::FILL_PATTERN_LIGHTVERTICAL,
+ 'thinreversediagstripe' => FillStyles::FILL_PATTERN_LIGHTUP,
+ 'thindiagstripe' => FillStyles::FILL_PATTERN_LIGHTDOWN,
+ 'thinhorzcross' => FillStyles::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch
+ 'thindiagcross' => FillStyles::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch
+ ],
+ ];
+
+ public function parseStyle(SimpleXMLElement $styleAttributes): array
+ {
+ $style = [];
+
+ foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValuex) {
+ $styleAttributeValue = (string) $styleAttributeValuex;
+ switch ($styleAttributeKey) {
+ case 'Color':
+ $style['fill']['endColor']['rgb'] = substr($styleAttributeValue, 1);
+ $style['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1);
+
+ break;
+ case 'PatternColor':
+ $style['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1);
+
+ break;
+ case 'Pattern':
+ $lcStyleAttributeValue = strtolower((string) $styleAttributeValue);
+ $style['fill']['fillType']
+ = self::FILL_MAPPINGS['fillType'][$lcStyleAttributeValue] ?? FillStyles::FILL_NONE;
+
+ break;
+ }
+ }
+
+ return $style;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Font.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Font.php
new file mode 100644
index 00000000000..16ab44d80d0
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Font.php
@@ -0,0 +1,79 @@
+ $styleAttributeValue) {
+ $styleAttributeValue = (string) $styleAttributeValue;
+ switch ($styleAttributeKey) {
+ case 'FontName':
+ $style['font']['name'] = $styleAttributeValue;
+
+ break;
+ case 'Size':
+ $style['font']['size'] = $styleAttributeValue;
+
+ break;
+ case 'Color':
+ $style['font']['color']['rgb'] = substr($styleAttributeValue, 1);
+
+ break;
+ case 'Bold':
+ $style['font']['bold'] = true;
+
+ break;
+ case 'Italic':
+ $style['font']['italic'] = true;
+
+ break;
+ case 'Underline':
+ $style = $this->parseUnderline($style, $styleAttributeValue);
+
+ break;
+ case 'VerticalAlign':
+ $style = $this->parseVerticalAlign($style, $styleAttributeValue);
+
+ break;
+ }
+ }
+
+ return $style;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php
new file mode 100644
index 00000000000..a31aa9ebd2b
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php
@@ -0,0 +1,33 @@
+ $styleAttributeValue) {
+ $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue);
+
+ switch ($styleAttributeValue) {
+ case 'Short Date':
+ $styleAttributeValue = 'dd/mm/yyyy';
+
+ break;
+ }
+
+ if ($styleAttributeValue > '') {
+ $style['numberFormat']['formatCode'] = $styleAttributeValue;
+ }
+ }
+
+ return $style;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php
new file mode 100644
index 00000000000..fc9ace825c5
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php
@@ -0,0 +1,32 @@
+')
+ : ($simple->attributes($node) ?? new SimpleXMLElement(''));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php
index 13f7cf71b9b..0d72b3055d6 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php
@@ -119,26 +119,26 @@ class ReferenceHelper
*
* @param string $cellAddress Address of the cell we're testing
* @param int $beforeRow Number of the row we're inserting/deleting before
- * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
+ * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
* @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
- * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
+ * @param int $numberOfCols Number of columns to insert/delete (negative values indicate deletion)
*
* @return bool
*/
- private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)
+ private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfCols)
{
[$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress);
$cellColumnIndex = Coordinate::columnIndexFromString($cellColumn);
// Is cell within the range of rows/columns if we're deleting
if (
- $pNumRows < 0 &&
- ($cellRow >= ($beforeRow + $pNumRows)) &&
+ $numberOfRows < 0 &&
+ ($cellRow >= ($beforeRow + $numberOfRows)) &&
($cellRow < $beforeRow)
) {
return true;
} elseif (
- $pNumCols < 0 &&
- ($cellColumnIndex >= ($beforeColumnIndex + $pNumCols)) &&
+ $numberOfCols < 0 &&
+ ($cellColumnIndex >= ($beforeColumnIndex + $numberOfCols)) &&
($cellColumnIndex < $beforeColumnIndex)
) {
return true;
@@ -150,30 +150,30 @@ class ReferenceHelper
/**
* Update page breaks when inserting/deleting rows/columns.
*
- * @param Worksheet $pSheet The worksheet that we're editing
- * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
+ * @param Worksheet $worksheet The worksheet that we're editing
+ * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
* @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
- * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
+ * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $beforeRow Number of the row we're inserting/deleting before
- * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
+ * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/
- protected function adjustPageBreaks(Worksheet $pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void
+ protected function adjustPageBreaks(Worksheet $worksheet, $beforeCellAddress, $beforeColumnIndex, $numberOfColumns, $beforeRow, $numberOfRows): void
{
- $aBreaks = $pSheet->getBreaks();
- ($pNumCols > 0 || $pNumRows > 0) ?
+ $aBreaks = $worksheet->getBreaks();
+ ($numberOfColumns > 0 || $numberOfRows > 0) ?
uksort($aBreaks, ['self', 'cellReverseSort']) : uksort($aBreaks, ['self', 'cellSort']);
foreach ($aBreaks as $key => $value) {
- if (self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) {
+ if (self::cellAddressInDeleteRange($key, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfColumns)) {
// If we're deleting, then clear any defined breaks that are within the range
// of rows/columns that we're deleting
- $pSheet->setBreak($key, Worksheet::BREAK_NONE);
+ $worksheet->setBreak($key, 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($key, $pBefore, $pNumCols, $pNumRows);
+ $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($key != $newReference) {
- $pSheet->setBreak($newReference, $value)
+ $worksheet->setBreak($newReference, $value)
->setBreak($key, Worksheet::BREAK_NONE);
}
}
@@ -183,51 +183,49 @@ class ReferenceHelper
/**
* Update cell comments when inserting/deleting rows/columns.
*
- * @param Worksheet $pSheet The worksheet that we're editing
- * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
+ * @param Worksheet $worksheet The worksheet that we're editing
+ * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
* @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
- * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
+ * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $beforeRow Number of the row we're inserting/deleting before
- * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
+ * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/
- protected function adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void
+ protected function adjustComments($worksheet, $beforeCellAddress, $beforeColumnIndex, $numberOfColumns, $beforeRow, $numberOfRows): void
{
- $aComments = $pSheet->getComments();
+ $aComments = $worksheet->getComments();
$aNewComments = []; // the new array of all comments
foreach ($aComments as $key => &$value) {
// Any comments inside a deleted range will be ignored
- if (!self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) {
+ if (!self::cellAddressInDeleteRange($key, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfColumns)) {
// Otherwise build a new array of comments indexed by the adjusted cell reference
- $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
+ $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
$aNewComments[$newReference] = $value;
}
}
// Replace the comments array with the new set of comments
- $pSheet->setComments($aNewComments);
+ $worksheet->setComments($aNewComments);
}
/**
* Update hyperlinks when inserting/deleting rows/columns.
*
- * @param Worksheet $pSheet The worksheet that we're editing
- * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
- * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
- * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
- * @param int $beforeRow Number of the row we're inserting/deleting before
- * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
+ * @param Worksheet $worksheet The worksheet that we're editing
+ * @param string $beforeCellAddress Insert/Delete 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)
*/
- protected function adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void
+ protected function adjustHyperlinks($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
{
- $aHyperlinkCollection = $pSheet->getHyperlinkCollection();
- ($pNumCols > 0 || $pNumRows > 0) ?
+ $aHyperlinkCollection = $worksheet->getHyperlinkCollection();
+ ($numberOfColumns > 0 || $numberOfRows > 0) ?
uksort($aHyperlinkCollection, ['self', 'cellReverseSort']) : uksort($aHyperlinkCollection, ['self', 'cellSort']);
foreach ($aHyperlinkCollection as $key => $value) {
- $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
+ $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($key != $newReference) {
- $pSheet->setHyperlink($newReference, $value);
- $pSheet->setHyperlink($key, null);
+ $worksheet->setHyperlink($newReference, $value);
+ $worksheet->setHyperlink($key, null);
}
}
}
@@ -235,24 +233,22 @@ class ReferenceHelper
/**
* Update data validations when inserting/deleting rows/columns.
*
- * @param Worksheet $pSheet The worksheet that we're editing
- * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
- * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
- * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
- * @param int $beforeRow Number of the row we're inserting/deleting before
- * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
+ * @param Worksheet $worksheet The worksheet that we're editing
+ * @param string $before Insert/Delete 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)
*/
- protected function adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void
+ protected function adjustDataValidations(Worksheet $worksheet, $before, $numberOfColumns, $numberOfRows): void
{
- $aDataValidationCollection = $pSheet->getDataValidationCollection();
- ($pNumCols > 0 || $pNumRows > 0) ?
+ $aDataValidationCollection = $worksheet->getDataValidationCollection();
+ ($numberOfColumns > 0 || $numberOfRows > 0) ?
uksort($aDataValidationCollection, ['self', 'cellReverseSort']) : uksort($aDataValidationCollection, ['self', 'cellSort']);
foreach ($aDataValidationCollection as $key => $value) {
- $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
+ $newReference = $this->updateCellReference($key, $before, $numberOfColumns, $numberOfRows);
if ($key != $newReference) {
- $pSheet->setDataValidation($newReference, $value);
- $pSheet->setDataValidation($key, null);
+ $worksheet->setDataValidation($newReference, $value);
+ $worksheet->setDataValidation($key, null);
}
}
}
@@ -260,44 +256,40 @@ class ReferenceHelper
/**
* Update merged cells when inserting/deleting rows/columns.
*
- * @param Worksheet $pSheet The worksheet that we're editing
- * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
- * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
- * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
- * @param int $beforeRow Number of the row we're inserting/deleting before
- * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
+ * @param Worksheet $worksheet The worksheet that we're editing
+ * @param string $beforeCellAddress Insert/Delete 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)
*/
- protected function adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void
+ protected function adjustMergeCells(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
{
- $aMergeCells = $pSheet->getMergeCells();
+ $aMergeCells = $worksheet->getMergeCells();
$aNewMergeCells = []; // the new array of all merge cells
foreach ($aMergeCells as $key => &$value) {
- $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
+ $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
$aNewMergeCells[$newReference] = $newReference;
}
- $pSheet->setMergeCells($aNewMergeCells); // replace the merge cells array
+ $worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array
}
/**
* Update protected cells when inserting/deleting rows/columns.
*
- * @param Worksheet $pSheet The worksheet that we're editing
- * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
- * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
- * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
- * @param int $beforeRow Number of the row we're inserting/deleting before
- * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
+ * @param Worksheet $worksheet The worksheet that we're editing
+ * @param string $beforeCellAddress Insert/Delete 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)
*/
- protected function adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void
+ protected function adjustProtectedCells(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
{
- $aProtectedCells = $pSheet->getProtectedCells();
- ($pNumCols > 0 || $pNumRows > 0) ?
+ $aProtectedCells = $worksheet->getProtectedCells();
+ ($numberOfColumns > 0 || $numberOfRows > 0) ?
uksort($aProtectedCells, ['self', 'cellReverseSort']) : uksort($aProtectedCells, ['self', 'cellSort']);
foreach ($aProtectedCells as $key => $value) {
- $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows);
+ $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($key != $newReference) {
- $pSheet->protectCells($newReference, $value, true);
- $pSheet->unprotectCells($key);
+ $worksheet->protectCells($newReference, $value, true);
+ $worksheet->unprotectCells($key);
}
}
}
@@ -305,54 +297,51 @@ class ReferenceHelper
/**
* Update column dimensions when inserting/deleting rows/columns.
*
- * @param Worksheet $pSheet The worksheet that we're editing
- * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
- * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
- * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
- * @param int $beforeRow Number of the row we're inserting/deleting before
- * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
+ * @param Worksheet $worksheet The worksheet that we're editing
+ * @param string $beforeCellAddress Insert/Delete 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)
*/
- protected function adjustColumnDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void
+ protected function adjustColumnDimensions(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void
{
- $aColumnDimensions = array_reverse($pSheet->getColumnDimensions(), true);
+ $aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true);
if (!empty($aColumnDimensions)) {
foreach ($aColumnDimensions as $objColumnDimension) {
- $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $pBefore, $pNumCols, $pNumRows);
+ $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $beforeCellAddress, $numberOfColumns, $numberOfRows);
[$newReference] = Coordinate::coordinateFromString($newReference);
if ($objColumnDimension->getColumnIndex() != $newReference) {
$objColumnDimension->setColumnIndex($newReference);
}
}
- $pSheet->refreshColumnDimensions();
+ $worksheet->refreshColumnDimensions();
}
}
/**
* Update row dimensions when inserting/deleting rows/columns.
*
- * @param Worksheet $pSheet The worksheet that we're editing
- * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1')
- * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before
- * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
+ * @param Worksheet $worksheet The worksheet that we're editing
+ * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1')
+ * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $beforeRow Number of the row we're inserting/deleting before
- * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
+ * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/
- protected function adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows): void
+ protected function adjustRowDimensions(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $beforeRow, $numberOfRows): void
{
- $aRowDimensions = array_reverse($pSheet->getRowDimensions(), true);
+ $aRowDimensions = array_reverse($worksheet->getRowDimensions(), true);
if (!empty($aRowDimensions)) {
foreach ($aRowDimensions as $objRowDimension) {
- $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows);
+ $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $beforeCellAddress, $numberOfColumns, $numberOfRows);
[, $newReference] = Coordinate::coordinateFromString($newReference);
if ($objRowDimension->getRowIndex() != $newReference) {
$objRowDimension->setRowIndex($newReference);
}
}
- $pSheet->refreshRowDimensions();
+ $worksheet->refreshRowDimensions();
- $copyDimension = $pSheet->getRowDimension($beforeRow - 1);
- for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; ++$i) {
- $newDimension = $pSheet->getRowDimension($i);
+ $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());
@@ -364,47 +353,46 @@ class ReferenceHelper
/**
* Insert a new column or row, updating all possible related data.
*
- * @param string $pBefore Insert before this cell address (e.g. 'A1')
- * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion)
- * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion)
- * @param Worksheet $pSheet The worksheet that we're editing
+ * @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($pBefore, $pNumCols, $pNumRows, Worksheet $pSheet): void
+ public function insertNewBefore($beforeCellAddress, $numberOfColumns, $numberOfRows, Worksheet $worksheet): void
{
- $remove = ($pNumCols < 0 || $pNumRows < 0);
- $allCoordinates = $pSheet->getCoordinates();
+ $remove = ($numberOfColumns < 0 || $numberOfRows < 0);
+ $allCoordinates = $worksheet->getCoordinates();
- // Get coordinate of $pBefore
- [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($pBefore);
- $beforeColumnIndex = Coordinate::columnIndexFromString($beforeColumn);
+ // Get coordinate of $beforeCellAddress
+ [$beforeColumn, $beforeRow] = Coordinate::indexesFromString($beforeCellAddress);
// Clear cells if we are removing columns or rows
- $highestColumn = $pSheet->getHighestColumn();
- $highestRow = $pSheet->getHighestRow();
+ $highestColumn = $worksheet->getHighestColumn();
+ $highestRow = $worksheet->getHighestRow();
// 1. Clear column strips if we are removing columns
- if ($pNumCols < 0 && $beforeColumnIndex - 2 + $pNumCols > 0) {
+ if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) {
for ($i = 1; $i <= $highestRow - 1; ++$i) {
- for ($j = $beforeColumnIndex - 1 + $pNumCols; $j <= $beforeColumnIndex - 2; ++$j) {
+ for ($j = $beforeColumn - 1 + $numberOfColumns; $j <= $beforeColumn - 2; ++$j) {
$coordinate = Coordinate::stringFromColumnIndex($j + 1) . $i;
- $pSheet->removeConditionalStyles($coordinate);
- if ($pSheet->cellExists($coordinate)) {
- $pSheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL);
- $pSheet->getCell($coordinate)->setXfIndex(0);
+ $worksheet->removeConditionalStyles($coordinate);
+ if ($worksheet->cellExists($coordinate)) {
+ $worksheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL);
+ $worksheet->getCell($coordinate)->setXfIndex(0);
}
}
}
}
// 2. Clear row strips if we are removing rows
- if ($pNumRows < 0 && $beforeRow - 1 + $pNumRows > 0) {
- for ($i = $beforeColumnIndex - 1; $i <= Coordinate::columnIndexFromString($highestColumn) - 1; ++$i) {
- for ($j = $beforeRow + $pNumRows; $j <= $beforeRow - 1; ++$j) {
+ if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) {
+ for ($i = $beforeColumn - 1; $i <= Coordinate::columnIndexFromString($highestColumn) - 1; ++$i) {
+ for ($j = $beforeRow + $numberOfRows; $j <= $beforeRow - 1; ++$j) {
$coordinate = Coordinate::stringFromColumnIndex($i + 1) . $j;
- $pSheet->removeConditionalStyles($coordinate);
- if ($pSheet->cellExists($coordinate)) {
- $pSheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL);
- $pSheet->getCell($coordinate)->setXfIndex(0);
+ $worksheet->removeConditionalStyles($coordinate);
+ if ($worksheet->cellExists($coordinate)) {
+ $worksheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL);
+ $worksheet->getCell($coordinate)->setXfIndex(0);
}
}
}
@@ -416,85 +404,85 @@ class ReferenceHelper
$allCoordinates = array_reverse($allCoordinates);
}
while ($coordinate = array_pop($allCoordinates)) {
- $cell = $pSheet->getCell($coordinate);
+ $cell = $worksheet->getCell($coordinate);
$cellIndex = Coordinate::columnIndexFromString($cell->getColumn());
- if ($cellIndex - 1 + $pNumCols < 0) {
+ if ($cellIndex - 1 + $numberOfColumns < 0) {
continue;
}
// New coordinate
- $newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $pNumCols) . ($cell->getRow() + $pNumRows);
+ $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 >= $beforeColumnIndex) && ($cell->getRow() >= $beforeRow)) {
+ if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) {
// Update cell styles
- $pSheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex());
+ $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex());
// Insert this cell at its new location
if ($cell->getDataType() == DataType::TYPE_FORMULA) {
// Formula should be adjusted
- $pSheet->getCell($newCoordinate)
- ->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle()));
+ $worksheet->getCell($newCoordinate)
+ ->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle()));
} else {
// Formula should not be adjusted
- $pSheet->getCell($newCoordinate)->setValue($cell->getValue());
+ $worksheet->getCell($newCoordinate)->setValueExplicit($cell->getValue(), $cell->getDataType());
}
// Clear the original cell
- $pSheet->getCellCollection()->delete($coordinate);
+ $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(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle()));
+ $cell->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle()));
}
}
}
// Duplicate styles for the newly inserted cells
- $highestColumn = $pSheet->getHighestColumn();
- $highestRow = $pSheet->getHighestRow();
+ $highestColumn = $worksheet->getHighestColumn();
+ $highestRow = $worksheet->getHighestRow();
- if ($pNumCols > 0 && $beforeColumnIndex - 2 > 0) {
+ if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) {
for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
// Style
- $coordinate = Coordinate::stringFromColumnIndex($beforeColumnIndex - 1) . $i;
- if ($pSheet->cellExists($coordinate)) {
- $xfIndex = $pSheet->getCell($coordinate)->getXfIndex();
- $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ?
- $pSheet->getConditionalStyles($coordinate) : false;
- for ($j = $beforeColumnIndex; $j <= $beforeColumnIndex - 1 + $pNumCols; ++$j) {
- $pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex);
+ $coordinate = Coordinate::stringFromColumnIndex($beforeColumn - 1) . $i;
+ if ($worksheet->cellExists($coordinate)) {
+ $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
+ $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ?
+ $worksheet->getConditionalStyles($coordinate) : false;
+ for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) {
+ $worksheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex);
if ($conditionalStyles) {
$cloned = [];
foreach ($conditionalStyles as $conditionalStyle) {
$cloned[] = clone $conditionalStyle;
}
- $pSheet->setConditionalStyles(Coordinate::stringFromColumnIndex($j) . $i, $cloned);
+ $worksheet->setConditionalStyles(Coordinate::stringFromColumnIndex($j) . $i, $cloned);
}
}
}
}
}
- if ($pNumRows > 0 && $beforeRow - 1 > 0) {
- for ($i = $beforeColumnIndex; $i <= Coordinate::columnIndexFromString($highestColumn); ++$i) {
+ if ($numberOfRows > 0 && $beforeRow - 1 > 0) {
+ for ($i = $beforeColumn; $i <= Coordinate::columnIndexFromString($highestColumn); ++$i) {
// Style
$coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1);
- if ($pSheet->cellExists($coordinate)) {
- $xfIndex = $pSheet->getCell($coordinate)->getXfIndex();
- $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ?
- $pSheet->getConditionalStyles($coordinate) : false;
- for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) {
- $pSheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
+ if ($worksheet->cellExists($coordinate)) {
+ $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
+ $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ?
+ $worksheet->getConditionalStyles($coordinate) : false;
+ for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) {
+ $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
if ($conditionalStyles) {
$cloned = [];
foreach ($conditionalStyles as $conditionalStyle) {
$cloned[] = clone $conditionalStyle;
}
- $pSheet->setConditionalStyles(Coordinate::stringFromColumnIndex($i) . $j, $cloned);
+ $worksheet->setConditionalStyles(Coordinate::stringFromColumnIndex($i) . $j, $cloned);
}
}
}
@@ -502,47 +490,47 @@ class ReferenceHelper
}
// Update worksheet: column dimensions
- $this->adjustColumnDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
+ $this->adjustColumnDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
// Update worksheet: row dimensions
- $this->adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
+ $this->adjustRowDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $beforeRow, $numberOfRows);
// Update worksheet: page breaks
- $this->adjustPageBreaks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
+ $this->adjustPageBreaks($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows);
// Update worksheet: comments
- $this->adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
+ $this->adjustComments($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows);
// Update worksheet: hyperlinks
- $this->adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
+ $this->adjustHyperlinks($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
// Update worksheet: data validations
- $this->adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
+ $this->adjustDataValidations($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
// Update worksheet: merge cells
- $this->adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
+ $this->adjustMergeCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
// Update worksheet: protected cells
- $this->adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows);
+ $this->adjustProtectedCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
// Update worksheet: autofilter
- $autoFilter = $pSheet->getAutoFilter();
+ $autoFilter = $worksheet->getAutoFilter();
$autoFilterRange = $autoFilter->getRange();
if (!empty($autoFilterRange)) {
- if ($pNumCols != 0) {
+ if ($numberOfColumns != 0) {
$autoFilterColumns = $autoFilter->getColumns();
if (count($autoFilterColumns) > 0) {
$column = '';
$row = 0;
- sscanf($pBefore, '%[A-Z]%d', $column, $row);
+ sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row);
$columnIndex = Coordinate::columnIndexFromString($column);
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange);
if ($columnIndex <= $rangeEnd[0]) {
- if ($pNumCols < 0) {
+ if ($numberOfColumns < 0) {
// If we're actually deleting any columns that fall within the autofilter range,
// then we delete any rules for those columns
- $deleteColumn = $columnIndex + $pNumCols - 1;
- $deleteCount = abs($pNumCols);
+ $deleteColumn = $columnIndex + $numberOfColumns - 1;
+ $deleteCount = abs($numberOfColumns);
for ($i = 1; $i <= $deleteCount; ++$i) {
if (isset($autoFilterColumns[Coordinate::stringFromColumnIndex($deleteColumn + 1)])) {
$autoFilter->clearColumn(Coordinate::stringFromColumnIndex($deleteColumn + 1));
@@ -553,10 +541,10 @@ class ReferenceHelper
$startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0];
// Shuffle columns in autofilter range
- if ($pNumCols > 0) {
+ if ($numberOfColumns > 0) {
$startColRef = $startCol;
$endColRef = $rangeEnd[0];
- $toColRef = $rangeEnd[0] + $pNumCols;
+ $toColRef = $rangeEnd[0] + $numberOfColumns;
do {
$autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef));
@@ -566,7 +554,7 @@ class ReferenceHelper
} else {
// For delete, we shuffle from beginning to end to avoid overwriting
$startColID = Coordinate::stringFromColumnIndex($startCol);
- $toColID = Coordinate::stringFromColumnIndex($startCol + $pNumCols);
+ $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns);
$endColID = Coordinate::stringFromColumnIndex($rangeEnd[0] + 1);
do {
$autoFilter->shiftColumn($startColID, $toColID);
@@ -577,62 +565,62 @@ class ReferenceHelper
}
}
}
- $pSheet->setAutoFilter($this->updateCellReference($autoFilterRange, $pBefore, $pNumCols, $pNumRows));
+ $worksheet->setAutoFilter($this->updateCellReference($autoFilterRange, $beforeCellAddress, $numberOfColumns, $numberOfRows));
}
// Update worksheet: freeze pane
- if ($pSheet->getFreezePane()) {
- $splitCell = $pSheet->getFreezePane();
- $topLeftCell = $pSheet->getTopLeftCell();
+ if ($worksheet->getFreezePane()) {
+ $splitCell = $worksheet->getFreezePane() ?? '';
+ $topLeftCell = $worksheet->getTopLeftCell() ?? '';
- $splitCell = $this->updateCellReference($splitCell, $pBefore, $pNumCols, $pNumRows);
- $topLeftCell = $this->updateCellReference($topLeftCell, $pBefore, $pNumCols, $pNumRows);
+ $splitCell = $this->updateCellReference($splitCell, $beforeCellAddress, $numberOfColumns, $numberOfRows);
+ $topLeftCell = $this->updateCellReference($topLeftCell, $beforeCellAddress, $numberOfColumns, $numberOfRows);
- $pSheet->freezePane($splitCell, $topLeftCell);
+ $worksheet->freezePane($splitCell, $topLeftCell);
}
// Page setup
- if ($pSheet->getPageSetup()->isPrintAreaSet()) {
- $pSheet->getPageSetup()->setPrintArea($this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows));
+ if ($worksheet->getPageSetup()->isPrintAreaSet()) {
+ $worksheet->getPageSetup()->setPrintArea($this->updateCellReference($worksheet->getPageSetup()->getPrintArea(), $beforeCellAddress, $numberOfColumns, $numberOfRows));
}
// Update worksheet: drawings
- $aDrawings = $pSheet->getDrawingCollection();
+ $aDrawings = $worksheet->getDrawingCollection();
foreach ($aDrawings as $objDrawing) {
- $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows);
+ $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($objDrawing->getCoordinates() != $newReference) {
$objDrawing->setCoordinates($newReference);
}
}
// Update workbook: define names
- if (count($pSheet->getParent()->getDefinedNames()) > 0) {
- foreach ($pSheet->getParent()->getDefinedNames() as $definedName) {
- if ($definedName->getWorksheet()->getHashCode() === $pSheet->getHashCode()) {
- $definedName->setValue($this->updateCellReference($definedName->getValue(), $pBefore, $pNumCols, $pNumRows));
+ if (count($worksheet->getParent()->getDefinedNames()) > 0) {
+ foreach ($worksheet->getParent()->getDefinedNames() as $definedName) {
+ if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) {
+ $definedName->setValue($this->updateCellReference($definedName->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows));
}
}
}
// Garbage collect
- $pSheet->garbageCollect();
+ $worksheet->garbageCollect();
}
/**
* Update references within formulas.
*
- * @param string $pFormula Formula to update
- * @param string $pBefore Insert before this one
- * @param int $pNumCols Number of columns to insert
- * @param int $pNumRows Number of rows to insert
- * @param string $sheetName Worksheet name/title
+ * @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($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, $sheetName = '')
+ public function updateFormulaReferences($formula = '', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0, $worksheetName = '')
{
// Update cell references in the formula
- $formulaBlocks = explode('"', $pFormula);
+ $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)
@@ -645,16 +633,16 @@ class ReferenceHelper
foreach ($matches as $match) {
$fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3] . ':' . $match[4];
- $modified3 = substr($this->updateCellReference('$A' . $match[3], $pBefore, $pNumCols, $pNumRows), 2);
- $modified4 = substr($this->updateCellReference('$A' . $match[4], $pBefore, $pNumCols, $pNumRows), 2);
+ $modified3 = substr($this->updateCellReference('$A' . $match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2);
+ $modified4 = substr($this->updateCellReference('$A' . $match[4], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2);
if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
- if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) {
+ 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 + trim($match[3], '$');
+ $row = 10000000 + (int) trim($match[3], '$');
$cellIndex = $column . $row;
$newCellTokens[$cellIndex] = preg_quote($toString, '/');
@@ -670,11 +658,11 @@ class ReferenceHelper
foreach ($matches as $match) {
$fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3] . ':' . $match[4];
- $modified3 = substr($this->updateCellReference($match[3] . '$1', $pBefore, $pNumCols, $pNumRows), 0, -2);
- $modified4 = substr($this->updateCellReference($match[4] . '$1', $pBefore, $pNumCols, $pNumRows), 0, -2);
+ $modified3 = substr($this->updateCellReference($match[3] . '$1', $beforeCellAddress, $numberOfColumns, $numberOfRows), 0, -2);
+ $modified4 = substr($this->updateCellReference($match[4] . '$1', $beforeCellAddress, $numberOfColumns, $numberOfRows), 0, -2);
if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
- if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) {
+ 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
@@ -695,17 +683,17 @@ class ReferenceHelper
foreach ($matches as $match) {
$fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3] . ':' . $match[4];
- $modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows);
- $modified4 = $this->updateCellReference($match[4], $pBefore, $pNumCols, $pNumRows);
+ $modified3 = $this->updateCellReference($match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows);
+ $modified4 = $this->updateCellReference($match[4], $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($match[3] . $match[4] !== $modified3 . $modified4) {
- if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) {
+ 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 = trim($row, '$') + 10000000;
+ $row = (int) trim($row, '$') + 10000000;
$cellIndex = $column . $row;
$newCellTokens[$cellIndex] = preg_quote($toString, '/');
@@ -723,16 +711,18 @@ class ReferenceHelper
$fromString = ($match[2] > '') ? $match[2] . '!' : '';
$fromString .= $match[3];
- $modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows);
+ $modified3 = $this->updateCellReference($match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($match[3] !== $modified3) {
- if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) {
+ 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 = trim($row, '$') + 10000000;
- $cellIndex = $row . $column;
+ $row = (int) trim($row, '$') + 10000000;
+ $cellIndex = $row . $rowAdditionalIndex . $column . $columnAdditionalIndex;
$newCellTokens[$cellIndex] = preg_quote($toString, '/');
$cellTokens[$cellIndex] = '/(? 0) {
- if ($pNumCols > 0 || $pNumRows > 0) {
+ if ($numberOfColumns > 0 || $numberOfRows > 0) {
krsort($cellTokens);
krsort($newCellTokens);
} else {
@@ -762,22 +752,22 @@ class ReferenceHelper
/**
* Update all cell references within a formula, irrespective of worksheet.
*/
- public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $insertColumns = 0, int $insertRows = 0): string
+ public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string
{
- $formula = $this->updateCellReferencesAllWorksheets($formula, $insertColumns, $insertRows);
+ $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows);
- if ($insertColumns !== 0) {
- $formula = $this->updateColumnRangesAllWorksheets($formula, $insertColumns);
+ if ($numberOfColumns !== 0) {
+ $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns);
}
- if ($insertRows !== 0) {
- $formula = $this->updateRowRangesAllWorksheets($formula, $insertRows);
+ if ($numberOfRows !== 0) {
+ $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows);
}
return $formula;
}
- private function updateCellReferencesAllWorksheets(string $formula, int $insertColumns, int $insertRows): string
+ private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string
{
$splitCount = preg_match_all(
'/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
@@ -804,11 +794,11 @@ class ReferenceHelper
$row = $rows[$splitCount][0];
if (!empty($column) && $column[0] !== '$') {
- $column = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($column) + $insertColumns);
+ $column = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($column) + $numberOfColumns);
$formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength);
}
if (!empty($row) && $row[0] !== '$') {
- $row += $insertRows;
+ $row += $numberOfRows;
$formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength);
}
}
@@ -816,7 +806,7 @@ class ReferenceHelper
return $formula;
}
- private function updateColumnRangesAllWorksheets(string $formula, int $insertColumns): string
+ private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string
{
$splitCount = preg_match_all(
'/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui',
@@ -843,11 +833,11 @@ class ReferenceHelper
$toColumn = $toColumns[$splitCount][0];
if (!empty($fromColumn) && $fromColumn[0] !== '$') {
- $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $insertColumns);
+ $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) + $insertColumns);
+ $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns);
$formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength);
}
}
@@ -855,7 +845,7 @@ class ReferenceHelper
return $formula;
}
- private function updateRowRangesAllWorksheets(string $formula, int $insertRows): string
+ private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string
{
$splitCount = preg_match_all(
'/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui',
@@ -882,11 +872,11 @@ class ReferenceHelper
$toRow = $toRows[$splitCount][0];
if (!empty($fromRow) && $fromRow[0] !== '$') {
- $fromRow += $insertRows;
+ $fromRow += $numberOfRows;
$formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength);
}
if (!empty($toRow) && $toRow[0] !== '$') {
- $toRow += $insertRows;
+ $toRow += $numberOfRows;
$formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength);
}
}
@@ -897,29 +887,29 @@ class ReferenceHelper
/**
* Update cell reference.
*
- * @param string $pCellRange Cell range
- * @param string $pBefore Insert before this one
- * @param int $pNumCols Number of columns to increment
- * @param int $pNumRows Number of rows to increment
+ * @param string $cellReference Cell address or range of addresses
+ * @param string $beforeCellAddress Insert before this one
+ * @param int $numberOfColumns Number of columns to increment
+ * @param int $numberOfRows Number of rows to increment
*
* @return string Updated cell range
*/
- public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0)
+ public function updateCellReference($cellReference = 'A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
{
// Is it in another worksheet? Will not have to update anything.
- if (strpos($pCellRange, '!') !== false) {
- return $pCellRange;
+ if (strpos($cellReference, '!') !== false) {
+ return $cellReference;
// Is it a range or a single cell?
- } elseif (!Coordinate::coordinateIsRange($pCellRange)) {
+ } elseif (!Coordinate::coordinateIsRange($cellReference)) {
// Single cell
- return $this->updateSingleCellReference($pCellRange, $pBefore, $pNumCols, $pNumRows);
- } elseif (Coordinate::coordinateIsRange($pCellRange)) {
+ return $this->updateSingleCellReference($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows);
+ } elseif (Coordinate::coordinateIsRange($cellReference)) {
// Range
- return $this->updateCellRange($pCellRange, $pBefore, $pNumCols, $pNumRows);
+ return $this->updateCellRange($cellReference, $beforeCellAddress, $numberOfColumns, $numberOfRows);
}
// Return original
- return $pCellRange;
+ return $cellReference;
}
/**
@@ -953,33 +943,33 @@ class ReferenceHelper
/**
* Update cell range.
*
- * @param string $pCellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3')
- * @param string $pBefore Insert before this one
- * @param int $pNumCols Number of columns to increment
- * @param int $pNumRows Number of rows to increment
+ * @param string $cellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3')
+ * @param string $beforeCellAddress Insert before this one
+ * @param int $numberOfColumns Number of columns to increment
+ * @param int $numberOfRows Number of rows to increment
*
* @return string Updated cell range
*/
- private function updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0)
+ private function updateCellRange($cellRange = 'A1:A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
{
- if (!Coordinate::coordinateIsRange($pCellRange)) {
+ if (!Coordinate::coordinateIsRange($cellRange)) {
throw new Exception('Only cell ranges may be passed to this method.');
}
// Update range
- $range = Coordinate::splitRange($pCellRange);
+ $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])) {
- $r = Coordinate::coordinateFromString($this->updateSingleCellReference($range[$i][$j] . '1', $pBefore, $pNumCols, $pNumRows));
+ $r = Coordinate::coordinateFromString($this->updateSingleCellReference($range[$i][$j] . '1', $beforeCellAddress, $numberOfColumns, $numberOfRows));
$range[$i][$j] = $r[0];
} elseif (ctype_digit($range[$i][$j])) {
- $r = Coordinate::coordinateFromString($this->updateSingleCellReference('A' . $range[$i][$j], $pBefore, $pNumCols, $pNumRows));
+ $r = Coordinate::coordinateFromString($this->updateSingleCellReference('A' . $range[$i][$j], $beforeCellAddress, $numberOfColumns, $numberOfRows));
$range[$i][$j] = $r[1];
} else {
- $range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $pBefore, $pNumCols, $pNumRows);
+ $range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $beforeCellAddress, $numberOfColumns, $numberOfRows);
}
}
}
@@ -991,24 +981,24 @@ class ReferenceHelper
/**
* Update single cell reference.
*
- * @param string $pCellReference Single cell reference
- * @param string $pBefore Insert before this one
- * @param int $pNumCols Number of columns to increment
- * @param int $pNumRows Number of rows to increment
+ * @param string $cellReference Single cell reference
+ * @param string $beforeCellAddress Insert before this one
+ * @param int $numberOfColumns Number of columns to increment
+ * @param int $numberOfRows Number of rows to increment
*
* @return string Updated cell reference
*/
- private function updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0)
+ private function updateSingleCellReference($cellReference = 'A1', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0)
{
- if (Coordinate::coordinateIsRange($pCellReference)) {
+ if (Coordinate::coordinateIsRange($cellReference)) {
throw new Exception('Only single cell references may be passed to this method.');
}
- // Get coordinate of $pBefore
- [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($pBefore);
+ // Get coordinate of $beforeCellAddress
+ [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress);
- // Get coordinate of $pCellReference
- [$newColumn, $newRow] = Coordinate::coordinateFromString($pCellReference);
+ // Get coordinate of $cellReference
+ [$newColumn, $newRow] = Coordinate::coordinateFromString($cellReference);
// Verify which parts should be updated
$updateColumn = (($newColumn[0] != '$') && ($beforeColumn[0] != '$') && (Coordinate::columnIndexFromString($newColumn) >= Coordinate::columnIndexFromString($beforeColumn)));
@@ -1016,12 +1006,12 @@ class ReferenceHelper
// Create new column reference
if ($updateColumn) {
- $newColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($newColumn) + $pNumCols);
+ $newColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($newColumn) + $numberOfColumns);
}
// Create new row reference
if ($updateRow) {
- $newRow = $newRow + $pNumRows;
+ $newRow = (int) $newRow + $numberOfRows;
}
// Return new reference
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/ITextElement.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/ITextElement.php
index 69954676028..39b70c868be 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/ITextElement.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/ITextElement.php
@@ -14,7 +14,7 @@ interface ITextElement
/**
* Set text.
*
- * @param $text string Text
+ * @param string $text Text
*
* @return ITextElement
*/
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/RichText.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/RichText.php
index 104177bd299..3a6e1f8e350 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/RichText.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/RichText.php
@@ -17,38 +17,36 @@ class RichText implements IComparable
/**
* Create a new RichText instance.
- *
- * @param Cell $pCell
*/
- public function __construct(?Cell $pCell = null)
+ public function __construct(?Cell $cell = null)
{
// Initialise variables
$this->richTextElements = [];
// Rich-Text string attached to cell?
- if ($pCell !== null) {
+ if ($cell !== null) {
// Add cell text and style
- if ($pCell->getValue() != '') {
- $objRun = new Run($pCell->getValue());
- $objRun->setFont(clone $pCell->getWorksheet()->getStyle($pCell->getCoordinate())->getFont());
+ if ($cell->getValue() != '') {
+ $objRun = new Run($cell->getValue());
+ $objRun->setFont(clone $cell->getWorksheet()->getStyle($cell->getCoordinate())->getFont());
$this->addText($objRun);
}
// Set parent value
- $pCell->setValueExplicit($this, DataType::TYPE_STRING);
+ $cell->setValueExplicit($this, DataType::TYPE_STRING);
}
}
/**
* Add text.
*
- * @param ITextElement $pText Rich text element
+ * @param ITextElement $text Rich text element
*
* @return $this
*/
- public function addText(ITextElement $pText)
+ public function addText(ITextElement $text)
{
- $this->richTextElements[] = $pText;
+ $this->richTextElements[] = $text;
return $this;
}
@@ -56,13 +54,13 @@ class RichText implements IComparable
/**
* Create text.
*
- * @param string $pText Text
+ * @param string $text Text
*
* @return TextElement
*/
- public function createText($pText)
+ public function createText($text)
{
- $objText = new TextElement($pText);
+ $objText = new TextElement($text);
$this->addText($objText);
return $objText;
@@ -71,13 +69,13 @@ class RichText implements IComparable
/**
* Create text run.
*
- * @param string $pText Text
+ * @param string $text Text
*
* @return Run
*/
- public function createTextRun($pText)
+ public function createTextRun($text)
{
- $objText = new Run($pText);
+ $objText = new Run($text);
$this->addText($objText);
return $objText;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/Run.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/Run.php
index 592d0e36b68..9c9f8072943 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/Run.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/Run.php
@@ -16,11 +16,11 @@ class Run extends TextElement implements ITextElement
/**
* Create a new Run instance.
*
- * @param string $pText Text
+ * @param string $text Text
*/
- public function __construct($pText = '')
+ public function __construct($text = '')
{
- parent::__construct($pText);
+ parent::__construct($text);
// Initialise variables
$this->font = new Font();
}
@@ -38,13 +38,13 @@ class Run extends TextElement implements ITextElement
/**
* Set font.
*
- * @param Font $pFont Font
+ * @param Font $font Font
*
* @return $this
*/
- public function setFont(?Font $pFont = null)
+ public function setFont(?Font $font = null)
{
- $this->font = $pFont;
+ $this->font = $font;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/TextElement.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/TextElement.php
index f8be5d55b0e..6bec005b4d5 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/TextElement.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/TextElement.php
@@ -14,12 +14,12 @@ class TextElement implements ITextElement
/**
* Create a new TextElement instance.
*
- * @param string $pText Text
+ * @param string $text Text
*/
- public function __construct($pText = '')
+ public function __construct($text = '')
{
// Initialise variables
- $this->text = $pText;
+ $this->text = $text;
}
/**
@@ -35,7 +35,7 @@ class TextElement implements ITextElement
/**
* Set text.
*
- * @param $text string Text
+ * @param string $text Text
*
* @return $this
*/
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php
index cfa505733c6..5fbbadb6764 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php
@@ -24,18 +24,7 @@ class Settings
*
* @var int
*/
- private static $libXmlLoaderOptions = null;
-
- /**
- * Allow/disallow libxml_disable_entity_loader() call when not thread safe.
- * Default behaviour is to do the check, but if you're running PHP versions
- * 7.2 < 7.2.1
- * then you may need to disable this check to prevent unwanted behaviour in other threads
- * SECURITY WARNING: Changing this flag is not recommended.
- *
- * @var bool
- */
- private static $libXmlDisableEntityLoader = true;
+ private static $libXmlLoaderOptions;
/**
* The cache implementation to be used for cell collection.
@@ -63,24 +52,29 @@ class Settings
*
* @return bool Success or failure
*/
- public static function setLocale($locale)
+ 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 $rendererClass Class name of the chart renderer
+ * @param string $rendererClassName Class name of the chart renderer
* eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph
*/
- public static function setChartRenderer($rendererClass): void
+ public static function setChartRenderer(string $rendererClassName): void
{
- if (!is_a($rendererClass, IRenderer::class, true)) {
+ if (!is_a($rendererClassName, IRenderer::class, true)) {
throw new Exception('Chart renderer must implement ' . IRenderer::class);
}
- self::$chartRenderer = $rendererClass;
+ self::$chartRenderer = $rendererClassName;
}
/**
@@ -89,11 +83,16 @@ class Settings
* @return null|string Class name of the chart renderer
* eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph
*/
- public static function getChartRenderer()
+ public static function getChartRenderer(): ?string
{
return self::$chartRenderer;
}
+ public static function htmlEntityFlags(): int
+ {
+ return \ENT_COMPAT;
+ }
+
/**
* Set default options for libxml loader.
*
@@ -113,40 +112,39 @@ class Settings
*
* @return int Default options for libxml loader
*/
- public static function getLibXmlLoaderOptions()
+ public static function getLibXmlLoaderOptions(): int
{
if (self::$libXmlLoaderOptions === null && defined('LIBXML_DTDLOAD')) {
self::setLibXmlLoaderOptions(LIBXML_DTDLOAD | LIBXML_DTDATTR);
} elseif (self::$libXmlLoaderOptions === null) {
- self::$libXmlLoaderOptions = true;
+ self::$libXmlLoaderOptions = 0;
}
return self::$libXmlLoaderOptions;
}
/**
- * Enable/Disable the entity loader for libxml loader.
- * Allow/disallow libxml_disable_entity_loader() call when not thread safe.
- * Default behaviour is to do the check, but if you're running PHP versions
- * 7.2 < 7.2.1
- * then you may need to disable this check to prevent unwanted behaviour in other threads
- * SECURITY WARNING: Changing this flag to false is not recommended.
+ * Deprecated, has no effect.
*
* @param bool $state
+ *
+ * @deprecated will be removed without replacement as it is no longer necessary on PHP 7.3.0+
*/
public static function setLibXmlDisableEntityLoader($state): void
{
- self::$libXmlDisableEntityLoader = (bool) $state;
+ // noop
}
/**
- * Return the state of the entity loader (disabled/enabled) for libxml loader.
+ * Deprecated, has no effect.
*
* @return bool $state
+ *
+ * @deprecated will be removed without replacement as it is no longer necessary on PHP 7.3.0+
*/
- public static function getLibXmlDisableEntityLoader()
+ public static function getLibXmlDisableEntityLoader(): bool
{
- return self::$libXmlDisableEntityLoader;
+ return true;
}
/**
@@ -158,11 +156,9 @@ class Settings
}
/**
- * Gets the implementation of cache that should be used for cell collection.
- *
- * @return CacheInterface
+ * Gets the implementation of cache that is being used for cell collection.
*/
- public static function getCache()
+ public static function getCache(): CacheInterface
{
if (!self::$cache) {
self::$cache = new Memory();
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/CodePage.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/CodePage.php
index 1d5d8933ed0..8718a6135ed 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/CodePage.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/CodePage.php
@@ -8,6 +8,7 @@ class CodePage
{
public const DEFAULT_CODE_PAGE = 'CP1252';
+ /** @var array */
private static $pageArray = [
0 => 'CP1252', // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program
367 => 'ASCII', // ASCII
@@ -56,7 +57,7 @@ class CodePage
10010 => 'MACROMANIA', // Macintosh Romania
10017 => 'MACUKRAINE', // Macintosh Ukraine
10021 => 'MACTHAI', // Macintosh Thai
- 10029 => 'MACCENTRALEUROPE', // Macintosh Central Europe
+ 10029 => ['MACCENTRALEUROPE', 'MAC-CENTRALEUROPE'], // Macintosh Central Europe
10079 => 'MACICELAND', // Macintosh Icelandic
10081 => 'MACTURKISH', // Macintosh Turkish
10082 => 'MACCROATIAN', // Macintosh Croatian
@@ -65,6 +66,7 @@ class CodePage
//32769 => 'unsupported', // ANSI Latin I (BIFF2-BIFF3)
65000 => 'UTF-7', // Unicode (UTF-7)
65001 => 'UTF-8', // Unicode (UTF-8)
+ 99999 => ['unsupported'], // Unicode (UTF-8)
];
public static function validate(string $codePage): bool
@@ -83,7 +85,20 @@ class CodePage
public static function numberToName(int $codePage): string
{
if (array_key_exists($codePage, self::$pageArray)) {
- return self::$pageArray[$codePage];
+ $value = self::$pageArray[$codePage];
+ if (is_array($value)) {
+ foreach ($value as $encoding) {
+ if (@iconv('UTF-8', $encoding, ' ') !== false) {
+ self::$pageArray[$codePage] = $encoding;
+
+ return $encoding;
+ }
+ }
+
+ throw new PhpSpreadsheetException("Code page $codePage not implemented on this system.");
+ } else {
+ return $value;
+ }
}
if ($codePage == 720 || $codePage == 32769) {
throw new PhpSpreadsheetException("Code page $codePage not supported."); // OEM Arabic
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Date.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Date.php
index 180a71596d6..5b0a2907a1f 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Date.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Date.php
@@ -2,9 +2,10 @@
namespace PhpOffice\PhpSpreadsheet\Shared;
+use DateTime;
use DateTimeInterface;
use DateTimeZone;
-use PhpOffice\PhpSpreadsheet\Calculation\DateTime;
+use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
@@ -65,17 +66,17 @@ class Date
/**
* Set the Excel calendar (Windows 1900 or Mac 1904).
*
- * @param int $baseDate Excel base date (1900 or 1904)
+ * @param int $baseYear Excel base date (1900 or 1904)
*
* @return bool Success or failure
*/
- public static function setExcelCalendar($baseDate)
+ public static function setExcelCalendar($baseYear)
{
if (
- ($baseDate == self::CALENDAR_WINDOWS_1900) ||
- ($baseDate == self::CALENDAR_MAC_1904)
+ ($baseYear == self::CALENDAR_WINDOWS_1900) ||
+ ($baseYear == self::CALENDAR_MAC_1904)
) {
- self::$excelCalendar = $baseDate;
+ self::$excelCalendar = $baseYear;
return true;
}
@@ -96,7 +97,7 @@ class Date
/**
* Set the Default timezone to use for dates.
*
- * @param DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions
+ * @param null|DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions
*
* @return bool Success or failure
*/
@@ -114,29 +115,39 @@ class Date
}
/**
- * Return the Default timezone being used for dates.
- *
- * @return DateTimeZone The timezone being used as default for Excel timestamp to PHP DateTime object
+ * Return the Default timezone, or UTC if default not set.
*/
- public static function getDefaultTimezone()
+ public static function getDefaultTimezone(): DateTimeZone
{
- if (self::$defaultTimeZone === null) {
- self::$defaultTimeZone = new DateTimeZone('UTC');
- }
+ return self::$defaultTimeZone ?? new DateTimeZone('UTC');
+ }
+ /**
+ * Return the Default timezone, or local timezone if default is not set.
+ */
+ public static function getDefaultOrLocalTimezone(): DateTimeZone
+ {
+ return self::$defaultTimeZone ?? new DateTimeZone(date_default_timezone_get());
+ }
+
+ /**
+ * Return the Default timezone even if null.
+ */
+ public static function getDefaultTimezoneOrNull(): ?DateTimeZone
+ {
return self::$defaultTimeZone;
}
/**
* Validate a timezone.
*
- * @param DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object
+ * @param null|DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object
*
- * @return DateTimeZone The timezone as a timezone object
+ * @return ?DateTimeZone The timezone as a timezone object
*/
private static function validateTimeZone($timeZone)
{
- if ($timeZone instanceof DateTimeZone) {
+ if ($timeZone instanceof DateTimeZone || $timeZone === null) {
return $timeZone;
}
if (in_array($timeZone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC))) {
@@ -152,28 +163,28 @@ class Date
* @param float|int $excelTimestamp MS Excel serialized date/time value
* @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp,
* if you don't want to treat it as a UTC value
- * Use the default (UST) unless you absolutely need a conversion
+ * Use the default (UTC) unless you absolutely need a conversion
*
- * @return \DateTime PHP date/time object
+ * @return DateTime PHP date/time object
*/
public static function excelToDateTimeObject($excelTimestamp, $timeZone = null)
{
$timeZone = ($timeZone === null) ? self::getDefaultTimezone() : self::validateTimeZone($timeZone);
if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) {
- if ($excelTimestamp < 1.0) {
+ if ($excelTimestamp < 1 && self::$excelCalendar === self::CALENDAR_WINDOWS_1900) {
// Unix timestamp base date
- $baseDate = new \DateTime('1970-01-01', $timeZone);
+ $baseDate = new DateTime('1970-01-01', $timeZone);
} else {
// MS Excel calendar base dates
if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) {
// Allow adjustment for 1900 Leap Year in MS Excel
- $baseDate = ($excelTimestamp < 60) ? new \DateTime('1899-12-31', $timeZone) : new \DateTime('1899-12-30', $timeZone);
+ $baseDate = ($excelTimestamp < 60) ? new DateTime('1899-12-31', $timeZone) : new DateTime('1899-12-30', $timeZone);
} else {
- $baseDate = new \DateTime('1904-01-01', $timeZone);
+ $baseDate = new DateTime('1904-01-01', $timeZone);
}
}
} else {
- $baseDate = new \DateTime('1899-12-30', $timeZone);
+ $baseDate = new DateTime('1899-12-30', $timeZone);
}
$days = floor($excelTimestamp);
@@ -195,11 +206,13 @@ class Date
/**
* Convert a MS serialized datetime value from Excel to a unix timestamp.
+ * The use of Unix timestamps, and therefore this function, is discouraged.
+ * They are not Y2038-safe on a 32-bit system, and have no timezone info.
*
* @param float|int $excelTimestamp MS Excel serialized date/time value
* @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp,
* if you don't want to treat it as a UTC value
- * Use the default (UST) unless you absolutely need a conversion
+ * Use the default (UTC) unless you absolutely need a conversion
*
* @return int Unix timetamp for this date/time
*/
@@ -212,7 +225,8 @@ class Date
/**
* Convert a date from PHP to an MS Excel serialized date/time value.
*
- * @param mixed $dateValue Unix Timestamp or PHP DateTime object or a string
+ * @param mixed $dateValue PHP DateTime object or a string - Unix timestamp is also permitted, but discouraged;
+ * not Y2038-safe on a 32-bit system, and no timezone info
*
* @return bool|float Excel date/time value
* or boolean FALSE on failure
@@ -251,18 +265,20 @@ class Date
/**
* Convert a Unix timestamp to an MS Excel serialized date/time value.
+ * The use of Unix timestamps, and therefore this function, is discouraged.
+ * They are not Y2038-safe on a 32-bit system, and have no timezone info.
*
- * @param int $dateValue Unix Timestamp
+ * @param int $unixTimestamp Unix Timestamp
*
- * @return float MS Excel serialized date/time value
+ * @return false|float MS Excel serialized date/time value
*/
- public static function timestampToExcel($dateValue)
+ public static function timestampToExcel($unixTimestamp)
{
- if (!is_numeric($dateValue)) {
+ if (!is_numeric($unixTimestamp)) {
return false;
}
- return self::dateTimeToExcel(new \DateTime('@' . $dateValue));
+ return self::dateTimeToExcel(new DateTime('@' . $unixTimestamp));
}
/**
@@ -303,8 +319,8 @@ class Date
}
// Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
- $century = substr($year, 0, 2);
- $decade = substr($year, 2, 2);
+ $century = (int) substr($year, 0, 2);
+ $decade = (int) substr($year, 2, 2);
$excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myexcelBaseDate + $excel1900isLeapYear;
$excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
@@ -317,12 +333,12 @@ class Date
*
* @return bool
*/
- public static function isDateTime(Cell $pCell)
+ public static function isDateTime(Cell $cell)
{
- return is_numeric($pCell->getCalculatedValue()) &&
+ return is_numeric($cell->getCalculatedValue()) &&
self::isDateTimeFormat(
- $pCell->getWorksheet()->getStyle(
- $pCell->getCoordinate()
+ $cell->getWorksheet()->getStyle(
+ $cell->getCoordinate()
)->getNumberFormat()
);
}
@@ -332,9 +348,9 @@ class Date
*
* @return bool
*/
- public static function isDateTimeFormat(NumberFormat $pFormat)
+ public static function isDateTimeFormat(NumberFormat $excelFormatCode)
{
- return self::isDateTimeFormatCode($pFormat->getFormatCode());
+ return self::isDateTimeFormatCode($excelFormatCode->getFormatCode());
}
private static $possibleDateFormatCharacters = 'eymdHs';
@@ -342,23 +358,23 @@ class Date
/**
* Is a given number format code a date/time?
*
- * @param string $pFormatCode
+ * @param string $excelFormatCode
*
* @return bool
*/
- public static function isDateTimeFormatCode($pFormatCode)
+ public static function isDateTimeFormatCode($excelFormatCode)
{
- if (strtolower($pFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) {
+ if (strtolower($excelFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) {
// "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check)
return false;
}
- if (preg_match('/[0#]E[+-]0/i', $pFormatCode)) {
+ if (preg_match('/[0#]E[+-]0/i', $excelFormatCode)) {
// Scientific format
return false;
}
// Switch on formatcode
- switch ($pFormatCode) {
+ switch ($excelFormatCode) {
// Explicitly defined date formats
case NumberFormat::FORMAT_DATE_YYYYMMDD:
case NumberFormat::FORMAT_DATE_YYYYMMDD2:
@@ -386,21 +402,21 @@ class Date
}
// Typically number, currency or accounting (or occasionally fraction) formats
- if ((substr($pFormatCode, 0, 1) == '_') || (substr($pFormatCode, 0, 2) == '0 ')) {
+ if ((substr($excelFormatCode, 0, 1) == '_') || (substr($excelFormatCode, 0, 2) == '0 ')) {
return false;
}
// Some "special formats" provided in German Excel versions were detected as date time value,
// so filter them out here - "\C\H\-00000" (Switzerland) and "\D-00000" (Germany).
- if (\strpos($pFormatCode, '-00000') !== false) {
+ if (\strpos($excelFormatCode, '-00000') !== false) {
return false;
}
// Try checking for any of the date formatting characters that don't appear within square braces
- if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $pFormatCode)) {
+ if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $excelFormatCode)) {
// We might also have a format mask containing quoted strings...
// we don't want to test for any of our characters within the quoted blocks
- if (strpos($pFormatCode, '"') !== false) {
+ if (strpos($excelFormatCode, '"') !== false) {
$segMatcher = false;
- foreach (explode('"', $pFormatCode) as $subVal) {
+ foreach (explode('"', $excelFormatCode) as $subVal) {
// Only test in alternate array entries (the non-quoted blocks)
if (
($segMatcher = !$segMatcher) &&
@@ -436,14 +452,14 @@ class Date
return false;
}
- $dateValueNew = DateTime::DATEVALUE($dateValue);
+ $dateValueNew = DateTimeExcel\DateValue::fromString($dateValue);
if ($dateValueNew === Functions::VALUE()) {
return false;
}
if (strpos($dateValue, ':') !== false) {
- $timeValue = DateTime::TIMEVALUE($dateValue);
+ $timeValue = DateTimeExcel\TimeValue::fromString($dateValue);
if ($timeValue === Functions::VALUE()) {
return false;
}
@@ -456,21 +472,21 @@ class Date
/**
* Converts a month name (either a long or a short name) to a month number.
*
- * @param string $month Month name or abbreviation
+ * @param string $monthName Month name or abbreviation
*
* @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name
*/
- public static function monthStringToNumber($month)
+ public static function monthStringToNumber($monthName)
{
$monthIndex = 1;
foreach (self::$monthNames as $shortMonthName => $longMonthName) {
- if (($month === $longMonthName) || ($month === $shortMonthName)) {
+ if (($monthName === $longMonthName) || ($monthName === $shortMonthName)) {
return $monthIndex;
}
++$monthIndex;
}
- return $month;
+ return $monthName;
}
/**
@@ -489,4 +505,19 @@ class Date
return $day;
}
+
+ public static function dateTimeFromTimestamp(string $date, ?DateTimeZone $timeZone = null): DateTime
+ {
+ $dtobj = DateTime::createFromFormat('U', $date) ?: new DateTime();
+ $dtobj->setTimeZone($timeZone ?? self::getDefaultOrLocalTimezone());
+
+ return $dtobj;
+ }
+
+ public static function formattedDateTimeFromTimestamp(string $date, string $format, ?DateTimeZone $timeZone = null): string
+ {
+ $dtobj = self::dateTimeFromTimestamp($date, $timeZone);
+
+ return $dtobj->format($format);
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Drawing.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Drawing.php
index f41fb695c46..0d8ad618ba2 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Drawing.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Drawing.php
@@ -3,32 +3,34 @@
namespace PhpOffice\PhpSpreadsheet\Shared;
use GdImage;
+use SimpleXMLElement;
class Drawing
{
/**
* Convert pixels to EMU.
*
- * @param int $pValue Value in pixels
+ * @param int $pixelValue Value in pixels
*
* @return int Value in EMU
*/
- public static function pixelsToEMU($pValue)
+ public static function pixelsToEMU($pixelValue)
{
- return round($pValue * 9525);
+ return $pixelValue * 9525;
}
/**
* Convert EMU to pixels.
*
- * @param int $pValue Value in EMU
+ * @param int|SimpleXMLElement $emuValue Value in EMU
*
* @return int Value in pixels
*/
- public static function EMUToPixels($pValue)
+ public static function EMUToPixels($emuValue)
{
- if ($pValue != 0) {
- return round($pValue / 9525);
+ $emuValue = (int) $emuValue;
+ if ($emuValue != 0) {
+ return (int) round($emuValue / 9525);
}
return 0;
@@ -39,50 +41,51 @@ class Drawing
* By inspection of a real Excel file using Calibri 11, one finds 1000px ~ 142.85546875
* This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional.
*
- * @param int $pValue Value in pixels
- * @param \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont Default font of the workbook
+ * @param int $pixelValue Value in pixels
*
- * @return int Value in cell dimension
+ * @return float|int Value in cell dimension
*/
- public static function pixelsToCellDimension($pValue, \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont)
+ public static function pixelsToCellDimension($pixelValue, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont)
{
// Font name and size
- $name = $pDefaultFont->getName();
- $size = $pDefaultFont->getSize();
+ $name = $defaultFont->getName();
+ $size = $defaultFont->getSize();
if (isset(Font::$defaultColumnWidths[$name][$size])) {
// Exact width can be determined
- $colWidth = $pValue * Font::$defaultColumnWidths[$name][$size]['width'] / Font::$defaultColumnWidths[$name][$size]['px'];
- } else {
- // We don't have data for this particular font and size, use approximation by
- // extrapolating from Calibri 11
- $colWidth = $pValue * 11 * Font::$defaultColumnWidths['Calibri'][11]['width'] / Font::$defaultColumnWidths['Calibri'][11]['px'] / $size;
+ return $pixelValue * Font::$defaultColumnWidths[$name][$size]['width']
+ / Font::$defaultColumnWidths[$name][$size]['px'];
}
- return $colWidth;
+ // We don't have data for this particular font and size, use approximation by
+ // extrapolating from Calibri 11
+ return $pixelValue * 11 * Font::$defaultColumnWidths['Calibri'][11]['width']
+ / Font::$defaultColumnWidths['Calibri'][11]['px'] / $size;
}
/**
* Convert column width from (intrinsic) Excel units to pixels.
*
- * @param float $pValue Value in cell dimension
- * @param \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont Default font of the workbook
+ * @param float $cellWidth Value in cell dimension
+ * @param \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont Default font of the workbook
*
* @return int Value in pixels
*/
- public static function cellDimensionToPixels($pValue, \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont)
+ public static function cellDimensionToPixels($cellWidth, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont)
{
// Font name and size
- $name = $pDefaultFont->getName();
- $size = $pDefaultFont->getSize();
+ $name = $defaultFont->getName();
+ $size = $defaultFont->getSize();
if (isset(Font::$defaultColumnWidths[$name][$size])) {
// Exact width can be determined
- $colWidth = $pValue * Font::$defaultColumnWidths[$name][$size]['px'] / Font::$defaultColumnWidths[$name][$size]['width'];
+ $colWidth = $cellWidth * Font::$defaultColumnWidths[$name][$size]['px']
+ / Font::$defaultColumnWidths[$name][$size]['width'];
} else {
// We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11
- $colWidth = $pValue * $size * Font::$defaultColumnWidths['Calibri'][11]['px'] / Font::$defaultColumnWidths['Calibri'][11]['width'] / 11;
+ $colWidth = $cellWidth * $size * Font::$defaultColumnWidths['Calibri'][11]['px']
+ / Font::$defaultColumnWidths['Calibri'][11]['width'] / 11;
}
// Round pixels to closest integer
@@ -94,26 +97,26 @@ class Drawing
/**
* Convert pixels to points.
*
- * @param int $pValue Value in pixels
+ * @param int $pixelValue Value in pixels
*
* @return float Value in points
*/
- public static function pixelsToPoints($pValue)
+ public static function pixelsToPoints($pixelValue)
{
- return $pValue * 0.75;
+ return $pixelValue * 0.75;
}
/**
* Convert points to pixels.
*
- * @param int $pValue Value in points
+ * @param int $pointValue Value in points
*
* @return int Value in pixels
*/
- public static function pointsToPixels($pValue)
+ public static function pointsToPixels($pointValue)
{
- if ($pValue != 0) {
- return (int) ceil($pValue / 0.75);
+ if ($pointValue != 0) {
+ return (int) ceil($pointValue / 0.75);
}
return 0;
@@ -122,26 +125,27 @@ class Drawing
/**
* Convert degrees to angle.
*
- * @param int $pValue Degrees
+ * @param int $degrees Degrees
*
* @return int Angle
*/
- public static function degreesToAngle($pValue)
+ public static function degreesToAngle($degrees)
{
- return (int) round($pValue * 60000);
+ return (int) round($degrees * 60000);
}
/**
* Convert angle to degrees.
*
- * @param int $pValue Angle
+ * @param int|SimpleXMLElement $angle Angle
*
* @return int Degrees
*/
- public static function angleToDegrees($pValue)
+ public static function angleToDegrees($angle)
{
- if ($pValue != 0) {
- return round($pValue / 60000);
+ $angle = (int) $angle;
+ if ($angle != 0) {
+ return (int) round($angle / 60000);
}
return 0;
@@ -152,14 +156,14 @@ class Drawing
*
* @see http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
*
- * @param string $p_sFile Path to Windows DIB (BMP) image
+ * @param string $bmpFilename Path to Windows DIB (BMP) image
*
* @return GdImage|resource
*/
- public static function imagecreatefrombmp($p_sFile)
+ public static function imagecreatefrombmp($bmpFilename)
{
// Load the image into a string
- $file = fopen($p_sFile, 'rb');
+ $file = fopen($bmpFilename, 'rb');
$read = fread($file, 10);
while (!feof($file) && ($read != '')) {
$read .= fread($file, 1024);
@@ -171,6 +175,8 @@ class Drawing
// Process the header
// Structure: http://www.fastgraph.com/help/bmp_header_format.html
+ $width = 0;
+ $height = 0;
if (substr($header, 0, 4) == '424d') {
// Cut it in parts of 2 bytes
$header_parts = str_split($header, 2);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php
index 1da877262fd..6bdc8f7dca3 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php
@@ -7,7 +7,7 @@ class SpgrContainer
/**
* Parent Shape Group Container.
*
- * @var \PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer
+ * @var null|SpgrContainer
*/
private $parent;
@@ -20,20 +20,16 @@ class SpgrContainer
/**
* Set parent Shape Group Container.
- *
- * @param \PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer $parent
*/
- public function setParent($parent): void
+ public function setParent(?self $parent): void
{
$this->parent = $parent;
}
/**
* Get the parent Shape Group Container if any.
- *
- * @return null|\PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer
*/
- public function getParent()
+ public function getParent(): ?self
{
return $this->parent;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer.php
index 1bd15b9eddd..36806aa683d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer.php
@@ -166,10 +166,10 @@ class DggContainer
/**
* Set identifier clusters. [ => , ...].
*
- * @param array $pValue
+ * @param array $IDCLs
*/
- public function setIDCLs($pValue): void
+ public function setIDCLs($IDCLs): void
{
- $this->IDCLs = $pValue;
+ $this->IDCLs = $IDCLs;
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php
index b07786ff658..7203b66bea2 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php
@@ -7,16 +7,14 @@ class BstoreContainer
/**
* BLIP Store Entries. Each of them holds one BLIP (Big Large Image or Picture).
*
- * @var array
+ * @var BstoreContainer\BSE[]
*/
private $BSECollection = [];
/**
* Add a BLIP Store Entry.
- *
- * @param BstoreContainer\BSE $BSE
*/
- public function addBSE($BSE): void
+ public function addBSE(BstoreContainer\BSE $BSE): void
{
$this->BSECollection[] = $BSE;
$BSE->setParent($this);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php
index e8851465771..d24af3f7c7b 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php
@@ -2,6 +2,8 @@
namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer;
+use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer;
+
class BSE
{
const BLIPTYPE_ERROR = 0x00;
@@ -18,7 +20,7 @@ class BSE
/**
* The parent BLIP Store Entry Container.
*
- * @var \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer
+ * @var BstoreContainer
*/
private $parent;
@@ -38,10 +40,8 @@ class BSE
/**
* Set parent BLIP Store Entry Container.
- *
- * @param \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer $parent
*/
- public function setParent($parent): void
+ public function setParent(BstoreContainer $parent): void
{
$this->parent = $parent;
}
@@ -58,10 +58,8 @@ class BSE
/**
* Set the BLIP.
- *
- * @param BSE\Blip $blip
*/
- public function setBlip($blip): void
+ public function setBlip(BSE\Blip $blip): void
{
$this->blip = $blip;
$blip->setParent($this);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php
index 500d7eaf3ee..03b261f8feb 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php
@@ -2,12 +2,14 @@
namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE;
+use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE;
+
class Blip
{
/**
* The parent BSE.
*
- * @var \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE
+ * @var BSE
*/
private $parent;
@@ -40,20 +42,16 @@ class Blip
/**
* Set parent BSE.
- *
- * @param \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE $parent
*/
- public function setParent($parent): void
+ public function setParent(BSE $parent): void
{
$this->parent = $parent;
}
/**
* Get parent BSE.
- *
- * @return \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE $parent
*/
- public function getParent()
+ public function getParent(): BSE
{
return $this->parent;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php
index bec7132fc84..f2fe8caa837 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php
@@ -2,7 +2,8 @@
namespace PhpOffice\PhpSpreadsheet\Shared;
-use InvalidArgumentException;
+use PhpOffice\PhpSpreadsheet\Exception;
+use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use ZipArchive;
class File
@@ -16,75 +17,81 @@ class File
/**
* Set the flag indicating whether the File Upload Temp directory should be used for temporary files.
- *
- * @param bool $useUploadTempDir Use File Upload Temporary directory (true or false)
*/
- public static function setUseUploadTempDirectory($useUploadTempDir): void
+ public static function setUseUploadTempDirectory(bool $useUploadTempDir): void
{
self::$useUploadTempDirectory = (bool) $useUploadTempDir;
}
/**
* Get the flag indicating whether the File Upload Temp directory should be used for temporary files.
- *
- * @return bool Use File Upload Temporary directory (true or false)
*/
- public static function getUseUploadTempDirectory()
+ public static function getUseUploadTempDirectory(): bool
{
return self::$useUploadTempDirectory;
}
+ // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
+ // Section 4.3.7
+ // Looks like there might be endian-ness considerations
+ private const ZIP_FIRST_4 = [
+ "\x50\x4b\x03\x04", // what it looks like on my system
+ "\x04\x03\x4b\x50", // what it says in documentation
+ ];
+
+ private static function validateZipFirst4(string $zipFile): bool
+ {
+ $contents = @file_get_contents($zipFile, false, null, 0, 4);
+
+ return in_array($contents, self::ZIP_FIRST_4, true);
+ }
+
/**
* Verify if a file exists.
- *
- * @param string $pFilename Filename
- *
- * @return bool
*/
- public static function fileExists($pFilename)
+ public static function fileExists(string $filename): bool
{
// Sick construction, but it seems that
// file_exists returns strange values when
// doing the original file_exists on ZIP archives...
- if (strtolower(substr($pFilename, 0, 3)) == 'zip') {
+ if (strtolower(substr($filename, 0, 6)) == 'zip://') {
// Open ZIP file and verify if the file exists
- $zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6);
- $archiveFile = substr($pFilename, strpos($pFilename, '#') + 1);
+ $zipFile = substr($filename, 6, strrpos($filename, '#') - 6);
+ $archiveFile = substr($filename, strrpos($filename, '#') + 1);
- $zip = new ZipArchive();
- if ($zip->open($zipFile) === true) {
- $returnValue = ($zip->getFromName($archiveFile) !== false);
- $zip->close();
+ if (self::validateZipFirst4($zipFile)) {
+ $zip = new ZipArchive();
+ $res = $zip->open($zipFile);
+ if ($res === true) {
+ $returnValue = ($zip->getFromName($archiveFile) !== false);
+ $zip->close();
- return $returnValue;
+ return $returnValue;
+ }
}
return false;
}
- return file_exists($pFilename);
+ return file_exists($filename);
}
/**
* Returns canonicalized absolute pathname, also for ZIP archives.
- *
- * @param string $pFilename
- *
- * @return string
*/
- public static function realpath($pFilename)
+ public static function realpath(string $filename): string
{
// Returnvalue
$returnValue = '';
// Try using realpath()
- if (file_exists($pFilename)) {
- $returnValue = realpath($pFilename);
+ if (file_exists($filename)) {
+ $returnValue = realpath($filename) ?: '';
}
// Found something?
- if ($returnValue == '' || ($returnValue === null)) {
- $pathArray = explode('/', $pFilename);
+ if ($returnValue === '') {
+ $pathArray = explode('/', $filename);
while (in_array('..', $pathArray) && $pathArray[0] != '..') {
$iMax = count($pathArray);
for ($i = 0; $i < $iMax; ++$i) {
@@ -104,45 +111,75 @@ class File
/**
* Get the systems temporary directory.
- *
- * @return string
*/
- public static function sysGetTempDir()
+ public static function sysGetTempDir(): string
{
- // Moodle hack!
- if (function_exists('make_temp_directory')) {
- $temp = make_temp_directory('phpspreadsheet');
- return realpath(dirname($temp));
- }
-
+ $path = sys_get_temp_dir();
if (self::$useUploadTempDirectory) {
// use upload-directory when defined to allow running on environments having very restricted
// open_basedir configs
if (ini_get('upload_tmp_dir') !== false) {
if ($temp = ini_get('upload_tmp_dir')) {
if (file_exists($temp)) {
- return realpath($temp);
+ $path = $temp;
}
}
}
}
- return realpath(sys_get_temp_dir());
+ return realpath($path) ?: '';
+ }
+
+ public static function temporaryFilename(): string
+ {
+ $filename = tempnam(self::sysGetTempDir(), 'phpspreadsheet');
+ if ($filename === false) {
+ throw new Exception('Could not create temporary file');
+ }
+
+ return $filename;
}
/**
* Assert that given path is an existing file and is readable, otherwise throw exception.
- *
- * @param string $filename
*/
- public static function assertFile($filename): void
+ public static function assertFile(string $filename, string $zipMember = ''): void
{
if (!is_file($filename)) {
- throw new InvalidArgumentException('File "' . $filename . '" does not exist.');
+ throw new ReaderException('File "' . $filename . '" does not exist.');
}
if (!is_readable($filename)) {
- throw new InvalidArgumentException('Could not open "' . $filename . '" for reading.');
+ throw new ReaderException('Could not open "' . $filename . '" for reading.');
+ }
+
+ if ($zipMember !== '') {
+ $zipfile = "zip://$filename#$zipMember";
+ if (!self::fileExists($zipfile)) {
+ throw new ReaderException("Could not find zip member $zipfile");
+ }
}
}
+
+ /**
+ * Same as assertFile, except return true/false and don't throw Exception.
+ */
+ public static function testFileNoThrow(string $filename, ?string $zipMember = null): bool
+ {
+ if (!is_file($filename)) {
+ return false;
+ }
+ if (!is_readable($filename)) {
+ return false;
+ }
+ if ($zipMember === null) {
+ return true;
+ }
+ // validate zip, but don't check specific member
+ if ($zipMember === '') {
+ return self::validateZipFirst4($filename);
+ }
+
+ return self::fileExists("zip://$filename#$zipMember");
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php
index ee1f8abac85..9a74befeb9b 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php
@@ -4,6 +4,8 @@ namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
+use PhpOffice\PhpSpreadsheet\Style\Alignment;
+use PhpOffice\PhpSpreadsheet\Style\Font as FontStyle;
class Font
{
@@ -44,10 +46,10 @@ class Font
const ARIAL_ITALIC = 'ariali.ttf';
const ARIAL_BOLD_ITALIC = 'arialbi.ttf';
- const CALIBRI = 'CALIBRI.TTF';
- const CALIBRI_BOLD = 'CALIBRIB.TTF';
- const CALIBRI_ITALIC = 'CALIBRII.TTF';
- const CALIBRI_BOLD_ITALIC = 'CALIBRIZ.TTF';
+ const CALIBRI = 'calibri.ttf';
+ const CALIBRI_BOLD = 'calibrib.ttf';
+ const CALIBRI_ITALIC = 'calibrii.ttf';
+ const CALIBRI_BOLD_ITALIC = 'calibriz.ttf';
const COMIC_SANS_MS = 'comic.ttf';
const COMIC_SANS_MS_BOLD = 'comicbd.ttf';
@@ -111,7 +113,7 @@ class Font
*
* @var string
*/
- private static $trueTypeFontPath = null;
+ private static $trueTypeFontPath;
/**
* How wide is a default column for a given default font and size?
@@ -163,16 +165,16 @@ class Font
/**
* Set autoSize method.
*
- * @param string $pValue see self::AUTOSIZE_METHOD_*
+ * @param string $method see self::AUTOSIZE_METHOD_*
*
* @return bool Success or failure
*/
- public static function setAutoSizeMethod($pValue)
+ public static function setAutoSizeMethod($method)
{
- if (!in_array($pValue, self::$autoSizeMethods)) {
+ if (!in_array($method, self::$autoSizeMethods)) {
return false;
}
- self::$autoSizeMethod = $pValue;
+ self::$autoSizeMethod = $method;
return true;
}
@@ -196,11 +198,11 @@ class Font
* ~/.fonts/
* .
*
- * @param string $pValue
+ * @param string $folderPath
*/
- public static function setTrueTypeFontPath($pValue): void
+ public static function setTrueTypeFontPath($folderPath): void
{
- self::$trueTypeFontPath = $pValue;
+ self::$trueTypeFontPath = $folderPath;
}
/**
@@ -216,14 +218,14 @@ class Font
/**
* Calculate an (approximate) OpenXML column width, based on font size and text contained.
*
- * @param \PhpOffice\PhpSpreadsheet\Style\Font $font Font object
+ * @param FontStyle $font Font object
* @param RichText|string $cellText Text to calculate width
* @param int $rotation Rotation angle
- * @param null|\PhpOffice\PhpSpreadsheet\Style\Font $defaultFont Font object
+ * @param null|FontStyle $defaultFont Font object
*
* @return int Column width
*/
- public static function calculateColumnWidth(\PhpOffice\PhpSpreadsheet\Style\Font $font, $cellText = '', $rotation = 0, ?\PhpOffice\PhpSpreadsheet\Style\Font $defaultFont = null)
+ public static function calculateColumnWidth(FontStyle $font, $cellText = '', $rotation = 0, ?FontStyle $defaultFont = null)
{
// If it is rich text, use plain text
if ($cellText instanceof RichText) {
@@ -231,7 +233,7 @@ class Font
}
// Special case if there are one or more newline characters ("\n")
- if (strpos($cellText, "\n") !== false) {
+ if (strpos($cellText ?? '', "\n") !== false) {
$lineTexts = explode("\n", $cellText);
$lineWidths = [];
foreach ($lineTexts as $lineText) {
@@ -243,6 +245,7 @@ class Font
// Try to get the exact text width in pixels
$approximate = self::$autoSizeMethod == self::AUTOSIZE_METHOD_APPROX;
+ $columnWidth = 0;
if (!$approximate) {
$columnWidthAdjust = ceil(self::getTextWidthPixelsExact('n', $font, 0) * 1.07);
@@ -263,22 +266,16 @@ class Font
}
// Convert from pixel width to column width
- $columnWidth = Drawing::pixelsToCellDimension($columnWidth, $defaultFont);
+ $columnWidth = Drawing::pixelsToCellDimension((int) $columnWidth, $defaultFont);
// Return
- return round($columnWidth, 6);
+ return (int) round($columnWidth, 6);
}
/**
* Get GD text width in pixels for a string of text in a certain font at a certain rotation angle.
- *
- * @param string $text
- * @param \PhpOffice\PhpSpreadsheet\Style\Font
- * @param int $rotation
- *
- * @return int
*/
- public static function getTextWidthPixelsExact($text, \PhpOffice\PhpSpreadsheet\Style\Font $font, $rotation = 0)
+ public static function getTextWidthPixelsExact(string $text, FontStyle $font, int $rotation = 0): int
{
if (!function_exists('imagettfbbox')) {
throw new PhpSpreadsheetException('GD library needs to be enabled');
@@ -307,7 +304,7 @@ class Font
*
* @return int Text width in pixels (no padding added)
*/
- public static function getTextWidthPixelsApprox($columnText, \PhpOffice\PhpSpreadsheet\Style\Font $font, $rotation = 0)
+ public static function getTextWidthPixelsApprox($columnText, FontStyle $font, $rotation = 0)
{
$fontName = $font->getName();
$fontSize = $font->getSize();
@@ -342,7 +339,7 @@ class Font
// Calculate approximate rotated column width
if ($rotation !== 0) {
- if ($rotation == -165) {
+ if ($rotation == Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) {
// stacked text
$columnWidth = 4; // approximation
} else {
@@ -395,11 +392,9 @@ class Font
/**
* Returns the font path given the font.
*
- * @param \PhpOffice\PhpSpreadsheet\Style\Font $font
- *
* @return string Path to TrueType font file
*/
- public static function getTrueTypeFontFileFromFont($font)
+ public static function getTrueTypeFontFileFromFont(FontStyle $font)
{
if (!file_exists(self::$trueTypeFontPath) || !is_dir(self::$trueTypeFontPath)) {
throw new PhpSpreadsheetException('Valid directory to TrueType Font files not specified');
@@ -525,13 +520,13 @@ class Font
/**
* Returns the associated charset for the font name.
*
- * @param string $name Font name
+ * @param string $fontName Font name
*
* @return int Character set code
*/
- public static function getCharsetFromFontName($name)
+ public static function getCharsetFromFontName($fontName)
{
- switch ($name) {
+ switch ($fontName) {
// Add more cases. Check FONT records in real Excel files.
case 'EucrosiaUPC':
return self::CHARSET_ANSI_THAI;
@@ -550,28 +545,28 @@ class Font
* Get the effective column width for columns without a column dimension or column with width -1
* For example, for Calibri 11 this is 9.140625 (64 px).
*
- * @param \PhpOffice\PhpSpreadsheet\Style\Font $font The workbooks default font
- * @param bool $pPixels true = return column width in pixels, false = return in OOXML units
+ * @param FontStyle $font The workbooks default font
+ * @param bool $returnAsPixels true = return column width in pixels, false = return in OOXML units
*
* @return mixed Column width
*/
- public static function getDefaultColumnWidthByFont(\PhpOffice\PhpSpreadsheet\Style\Font $font, $pPixels = false)
+ public static function getDefaultColumnWidthByFont(FontStyle $font, $returnAsPixels = false)
{
if (isset(self::$defaultColumnWidths[$font->getName()][$font->getSize()])) {
// Exact width can be determined
- $columnWidth = $pPixels ?
+ $columnWidth = $returnAsPixels ?
self::$defaultColumnWidths[$font->getName()][$font->getSize()]['px']
: self::$defaultColumnWidths[$font->getName()][$font->getSize()]['width'];
} else {
// We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11
- $columnWidth = $pPixels ?
+ $columnWidth = $returnAsPixels ?
self::$defaultColumnWidths['Calibri'][11]['px']
: self::$defaultColumnWidths['Calibri'][11]['width'];
$columnWidth = $columnWidth * $font->getSize() / 11;
// Round pixels to closest integer
- if ($pPixels) {
+ if ($returnAsPixels) {
$columnWidth = (int) round($columnWidth);
}
}
@@ -583,11 +578,11 @@ class Font
* Get the effective row height for rows without a row dimension or rows with height -1
* For example, for Calibri 11 this is 15 points.
*
- * @param \PhpOffice\PhpSpreadsheet\Style\Font $font The workbooks default font
+ * @param FontStyle $font The workbooks default font
*
* @return float Row height in points
*/
- public static function getDefaultRowHeightByFont(\PhpOffice\PhpSpreadsheet\Style\Font $font)
+ public static function getDefaultRowHeightByFont(FontStyle $font)
{
switch ($font->getName()) {
case 'Arial':
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/IntOrFloat.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/IntOrFloat.php
new file mode 100644
index 00000000000..060f09c8831
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/IntOrFloat.php
@@ -0,0 +1,21 @@
+getRowDimension() == $this->m) {
if ($this->isspd) {
- $X = $B->getArrayCopy();
+ $X = $B->getArray();
$nx = $B->getColumnDimension();
for ($k = 0; $k < $this->m; ++$k) {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php
index 4c67c3a908f..5c6ccfd3acc 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php
@@ -18,9 +18,9 @@ namespace PhpOffice\PhpSpreadsheet\Shared\JAMA;
* conditioned, or even singular, so the validity of the equation
* A = V*D*inverse(V) depends upon V.cond().
*
- * @author Paul Meagher
+ * @author Paul Meagher
*
- * @version 1.1
+ * @version 1.1
*/
class EigenvalueDecomposition
{
@@ -70,6 +70,11 @@ class EigenvalueDecomposition
private $cdivi;
+ /**
+ * @var array
+ */
+ private $A;
+
/**
* Symmetric Householder reduction to tridiagonal form.
*/
@@ -80,6 +85,7 @@ class EigenvalueDecomposition
// Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
// Fortran subroutine in EISPACK.
$this->d = $this->V[$this->n - 1];
+ $j = 0;
// Householder reduction to tridiagonal form.
for ($i = $this->n - 1; $i > 0; --$i) {
$i_ = $i - 1;
@@ -781,9 +787,9 @@ class EigenvalueDecomposition
/**
* Constructor: Check for symmetry, then construct the eigenvalue decomposition.
*
- * @param mixed $Arg A Square matrix
+ * @param Matrix $Arg A Square matrix
*/
- public function __construct($Arg)
+ public function __construct(Matrix $Arg)
{
$this->A = $Arg->getArray();
$this->n = $Arg->getColumnDimension();
@@ -848,6 +854,7 @@ class EigenvalueDecomposition
*/
public function getD()
{
+ $D = [];
for ($i = 0; $i < $this->n; ++$i) {
$D[$i] = array_fill(0, $this->n, 0.0);
$D[$i][$i] = $this->d[$i];
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php
index 4aecff73431..ecfe42bad98 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php
@@ -135,6 +135,7 @@ class LUDecomposition
*/
public function getL()
{
+ $L = [];
for ($i = 0; $i < $this->m; ++$i) {
for ($j = 0; $j < $this->n; ++$j) {
if ($i > $j) {
@@ -159,6 +160,7 @@ class LUDecomposition
*/
public function getU()
{
+ $U = [];
for ($i = 0; $i < $this->n; ++$i) {
for ($j = 0; $j < $this->n; ++$j) {
if ($i <= $j) {
@@ -219,7 +221,7 @@ class LUDecomposition
/**
* Count determinants.
*
- * @return array d matrix deterninat
+ * @return float
*/
public function det()
{
@@ -240,11 +242,11 @@ class LUDecomposition
/**
* Solve A*X = B.
*
- * @param mixed $B a Matrix with as many rows as A and any number of columns
+ * @param Matrix $B a Matrix with as many rows as A and any number of columns
*
* @return Matrix X so that L*U*X = B(piv,:)
*/
- public function solve($B)
+ public function solve(Matrix $B)
{
if ($B->getRowDimension() == $this->m) {
if ($this->isNonsingular()) {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/Matrix.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/Matrix.php
index a5cb6de0f61..adf399ac7fb 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/Matrix.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/Matrix.php
@@ -147,7 +147,7 @@ class Matrix
* @param int $i Row position
* @param int $j Column position
*
- * @return mixed Element (int/float/double)
+ * @return float|int
*/
public function get($i = null, $j = null)
{
@@ -323,11 +323,9 @@ class Matrix
*
* @param int $i Row position
* @param int $j Column position
- * @param mixed $c Int/float/double value
- *
- * @return mixed Element (int/float/double)
+ * @param float|int $c value
*/
- public function set($i = null, $j = null, $c = null)
+ public function set($i = null, $j = null, $c = null): void
{
// Optimized set version just has this
$this->A[$i][$j] = $c;
@@ -456,17 +454,6 @@ class Matrix
return $s;
}
- /**
- * uminus.
- *
- * Unary minus matrix -A
- *
- * @return Matrix Unary minus matrix
- */
- public function uminus()
- {
- }
-
/**
* plus.
*
@@ -1164,7 +1151,7 @@ class Matrix
*
* @return Matrix ... Solution if A is square, least squares solution otherwise
*/
- public function solve($B)
+ public function solve(self $B)
{
if ($this->m == $this->n) {
$LU = new LUDecomposition($this);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php
index 3bb8a10ef91..9b51f41390b 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php
@@ -15,9 +15,9 @@ use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException;
* of simultaneous linear equations. This will fail if isFullRank()
* returns false.
*
- * @author Paul Meagher
+ * @author Paul Meagher
*
- * @version 1.1
+ * @version 1.1
*/
class QRDecomposition
{
@@ -54,47 +54,43 @@ class QRDecomposition
/**
* QR Decomposition computed by Householder reflections.
*
- * @param matrix $A Rectangular matrix
+ * @param Matrix $A Rectangular matrix
*/
- public function __construct($A)
+ public function __construct(Matrix $A)
{
- if ($A instanceof Matrix) {
- // Initialize.
- $this->QR = $A->getArray();
- $this->m = $A->getRowDimension();
- $this->n = $A->getColumnDimension();
- // Main loop.
- for ($k = 0; $k < $this->n; ++$k) {
- // Compute 2-norm of k-th column without under/overflow.
- $nrm = 0.0;
- for ($i = $k; $i < $this->m; ++$i) {
- $nrm = hypo($nrm, $this->QR[$i][$k]);
- }
- if ($nrm != 0.0) {
- // Form k-th Householder vector.
- if ($this->QR[$k][$k] < 0) {
- $nrm = -$nrm;
- }
- for ($i = $k; $i < $this->m; ++$i) {
- $this->QR[$i][$k] /= $nrm;
- }
- $this->QR[$k][$k] += 1.0;
- // Apply transformation to remaining columns.
- for ($j = $k + 1; $j < $this->n; ++$j) {
- $s = 0.0;
- for ($i = $k; $i < $this->m; ++$i) {
- $s += $this->QR[$i][$k] * $this->QR[$i][$j];
- }
- $s = -$s / $this->QR[$k][$k];
- for ($i = $k; $i < $this->m; ++$i) {
- $this->QR[$i][$j] += $s * $this->QR[$i][$k];
- }
- }
- }
- $this->Rdiag[$k] = -$nrm;
+ // Initialize.
+ $this->QR = $A->getArray();
+ $this->m = $A->getRowDimension();
+ $this->n = $A->getColumnDimension();
+ // Main loop.
+ for ($k = 0; $k < $this->n; ++$k) {
+ // Compute 2-norm of k-th column without under/overflow.
+ $nrm = 0.0;
+ for ($i = $k; $i < $this->m; ++$i) {
+ $nrm = hypo($nrm, $this->QR[$i][$k]);
}
- } else {
- throw new CalculationException(Matrix::ARGUMENT_TYPE_EXCEPTION);
+ if ($nrm != 0.0) {
+ // Form k-th Householder vector.
+ if ($this->QR[$k][$k] < 0) {
+ $nrm = -$nrm;
+ }
+ for ($i = $k; $i < $this->m; ++$i) {
+ $this->QR[$i][$k] /= $nrm;
+ }
+ $this->QR[$k][$k] += 1.0;
+ // Apply transformation to remaining columns.
+ for ($j = $k + 1; $j < $this->n; ++$j) {
+ $s = 0.0;
+ for ($i = $k; $i < $this->m; ++$i) {
+ $s += $this->QR[$i][$k] * $this->QR[$i][$j];
+ }
+ $s = -$s / $this->QR[$k][$k];
+ for ($i = $k; $i < $this->m; ++$i) {
+ $this->QR[$i][$j] += $s * $this->QR[$i][$k];
+ }
+ }
+ }
+ $this->Rdiag[$k] = -$nrm;
}
}
@@ -205,13 +201,13 @@ class QRDecomposition
*
* @return Matrix matrix that minimizes the two norm of Q*R*X-B
*/
- public function solve($B)
+ public function solve(Matrix $B)
{
if ($B->getRowDimension() == $this->m) {
if ($this->isFullRank()) {
// Copy right hand side
$nx = $B->getColumnDimension();
- $X = $B->getArrayCopy();
+ $X = $B->getArray();
// Compute Y = transpose(Q)*B
for ($k = 0; $k < $this->n; ++$k) {
for ($j = 0; $j < $nx; ++$j) {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php
index b997fb7cc1c..6c8999d0289 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php
@@ -65,7 +65,7 @@ class SingularValueDecomposition
public function __construct($Arg)
{
// Initialize.
- $A = $Arg->getArrayCopy();
+ $A = $Arg->getArray();
$this->m = $Arg->getRowDimension();
$this->n = $Arg->getColumnDimension();
$nu = min($this->m, $this->n);
@@ -476,6 +476,7 @@ class SingularValueDecomposition
*/
public function getS()
{
+ $S = [];
for ($i = 0; $i < $this->n; ++$i) {
for ($j = 0; $j < $this->n; ++$j) {
$S[$i][$j] = 0.0;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/PasswordHasher.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/PasswordHasher.php
index 9fefe88fb5e..0d58a8686ba 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/PasswordHasher.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/PasswordHasher.php
@@ -2,11 +2,13 @@
namespace PhpOffice\PhpSpreadsheet\Shared;
-use PhpOffice\PhpSpreadsheet\Exception;
+use PhpOffice\PhpSpreadsheet\Exception as SpException;
use PhpOffice\PhpSpreadsheet\Worksheet\Protection;
class PasswordHasher
{
+ const MAX_PASSWORD_LENGTH = 255;
+
/**
* Get algorithm name for PHP.
*/
@@ -34,36 +36,40 @@ class PasswordHasher
return $mapping[$algorithmName];
}
- throw new Exception('Unsupported password algorithm: ' . $algorithmName);
+ throw new SpException('Unsupported password algorithm: ' . $algorithmName);
}
/**
* Create a password hash from a given string.
*
- * This method is based on the algorithm provided by
+ * This method is based on the spec at:
+ * https://interoperability.blob.core.windows.net/files/MS-OFFCRYPTO/[MS-OFFCRYPTO].pdf
+ * 2.3.7.1 Binary Document Password Verifier Derivation Method 1
+ *
+ * It replaces a method based on the algorithm provided by
* Daniel Rentz of OpenOffice and the PEAR package
* Spreadsheet_Excel_Writer by Xavier Noguer .
*
- * @param string $pPassword Password to hash
+ * Scrutinizer will squawk at the use of bitwise operations here,
+ * but it should ultimately pass.
+ *
+ * @param string $password Password to hash
*/
- private static function defaultHashPassword(string $pPassword): string
+ private static function defaultHashPassword(string $password): string
{
- $password = 0x0000;
- $charPos = 1; // char position
-
- // split the plain text password in its component characters
- $chars = preg_split('//', $pPassword, -1, PREG_SPLIT_NO_EMPTY);
- foreach ($chars as $char) {
- $value = ord($char) << $charPos++; // shifted ASCII value
- $rotated_bits = $value >> 15; // rotated bits beyond bit 15
- $value &= 0x7fff; // first 15 bits
- $password ^= ($value | $rotated_bits);
+ $verifier = 0;
+ $pwlen = strlen($password);
+ $passwordArray = pack('c', $pwlen) . $password;
+ for ($i = $pwlen; $i >= 0; --$i) {
+ $intermediate1 = (($verifier & 0x4000) === 0) ? 0 : 1;
+ $intermediate2 = 2 * $verifier;
+ $intermediate2 = $intermediate2 & 0x7fff;
+ $intermediate3 = $intermediate1 | $intermediate2;
+ $verifier = $intermediate3 ^ ord($passwordArray[$i]);
}
+ $verifier ^= 0xCE4B;
- $password ^= strlen($pPassword);
- $password ^= 0xCE4B;
-
- return strtoupper(dechex($password));
+ return strtoupper(dechex($verifier));
}
/**
@@ -82,6 +88,9 @@ class PasswordHasher
*/
public static function hashPassword(string $password, string $algorithm = '', string $salt = '', int $spinCount = 10000): string
{
+ if (strlen($password) > self::MAX_PASSWORD_LENGTH) {
+ throw new SpException('Password exceeds ' . self::MAX_PASSWORD_LENGTH . ' characters');
+ }
$phpAlgorithm = self::getAlgorithm($algorithm);
if (!$phpAlgorithm) {
return self::defaultHashPassword($password);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/StringHelper.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/StringHelper.php
index 9ae324132d1..435d0e4cda5 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/StringHelper.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/StringHelper.php
@@ -294,15 +294,15 @@ class StringHelper
* So you could end up with something like _x0008_ in a string (either in a cell value ()
* element or in the shared string element.
*
- * @param string $value Value to unescape
+ * @param string $textValue Value to unescape
*
* @return string
*/
- public static function controlCharacterOOXML2PHP($value)
+ public static function controlCharacterOOXML2PHP($textValue)
{
self::buildCharacterSets();
- return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $value);
+ return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $textValue);
}
/**
@@ -316,64 +316,64 @@ class StringHelper
* So you could end up with something like _x0008_ in a string (either in a cell value ()
* element or in the shared string element.
*
- * @param string $value Value to escape
+ * @param string $textValue Value to escape
*
* @return string
*/
- public static function controlCharacterPHP2OOXML($value)
+ public static function controlCharacterPHP2OOXML($textValue)
{
self::buildCharacterSets();
- return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $value);
+ return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $textValue);
}
/**
* Try to sanitize UTF8, stripping invalid byte sequences. Not perfect. Does not surrogate characters.
*
- * @param string $value
+ * @param string $textValue
*
* @return string
*/
- public static function sanitizeUTF8($value)
+ public static function sanitizeUTF8($textValue)
{
if (self::getIsIconvEnabled()) {
- $value = @iconv('UTF-8', 'UTF-8', $value);
+ $textValue = @iconv('UTF-8', 'UTF-8', $textValue);
- return $value;
+ return $textValue;
}
- $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
+ $textValue = mb_convert_encoding($textValue, 'UTF-8', 'UTF-8');
- return $value;
+ return $textValue;
}
/**
* Check if a string contains UTF8 data.
*
- * @param string $value
+ * @param string $textValue
*
* @return bool
*/
- public static function isUTF8($value)
+ public static function isUTF8($textValue)
{
- return $value === '' || preg_match('/^./su', $value) === 1;
+ return $textValue === '' || preg_match('/^./su', $textValue) === 1;
}
/**
* Formats a numeric value as a string for output in various output writers forcing
* point as decimal separator in case locale is other than English.
*
- * @param mixed $value
+ * @param mixed $numericValue
*
* @return string
*/
- public static function formatNumber($value)
+ public static function formatNumber($numericValue)
{
- if (is_float($value)) {
- return str_replace(',', '.', $value);
+ if (is_float($numericValue)) {
+ return str_replace(',', '.', $numericValue);
}
- return (string) $value;
+ return (string) $numericValue;
}
/**
@@ -383,25 +383,25 @@ class StringHelper
* although this will give wrong results for non-ASCII strings
* see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
*
- * @param string $value UTF-8 encoded string
+ * @param string $textValue UTF-8 encoded string
* @param mixed[] $arrcRuns Details of rich text runs in $value
*
* @return string
*/
- public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = [])
+ public static function UTF8toBIFF8UnicodeShort($textValue, $arrcRuns = [])
{
// character count
- $ln = self::countCharacters($value, 'UTF-8');
+ $ln = self::countCharacters($textValue, 'UTF-8');
// option flags
if (empty($arrcRuns)) {
$data = pack('CC', $ln, 0x0001);
// characters
- $data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8');
+ $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
} else {
$data = pack('vC', $ln, 0x09);
$data .= pack('v', count($arrcRuns));
// characters
- $data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8');
+ $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
foreach ($arrcRuns as $cRun) {
$data .= pack('v', $cRun['strlen']);
$data .= pack('v', $cRun['fontidx']);
@@ -418,17 +418,17 @@ class StringHelper
* although this will give wrong results for non-ASCII strings
* see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
*
- * @param string $value UTF-8 encoded string
+ * @param string $textValue UTF-8 encoded string
*
* @return string
*/
- public static function UTF8toBIFF8UnicodeLong($value)
+ public static function UTF8toBIFF8UnicodeLong($textValue)
{
// character count
- $ln = self::countCharacters($value, 'UTF-8');
+ $ln = self::countCharacters($textValue, 'UTF-8');
// characters
- $chars = self::convertEncoding($value, 'UTF-16LE', 'UTF-8');
+ $chars = self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
return pack('vC', $ln, 0x0001) . $chars;
}
@@ -436,91 +436,91 @@ class StringHelper
/**
* Convert string from one encoding to another.
*
- * @param string $value
+ * @param string $textValue
* @param string $to Encoding to convert to, e.g. 'UTF-8'
* @param string $from Encoding to convert from, e.g. 'UTF-16LE'
*
* @return string
*/
- public static function convertEncoding($value, $to, $from)
+ public static function convertEncoding($textValue, $to, $from)
{
if (self::getIsIconvEnabled()) {
- $result = iconv($from, $to . self::$iconvOptions, $value);
+ $result = iconv($from, $to . self::$iconvOptions, $textValue);
if (false !== $result) {
return $result;
}
}
- return mb_convert_encoding($value, $to, $from);
+ return mb_convert_encoding($textValue, $to, $from);
}
/**
* Get character count.
*
- * @param string $value
- * @param string $enc Encoding
+ * @param string $textValue
+ * @param string $encoding Encoding
*
* @return int Character count
*/
- public static function countCharacters($value, $enc = 'UTF-8')
+ public static function countCharacters($textValue, $encoding = 'UTF-8')
{
- return mb_strlen($value, $enc);
+ return mb_strlen($textValue ?? '', $encoding);
}
/**
* Get a substring of a UTF-8 encoded string.
*
- * @param string $pValue UTF-8 encoded string
- * @param int $pStart Start offset
- * @param int $pLength Maximum number of characters in substring
+ * @param string $textValue UTF-8 encoded string
+ * @param int $offset Start offset
+ * @param int $length Maximum number of characters in substring
*
* @return string
*/
- public static function substring($pValue, $pStart, $pLength = 0)
+ public static function substring($textValue, $offset, $length = 0)
{
- return mb_substr($pValue, $pStart, $pLength, 'UTF-8');
+ return mb_substr($textValue, $offset, $length, 'UTF-8');
}
/**
* Convert a UTF-8 encoded string to upper case.
*
- * @param string $pValue UTF-8 encoded string
+ * @param string $textValue UTF-8 encoded string
*
* @return string
*/
- public static function strToUpper($pValue)
+ public static function strToUpper($textValue)
{
- return mb_convert_case($pValue, MB_CASE_UPPER, 'UTF-8');
+ return mb_convert_case($textValue ?? '', MB_CASE_UPPER, 'UTF-8');
}
/**
* Convert a UTF-8 encoded string to lower case.
*
- * @param string $pValue UTF-8 encoded string
+ * @param string $textValue UTF-8 encoded string
*
* @return string
*/
- public static function strToLower($pValue)
+ public static function strToLower($textValue)
{
- return mb_convert_case($pValue, MB_CASE_LOWER, 'UTF-8');
+ return mb_convert_case($textValue ?? '', MB_CASE_LOWER, 'UTF-8');
}
/**
* Convert a UTF-8 encoded string to title/proper case
* (uppercase every first character in each word, lower case all other characters).
*
- * @param string $pValue UTF-8 encoded string
+ * @param string $textValue UTF-8 encoded string
*
* @return string
*/
- public static function strToTitle($pValue)
+ public static function strToTitle($textValue)
{
- return mb_convert_case($pValue, MB_CASE_TITLE, 'UTF-8');
+ return mb_convert_case($textValue, MB_CASE_TITLE, 'UTF-8');
}
- public static function mbIsUpper($char)
+ public static function mbIsUpper($character)
{
- return mb_strtolower($char, 'UTF-8') != $char;
+ return mb_strtolower($character, 'UTF-8') != $character;
}
public static function mbStrSplit($string)
@@ -534,13 +534,13 @@ class StringHelper
* Reverse the case of a string, so that all uppercase characters become lowercase
* and all lowercase characters become uppercase.
*
- * @param string $pValue UTF-8 encoded string
+ * @param string $textValue UTF-8 encoded string
*
* @return string
*/
- public static function strCaseReverse($pValue)
+ public static function strCaseReverse($textValue)
{
- $characters = self::mbStrSplit($pValue);
+ $characters = self::mbStrSplit($textValue);
foreach ($characters as &$character) {
if (self::mbIsUpper($character)) {
$character = mb_strtolower($character, 'UTF-8');
@@ -556,7 +556,7 @@ class StringHelper
* 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
+ * @param string $operand string value to test
*
* @return bool
*/
@@ -601,11 +601,11 @@ class StringHelper
* Set the decimal separator. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
*
- * @param string $pValue Character for decimal separator
+ * @param string $separator Character for decimal separator
*/
- public static function setDecimalSeparator($pValue): void
+ public static function setDecimalSeparator($separator): void
{
- self::$decimalSeparator = $pValue;
+ self::$decimalSeparator = $separator;
}
/**
@@ -634,11 +634,11 @@ class StringHelper
* Set the thousands separator. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
*
- * @param string $pValue Character for thousands separator
+ * @param string $separator Character for thousands separator
*/
- public static function setThousandsSeparator($pValue): void
+ public static function setThousandsSeparator($separator): void
{
- self::$thousandsSeparator = $pValue;
+ self::$thousandsSeparator = $separator;
}
/**
@@ -672,51 +672,51 @@ class StringHelper
* Set the currency code. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
*
- * @param string $pValue Character for currency code
+ * @param string $currencyCode Character for currency code
*/
- public static function setCurrencyCode($pValue): void
+ public static function setCurrencyCode($currencyCode): void
{
- self::$currencyCode = $pValue;
+ self::$currencyCode = $currencyCode;
}
/**
* Convert SYLK encoded string to UTF-8.
*
- * @param string $pValue
+ * @param string $textValue
*
* @return string UTF-8 encoded string
*/
- public static function SYLKtoUTF8($pValue)
+ public static function SYLKtoUTF8($textValue)
{
self::buildCharacterSets();
// If there is no escape character in the string there is nothing to do
- if (strpos($pValue, '') === false) {
- return $pValue;
+ if (strpos($textValue, '') === false) {
+ return $textValue;
}
foreach (self::$SYLKCharacters as $k => $v) {
- $pValue = str_replace($k, $v, $pValue);
+ $textValue = str_replace($k, $v, $textValue);
}
- return $pValue;
+ return $textValue;
}
/**
* Retrieve any leading numeric part of a string, or return the full string if no leading numeric
* (handles basic integer or float, but not exponent or non decimal).
*
- * @param string $value
+ * @param string $textValue
*
* @return mixed string or only the leading numeric part of the string
*/
- public static function testStringAsNumeric($value)
+ public static function testStringAsNumeric($textValue)
{
- if (is_numeric($value)) {
- return $value;
+ if (is_numeric($textValue)) {
+ return $textValue;
}
- $v = (float) $value;
+ $v = (float) $textValue;
- return (is_numeric(substr($value, 0, strlen($v)))) ? $v : $value;
+ return (is_numeric(substr($textValue, 0, strlen($v)))) ? $v : $textValue;
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/TimeZone.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/TimeZone.php
index 43fd365369f..dabb88f2d08 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/TimeZone.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/TimeZone.php
@@ -17,26 +17,26 @@ class TimeZone
/**
* Validate a Timezone name.
*
- * @param string $timezone Time zone (e.g. 'Europe/London')
+ * @param string $timezoneName Time zone (e.g. 'Europe/London')
*
* @return bool Success or failure
*/
- private static function validateTimeZone($timezone)
+ private static function validateTimeZone($timezoneName)
{
- return in_array($timezone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC));
+ return in_array($timezoneName, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC));
}
/**
* Set the Default Timezone used for date/time conversions.
*
- * @param string $timezone Time zone (e.g. 'Europe/London')
+ * @param string $timezoneName Time zone (e.g. 'Europe/London')
*
* @return bool Success or failure
*/
- public static function setTimeZone($timezone)
+ public static function setTimeZone($timezoneName)
{
- if (self::validateTimezone($timezone)) {
- self::$timezone = $timezone;
+ if (self::validateTimezone($timezoneName)) {
+ self::$timezone = $timezoneName;
return true;
}
@@ -58,24 +58,20 @@ class TimeZone
* Return the Timezone offset used for date/time conversions to/from UST
* This requires both the timezone and the calculated date/time to allow for local DST.
*
- * @param string $timezone The timezone for finding the adjustment to UST
- * @param int $timestamp PHP date/time value
+ * @param ?string $timezoneName The timezone for finding the adjustment to UST
+ * @param float|int $timestamp PHP date/time value
*
* @return int Number of seconds for timezone adjustment
*/
- public static function getTimeZoneAdjustment($timezone, $timestamp)
+ public static function getTimeZoneAdjustment($timezoneName, $timestamp)
{
- if ($timezone !== null) {
- if (!self::validateTimezone($timezone)) {
- throw new PhpSpreadsheetException('Invalid timezone ' . $timezone);
- }
- } else {
- $timezone = self::$timezone;
+ $timezoneName = $timezoneName ?? self::$timezone;
+ $dtobj = Date::dateTimeFromTimestamp("$timestamp");
+ if (!self::validateTimezone($timezoneName)) {
+ throw new PhpSpreadsheetException("Invalid timezone $timezoneName");
}
+ $dtobj->setTimeZone(new DateTimeZone($timezoneName));
- $objTimezone = new DateTimeZone($timezone);
- $transitions = $objTimezone->getTransitions($timestamp, $timestamp);
-
- return (count($transitions) > 0) ? $transitions[0]['offset'] : 0;
+ return $dtobj->getOffset();
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/BestFit.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/BestFit.php
index c94997226bd..7df4895332b 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/BestFit.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/BestFit.php
@@ -2,7 +2,7 @@
namespace PhpOffice\PhpSpreadsheet\Shared\Trend;
-class BestFit
+abstract class BestFit
{
/**
* Indicator flag for a calculation error.
@@ -96,24 +96,18 @@ class BestFit
*
* @param float $xValue X-Value
*
- * @return bool Y-Value
+ * @return float Y-Value
*/
- public function getValueOfYForX($xValue)
- {
- return false;
- }
+ abstract public function getValueOfYForX($xValue);
/**
* Return the X-Value for a specified value of Y.
*
* @param float $yValue Y-Value
*
- * @return bool X-Value
+ * @return float X-Value
*/
- public function getValueOfXForY($yValue)
- {
- return false;
- }
+ abstract public function getValueOfXForY($yValue);
/**
* Return the original set of X-Values.
@@ -130,12 +124,9 @@ class BestFit
*
* @param int $dp Number of places of decimal precision to display
*
- * @return bool
+ * @return string
*/
- public function getEquation($dp = 0)
- {
- return false;
- }
+ abstract public function getEquation($dp = 0);
/**
* Return the Slope of the line.
@@ -348,13 +339,13 @@ class BestFit
$bestFitY = $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue);
$SSres += ($this->yValues[$xKey] - $bestFitY) * ($this->yValues[$xKey] - $bestFitY);
- if ($const) {
+ if ($const === true) {
$SStot += ($this->yValues[$xKey] - $meanY) * ($this->yValues[$xKey] - $meanY);
} else {
$SStot += $this->yValues[$xKey] * $this->yValues[$xKey];
}
$SScov += ($this->xValues[$xKey] - $meanX) * ($this->yValues[$xKey] - $meanY);
- if ($const) {
+ if ($const === true) {
$SSsex += ($this->xValues[$xKey] - $meanX) * ($this->xValues[$xKey] - $meanX);
} else {
$SSsex += $this->xValues[$xKey] * $this->xValues[$xKey];
@@ -362,7 +353,7 @@ class BestFit
}
$this->SSResiduals = $SSres;
- $this->DFResiduals = $this->valueCount - 1 - $const;
+ $this->DFResiduals = $this->valueCount - 1 - ($const === true ? 1 : 0);
if ($this->DFResiduals == 0.0) {
$this->stdevOfResiduals = 0.0;
@@ -395,27 +386,39 @@ class BestFit
}
}
+ private function sumSquares(array $values)
+ {
+ return array_sum(
+ array_map(
+ function ($value) {
+ return $value ** 2;
+ },
+ $values
+ )
+ );
+ }
+
/**
* @param float[] $yValues
* @param float[] $xValues
- * @param bool $const
*/
- protected function leastSquareFit(array $yValues, array $xValues, $const): void
+ protected function leastSquareFit(array $yValues, array $xValues, bool $const): void
{
// calculate sums
- $x_sum = array_sum($xValues);
- $y_sum = array_sum($yValues);
- $meanX = $x_sum / $this->valueCount;
- $meanY = $y_sum / $this->valueCount;
- $mBase = $mDivisor = $xx_sum = $xy_sum = $yy_sum = 0.0;
+ $sumValuesX = array_sum($xValues);
+ $sumValuesY = array_sum($yValues);
+ $meanValueX = $sumValuesX / $this->valueCount;
+ $meanValueY = $sumValuesY / $this->valueCount;
+ $sumSquaresX = $this->sumSquares($xValues);
+ $sumSquaresY = $this->sumSquares($yValues);
+ $mBase = $mDivisor = 0.0;
+ $xy_sum = 0.0;
for ($i = 0; $i < $this->valueCount; ++$i) {
$xy_sum += $xValues[$i] * $yValues[$i];
- $xx_sum += $xValues[$i] * $xValues[$i];
- $yy_sum += $yValues[$i] * $yValues[$i];
- if ($const) {
- $mBase += ($xValues[$i] - $meanX) * ($yValues[$i] - $meanY);
- $mDivisor += ($xValues[$i] - $meanX) * ($xValues[$i] - $meanX);
+ if ($const === true) {
+ $mBase += ($xValues[$i] - $meanValueX) * ($yValues[$i] - $meanValueY);
+ $mDivisor += ($xValues[$i] - $meanValueX) * ($xValues[$i] - $meanValueX);
} else {
$mBase += $xValues[$i] * $yValues[$i];
$mDivisor += $xValues[$i] * $xValues[$i];
@@ -426,13 +429,9 @@ class BestFit
$this->slope = $mBase / $mDivisor;
// calculate intersect
- if ($const) {
- $this->intersect = $meanY - ($this->slope * $meanX);
- } else {
- $this->intersect = 0;
- }
+ $this->intersect = ($const === true) ? $meanValueY - ($this->slope * $meanValueX) : 0.0;
- $this->calculateGoodnessOfFit($x_sum, $y_sum, $xx_sum, $yy_sum, $xy_sum, $meanX, $meanY, $const);
+ $this->calculateGoodnessOfFit($sumValuesX, $sumValuesY, $sumSquaresX, $sumSquaresY, $xy_sum, $meanValueX, $meanValueY, $const);
}
/**
@@ -440,23 +439,22 @@ class BestFit
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
- * @param bool $const
*/
- public function __construct($yValues, $xValues = [], $const = true)
+ public function __construct($yValues, $xValues = [])
{
// Calculate number of points
- $nY = count($yValues);
- $nX = count($xValues);
+ $yValueCount = count($yValues);
+ $xValueCount = count($xValues);
// Define X Values if necessary
- if ($nX == 0) {
- $xValues = range(1, $nY);
- } elseif ($nY != $nX) {
+ if ($xValueCount === 0) {
+ $xValues = range(1, $yValueCount);
+ } elseif ($yValueCount !== $xValueCount) {
// Ensure both arrays of points are the same size
$this->error = true;
}
- $this->valueCount = $nY;
+ $this->valueCount = $yValueCount;
$this->xValues = $xValues;
$this->yValues = $yValues;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php
index 82866dee80d..eb8cd746d36 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php
@@ -88,20 +88,17 @@ class ExponentialBestFit extends BestFit
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
- * @param bool $const
*/
- private function exponentialRegression($yValues, $xValues, $const): void
+ private function exponentialRegression(array $yValues, array $xValues, bool $const): void
{
- foreach ($yValues as &$value) {
- if ($value < 0.0) {
- $value = 0 - log(abs($value));
- } elseif ($value > 0.0) {
- $value = log($value);
- }
- }
- unset($value);
+ $adjustedYValues = array_map(
+ function ($value) {
+ return ($value < 0.0) ? 0 - log(abs($value)) : log($value);
+ },
+ $yValues
+ );
- $this->leastSquareFit($yValues, $xValues, $const);
+ $this->leastSquareFit($adjustedYValues, $xValues, $const);
}
/**
@@ -116,7 +113,7 @@ class ExponentialBestFit extends BestFit
parent::__construct($yValues, $xValues);
if (!$this->error) {
- $this->exponentialRegression($yValues, $xValues, $const);
+ $this->exponentialRegression($yValues, $xValues, (bool) $const);
}
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php
index 26a562c5516..65d6b4ff44d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php
@@ -56,9 +56,8 @@ class LinearBestFit extends BestFit
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
- * @param bool $const
*/
- private function linearRegression($yValues, $xValues, $const): void
+ private function linearRegression(array $yValues, array $xValues, bool $const): void
{
$this->leastSquareFit($yValues, $xValues, $const);
}
@@ -75,7 +74,7 @@ class LinearBestFit extends BestFit
parent::__construct($yValues, $xValues);
if (!$this->error) {
- $this->linearRegression($yValues, $xValues, $const);
+ $this->linearRegression($yValues, $xValues, (bool) $const);
}
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php
index c469067d47c..2366dc636aa 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php
@@ -48,7 +48,7 @@ class LogarithmicBestFit extends BestFit
$slope = $this->getSlope($dp);
$intersect = $this->getIntersect($dp);
- return 'Y = ' . $intersect . ' + ' . $slope . ' * log(X)';
+ return 'Y = ' . $slope . ' * log(' . $intersect . ' * X)';
}
/**
@@ -56,20 +56,17 @@ class LogarithmicBestFit extends BestFit
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
- * @param bool $const
*/
- private function logarithmicRegression($yValues, $xValues, $const): void
+ private function logarithmicRegression(array $yValues, array $xValues, bool $const): void
{
- foreach ($xValues as &$value) {
- if ($value < 0.0) {
- $value = 0 - log(abs($value));
- } elseif ($value > 0.0) {
- $value = log($value);
- }
- }
- unset($value);
+ $adjustedYValues = array_map(
+ function ($value) {
+ return ($value < 0.0) ? 0 - log(abs($value)) : log($value);
+ },
+ $yValues
+ );
- $this->leastSquareFit($yValues, $xValues, $const);
+ $this->leastSquareFit($adjustedYValues, $xValues, $const);
}
/**
@@ -84,7 +81,7 @@ class LogarithmicBestFit extends BestFit
parent::__construct($yValues, $xValues);
if (!$this->error) {
- $this->logarithmicRegression($yValues, $xValues, $const);
+ $this->logarithmicRegression($yValues, $xValues, (bool) $const);
}
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php
index d959eddb751..2c8eea5b7cd 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php
@@ -42,6 +42,7 @@ class PolynomialBestFit extends BestFit
{
$retVal = $this->getIntersect();
$slope = $this->getSlope();
+ // @phpstan-ignore-next-line
foreach ($slope as $key => $value) {
if ($value != 0.0) {
$retVal += $value * $xValue ** ($key + 1);
@@ -76,6 +77,7 @@ class PolynomialBestFit extends BestFit
$intersect = $this->getIntersect($dp);
$equation = 'Y = ' . $intersect;
+ // @phpstan-ignore-next-line
foreach ($slope as $key => $value) {
if ($value != 0.0) {
$equation .= ' + ' . $value . ' * X';
@@ -93,7 +95,7 @@ class PolynomialBestFit extends BestFit
*
* @param int $dp Number of places of decimal precision to display
*
- * @return string
+ * @return float
*/
public function getSlope($dp = 0)
{
@@ -103,6 +105,7 @@ class PolynomialBestFit extends BestFit
$coefficients[] = round($coefficient, $dp);
}
+ // @phpstan-ignore-next-line
return $coefficients;
}
@@ -178,9 +181,8 @@ class PolynomialBestFit extends BestFit
* @param int $order Order of Polynomial for this regression
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
- * @param bool $const
*/
- public function __construct($order, $yValues, $xValues = [], $const = true)
+ public function __construct($order, $yValues, $xValues = [])
{
parent::__construct($yValues, $xValues);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php
index c53eab6381d..cafd01158e9 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php
@@ -72,28 +72,23 @@ class PowerBestFit extends BestFit
*
* @param float[] $yValues The set of Y-values for this regression
* @param float[] $xValues The set of X-values for this regression
- * @param bool $const
*/
- private function powerRegression($yValues, $xValues, $const): void
+ private function powerRegression(array $yValues, array $xValues, bool $const): void
{
- foreach ($xValues as &$value) {
- if ($value < 0.0) {
- $value = 0 - log(abs($value));
- } elseif ($value > 0.0) {
- $value = log($value);
- }
- }
- unset($value);
- foreach ($yValues as &$value) {
- if ($value < 0.0) {
- $value = 0 - log(abs($value));
- } elseif ($value > 0.0) {
- $value = log($value);
- }
- }
- unset($value);
+ $adjustedYValues = array_map(
+ function ($value) {
+ return ($value < 0.0) ? 0 - log(abs($value)) : log($value);
+ },
+ $yValues
+ );
+ $adjustedXValues = array_map(
+ function ($value) {
+ return ($value < 0.0) ? 0 - log(abs($value)) : log($value);
+ },
+ $xValues
+ );
- $this->leastSquareFit($yValues, $xValues, $const);
+ $this->leastSquareFit($adjustedYValues, $adjustedXValues, $const);
}
/**
@@ -108,7 +103,7 @@ class PowerBestFit extends BestFit
parent::__construct($yValues, $xValues);
if (!$this->error) {
- $this->powerRegression($yValues, $xValues, $const);
+ $this->powerRegression($yValues, $xValues, (bool) $const);
}
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/Trend.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/Trend.php
index 1b7b3901078..61d1183aba3 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/Trend.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/Trend.php
@@ -44,7 +44,7 @@ class Trend
/**
* Cached results for each method when trying to identify which provides the best fit.
*
- * @var bestFit[]
+ * @var BestFit[]
*/
private static $trendCache = [];
@@ -55,10 +55,9 @@ class Trend
$nX = count($xValues);
// Define X Values if necessary
- if ($nX == 0) {
+ if ($nX === 0) {
$xValues = range(1, $nY);
- $nX = $nY;
- } elseif ($nY != $nX) {
+ } elseif ($nY !== $nX) {
// Ensure both arrays of points are the same size
trigger_error('Trend(): Number of elements in coordinate arrays do not match.', E_USER_ERROR);
}
@@ -84,7 +83,7 @@ class Trend
case self::TREND_POLYNOMIAL_6:
if (!isset(self::$trendCache[$key])) {
$order = substr($trendType, -1);
- self::$trendCache[$key] = new PolynomialBestFit($order, $yValues, $xValues, $const);
+ self::$trendCache[$key] = new PolynomialBestFit($order, $yValues, $xValues);
}
return self::$trendCache[$key];
@@ -92,6 +91,8 @@ class Trend
case self::TREND_BEST_FIT_NO_POLY:
// If the request is to determine the best fit regression, then we test each Trend line in turn
// Start by generating an instance of each available Trend method
+ $bestFit = [];
+ $bestFitValue = [];
foreach (self::$trendTypes as $trendMethod) {
$className = '\PhpOffice\PhpSpreadsheet\Shared\Trend\\' . $trendType . 'BestFit';
$bestFit[$trendMethod] = new $className($yValues, $xValues, $const);
@@ -100,7 +101,7 @@ class Trend
if ($trendType != self::TREND_BEST_FIT_NO_POLY) {
foreach (self::$trendTypePolynomialOrders as $trendMethod) {
$order = substr($trendMethod, -1);
- $bestFit[$trendMethod] = new PolynomialBestFit($order, $yValues, $xValues, $const);
+ $bestFit[$trendMethod] = new PolynomialBestFit($order, $yValues, $xValues);
if ($bestFit[$trendMethod]->getError()) {
unset($bestFit[$trendMethod]);
} else {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/XMLWriter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/XMLWriter.php
index 4f7a6a06afc..84ad8a83806 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/XMLWriter.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/XMLWriter.php
@@ -20,20 +20,20 @@ class XMLWriter extends \XMLWriter
/**
* Create a new XMLWriter instance.
*
- * @param int $pTemporaryStorage Temporary storage location
- * @param string $pTemporaryStorageFolder Temporary storage folder
+ * @param int $temporaryStorage Temporary storage location
+ * @param string $temporaryStorageFolder Temporary storage folder
*/
- public function __construct($pTemporaryStorage = self::STORAGE_MEMORY, $pTemporaryStorageFolder = null)
+ public function __construct($temporaryStorage = self::STORAGE_MEMORY, $temporaryStorageFolder = null)
{
// Open temporary storage
- if ($pTemporaryStorage == self::STORAGE_MEMORY) {
+ if ($temporaryStorage == self::STORAGE_MEMORY) {
$this->openMemory();
} else {
// Create temporary filename
- if ($pTemporaryStorageFolder === null) {
- $pTemporaryStorageFolder = File::sysGetTempDir();
+ if ($temporaryStorageFolder === null) {
+ $temporaryStorageFolder = File::sysGetTempDir();
}
- $this->tempFileName = @tempnam($pTemporaryStorageFolder, 'xml');
+ $this->tempFileName = @tempnam($temporaryStorageFolder, 'xml');
// Open storage
if ($this->openUri($this->tempFileName) === false) {
@@ -77,16 +77,16 @@ class XMLWriter extends \XMLWriter
/**
* Wrapper method for writeRaw.
*
- * @param string|string[] $text
+ * @param null|string|string[] $rawTextData
*
* @return bool
*/
- public function writeRawData($text)
+ public function writeRawData($rawTextData)
{
- if (is_array($text)) {
- $text = implode("\n", $text);
+ if (is_array($rawTextData)) {
+ $rawTextData = implode("\n", $rawTextData);
}
- return $this->writeRaw(htmlspecialchars($text));
+ return $this->writeRaw(htmlspecialchars($rawTextData ?? ''));
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php
index c8e8f72cfa6..350ba652fcc 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php
@@ -55,7 +55,7 @@ class Spreadsheet
/**
* Calculation Engine.
*
- * @var Calculation
+ * @var null|Calculation
*/
private $calculationEngine;
@@ -69,7 +69,7 @@ class Spreadsheet
/**
* Named ranges.
*
- * @var NamedRange[]
+ * @var DefinedName[]
*/
private $definedNames = [];
@@ -104,21 +104,21 @@ class Spreadsheet
/**
* macrosCode : all macros code as binary data (the vbaProject.bin file, this include form, code, etc.), null if no macro.
*
- * @var string
+ * @var null|string
*/
private $macrosCode;
/**
* macrosCertificate : if macros are signed, contains binary data vbaProjectSignature.bin file, null if not signed.
*
- * @var string
+ * @var null|string
*/
private $macrosCertificate;
/**
* ribbonXMLData : null if workbook is'nt Excel 2007 or not contain a customized UI.
*
- * @var null|string
+ * @var null|array{target: string, data: string}
*/
private $ribbonXMLData;
@@ -298,11 +298,9 @@ class Spreadsheet
/**
* retrieve ribbon XML Data.
*
- * return string|null|array
- *
* @param string $what
*
- * @return string
+ * @return null|array|string
*/
public function getRibbonXMLData($what = 'all') //we need some constants here...
{
@@ -373,7 +371,9 @@ class Spreadsheet
*/
private function getExtensionOnly($path)
{
- return pathinfo($path, PATHINFO_EXTENSION);
+ $extension = pathinfo($path, PATHINFO_EXTENSION);
+
+ return is_array($extension) ? '' : $extension;
}
/**
@@ -439,27 +439,27 @@ class Spreadsheet
/**
* Check if a sheet with a specified code name already exists.
*
- * @param string $pSheetCodeName Name of the worksheet to check
+ * @param string $codeName Name of the worksheet to check
*
* @return bool
*/
- public function sheetCodeNameExists($pSheetCodeName)
+ public function sheetCodeNameExists($codeName)
{
- return $this->getSheetByCodeName($pSheetCodeName) !== null;
+ return $this->getSheetByCodeName($codeName) !== null;
}
/**
* Get sheet by code name. Warning : sheet don't have always a code name !
*
- * @param string $pName Sheet name
+ * @param string $codeName Sheet name
*
- * @return Worksheet
+ * @return null|Worksheet
*/
- public function getSheetByCodeName($pName)
+ public function getSheetByCodeName($codeName)
{
$worksheetCount = count($this->workSheetCollection);
for ($i = 0; $i < $worksheetCount; ++$i) {
- if ($this->workSheetCollection[$i]->getCodeName() == $pName) {
+ if ($this->workSheetCollection[$i]->getCodeName() == $codeName) {
return $this->workSheetCollection[$i];
}
}
@@ -503,8 +503,10 @@ class Spreadsheet
*/
public function __destruct()
{
- $this->calculationEngine = null;
$this->disconnectWorksheets();
+ $this->calculationEngine = null;
+ $this->cellXfCollection = [];
+ $this->cellStyleXfCollection = [];
}
/**
@@ -513,19 +515,17 @@ class Spreadsheet
*/
public function disconnectWorksheets(): void
{
- $worksheet = null;
- foreach ($this->workSheetCollection as $k => &$worksheet) {
+ foreach ($this->workSheetCollection as $worksheet) {
$worksheet->disconnectCells();
- $this->workSheetCollection[$k] = null;
+ unset($worksheet);
}
- unset($worksheet);
$this->workSheetCollection = [];
}
/**
* Return the calculation engine for this worksheet.
*
- * @return Calculation
+ * @return null|Calculation
*/
public function getCalculationEngine()
{
@@ -545,9 +545,9 @@ class Spreadsheet
/**
* Set properties.
*/
- public function setProperties(Document\Properties $pValue): void
+ public function setProperties(Document\Properties $documentProperties): void
{
- $this->properties = $pValue;
+ $this->properties = $documentProperties;
}
/**
@@ -563,9 +563,9 @@ class Spreadsheet
/**
* Set security.
*/
- public function setSecurity(Document\Security $pValue): void
+ public function setSecurity(Document\Security $documentSecurity): void
{
- $this->security = $pValue;
+ $this->security = $documentSecurity;
}
/**
@@ -596,75 +596,76 @@ class Spreadsheet
/**
* Check if a sheet with a specified name already exists.
*
- * @param string $pSheetName Name of the worksheet to check
+ * @param string $worksheetName Name of the worksheet to check
*
* @return bool
*/
- public function sheetNameExists($pSheetName)
+ public function sheetNameExists($worksheetName)
{
- return $this->getSheetByName($pSheetName) !== null;
+ return $this->getSheetByName($worksheetName) !== null;
}
/**
* Add sheet.
*
- * @param null|int $iSheetIndex Index where sheet should go (0,1,..., or null for last)
+ * @param Worksheet $worksheet The worskeet to add
+ * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
*
* @return Worksheet
*/
- public function addSheet(Worksheet $pSheet, $iSheetIndex = null)
+ public function addSheet(Worksheet $worksheet, $sheetIndex = null)
{
- if ($this->sheetNameExists($pSheet->getTitle())) {
+ if ($this->sheetNameExists($worksheet->getTitle())) {
throw new Exception(
- "Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename this worksheet first."
+ "Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first."
);
}
- if ($iSheetIndex === null) {
+ if ($sheetIndex === null) {
if ($this->activeSheetIndex < 0) {
$this->activeSheetIndex = 0;
}
- $this->workSheetCollection[] = $pSheet;
+ $this->workSheetCollection[] = $worksheet;
} else {
// Insert the sheet at the requested index
array_splice(
$this->workSheetCollection,
- $iSheetIndex,
+ $sheetIndex,
0,
- [$pSheet]
+ [$worksheet]
);
// Adjust active sheet index if necessary
- if ($this->activeSheetIndex >= $iSheetIndex) {
+ if ($this->activeSheetIndex >= $sheetIndex) {
++$this->activeSheetIndex;
}
}
- if ($pSheet->getParent() === null) {
- $pSheet->rebindParent($this);
+ if ($worksheet->getParent() === null) {
+ $worksheet->rebindParent($this);
}
- return $pSheet;
+ return $worksheet;
}
/**
* Remove sheet by index.
*
- * @param int $pIndex Active sheet index
+ * @param int $sheetIndex Index position of the worksheet to remove
*/
- public function removeSheetByIndex($pIndex): void
+ public function removeSheetByIndex($sheetIndex): void
{
$numSheets = count($this->workSheetCollection);
- if ($pIndex > $numSheets - 1) {
+ if ($sheetIndex > $numSheets - 1) {
throw new Exception(
- "You tried to remove a sheet by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}."
+ "You tried to remove a sheet by the out of bounds index: {$sheetIndex}. The actual number of sheets is {$numSheets}."
);
}
- array_splice($this->workSheetCollection, $pIndex, 1);
+ array_splice($this->workSheetCollection, $sheetIndex, 1);
// Adjust active sheet index if necessary
if (
- ($this->activeSheetIndex >= $pIndex) &&
+ ($this->activeSheetIndex >= $sheetIndex) &&
($this->activeSheetIndex > 0 || $numSheets <= 1)
) {
--$this->activeSheetIndex;
@@ -674,21 +675,21 @@ class Spreadsheet
/**
* Get sheet by index.
*
- * @param int $pIndex Sheet index
+ * @param int $sheetIndex Sheet index
*
* @return Worksheet
*/
- public function getSheet($pIndex)
+ public function getSheet($sheetIndex)
{
- if (!isset($this->workSheetCollection[$pIndex])) {
+ if (!isset($this->workSheetCollection[$sheetIndex])) {
$numSheets = $this->getSheetCount();
throw new Exception(
- "Your requested sheet index: {$pIndex} is out of bounds. The actual number of sheets is {$numSheets}."
+ "Your requested sheet index: {$sheetIndex} is out of bounds. The actual number of sheets is {$numSheets}."
);
}
- return $this->workSheetCollection[$pIndex];
+ return $this->workSheetCollection[$sheetIndex];
}
/**
@@ -704,15 +705,15 @@ class Spreadsheet
/**
* Get sheet by name.
*
- * @param string $pName Sheet name
+ * @param string $worksheetName Sheet name
*
* @return null|Worksheet
*/
- public function getSheetByName($pName)
+ public function getSheetByName($worksheetName)
{
$worksheetCount = count($this->workSheetCollection);
for ($i = 0; $i < $worksheetCount; ++$i) {
- if ($this->workSheetCollection[$i]->getTitle() === trim($pName, "'")) {
+ if ($this->workSheetCollection[$i]->getTitle() === trim($worksheetName, "'")) {
return $this->workSheetCollection[$i];
}
}
@@ -725,10 +726,10 @@ class Spreadsheet
*
* @return int index
*/
- public function getIndex(Worksheet $pSheet)
+ public function getIndex(Worksheet $worksheet)
{
foreach ($this->workSheetCollection as $key => $value) {
- if ($value->getHashCode() === $pSheet->getHashCode()) {
+ if ($value->getHashCode() === $worksheet->getHashCode()) {
return $key;
}
}
@@ -739,27 +740,27 @@ class Spreadsheet
/**
* Set index for sheet by sheet name.
*
- * @param string $sheetName Sheet name to modify index for
- * @param int $newIndex New index for the sheet
+ * @param string $worksheetName Sheet name to modify index for
+ * @param int $newIndexPosition New index for the sheet
*
* @return int New sheet index
*/
- public function setIndexByName($sheetName, $newIndex)
+ public function setIndexByName($worksheetName, $newIndexPosition)
{
- $oldIndex = $this->getIndex($this->getSheetByName($sheetName));
- $pSheet = array_splice(
+ $oldIndex = $this->getIndex($this->getSheetByName($worksheetName));
+ $worksheet = array_splice(
$this->workSheetCollection,
$oldIndex,
1
);
array_splice(
$this->workSheetCollection,
- $newIndex,
+ $newIndexPosition,
0,
- $pSheet
+ $worksheet
);
- return $newIndex;
+ return $newIndexPosition;
}
/**
@@ -785,20 +786,20 @@ class Spreadsheet
/**
* Set active sheet index.
*
- * @param int $pIndex Active sheet index
+ * @param int $worksheetIndex Active sheet index
*
* @return Worksheet
*/
- public function setActiveSheetIndex($pIndex)
+ public function setActiveSheetIndex($worksheetIndex)
{
$numSheets = count($this->workSheetCollection);
- if ($pIndex > $numSheets - 1) {
+ if ($worksheetIndex > $numSheets - 1) {
throw new Exception(
- "You tried to set a sheet active by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}."
+ "You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}."
);
}
- $this->activeSheetIndex = $pIndex;
+ $this->activeSheetIndex = $worksheetIndex;
return $this->getActiveSheet();
}
@@ -806,19 +807,19 @@ class Spreadsheet
/**
* Set active sheet index by name.
*
- * @param string $pValue Sheet title
+ * @param string $worksheetName Sheet title
*
* @return Worksheet
*/
- public function setActiveSheetIndexByName($pValue)
+ public function setActiveSheetIndexByName($worksheetName)
{
- if (($worksheet = $this->getSheetByName($pValue)) instanceof Worksheet) {
+ if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) {
$this->setActiveSheetIndex($this->getIndex($worksheet));
return $worksheet;
}
- throw new Exception('Workbook does not contain sheet:' . $pValue);
+ throw new Exception('Workbook does not contain sheet:' . $worksheetName);
}
/**
@@ -840,41 +841,41 @@ class Spreadsheet
/**
* Add external sheet.
*
- * @param Worksheet $pSheet External sheet to add
- * @param null|int $iSheetIndex Index where sheet should go (0,1,..., or null for last)
+ * @param Worksheet $worksheet External sheet to add
+ * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
*
* @return Worksheet
*/
- public function addExternalSheet(Worksheet $pSheet, $iSheetIndex = null)
+ public function addExternalSheet(Worksheet $worksheet, $sheetIndex = null)
{
- if ($this->sheetNameExists($pSheet->getTitle())) {
- throw new Exception("Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first.");
+ if ($this->sheetNameExists($worksheet->getTitle())) {
+ throw new Exception("Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename the external sheet first.");
}
// count how many cellXfs there are in this workbook currently, we will need this below
$countCellXfs = count($this->cellXfCollection);
// copy all the shared cellXfs from the external workbook and append them to the current
- foreach ($pSheet->getParent()->getCellXfCollection() as $cellXf) {
+ foreach ($worksheet->getParent()->getCellXfCollection() as $cellXf) {
$this->addCellXf(clone $cellXf);
}
// move sheet to this workbook
- $pSheet->rebindParent($this);
+ $worksheet->rebindParent($this);
// update the cellXfs
- foreach ($pSheet->getCoordinates(false) as $coordinate) {
- $cell = $pSheet->getCell($coordinate);
+ foreach ($worksheet->getCoordinates(false) as $coordinate) {
+ $cell = $worksheet->getCell($coordinate);
$cell->setXfIndex($cell->getXfIndex() + $countCellXfs);
}
- return $this->addSheet($pSheet, $iSheetIndex);
+ return $this->addSheet($worksheet, $sheetIndex);
}
/**
* Get an array of all Named Ranges.
*
- * @return NamedRange[]
+ * @return DefinedName[]
*/
public function getNamedRanges(): array
{
@@ -889,7 +890,7 @@ class Spreadsheet
/**
* Get an array of all Named Formulae.
*
- * @return NamedFormula[]
+ * @return DefinedName[]
*/
public function getNamedFormulae(): array
{
@@ -948,9 +949,9 @@ class Spreadsheet
/**
* Get named range.
*
- * @param null|Worksheet $pSheet Scope. Use null for global scope
+ * @param null|Worksheet $worksheet Scope. Use null for global scope
*/
- public function getNamedRange(string $namedRange, ?Worksheet $pSheet = null): ?NamedRange
+ public function getNamedRange(string $namedRange, ?Worksheet $worksheet = null): ?NamedRange
{
$returnValue = null;
@@ -959,7 +960,7 @@ class Spreadsheet
// first look for global named range
$returnValue = $this->getGlobalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE);
// then look for local named range (has priority over global named range if both names exist)
- $returnValue = $this->getLocalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE, $pSheet) ?: $returnValue;
+ $returnValue = $this->getLocalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE, $worksheet) ?: $returnValue;
}
return $returnValue instanceof NamedRange ? $returnValue : null;
@@ -968,9 +969,9 @@ class Spreadsheet
/**
* Get named formula.
*
- * @param null|Worksheet $pSheet Scope. Use null for global scope
+ * @param null|Worksheet $worksheet Scope. Use null for global scope
*/
- public function getNamedFormula(string $namedFormula, ?Worksheet $pSheet = null): ?NamedFormula
+ public function getNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): ?NamedFormula
{
$returnValue = null;
@@ -979,7 +980,7 @@ class Spreadsheet
// first look for global named formula
$returnValue = $this->getGlobalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA);
// then look for local named formula (has priority over global named formula if both names exist)
- $returnValue = $this->getLocalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA, $pSheet) ?: $returnValue;
+ $returnValue = $this->getLocalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA, $worksheet) ?: $returnValue;
}
return $returnValue instanceof NamedFormula ? $returnValue : null;
@@ -994,13 +995,13 @@ class Spreadsheet
return null;
}
- private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $pSheet = null): ?DefinedName
+ private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $worksheet = null): ?DefinedName
{
if (
- ($pSheet !== null) && isset($this->definedNames[$pSheet->getTitle() . '!' . $name])
- && $this->definedNames[$pSheet->getTitle() . '!' . $name]->isFormula() === $type
+ ($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name])
+ && $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type
) {
- return $this->definedNames[$pSheet->getTitle() . '!' . $name];
+ return $this->definedNames[$worksheet->getTitle() . '!' . $name];
}
return null;
@@ -1009,9 +1010,9 @@ class Spreadsheet
/**
* Get named range.
*
- * @param null|Worksheet $pSheet Scope. Use null for global scope
+ * @param null|Worksheet $worksheet Scope. Use null for global scope
*/
- public function getDefinedName(string $definedName, ?Worksheet $pSheet = null): ?DefinedName
+ public function getDefinedName(string $definedName, ?Worksheet $worksheet = null): ?DefinedName
{
$returnValue = null;
@@ -1023,8 +1024,8 @@ class Spreadsheet
}
// then look for local defined name (has priority over global defined name if both names exist)
- if (($pSheet !== null) && isset($this->definedNames[$pSheet->getTitle() . '!' . $definedName])) {
- $returnValue = $this->definedNames[$pSheet->getTitle() . '!' . $definedName];
+ if (($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
+ $returnValue = $this->definedNames[$worksheet->getTitle() . '!' . $definedName];
}
}
@@ -1034,53 +1035,53 @@ class Spreadsheet
/**
* Remove named range.
*
- * @param null|Worksheet $pSheet scope: use null for global scope
+ * @param null|Worksheet $worksheet scope: use null for global scope
*
* @return $this
*/
- public function removeNamedRange(string $namedRange, ?Worksheet $pSheet = null): self
+ public function removeNamedRange(string $namedRange, ?Worksheet $worksheet = null): self
{
- if ($this->getNamedRange($namedRange, $pSheet) === null) {
+ if ($this->getNamedRange($namedRange, $worksheet) === null) {
return $this;
}
- return $this->removeDefinedName($namedRange, $pSheet);
+ return $this->removeDefinedName($namedRange, $worksheet);
}
/**
* Remove named formula.
*
- * @param null|Worksheet $pSheet scope: use null for global scope
+ * @param null|Worksheet $worksheet scope: use null for global scope
*
* @return $this
*/
- public function removeNamedFormula(string $namedFormula, ?Worksheet $pSheet = null): self
+ public function removeNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): self
{
- if ($this->getNamedFormula($namedFormula, $pSheet) === null) {
+ if ($this->getNamedFormula($namedFormula, $worksheet) === null) {
return $this;
}
- return $this->removeDefinedName($namedFormula, $pSheet);
+ return $this->removeDefinedName($namedFormula, $worksheet);
}
/**
* Remove defined name.
*
- * @param null|Worksheet $pSheet scope: use null for global scope
+ * @param null|Worksheet $worksheet scope: use null for global scope
*
* @return $this
*/
- public function removeDefinedName(string $definedName, ?Worksheet $pSheet = null): self
+ public function removeDefinedName(string $definedName, ?Worksheet $worksheet = null): self
{
$definedName = StringHelper::strToUpper($definedName);
- if ($pSheet === null) {
+ if ($worksheet === null) {
if (isset($this->definedNames[$definedName])) {
unset($this->definedNames[$definedName]);
}
} else {
- if (isset($this->definedNames[$pSheet->getTitle() . '!' . $definedName])) {
- unset($this->definedNames[$pSheet->getTitle() . '!' . $definedName]);
+ if (isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
+ unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]);
} elseif (isset($this->definedNames[$definedName])) {
unset($this->definedNames[$definedName]);
}
@@ -1122,6 +1123,7 @@ class Spreadsheet
*/
public function __clone()
{
+ // @phpstan-ignore-next-line
foreach ($this as $key => $val) {
if (is_object($val) || (is_array($val))) {
$this->{$key} = unserialize(serialize($val));
@@ -1142,26 +1144,26 @@ class Spreadsheet
/**
* Get cellXf by index.
*
- * @param int $pIndex
+ * @param int $cellStyleIndex
*
* @return Style
*/
- public function getCellXfByIndex($pIndex)
+ public function getCellXfByIndex($cellStyleIndex)
{
- return $this->cellXfCollection[$pIndex];
+ return $this->cellXfCollection[$cellStyleIndex];
}
/**
* Get cellXf by hash code.
*
- * @param string $pValue
+ * @param string $hashcode
*
* @return false|Style
*/
- public function getCellXfByHashCode($pValue)
+ public function getCellXfByHashCode($hashcode)
{
foreach ($this->cellXfCollection as $cellXf) {
- if ($cellXf->getHashCode() === $pValue) {
+ if ($cellXf->getHashCode() === $hashcode) {
return $cellXf;
}
}
@@ -1172,13 +1174,11 @@ class Spreadsheet
/**
* Check if style exists in style collection.
*
- * @param Style $pCellStyle
- *
* @return bool
*/
- public function cellXfExists($pCellStyle)
+ public function cellXfExists(Style $cellStyleIndex)
{
- return in_array($pCellStyle, $this->cellXfCollection, true);
+ return in_array($cellStyleIndex, $this->cellXfCollection, true);
}
/**
@@ -1207,26 +1207,26 @@ class Spreadsheet
/**
* Remove cellXf by index. It is ensured that all cells get their xf index updated.
*
- * @param int $pIndex Index to cellXf
+ * @param int $cellStyleIndex Index to cellXf
*/
- public function removeCellXfByIndex($pIndex): void
+ public function removeCellXfByIndex($cellStyleIndex): void
{
- if ($pIndex > count($this->cellXfCollection) - 1) {
+ if ($cellStyleIndex > count($this->cellXfCollection) - 1) {
throw new Exception('CellXf index is out of bounds.');
}
// first remove the cellXf
- array_splice($this->cellXfCollection, $pIndex, 1);
+ array_splice($this->cellXfCollection, $cellStyleIndex, 1);
// then update cellXf indexes for cells
foreach ($this->workSheetCollection as $worksheet) {
foreach ($worksheet->getCoordinates(false) as $coordinate) {
$cell = $worksheet->getCell($coordinate);
$xfIndex = $cell->getXfIndex();
- if ($xfIndex > $pIndex) {
+ if ($xfIndex > $cellStyleIndex) {
// decrease xf index by 1
$cell->setXfIndex($xfIndex - 1);
- } elseif ($xfIndex == $pIndex) {
+ } elseif ($xfIndex == $cellStyleIndex) {
// set to default xf index 0
$cell->setXfIndex(0);
}
@@ -1257,26 +1257,26 @@ class Spreadsheet
/**
* Get cellStyleXf by index.
*
- * @param int $pIndex Index to cellXf
+ * @param int $cellStyleIndex Index to cellXf
*
* @return Style
*/
- public function getCellStyleXfByIndex($pIndex)
+ public function getCellStyleXfByIndex($cellStyleIndex)
{
- return $this->cellStyleXfCollection[$pIndex];
+ return $this->cellStyleXfCollection[$cellStyleIndex];
}
/**
* Get cellStyleXf by hash code.
*
- * @param string $pValue
+ * @param string $hashcode
*
* @return false|Style
*/
- public function getCellStyleXfByHashCode($pValue)
+ public function getCellStyleXfByHashCode($hashcode)
{
foreach ($this->cellStyleXfCollection as $cellStyleXf) {
- if ($cellStyleXf->getHashCode() === $pValue) {
+ if ($cellStyleXf->getHashCode() === $hashcode) {
return $cellStyleXf;
}
}
@@ -1287,23 +1287,23 @@ class Spreadsheet
/**
* Add a cellStyleXf to the workbook.
*/
- public function addCellStyleXf(Style $pStyle): void
+ public function addCellStyleXf(Style $style): void
{
- $this->cellStyleXfCollection[] = $pStyle;
- $pStyle->setIndex(count($this->cellStyleXfCollection) - 1);
+ $this->cellStyleXfCollection[] = $style;
+ $style->setIndex(count($this->cellStyleXfCollection) - 1);
}
/**
* Remove cellStyleXf by index.
*
- * @param int $pIndex Index to cellXf
+ * @param int $cellStyleIndex Index to cellXf
*/
- public function removeCellStyleXfByIndex($pIndex): void
+ public function removeCellStyleXfByIndex($cellStyleIndex): void
{
- if ($pIndex > count($this->cellStyleXfCollection) - 1) {
+ if ($cellStyleIndex > count($this->cellStyleXfCollection) - 1) {
throw new Exception('CellStyleXf index is out of bounds.');
}
- array_splice($this->cellStyleXfCollection, $pIndex, 1);
+ array_splice($this->cellStyleXfCollection, $cellStyleIndex, 1);
}
/**
@@ -1341,6 +1341,7 @@ class Spreadsheet
// remove cellXfs without references and create mapping so we can update xfIndex
// for all cells and columns
$countNeededCellXfs = 0;
+ $map = [];
foreach ($this->cellXfCollection as $index => $cellXf) {
if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf
++$countNeededCellXfs;
@@ -1588,4 +1589,17 @@ class Spreadsheet
throw new Exception('Tab ratio must be between 0 and 1000.');
}
}
+
+ public function reevaluateAutoFilters(bool $resetToMax): void
+ {
+ foreach ($this->workSheetCollection as $sheet) {
+ $filter = $sheet->getAutoFilter();
+ if (!empty($filter->getRange())) {
+ if ($resetToMax) {
+ $filter->setRangeToMaxRow();
+ }
+ $filter->showHideRows();
+ }
+ }
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php
index 04a089fe420..83ac5b0dabf 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php
@@ -35,21 +35,21 @@ class Alignment extends Supervisor
/**
* Horizontal alignment.
*
- * @var string
+ * @var null|string
*/
protected $horizontal = self::HORIZONTAL_GENERAL;
/**
* Vertical alignment.
*
- * @var string
+ * @var null|string
*/
protected $vertical = self::VERTICAL_BOTTOM;
/**
* Text rotation.
*
- * @var int
+ * @var null|int
*/
protected $textRotation = 0;
@@ -111,7 +111,10 @@ class Alignment extends Supervisor
*/
public function getSharedComponent()
{
- return $this->parent->getSharedComponent()->getAlignment();
+ /** @var Style */
+ $parent = $this->parent;
+
+ return $parent->getSharedComponent()->getAlignment();
}
/**
@@ -140,36 +143,36 @@ class Alignment extends Supervisor
* );
*
*
- * @param array $pStyles Array containing style information
+ * @param array $styleArray Array containing style information
*
* @return $this
*/
- public function applyFromArray(array $pStyles)
+ public function applyFromArray(array $styleArray)
{
if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())
- ->applyFromArray($this->getStyleArray($pStyles));
+ ->applyFromArray($this->getStyleArray($styleArray));
} else {
- if (isset($pStyles['horizontal'])) {
- $this->setHorizontal($pStyles['horizontal']);
+ if (isset($styleArray['horizontal'])) {
+ $this->setHorizontal($styleArray['horizontal']);
}
- if (isset($pStyles['vertical'])) {
- $this->setVertical($pStyles['vertical']);
+ if (isset($styleArray['vertical'])) {
+ $this->setVertical($styleArray['vertical']);
}
- if (isset($pStyles['textRotation'])) {
- $this->setTextRotation($pStyles['textRotation']);
+ if (isset($styleArray['textRotation'])) {
+ $this->setTextRotation($styleArray['textRotation']);
}
- if (isset($pStyles['wrapText'])) {
- $this->setWrapText($pStyles['wrapText']);
+ if (isset($styleArray['wrapText'])) {
+ $this->setWrapText($styleArray['wrapText']);
}
- if (isset($pStyles['shrinkToFit'])) {
- $this->setShrinkToFit($pStyles['shrinkToFit']);
+ if (isset($styleArray['shrinkToFit'])) {
+ $this->setShrinkToFit($styleArray['shrinkToFit']);
}
- if (isset($pStyles['indent'])) {
- $this->setIndent($pStyles['indent']);
+ if (isset($styleArray['indent'])) {
+ $this->setIndent($styleArray['indent']);
}
- if (isset($pStyles['readOrder'])) {
- $this->setReadOrder($pStyles['readOrder']);
+ if (isset($styleArray['readOrder'])) {
+ $this->setReadOrder($styleArray['readOrder']);
}
}
@@ -179,7 +182,7 @@ class Alignment extends Supervisor
/**
* Get Horizontal.
*
- * @return string
+ * @return null|string
*/
public function getHorizontal()
{
@@ -193,21 +196,21 @@ class Alignment extends Supervisor
/**
* Set Horizontal.
*
- * @param string $pValue see self::HORIZONTAL_*
+ * @param string $horizontalAlignment see self::HORIZONTAL_*
*
* @return $this
*/
- public function setHorizontal($pValue)
+ public function setHorizontal(string $horizontalAlignment)
{
- if ($pValue == '') {
- $pValue = self::HORIZONTAL_GENERAL;
+ if ($horizontalAlignment == '') {
+ $horizontalAlignment = self::HORIZONTAL_GENERAL;
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['horizontal' => $pValue]);
+ $styleArray = $this->getStyleArray(['horizontal' => $horizontalAlignment]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->horizontal = $pValue;
+ $this->horizontal = $horizontalAlignment;
}
return $this;
@@ -216,7 +219,7 @@ class Alignment extends Supervisor
/**
* Get Vertical.
*
- * @return string
+ * @return null|string
*/
public function getVertical()
{
@@ -230,21 +233,21 @@ class Alignment extends Supervisor
/**
* Set Vertical.
*
- * @param string $pValue see self::VERTICAL_*
+ * @param string $verticalAlignment see self::VERTICAL_*
*
* @return $this
*/
- public function setVertical($pValue)
+ public function setVertical($verticalAlignment)
{
- if ($pValue == '') {
- $pValue = self::VERTICAL_BOTTOM;
+ if ($verticalAlignment == '') {
+ $verticalAlignment = self::VERTICAL_BOTTOM;
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['vertical' => $pValue]);
+ $styleArray = $this->getStyleArray(['vertical' => $verticalAlignment]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->vertical = $pValue;
+ $this->vertical = $verticalAlignment;
}
return $this;
@@ -253,7 +256,7 @@ class Alignment extends Supervisor
/**
* Get TextRotation.
*
- * @return int
+ * @return null|int
*/
public function getTextRotation()
{
@@ -267,24 +270,24 @@ class Alignment extends Supervisor
/**
* Set TextRotation.
*
- * @param int $pValue
+ * @param int $angleInDegrees
*
* @return $this
*/
- public function setTextRotation($pValue)
+ public function setTextRotation($angleInDegrees)
{
// Excel2007 value 255 => PhpSpreadsheet value -165
- if ($pValue == self::TEXTROTATION_STACK_EXCEL) {
- $pValue = self::TEXTROTATION_STACK_PHPSPREADSHEET;
+ if ($angleInDegrees == self::TEXTROTATION_STACK_EXCEL) {
+ $angleInDegrees = self::TEXTROTATION_STACK_PHPSPREADSHEET;
}
// Set rotation
- if (($pValue >= -90 && $pValue <= 90) || $pValue == self::TEXTROTATION_STACK_PHPSPREADSHEET) {
+ if (($angleInDegrees >= -90 && $angleInDegrees <= 90) || $angleInDegrees == self::TEXTROTATION_STACK_PHPSPREADSHEET) {
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['textRotation' => $pValue]);
+ $styleArray = $this->getStyleArray(['textRotation' => $angleInDegrees]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->textRotation = $pValue;
+ $this->textRotation = $angleInDegrees;
}
} else {
throw new PhpSpreadsheetException('Text rotation should be a value between -90 and 90.');
@@ -310,20 +313,20 @@ class Alignment extends Supervisor
/**
* Set Wrap Text.
*
- * @param bool $pValue
+ * @param bool $wrapped
*
* @return $this
*/
- public function setWrapText($pValue)
+ public function setWrapText($wrapped)
{
- if ($pValue == '') {
- $pValue = false;
+ if ($wrapped == '') {
+ $wrapped = false;
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['wrapText' => $pValue]);
+ $styleArray = $this->getStyleArray(['wrapText' => $wrapped]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->wrapText = $pValue;
+ $this->wrapText = $wrapped;
}
return $this;
@@ -346,20 +349,20 @@ class Alignment extends Supervisor
/**
* Set Shrink to fit.
*
- * @param bool $pValue
+ * @param bool $shrink
*
* @return $this
*/
- public function setShrinkToFit($pValue)
+ public function setShrinkToFit($shrink)
{
- if ($pValue == '') {
- $pValue = false;
+ if ($shrink == '') {
+ $shrink = false;
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['shrinkToFit' => $pValue]);
+ $styleArray = $this->getStyleArray(['shrinkToFit' => $shrink]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->shrinkToFit = $pValue;
+ $this->shrinkToFit = $shrink;
}
return $this;
@@ -382,26 +385,27 @@ class Alignment extends Supervisor
/**
* Set indent.
*
- * @param int $pValue
+ * @param int $indent
*
* @return $this
*/
- public function setIndent($pValue)
+ public function setIndent($indent)
{
- if ($pValue > 0) {
+ if ($indent > 0) {
if (
$this->getHorizontal() != self::HORIZONTAL_GENERAL &&
$this->getHorizontal() != self::HORIZONTAL_LEFT &&
- $this->getHorizontal() != self::HORIZONTAL_RIGHT
+ $this->getHorizontal() != self::HORIZONTAL_RIGHT &&
+ $this->getHorizontal() != self::HORIZONTAL_DISTRIBUTED
) {
- $pValue = 0; // indent not supported
+ $indent = 0; // indent not supported
}
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['indent' => $pValue]);
+ $styleArray = $this->getStyleArray(['indent' => $indent]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->indent = $pValue;
+ $this->indent = $indent;
}
return $this;
@@ -424,20 +428,20 @@ class Alignment extends Supervisor
/**
* Set read order.
*
- * @param int $pValue
+ * @param int $readOrder
*
* @return $this
*/
- public function setReadOrder($pValue)
+ public function setReadOrder($readOrder)
{
- if ($pValue < 0 || $pValue > 2) {
- $pValue = 0;
+ if ($readOrder < 0 || $readOrder > 2) {
+ $readOrder = 0;
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['readOrder' => $pValue]);
+ $styleArray = $this->getStyleArray(['readOrder' => $readOrder]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->readOrder = $pValue;
+ $this->readOrder = $readOrder;
}
return $this;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Border.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Border.php
index 1d3096f01d5..a5ec980a09d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Border.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Border.php
@@ -37,7 +37,7 @@ class Border extends Supervisor
protected $color;
/**
- * @var int
+ * @var null|int
*/
public $colorIndex;
@@ -47,11 +47,8 @@ class Border extends Supervisor
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
- * @param bool $isConditional Flag indicating if this is a conditional style or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
*/
- public function __construct($isSupervisor = false, $isConditional = false)
+ public function __construct($isSupervisor = false)
{
// Supervisor?
parent::__construct($isSupervisor);
@@ -73,17 +70,22 @@ class Border extends Supervisor
*/
public function getSharedComponent()
{
+ /** @var Style */
+ $parent = $this->parent;
+
+ /** @var Borders $sharedComponent */
+ $sharedComponent = $parent->getSharedComponent();
switch ($this->parentPropertyName) {
case 'bottom':
- return $this->parent->getSharedComponent()->getBottom();
+ return $sharedComponent->getBottom();
case 'diagonal':
- return $this->parent->getSharedComponent()->getDiagonal();
+ return $sharedComponent->getDiagonal();
case 'left':
- return $this->parent->getSharedComponent()->getLeft();
+ return $sharedComponent->getLeft();
case 'right':
- return $this->parent->getSharedComponent()->getRight();
+ return $sharedComponent->getRight();
case 'top':
- return $this->parent->getSharedComponent()->getTop();
+ return $sharedComponent->getTop();
}
throw new PhpSpreadsheetException('Cannot get shared component for a pseudo-border.');
@@ -98,7 +100,10 @@ class Border extends Supervisor
*/
public function getStyleArray($array)
{
- return $this->parent->getStyleArray([$this->parentPropertyName => $array]);
+ /** @var Style */
+ $parent = $this->parent;
+
+ return $parent->getStyleArray([$this->parentPropertyName => $array]);
}
/**
@@ -115,20 +120,20 @@ class Border extends Supervisor
* );
*
*
- * @param array $pStyles Array containing style information
+ * @param array $styleArray Array containing style information
*
* @return $this
*/
- public function applyFromArray(array $pStyles)
+ public function applyFromArray(array $styleArray)
{
if ($this->isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
- if (isset($pStyles['borderStyle'])) {
- $this->setBorderStyle($pStyles['borderStyle']);
+ if (isset($styleArray['borderStyle'])) {
+ $this->setBorderStyle($styleArray['borderStyle']);
}
- if (isset($pStyles['color'])) {
- $this->getColor()->applyFromArray($pStyles['color']);
+ if (isset($styleArray['color'])) {
+ $this->getColor()->applyFromArray($styleArray['color']);
}
}
@@ -152,24 +157,25 @@ class Border extends Supervisor
/**
* Set Border style.
*
- * @param bool|string $pValue
+ * @param bool|string $style
* When passing a boolean, FALSE equates Border::BORDER_NONE
* and TRUE to Border::BORDER_MEDIUM
*
* @return $this
*/
- public function setBorderStyle($pValue)
+ public function setBorderStyle($style)
{
- if (empty($pValue)) {
- $pValue = self::BORDER_NONE;
- } elseif (is_bool($pValue) && $pValue) {
- $pValue = self::BORDER_MEDIUM;
+ if (empty($style)) {
+ $style = self::BORDER_NONE;
+ } elseif (is_bool($style)) {
+ $style = self::BORDER_MEDIUM;
}
+
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['borderStyle' => $pValue]);
+ $styleArray = $this->getStyleArray(['borderStyle' => $style]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->borderStyle = $pValue;
+ $this->borderStyle = $style;
}
return $this;
@@ -190,10 +196,10 @@ class Border extends Supervisor
*
* @return $this
*/
- public function setColor(Color $pValue)
+ public function setColor(Color $color)
{
// make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+ $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) {
$styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Borders.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Borders.php
index a1acfdd4b95..56a52709ed6 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Borders.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Borders.php
@@ -95,21 +95,18 @@ class Borders extends Supervisor
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
- * @param bool $isConditional Flag indicating if this is a conditional style or not
- * Leave this value at default unless you understand exactly what
- * its ramifications are
*/
- public function __construct($isSupervisor = false, $isConditional = false)
+ public function __construct($isSupervisor = false)
{
// Supervisor?
parent::__construct($isSupervisor);
// Initialise values
- $this->left = new Border($isSupervisor, $isConditional);
- $this->right = new Border($isSupervisor, $isConditional);
- $this->top = new Border($isSupervisor, $isConditional);
- $this->bottom = new Border($isSupervisor, $isConditional);
- $this->diagonal = new Border($isSupervisor, $isConditional);
+ $this->left = new Border($isSupervisor);
+ $this->right = new Border($isSupervisor);
+ $this->top = new Border($isSupervisor);
+ $this->bottom = new Border($isSupervisor);
+ $this->diagonal = new Border($isSupervisor);
$this->diagonalDirection = self::DIAGONAL_NONE;
// Specially for supervisor
@@ -143,7 +140,10 @@ class Borders extends Supervisor
*/
public function getSharedComponent()
{
- return $this->parent->getSharedComponent()->getBorders();
+ /** @var Style */
+ $parent = $this->parent;
+
+ return $parent->getSharedComponent()->getBorders();
}
/**
@@ -193,38 +193,38 @@ class Borders extends Supervisor
* );
*
*
- * @param array $pStyles Array containing style information
+ * @param array $styleArray Array containing style information
*
* @return $this
*/
- public function applyFromArray(array $pStyles)
+ public function applyFromArray(array $styleArray)
{
if ($this->isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
- if (isset($pStyles['left'])) {
- $this->getLeft()->applyFromArray($pStyles['left']);
+ if (isset($styleArray['left'])) {
+ $this->getLeft()->applyFromArray($styleArray['left']);
}
- if (isset($pStyles['right'])) {
- $this->getRight()->applyFromArray($pStyles['right']);
+ if (isset($styleArray['right'])) {
+ $this->getRight()->applyFromArray($styleArray['right']);
}
- if (isset($pStyles['top'])) {
- $this->getTop()->applyFromArray($pStyles['top']);
+ if (isset($styleArray['top'])) {
+ $this->getTop()->applyFromArray($styleArray['top']);
}
- if (isset($pStyles['bottom'])) {
- $this->getBottom()->applyFromArray($pStyles['bottom']);
+ if (isset($styleArray['bottom'])) {
+ $this->getBottom()->applyFromArray($styleArray['bottom']);
}
- if (isset($pStyles['diagonal'])) {
- $this->getDiagonal()->applyFromArray($pStyles['diagonal']);
+ if (isset($styleArray['diagonal'])) {
+ $this->getDiagonal()->applyFromArray($styleArray['diagonal']);
}
- if (isset($pStyles['diagonalDirection'])) {
- $this->setDiagonalDirection($pStyles['diagonalDirection']);
+ if (isset($styleArray['diagonalDirection'])) {
+ $this->setDiagonalDirection($styleArray['diagonalDirection']);
}
- if (isset($pStyles['allBorders'])) {
- $this->getLeft()->applyFromArray($pStyles['allBorders']);
- $this->getRight()->applyFromArray($pStyles['allBorders']);
- $this->getTop()->applyFromArray($pStyles['allBorders']);
- $this->getBottom()->applyFromArray($pStyles['allBorders']);
+ if (isset($styleArray['allBorders'])) {
+ $this->getLeft()->applyFromArray($styleArray['allBorders']);
+ $this->getRight()->applyFromArray($styleArray['allBorders']);
+ $this->getTop()->applyFromArray($styleArray['allBorders']);
+ $this->getBottom()->applyFromArray($styleArray['allBorders']);
}
}
@@ -368,20 +368,20 @@ class Borders extends Supervisor
/**
* Set DiagonalDirection.
*
- * @param int $pValue see self::DIAGONAL_*
+ * @param int $direction see self::DIAGONAL_*
*
* @return $this
*/
- public function setDiagonalDirection($pValue)
+ public function setDiagonalDirection($direction)
{
- if ($pValue == '') {
- $pValue = self::DIAGONAL_NONE;
+ if ($direction == '') {
+ $direction = self::DIAGONAL_NONE;
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['diagonalDirection' => $pValue]);
+ $styleArray = $this->getStyleArray(['diagonalDirection' => $direction]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->diagonalDirection = $pValue;
+ $this->diagonalDirection = $direction;
}
return $this;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Color.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Color.php
index ad598f113a4..c2d4f749055 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Color.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Color.php
@@ -27,6 +27,10 @@ class Color extends Supervisor
const COLOR_YELLOW = 'FFFFFF00';
const COLOR_DARKYELLOW = 'FF808000';
+ const VALIDATE_ARGB_SIZE = 8;
+ const VALIDATE_RGB_SIZE = 6;
+ const VALIDATE_COLOR_VALUE = '/^[A-F0-9]{%d}$/i';
+
/**
* Indexed colors array.
*
@@ -37,14 +41,17 @@ class Color extends Supervisor
/**
* ARGB - Alpha RGB.
*
- * @var string
+ * @var null|string
*/
protected $argb;
+ /** @var bool */
+ private $hasChanged = false;
+
/**
* Create a new Color.
*
- * @param string $pARGB ARGB value for the colour
+ * @param string $colorValue ARGB value for the colour, or named colour
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
@@ -52,14 +59,14 @@ class Color extends Supervisor
* Leave this value at default unless you understand exactly what
* its ramifications are
*/
- public function __construct($pARGB = self::COLOR_BLACK, $isSupervisor = false, $isConditional = false)
+ public function __construct($colorValue = self::COLOR_BLACK, $isSupervisor = false, $isConditional = false)
{
// Supervisor?
parent::__construct($isSupervisor);
// Initialise values
if (!$isConditional) {
- $this->argb = $pARGB;
+ $this->argb = $this->validateColor($colorValue, self::VALIDATE_ARGB_SIZE) ? $colorValue : self::COLOR_BLACK;
}
}
@@ -71,14 +78,19 @@ class Color extends Supervisor
*/
public function getSharedComponent()
{
- if ($this->parentPropertyName === 'endColor') {
- return $this->parent->getSharedComponent()->getEndColor();
- }
- if ($this->parentPropertyName === 'startColor') {
- return $this->parent->getSharedComponent()->getStartColor();
+ /** @var Style */
+ $parent = $this->parent;
+ /** @var Border|Fill $sharedComponent */
+ $sharedComponent = $parent->getSharedComponent();
+ if ($sharedComponent instanceof Fill) {
+ if ($this->parentPropertyName === 'endColor') {
+ return $sharedComponent->getEndColor();
+ }
+
+ return $sharedComponent->getStartColor();
}
- return $this->parent->getSharedComponent()->getColor();
+ return $sharedComponent->getColor();
}
/**
@@ -90,7 +102,10 @@ class Color extends Supervisor
*/
public function getStyleArray($array)
{
- return $this->parent->getStyleArray([$this->parentPropertyName => $array]);
+ /** @var Style */
+ $parent = $this->parent;
+
+ return $parent->getStyleArray([$this->parentPropertyName => $array]);
}
/**
@@ -100,32 +115,36 @@ class Color extends Supervisor
* $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray(['rgb' => '808080']);
*
*
- * @param array $pStyles Array containing style information
+ * @param array $styleArray Array containing style information
*
* @return $this
*/
- public function applyFromArray(array $pStyles)
+ public function applyFromArray(array $styleArray)
{
if ($this->isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
- if (isset($pStyles['rgb'])) {
- $this->setRGB($pStyles['rgb']);
+ if (isset($styleArray['rgb'])) {
+ $this->setRGB($styleArray['rgb']);
}
- if (isset($pStyles['argb'])) {
- $this->setARGB($pStyles['argb']);
+ if (isset($styleArray['argb'])) {
+ $this->setARGB($styleArray['argb']);
}
}
return $this;
}
+ private function validateColor(string $colorValue, int $size): bool
+ {
+ return in_array(ucfirst(strtolower($colorValue)), self::NAMED_COLORS) ||
+ preg_match(sprintf(self::VALIDATE_COLOR_VALUE, $size), $colorValue);
+ }
+
/**
* Get ARGB.
- *
- * @return string
*/
- public function getARGB()
+ public function getARGB(): ?string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getARGB();
@@ -137,20 +156,24 @@ class Color extends Supervisor
/**
* Set ARGB.
*
- * @param string $pValue see self::COLOR_*
+ * @param string $colorValue ARGB value, or a named color
*
* @return $this
*/
- public function setARGB($pValue)
+ public function setARGB(?string $colorValue = self::COLOR_BLACK)
{
- if ($pValue == '') {
- $pValue = self::COLOR_BLACK;
+ $this->hasChanged = true;
+ if ($colorValue === '' || $colorValue === null) {
+ $colorValue = self::COLOR_BLACK;
+ } elseif (!$this->validateColor($colorValue, self::VALIDATE_ARGB_SIZE)) {
+ return $this;
}
+
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['argb' => $pValue]);
+ $styleArray = $this->getStyleArray(['argb' => $colorValue]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->argb = $pValue;
+ $this->argb = $colorValue;
}
return $this;
@@ -158,35 +181,37 @@ class Color extends Supervisor
/**
* Get RGB.
- *
- * @return string
*/
- public function getRGB()
+ public function getRGB(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getRGB();
}
- return substr($this->argb, 2);
+ return substr($this->argb ?? '', 2);
}
/**
* Set RGB.
*
- * @param string $pValue RGB value
+ * @param string $colorValue RGB value, or a named color
*
* @return $this
*/
- public function setRGB($pValue)
+ public function setRGB(?string $colorValue = self::COLOR_BLACK)
{
- if ($pValue == '') {
- $pValue = '000000';
+ $this->hasChanged = true;
+ if ($colorValue === '' || $colorValue === null) {
+ $colorValue = '000000';
+ } elseif (!$this->validateColor($colorValue, self::VALIDATE_RGB_SIZE)) {
+ return $this;
}
+
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['argb' => 'FF' . $pValue]);
+ $styleArray = $this->getStyleArray(['argb' => 'FF' . $colorValue]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->argb = 'FF' . $pValue;
+ $this->argb = 'FF' . $colorValue;
}
return $this;
@@ -195,78 +220,81 @@ class Color extends Supervisor
/**
* Get a specified colour component of an RGB value.
*
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param int $offset Position within the RGB value to extract
* @param bool $hex Flag indicating whether the component should be returned as a hex or a
* decimal value
*
- * @return string The extracted colour component
+ * @return int|string The extracted colour component
*/
- private static function getColourComponent($RGB, $offset, $hex = true)
+ private static function getColourComponent($rgbValue, $offset, $hex = true)
{
- $colour = substr($RGB, $offset, 2);
+ $colour = substr($rgbValue, $offset, 2);
- return ($hex) ? $colour : hexdec($colour);
+ return ($hex) ? $colour : (int) hexdec($colour);
}
/**
* Get the red colour component of an RGB value.
*
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param bool $hex Flag indicating whether the component should be returned as a hex or a
* decimal value
*
- * @return string The red colour component
+ * @return int|string The red colour component
*/
- public static function getRed($RGB, $hex = true)
+ public static function getRed($rgbValue, $hex = true)
{
- return self::getColourComponent($RGB, strlen($RGB) - 6, $hex);
+ return self::getColourComponent($rgbValue, strlen($rgbValue) - 6, $hex);
}
/**
* Get the green colour component of an RGB value.
*
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param bool $hex Flag indicating whether the component should be returned as a hex or a
* decimal value
*
- * @return string The green colour component
+ * @return int|string The green colour component
*/
- public static function getGreen($RGB, $hex = true)
+ public static function getGreen($rgbValue, $hex = true)
{
- return self::getColourComponent($RGB, strlen($RGB) - 4, $hex);
+ return self::getColourComponent($rgbValue, strlen($rgbValue) - 4, $hex);
}
/**
* Get the blue colour component of an RGB value.
*
- * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE
+ * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param bool $hex Flag indicating whether the component should be returned as a hex or a
* decimal value
*
- * @return string The blue colour component
+ * @return int|string The blue colour component
*/
- public static function getBlue($RGB, $hex = true)
+ public static function getBlue($rgbValue, $hex = true)
{
- return self::getColourComponent($RGB, strlen($RGB) - 2, $hex);
+ return self::getColourComponent($rgbValue, strlen($rgbValue) - 2, $hex);
}
/**
* Adjust the brightness of a color.
*
- * @param string $hex The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
+ * @param string $hexColourValue The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
* @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1
*
* @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
*/
- public static function changeBrightness($hex, $adjustPercentage)
+ public static function changeBrightness($hexColourValue, $adjustPercentage)
{
- $rgba = (strlen($hex) === 8);
+ $rgba = (strlen($hexColourValue) === 8);
$adjustPercentage = max(-1.0, min(1.0, $adjustPercentage));
- $red = self::getRed($hex, false);
- $green = self::getGreen($hex, false);
- $blue = self::getBlue($hex, false);
+ /** @var int $red */
+ $red = self::getRed($hexColourValue, false);
+ /** @var int $green */
+ $green = self::getGreen($hexColourValue, false);
+ /** @var int $blue */
+ $blue = self::getBlue($hexColourValue, false);
if ($adjustPercentage > 0) {
$red += (255 - $red) * $adjustPercentage;
$green += (255 - $green) * $adjustPercentage;
@@ -289,16 +317,16 @@ class Color extends Supervisor
/**
* Get indexed color.
*
- * @param int $pIndex Index entry point into the colour array
+ * @param int $colorIndex Index entry point into the colour array
* @param bool $background Flag to indicate whether default background or foreground colour
* should be returned if the indexed colour doesn't exist
*
- * @return self
+ * @return Color
*/
- public static function indexedColor($pIndex, $background = false)
+ public static function indexedColor($colorIndex, $background = false): self
{
// Clean parameter
- $pIndex = (int) $pIndex;
+ $colorIndex = (int) $colorIndex;
// Indexed colors
if (self::$indexedColors === null) {
@@ -362,15 +390,11 @@ class Color extends Supervisor
];
}
- if (isset(self::$indexedColors[$pIndex])) {
- return new self(self::$indexedColors[$pIndex]);
+ if (isset(self::$indexedColors[$colorIndex])) {
+ return new self(self::$indexedColors[$colorIndex]);
}
- if ($background) {
- return new self(self::COLOR_WHITE);
- }
-
- return new self(self::COLOR_BLACK);
+ return ($background) ? new self(self::COLOR_WHITE) : new self(self::COLOR_BLACK);
}
/**
@@ -378,7 +402,7 @@ class Color extends Supervisor
*
* @return string Hash code
*/
- public function getHashCode()
+ public function getHashCode(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getHashCode();
@@ -397,4 +421,13 @@ class Color extends Supervisor
return $exportedArray;
}
+
+ public function getHasChanged(): bool
+ {
+ if ($this->isSupervisor) {
+ return $this->getSharedComponent()->hasChanged;
+ }
+
+ return $this->hasChanged;
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Conditional.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Conditional.php
index e4fe0acc7f6..e148ee82ba6 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Conditional.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Conditional.php
@@ -3,6 +3,7 @@
namespace PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\IComparable;
+use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar;
class Conditional implements IComparable
{
@@ -13,6 +14,19 @@ class Conditional implements IComparable
const CONDITION_EXPRESSION = 'expression';
const CONDITION_CONTAINSBLANKS = 'containsBlanks';
const CONDITION_NOTCONTAINSBLANKS = 'notContainsBlanks';
+ const CONDITION_DATABAR = 'dataBar';
+ const CONDITION_NOTCONTAINSTEXT = 'notContainsText';
+
+ private const CONDITION_TYPES = [
+ self::CONDITION_CELLIS,
+ self::CONDITION_CONTAINSBLANKS,
+ self::CONDITION_CONTAINSTEXT,
+ self::CONDITION_DATABAR,
+ self::CONDITION_EXPRESSION,
+ self::CONDITION_NONE,
+ self::CONDITION_NOTCONTAINSBLANKS,
+ self::CONDITION_NOTCONTAINSTEXT,
+ ];
// Operator types
const OPERATOR_NONE = '';
@@ -64,6 +78,11 @@ class Conditional implements IComparable
*/
private $condition = [];
+ /**
+ * @var ConditionalDataBar
+ */
+ private $dataBar;
+
/**
* Style.
*
@@ -93,13 +112,13 @@ class Conditional implements IComparable
/**
* Set Condition type.
*
- * @param string $pValue Condition type, see self::CONDITION_*
+ * @param string $type Condition type, see self::CONDITION_*
*
* @return $this
*/
- public function setConditionType($pValue)
+ public function setConditionType($type)
{
- $this->conditionType = $pValue;
+ $this->conditionType = $type;
return $this;
}
@@ -117,13 +136,13 @@ class Conditional implements IComparable
/**
* Set Operator type.
*
- * @param string $pValue Conditional operator type, see self::OPERATOR_*
+ * @param string $type Conditional operator type, see self::OPERATOR_*
*
* @return $this
*/
- public function setOperatorType($pValue)
+ public function setOperatorType($type)
{
- $this->operatorType = $pValue;
+ $this->operatorType = $type;
return $this;
}
@@ -141,13 +160,13 @@ class Conditional implements IComparable
/**
* Set text.
*
- * @param string $value
+ * @param string $text
*
* @return $this
*/
- public function setText($value)
+ public function setText($text)
{
- $this->text = $value;
+ $this->text = $text;
return $this;
}
@@ -165,13 +184,13 @@ class Conditional implements IComparable
/**
* Set StopIfTrue.
*
- * @param bool $value
+ * @param bool $stopIfTrue
*
* @return $this
*/
- public function setStopIfTrue($value)
+ public function setStopIfTrue($stopIfTrue)
{
- $this->stopIfTrue = $value;
+ $this->stopIfTrue = $stopIfTrue;
return $this;
}
@@ -189,16 +208,16 @@ class Conditional implements IComparable
/**
* Set Conditions.
*
- * @param bool|float|int|string|string[] $pValue Condition
+ * @param bool|float|int|string|string[] $conditions Condition
*
* @return $this
*/
- public function setConditions($pValue)
+ public function setConditions($conditions)
{
- if (!is_array($pValue)) {
- $pValue = [$pValue];
+ if (!is_array($conditions)) {
+ $conditions = [$conditions];
}
- $this->condition = $pValue;
+ $this->condition = $conditions;
return $this;
}
@@ -206,13 +225,13 @@ class Conditional implements IComparable
/**
* Add Condition.
*
- * @param string $pValue Condition
+ * @param string $condition Condition
*
* @return $this
*/
- public function addCondition($pValue)
+ public function addCondition($condition)
{
- $this->condition[] = $pValue;
+ $this->condition[] = $condition;
return $this;
}
@@ -230,13 +249,33 @@ class Conditional implements IComparable
/**
* Set Style.
*
- * @param Style $pValue
+ * @return $this
+ */
+ public function setStyle(?Style $style = null)
+ {
+ $this->style = $style;
+
+ return $this;
+ }
+
+ /**
+ * get DataBar.
+ *
+ * @return null|ConditionalDataBar
+ */
+ public function getDataBar()
+ {
+ return $this->dataBar;
+ }
+
+ /**
+ * set DataBar.
*
* @return $this
*/
- public function setStyle(?Style $pValue = null)
+ public function setDataBar(ConditionalDataBar $dataBar)
{
- $this->style = $pValue;
+ $this->dataBar = $dataBar;
return $this;
}
@@ -271,4 +310,12 @@ class Conditional implements IComparable
}
}
}
+
+ /**
+ * Verify if param is valid condition type.
+ */
+ public static function isValidConditionType(string $type): bool
+ {
+ return in_array($type, self::CONDITION_TYPES);
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php
new file mode 100644
index 00000000000..54513670e43
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php
@@ -0,0 +1,102 @@
+ attribute */
+
+ /** @var null|bool */
+ private $showValue;
+
+ /** children */
+
+ /** @var ConditionalFormatValueObject */
+ private $minimumConditionalFormatValueObject;
+
+ /** @var ConditionalFormatValueObject */
+ private $maximumConditionalFormatValueObject;
+
+ /** @var string */
+ private $color;
+
+ /** */
+
+ /** @var ConditionalFormattingRuleExtension */
+ private $conditionalFormattingRuleExt;
+
+ /**
+ * @return null|bool
+ */
+ public function getShowValue()
+ {
+ return $this->showValue;
+ }
+
+ /**
+ * @param bool $showValue
+ */
+ public function setShowValue($showValue)
+ {
+ $this->showValue = $showValue;
+
+ return $this;
+ }
+
+ /**
+ * @return ConditionalFormatValueObject
+ */
+ public function getMinimumConditionalFormatValueObject()
+ {
+ return $this->minimumConditionalFormatValueObject;
+ }
+
+ public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject)
+ {
+ $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject;
+
+ return $this;
+ }
+
+ /**
+ * @return ConditionalFormatValueObject
+ */
+ public function getMaximumConditionalFormatValueObject()
+ {
+ return $this->maximumConditionalFormatValueObject;
+ }
+
+ public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject)
+ {
+ $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject;
+
+ return $this;
+ }
+
+ public function getColor(): string
+ {
+ return $this->color;
+ }
+
+ public function setColor(string $color): self
+ {
+ $this->color = $color;
+
+ return $this;
+ }
+
+ /**
+ * @return ConditionalFormattingRuleExtension
+ */
+ public function getConditionalFormattingRuleExt()
+ {
+ return $this->conditionalFormattingRuleExt;
+ }
+
+ public function setConditionalFormattingRuleExt(ConditionalFormattingRuleExtension $conditionalFormattingRuleExt)
+ {
+ $this->conditionalFormattingRuleExt = $conditionalFormattingRuleExt;
+
+ return $this;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php
new file mode 100644
index 00000000000..c709cf3e70a
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php
@@ -0,0 +1,290 @@
+ attributes */
+
+ /** @var int */
+ private $minLength;
+
+ /** @var int */
+ private $maxLength;
+
+ /** @var null|bool */
+ private $border;
+
+ /** @var null|bool */
+ private $gradient;
+
+ /** @var string */
+ private $direction;
+
+ /** @var null|bool */
+ private $negativeBarBorderColorSameAsPositive;
+
+ /** @var string */
+ private $axisPosition;
+
+ // children
+
+ /** @var ConditionalFormatValueObject */
+ private $maximumConditionalFormatValueObject;
+
+ /** @var ConditionalFormatValueObject */
+ private $minimumConditionalFormatValueObject;
+
+ /** @var string */
+ private $borderColor;
+
+ /** @var string */
+ private $negativeFillColor;
+
+ /** @var string */
+ private $negativeBorderColor;
+
+ /** @var array */
+ private $axisColor = [
+ 'rgb' => null,
+ 'theme' => null,
+ 'tint' => null,
+ ];
+
+ public function getXmlAttributes()
+ {
+ $ret = [];
+ foreach (['minLength', 'maxLength', 'direction', 'axisPosition'] as $attrKey) {
+ if (null !== $this->{$attrKey}) {
+ $ret[$attrKey] = $this->{$attrKey};
+ }
+ }
+ foreach (['border', 'gradient', 'negativeBarBorderColorSameAsPositive'] as $attrKey) {
+ if (null !== $this->{$attrKey}) {
+ $ret[$attrKey] = $this->{$attrKey} ? '1' : '0';
+ }
+ }
+
+ return $ret;
+ }
+
+ public function getXmlElements()
+ {
+ $ret = [];
+ $elms = ['borderColor', 'negativeFillColor', 'negativeBorderColor'];
+ foreach ($elms as $elmKey) {
+ if (null !== $this->{$elmKey}) {
+ $ret[$elmKey] = ['rgb' => $this->{$elmKey}];
+ }
+ }
+ foreach (array_filter($this->axisColor) as $attrKey => $axisColorAttr) {
+ if (!isset($ret['axisColor'])) {
+ $ret['axisColor'] = [];
+ }
+ $ret['axisColor'][$attrKey] = $axisColorAttr;
+ }
+
+ return $ret;
+ }
+
+ /**
+ * @return int
+ */
+ public function getMinLength()
+ {
+ return $this->minLength;
+ }
+
+ public function setMinLength(int $minLength): self
+ {
+ $this->minLength = $minLength;
+
+ return $this;
+ }
+
+ /**
+ * @return int
+ */
+ public function getMaxLength()
+ {
+ return $this->maxLength;
+ }
+
+ public function setMaxLength(int $maxLength): self
+ {
+ $this->maxLength = $maxLength;
+
+ return $this;
+ }
+
+ /**
+ * @return null|bool
+ */
+ public function getBorder()
+ {
+ return $this->border;
+ }
+
+ public function setBorder(bool $border): self
+ {
+ $this->border = $border;
+
+ return $this;
+ }
+
+ /**
+ * @return null|bool
+ */
+ public function getGradient()
+ {
+ return $this->gradient;
+ }
+
+ public function setGradient(bool $gradient): self
+ {
+ $this->gradient = $gradient;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getDirection()
+ {
+ return $this->direction;
+ }
+
+ public function setDirection(string $direction): self
+ {
+ $this->direction = $direction;
+
+ return $this;
+ }
+
+ /**
+ * @return null|bool
+ */
+ public function getNegativeBarBorderColorSameAsPositive()
+ {
+ return $this->negativeBarBorderColorSameAsPositive;
+ }
+
+ public function setNegativeBarBorderColorSameAsPositive(bool $negativeBarBorderColorSameAsPositive): self
+ {
+ $this->negativeBarBorderColorSameAsPositive = $negativeBarBorderColorSameAsPositive;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getAxisPosition()
+ {
+ return $this->axisPosition;
+ }
+
+ public function setAxisPosition(string $axisPosition): self
+ {
+ $this->axisPosition = $axisPosition;
+
+ return $this;
+ }
+
+ /**
+ * @return ConditionalFormatValueObject
+ */
+ public function getMaximumConditionalFormatValueObject()
+ {
+ return $this->maximumConditionalFormatValueObject;
+ }
+
+ public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject)
+ {
+ $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject;
+
+ return $this;
+ }
+
+ /**
+ * @return ConditionalFormatValueObject
+ */
+ public function getMinimumConditionalFormatValueObject()
+ {
+ return $this->minimumConditionalFormatValueObject;
+ }
+
+ public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject)
+ {
+ $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getBorderColor()
+ {
+ return $this->borderColor;
+ }
+
+ public function setBorderColor(string $borderColor): self
+ {
+ $this->borderColor = $borderColor;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getNegativeFillColor()
+ {
+ return $this->negativeFillColor;
+ }
+
+ public function setNegativeFillColor(string $negativeFillColor): self
+ {
+ $this->negativeFillColor = $negativeFillColor;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getNegativeBorderColor()
+ {
+ return $this->negativeBorderColor;
+ }
+
+ public function setNegativeBorderColor(string $negativeBorderColor): self
+ {
+ $this->negativeBorderColor = $negativeBorderColor;
+
+ return $this;
+ }
+
+ public function getAxisColor(): array
+ {
+ return $this->axisColor;
+ }
+
+ /**
+ * @param mixed $rgb
+ * @param null|mixed $theme
+ * @param null|mixed $tint
+ */
+ public function setAxisColor($rgb, $theme = null, $tint = null): self
+ {
+ $this->axisColor = [
+ 'rgb' => $rgb,
+ 'theme' => $theme,
+ 'tint' => $tint,
+ ];
+
+ return $this;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php
new file mode 100644
index 00000000000..107969bf9f0
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php
@@ -0,0 +1,78 @@
+type = $type;
+ $this->value = $value;
+ $this->cellFormula = $cellFormula;
+ }
+
+ /**
+ * @return mixed
+ */
+ public function getType()
+ {
+ return $this->type;
+ }
+
+ /**
+ * @param mixed $type
+ */
+ public function setType($type)
+ {
+ $this->type = $type;
+
+ return $this;
+ }
+
+ /**
+ * @return mixed
+ */
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ /**
+ * @param mixed $value
+ */
+ public function setValue($value)
+ {
+ $this->value = $value;
+
+ return $this;
+ }
+
+ /**
+ * @return mixed
+ */
+ public function getCellFormula()
+ {
+ return $this->cellFormula;
+ }
+
+ /**
+ * @param mixed $cellFormula
+ */
+ public function setCellFormula($cellFormula)
+ {
+ $this->cellFormula = $cellFormula;
+
+ return $this;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php
new file mode 100644
index 00000000000..d8ef990c587
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php
@@ -0,0 +1,208 @@
+ attributes */
+ private $id;
+
+ /** @var string Conditional Formatting Rule */
+ private $cfRule;
+
+ /** children */
+
+ /** @var ConditionalDataBarExtension */
+ private $dataBar;
+
+ /** @var string Sequence of References */
+ private $sqref;
+
+ /**
+ * ConditionalFormattingRuleExtension constructor.
+ */
+ public function __construct($id = null, string $cfRule = self::CONDITION_EXTENSION_DATABAR)
+ {
+ if (null === $id) {
+ $this->id = '{' . $this->generateUuid() . '}';
+ } else {
+ $this->id = $id;
+ }
+ $this->cfRule = $cfRule;
+ }
+
+ private function generateUuid()
+ {
+ $chars = str_split('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');
+
+ foreach ($chars as $i => $char) {
+ if ($char === 'x') {
+ $chars[$i] = dechex(random_int(0, 15));
+ } elseif ($char === 'y') {
+ $chars[$i] = dechex(random_int(8, 11));
+ }
+ }
+
+ return implode('', $chars);
+ }
+
+ public static function parseExtLstXml($extLstXml)
+ {
+ $conditionalFormattingRuleExtensions = [];
+ $conditionalFormattingRuleExtensionXml = null;
+ if ($extLstXml instanceof SimpleXMLElement) {
+ foreach ((count($extLstXml) > 0 ? $extLstXml : [$extLstXml]) as $extLst) {
+ //this uri is conditionalFormattings
+ //https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627
+ if (isset($extLst->ext['uri']) && (string) $extLst->ext['uri'] === '{78C0D931-6437-407d-A8EE-F0AAD7539E65}') {
+ $conditionalFormattingRuleExtensionXml = $extLst->ext;
+ }
+ }
+
+ if ($conditionalFormattingRuleExtensionXml) {
+ $ns = $conditionalFormattingRuleExtensionXml->getNamespaces(true);
+ $extFormattingsXml = $conditionalFormattingRuleExtensionXml->children($ns['x14']);
+
+ foreach ($extFormattingsXml->children($ns['x14']) as $extFormattingXml) {
+ $extCfRuleXml = $extFormattingXml->cfRule;
+ $attributes = $extCfRuleXml->attributes();
+ if (!$attributes || ((string) $attributes->type) !== Conditional::CONDITION_DATABAR) {
+ continue;
+ }
+
+ $extFormattingRuleObj = new self((string) $attributes->id);
+ $extFormattingRuleObj->setSqref((string) $extFormattingXml->children($ns['xm'])->sqref);
+ $conditionalFormattingRuleExtensions[$extFormattingRuleObj->getId()] = $extFormattingRuleObj;
+
+ $extDataBarObj = new ConditionalDataBarExtension();
+ $extFormattingRuleObj->setDataBarExt($extDataBarObj);
+ $dataBarXml = $extCfRuleXml->dataBar;
+ self::parseExtDataBarAttributesFromXml($extDataBarObj, $dataBarXml);
+ self::parseExtDataBarElementChildrenFromXml($extDataBarObj, $dataBarXml, $ns);
+ }
+ }
+ }
+
+ return $conditionalFormattingRuleExtensions;
+ }
+
+ private static function parseExtDataBarAttributesFromXml(
+ ConditionalDataBarExtension $extDataBarObj,
+ SimpleXMLElement $dataBarXml
+ ): void {
+ $dataBarAttribute = $dataBarXml->attributes();
+ if ($dataBarAttribute->minLength) {
+ $extDataBarObj->setMinLength((int) $dataBarAttribute->minLength);
+ }
+ if ($dataBarAttribute->maxLength) {
+ $extDataBarObj->setMaxLength((int) $dataBarAttribute->maxLength);
+ }
+ if ($dataBarAttribute->border) {
+ $extDataBarObj->setBorder((bool) (string) $dataBarAttribute->border);
+ }
+ if ($dataBarAttribute->gradient) {
+ $extDataBarObj->setGradient((bool) (string) $dataBarAttribute->gradient);
+ }
+ if ($dataBarAttribute->direction) {
+ $extDataBarObj->setDirection((string) $dataBarAttribute->direction);
+ }
+ if ($dataBarAttribute->negativeBarBorderColorSameAsPositive) {
+ $extDataBarObj->setNegativeBarBorderColorSameAsPositive((bool) (string) $dataBarAttribute->negativeBarBorderColorSameAsPositive);
+ }
+ if ($dataBarAttribute->axisPosition) {
+ $extDataBarObj->setAxisPosition((string) $dataBarAttribute->axisPosition);
+ }
+ }
+
+ private static function parseExtDataBarElementChildrenFromXml(ConditionalDataBarExtension $extDataBarObj, SimpleXMLElement $dataBarXml, $ns): void
+ {
+ if ($dataBarXml->borderColor) {
+ $extDataBarObj->setBorderColor((string) $dataBarXml->borderColor->attributes()['rgb']);
+ }
+ if ($dataBarXml->negativeFillColor) {
+ $extDataBarObj->setNegativeFillColor((string) $dataBarXml->negativeFillColor->attributes()['rgb']);
+ }
+ if ($dataBarXml->negativeBorderColor) {
+ $extDataBarObj->setNegativeBorderColor((string) $dataBarXml->negativeBorderColor->attributes()['rgb']);
+ }
+ if ($dataBarXml->axisColor) {
+ $axisColorAttr = $dataBarXml->axisColor->attributes();
+ $extDataBarObj->setAxisColor((string) $axisColorAttr['rgb'], (string) $axisColorAttr['theme'], (string) $axisColorAttr['tint']);
+ }
+ $cfvoIndex = 0;
+ foreach ($dataBarXml->cfvo as $cfvo) {
+ $f = (string) $cfvo->children($ns['xm'])->f;
+ $attributes = $cfvo->attributes();
+ if (!($attributes)) {
+ continue;
+ }
+
+ if ($cfvoIndex === 0) {
+ $extDataBarObj->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $attributes['type'], null, (empty($f) ? null : $f)));
+ }
+ if ($cfvoIndex === 1) {
+ $extDataBarObj->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $attributes['type'], null, (empty($f) ? null : $f)));
+ }
+ ++$cfvoIndex;
+ }
+ }
+
+ /**
+ * @return mixed
+ */
+ public function getId()
+ {
+ return $this->id;
+ }
+
+ /**
+ * @param mixed $id
+ */
+ public function setId($id): self
+ {
+ $this->id = $id;
+
+ return $this;
+ }
+
+ public function getCfRule(): string
+ {
+ return $this->cfRule;
+ }
+
+ public function setCfRule(string $cfRule): self
+ {
+ $this->cfRule = $cfRule;
+
+ return $this;
+ }
+
+ public function getDataBarExt(): ConditionalDataBarExtension
+ {
+ return $this->dataBar;
+ }
+
+ public function setDataBarExt(ConditionalDataBarExtension $dataBar): self
+ {
+ $this->dataBar = $dataBar;
+
+ return $this;
+ }
+
+ public function getSqref(): string
+ {
+ return $this->sqref;
+ }
+
+ public function setSqref(string $sqref): self
+ {
+ $this->sqref = $sqref;
+
+ return $this;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Fill.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Fill.php
index 3891bc47378..bd87a792647 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Fill.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Fill.php
@@ -28,19 +28,19 @@ class Fill extends Supervisor
const FILL_PATTERN_MEDIUMGRAY = 'mediumGray';
/**
- * @var int
+ * @var null|int
*/
public $startcolorIndex;
/**
- * @var int
+ * @var null|int
*/
public $endcolorIndex;
/**
* Fill type.
*
- * @var string
+ * @var null|string
*/
protected $fillType = self::FILL_NONE;
@@ -49,7 +49,7 @@ class Fill extends Supervisor
*
* @var float
*/
- protected $rotation = 0;
+ protected $rotation = 0.0;
/**
* Start color.
@@ -65,6 +65,9 @@ class Fill extends Supervisor
*/
protected $endColor;
+ /** @var bool */
+ private $colorChanged = false;
+
/**
* Create a new Fill.
*
@@ -102,7 +105,10 @@ class Fill extends Supervisor
*/
public function getSharedComponent()
{
- return $this->parent->getSharedComponent()->getFill();
+ /** @var Style */
+ $parent = $this->parent;
+
+ return $parent->getSharedComponent()->getFill();
}
/**
@@ -124,7 +130,7 @@ class Fill extends Supervisor
* $spreadsheet->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray(
* [
* 'fillType' => Fill::FILL_GRADIENT_LINEAR,
- * 'rotation' => 0,
+ * 'rotation' => 0.0,
* 'startColor' => [
* 'rgb' => '000000'
* ],
@@ -135,30 +141,30 @@ class Fill extends Supervisor
* );
*
*
- * @param array $pStyles Array containing style information
+ * @param array $styleArray Array containing style information
*
* @return $this
*/
- public function applyFromArray(array $pStyles)
+ public function applyFromArray(array $styleArray)
{
if ($this->isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
- if (isset($pStyles['fillType'])) {
- $this->setFillType($pStyles['fillType']);
+ if (isset($styleArray['fillType'])) {
+ $this->setFillType($styleArray['fillType']);
}
- if (isset($pStyles['rotation'])) {
- $this->setRotation($pStyles['rotation']);
+ if (isset($styleArray['rotation'])) {
+ $this->setRotation($styleArray['rotation']);
}
- if (isset($pStyles['startColor'])) {
- $this->getStartColor()->applyFromArray($pStyles['startColor']);
+ if (isset($styleArray['startColor'])) {
+ $this->getStartColor()->applyFromArray($styleArray['startColor']);
}
- if (isset($pStyles['endColor'])) {
- $this->getEndColor()->applyFromArray($pStyles['endColor']);
+ if (isset($styleArray['endColor'])) {
+ $this->getEndColor()->applyFromArray($styleArray['endColor']);
}
- if (isset($pStyles['color'])) {
- $this->getStartColor()->applyFromArray($pStyles['color']);
- $this->getEndColor()->applyFromArray($pStyles['color']);
+ if (isset($styleArray['color'])) {
+ $this->getStartColor()->applyFromArray($styleArray['color']);
+ $this->getEndColor()->applyFromArray($styleArray['color']);
}
}
@@ -168,7 +174,7 @@ class Fill extends Supervisor
/**
* Get Fill Type.
*
- * @return string
+ * @return null|string
*/
public function getFillType()
{
@@ -182,17 +188,17 @@ class Fill extends Supervisor
/**
* Set Fill Type.
*
- * @param string $pValue Fill type, see self::FILL_*
+ * @param string $fillType Fill type, see self::FILL_*
*
* @return $this
*/
- public function setFillType($pValue)
+ public function setFillType($fillType)
{
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['fillType' => $pValue]);
+ $styleArray = $this->getStyleArray(['fillType' => $fillType]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->fillType = $pValue;
+ $this->fillType = $fillType;
}
return $this;
@@ -215,17 +221,17 @@ class Fill extends Supervisor
/**
* Set Rotation.
*
- * @param float $pValue
+ * @param float $angleInDegrees
*
* @return $this
*/
- public function setRotation($pValue)
+ public function setRotation($angleInDegrees)
{
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['rotation' => $pValue]);
+ $styleArray = $this->getStyleArray(['rotation' => $angleInDegrees]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->rotation = $pValue;
+ $this->rotation = $angleInDegrees;
}
return $this;
@@ -246,10 +252,11 @@ class Fill extends Supervisor
*
* @return $this
*/
- public function setStartColor(Color $pValue)
+ public function setStartColor(Color $color)
{
+ $this->colorChanged = true;
// make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+ $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) {
$styleArray = $this->getStartColor()->getStyleArray(['argb' => $color->getARGB()]);
@@ -276,10 +283,11 @@ class Fill extends Supervisor
*
* @return $this
*/
- public function setEndColor(Color $pValue)
+ public function setEndColor(Color $color)
{
+ $this->colorChanged = true;
// make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+ $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) {
$styleArray = $this->getEndColor()->getStyleArray(['argb' => $color->getARGB()]);
@@ -291,6 +299,17 @@ class Fill extends Supervisor
return $this;
}
+ public function getColorsChanged(): bool
+ {
+ if ($this->isSupervisor) {
+ $changed = $this->getSharedComponent()->colorChanged;
+ } else {
+ $changed = $this->colorChanged;
+ }
+
+ return $changed || $this->startColor->getHasChanged() || $this->endColor->getHasChanged();
+ }
+
/**
* Get hash code.
*
@@ -308,6 +327,7 @@ class Fill extends Supervisor
$this->getRotation() .
($this->getFillType() !== self::FILL_NONE ? $this->getStartColor()->getHashCode() : '') .
($this->getFillType() !== self::FILL_NONE ? $this->getEndColor()->getHashCode() : '') .
+ ((string) $this->getColorsChanged()) .
__CLASS__
);
}
@@ -315,10 +335,12 @@ class Fill extends Supervisor
protected function exportArray1(): array
{
$exportedArray = [];
- $this->exportArray2($exportedArray, 'endColor', $this->getEndColor());
$this->exportArray2($exportedArray, 'fillType', $this->getFillType());
$this->exportArray2($exportedArray, 'rotation', $this->getRotation());
- $this->exportArray2($exportedArray, 'startColor', $this->getStartColor());
+ if ($this->getColorsChanged()) {
+ $this->exportArray2($exportedArray, 'endColor', $this->getEndColor());
+ $this->exportArray2($exportedArray, 'startColor', $this->getStartColor());
+ }
return $exportedArray;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Font.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Font.php
index ad405708373..13fe2b67cdf 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Font.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Font.php
@@ -14,56 +14,56 @@ class Font extends Supervisor
/**
* Font Name.
*
- * @var string
+ * @var null|string
*/
protected $name = 'Calibri';
/**
* Font Size.
*
- * @var float
+ * @var null|float
*/
protected $size = 11;
/**
* Bold.
*
- * @var bool
+ * @var null|bool
*/
protected $bold = false;
/**
* Italic.
*
- * @var bool
+ * @var null|bool
*/
protected $italic = false;
/**
* Superscript.
*
- * @var bool
+ * @var null|bool
*/
protected $superscript = false;
/**
* Subscript.
*
- * @var bool
+ * @var null|bool
*/
protected $subscript = false;
/**
* Underline.
*
- * @var string
+ * @var null|string
*/
protected $underline = self::UNDERLINE_NONE;
/**
* Strikethrough.
*
- * @var bool
+ * @var null|bool
*/
protected $strikethrough = false;
@@ -75,7 +75,7 @@ class Font extends Supervisor
protected $color;
/**
- * @var int
+ * @var null|int
*/
public $colorIndex;
@@ -122,7 +122,10 @@ class Font extends Supervisor
*/
public function getSharedComponent()
{
- return $this->parent->getSharedComponent()->getFont();
+ /** @var Style */
+ $parent = $this->parent;
+
+ return $parent->getSharedComponent()->getFont();
}
/**
@@ -155,41 +158,41 @@ class Font extends Supervisor
* );
*
*
- * @param array $pStyles Array containing style information
+ * @param array $styleArray Array containing style information
*
* @return $this
*/
- public function applyFromArray(array $pStyles)
+ public function applyFromArray(array $styleArray)
{
if ($this->isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
- if (isset($pStyles['name'])) {
- $this->setName($pStyles['name']);
+ if (isset($styleArray['name'])) {
+ $this->setName($styleArray['name']);
}
- if (isset($pStyles['bold'])) {
- $this->setBold($pStyles['bold']);
+ if (isset($styleArray['bold'])) {
+ $this->setBold($styleArray['bold']);
}
- if (isset($pStyles['italic'])) {
- $this->setItalic($pStyles['italic']);
+ if (isset($styleArray['italic'])) {
+ $this->setItalic($styleArray['italic']);
}
- if (isset($pStyles['superscript'])) {
- $this->setSuperscript($pStyles['superscript']);
+ if (isset($styleArray['superscript'])) {
+ $this->setSuperscript($styleArray['superscript']);
}
- if (isset($pStyles['subscript'])) {
- $this->setSubscript($pStyles['subscript']);
+ if (isset($styleArray['subscript'])) {
+ $this->setSubscript($styleArray['subscript']);
}
- if (isset($pStyles['underline'])) {
- $this->setUnderline($pStyles['underline']);
+ if (isset($styleArray['underline'])) {
+ $this->setUnderline($styleArray['underline']);
}
- if (isset($pStyles['strikethrough'])) {
- $this->setStrikethrough($pStyles['strikethrough']);
+ if (isset($styleArray['strikethrough'])) {
+ $this->setStrikethrough($styleArray['strikethrough']);
}
- if (isset($pStyles['color'])) {
- $this->getColor()->applyFromArray($pStyles['color']);
+ if (isset($styleArray['color'])) {
+ $this->getColor()->applyFromArray($styleArray['color']);
}
- if (isset($pStyles['size'])) {
- $this->setSize($pStyles['size']);
+ if (isset($styleArray['size'])) {
+ $this->setSize($styleArray['size']);
}
}
@@ -199,7 +202,7 @@ class Font extends Supervisor
/**
* Get Name.
*
- * @return string
+ * @return null|string
*/
public function getName()
{
@@ -213,20 +216,20 @@ class Font extends Supervisor
/**
* Set Name.
*
- * @param string $pValue
+ * @param string $fontname
*
* @return $this
*/
- public function setName($pValue)
+ public function setName($fontname)
{
- if ($pValue == '') {
- $pValue = 'Calibri';
+ if ($fontname == '') {
+ $fontname = 'Calibri';
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['name' => $pValue]);
+ $styleArray = $this->getStyleArray(['name' => $fontname]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->name = $pValue;
+ $this->name = $fontname;
}
return $this;
@@ -235,7 +238,7 @@ class Font extends Supervisor
/**
* Get Size.
*
- * @return float
+ * @return null|float
*/
public function getSize()
{
@@ -249,20 +252,27 @@ class Font extends Supervisor
/**
* Set Size.
*
- * @param float $pValue
+ * @param mixed $sizeInPoints A float representing the value of a positive measurement in points (1/72 of an inch)
*
* @return $this
*/
- public function setSize($pValue)
+ public function setSize($sizeInPoints)
{
- if ($pValue == '') {
- $pValue = 10;
+ if (is_string($sizeInPoints) || is_int($sizeInPoints)) {
+ $sizeInPoints = (float) $sizeInPoints; // $pValue = 0 if given string is not numeric
}
+
+ // Size must be a positive floating point number
+ // ECMA-376-1:2016, part 1, chapter 18.4.11 sz (Font Size), p. 1536
+ if (!is_float($sizeInPoints) || !($sizeInPoints > 0)) {
+ $sizeInPoints = 10.0;
+ }
+
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['size' => $pValue]);
+ $styleArray = $this->getStyleArray(['size' => $sizeInPoints]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->size = $pValue;
+ $this->size = $sizeInPoints;
}
return $this;
@@ -271,7 +281,7 @@ class Font extends Supervisor
/**
* Get Bold.
*
- * @return bool
+ * @return null|bool
*/
public function getBold()
{
@@ -285,20 +295,20 @@ class Font extends Supervisor
/**
* Set Bold.
*
- * @param bool $pValue
+ * @param bool $bold
*
* @return $this
*/
- public function setBold($pValue)
+ public function setBold($bold)
{
- if ($pValue == '') {
- $pValue = false;
+ if ($bold == '') {
+ $bold = false;
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['bold' => $pValue]);
+ $styleArray = $this->getStyleArray(['bold' => $bold]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->bold = $pValue;
+ $this->bold = $bold;
}
return $this;
@@ -307,7 +317,7 @@ class Font extends Supervisor
/**
* Get Italic.
*
- * @return bool
+ * @return null|bool
*/
public function getItalic()
{
@@ -321,20 +331,20 @@ class Font extends Supervisor
/**
* Set Italic.
*
- * @param bool $pValue
+ * @param bool $italic
*
* @return $this
*/
- public function setItalic($pValue)
+ public function setItalic($italic)
{
- if ($pValue == '') {
- $pValue = false;
+ if ($italic == '') {
+ $italic = false;
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['italic' => $pValue]);
+ $styleArray = $this->getStyleArray(['italic' => $italic]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->italic = $pValue;
+ $this->italic = $italic;
}
return $this;
@@ -343,7 +353,7 @@ class Font extends Supervisor
/**
* Get Superscript.
*
- * @return bool
+ * @return null|bool
*/
public function getSuperscript()
{
@@ -359,13 +369,13 @@ class Font extends Supervisor
*
* @return $this
*/
- public function setSuperscript(bool $pValue)
+ public function setSuperscript(bool $superscript)
{
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['superscript' => $pValue]);
+ $styleArray = $this->getStyleArray(['superscript' => $superscript]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->superscript = $pValue;
+ $this->superscript = $superscript;
if ($this->superscript) {
$this->subscript = false;
}
@@ -377,7 +387,7 @@ class Font extends Supervisor
/**
* Get Subscript.
*
- * @return bool
+ * @return null|bool
*/
public function getSubscript()
{
@@ -393,13 +403,13 @@ class Font extends Supervisor
*
* @return $this
*/
- public function setSubscript(bool $pValue)
+ public function setSubscript(bool $subscript)
{
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['subscript' => $pValue]);
+ $styleArray = $this->getStyleArray(['subscript' => $subscript]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->subscript = $pValue;
+ $this->subscript = $subscript;
if ($this->subscript) {
$this->superscript = false;
}
@@ -411,7 +421,7 @@ class Font extends Supervisor
/**
* Get Underline.
*
- * @return string
+ * @return null|string
*/
public function getUnderline()
{
@@ -425,24 +435,24 @@ class Font extends Supervisor
/**
* Set Underline.
*
- * @param bool|string $pValue \PhpOffice\PhpSpreadsheet\Style\Font underline type
+ * @param bool|string $underlineStyle \PhpOffice\PhpSpreadsheet\Style\Font underline type
* If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE,
* false equates to UNDERLINE_NONE
*
* @return $this
*/
- public function setUnderline($pValue)
+ public function setUnderline($underlineStyle)
{
- if (is_bool($pValue)) {
- $pValue = ($pValue) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE;
- } elseif ($pValue == '') {
- $pValue = self::UNDERLINE_NONE;
+ if (is_bool($underlineStyle)) {
+ $underlineStyle = ($underlineStyle) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE;
+ } elseif ($underlineStyle == '') {
+ $underlineStyle = self::UNDERLINE_NONE;
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['underline' => $pValue]);
+ $styleArray = $this->getStyleArray(['underline' => $underlineStyle]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->underline = $pValue;
+ $this->underline = $underlineStyle;
}
return $this;
@@ -451,7 +461,7 @@ class Font extends Supervisor
/**
* Get Strikethrough.
*
- * @return bool
+ * @return null|bool
*/
public function getStrikethrough()
{
@@ -465,21 +475,21 @@ class Font extends Supervisor
/**
* Set Strikethrough.
*
- * @param bool $pValue
+ * @param bool $strikethru
*
* @return $this
*/
- public function setStrikethrough($pValue)
+ public function setStrikethrough($strikethru)
{
- if ($pValue == '') {
- $pValue = false;
+ if ($strikethru == '') {
+ $strikethru = false;
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['strikethrough' => $pValue]);
+ $styleArray = $this->getStyleArray(['strikethrough' => $strikethru]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->strikethrough = $pValue;
+ $this->strikethrough = $strikethru;
}
return $this;
@@ -500,10 +510,10 @@ class Font extends Supervisor
*
* @return $this
*/
- public function setColor(Color $pValue)
+ public function setColor(Color $color)
{
// make sure parameter is a real color and not a supervisor
- $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue;
+ $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) {
$styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat.php
index 0b761bd3c3e..536b1d54db1 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat.php
@@ -2,10 +2,6 @@
namespace PhpOffice\PhpSpreadsheet\Style;
-use PhpOffice\PhpSpreadsheet\Calculation\MathTrig;
-use PhpOffice\PhpSpreadsheet\Shared\Date;
-use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
-
class NumberFormat extends Supervisor
{
// Pre-defined formats
@@ -68,14 +64,14 @@ class NumberFormat extends Supervisor
/**
* Format Code.
*
- * @var string
+ * @var null|string
*/
protected $formatCode = self::FORMAT_GENERAL;
/**
* Built-in format Code.
*
- * @var string
+ * @var false|int
*/
protected $builtInFormatCode = 0;
@@ -108,7 +104,10 @@ class NumberFormat extends Supervisor
*/
public function getSharedComponent()
{
- return $this->parent->getSharedComponent()->getNumberFormat();
+ /** @var Style */
+ $parent = $this->parent;
+
+ return $parent->getSharedComponent()->getNumberFormat();
}
/**
@@ -134,17 +133,17 @@ class NumberFormat extends Supervisor
* );
*
*
- * @param array $pStyles Array containing style information
+ * @param array $styleArray Array containing style information
*
* @return $this
*/
- public function applyFromArray(array $pStyles)
+ public function applyFromArray(array $styleArray)
{
if ($this->isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
- if (isset($pStyles['formatCode'])) {
- $this->setFormatCode($pStyles['formatCode']);
+ if (isset($styleArray['formatCode'])) {
+ $this->setFormatCode($styleArray['formatCode']);
}
}
@@ -154,14 +153,14 @@ class NumberFormat extends Supervisor
/**
* Get Format Code.
*
- * @return string
+ * @return null|string
*/
public function getFormatCode()
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getFormatCode();
}
- if ($this->builtInFormatCode !== false) {
+ if (is_int($this->builtInFormatCode)) {
return self::builtInFormatCode($this->builtInFormatCode);
}
@@ -171,21 +170,21 @@ class NumberFormat extends Supervisor
/**
* Set Format Code.
*
- * @param string $pValue see self::FORMAT_*
+ * @param string $formatCode see self::FORMAT_*
*
* @return $this
*/
- public function setFormatCode($pValue)
+ public function setFormatCode($formatCode)
{
- if ($pValue == '') {
- $pValue = self::FORMAT_GENERAL;
+ if ($formatCode == '') {
+ $formatCode = self::FORMAT_GENERAL;
}
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['formatCode' => $pValue]);
+ $styleArray = $this->getStyleArray(['formatCode' => $formatCode]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->formatCode = $pValue;
- $this->builtInFormatCode = self::builtInFormatCodeIndex($pValue);
+ $this->formatCode = $formatCode;
+ $this->builtInFormatCode = self::builtInFormatCodeIndex($formatCode);
}
return $this;
@@ -194,7 +193,7 @@ class NumberFormat extends Supervisor
/**
* Get Built-In Format Code.
*
- * @return int
+ * @return false|int
*/
public function getBuiltInFormatCode()
{
@@ -208,18 +207,18 @@ class NumberFormat extends Supervisor
/**
* Set Built-In Format Code.
*
- * @param int $pValue
+ * @param int $formatCodeIndex
*
* @return $this
*/
- public function setBuiltInFormatCode($pValue)
+ public function setBuiltInFormatCode($formatCodeIndex)
{
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($pValue)]);
+ $styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($formatCodeIndex)]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->builtInFormatCode = $pValue;
- $this->formatCode = self::builtInFormatCode($pValue);
+ $this->builtInFormatCode = $formatCodeIndex;
+ $this->formatCode = self::builtInFormatCode($formatCodeIndex);
}
return $this;
@@ -331,21 +330,21 @@ class NumberFormat extends Supervisor
/**
* Get built-in format code.
*
- * @param int $pIndex
+ * @param int $index
*
* @return string
*/
- public static function builtInFormatCode($pIndex)
+ public static function builtInFormatCode($index)
{
// Clean parameter
- $pIndex = (int) $pIndex;
+ $index = (int) $index;
// Ensure built-in format codes are available
self::fillBuiltInFormatCodes();
// Lookup format code
- if (isset(self::$builtInFormats[$pIndex])) {
- return self::$builtInFormats[$pIndex];
+ if (isset(self::$builtInFormats[$index])) {
+ return self::$builtInFormats[$index];
}
return '';
@@ -354,18 +353,18 @@ class NumberFormat extends Supervisor
/**
* Get built-in format code index.
*
- * @param string $formatCode
+ * @param string $formatCodeIndex
*
- * @return bool|int
+ * @return false|int
*/
- public static function builtInFormatCodeIndex($formatCode)
+ public static function builtInFormatCodeIndex($formatCodeIndex)
{
// Ensure built-in format codes are available
self::fillBuiltInFormatCodes();
// Lookup format code
- if (array_key_exists($formatCode, self::$flippedBuiltInFormats)) {
- return self::$flippedBuiltInFormats[$formatCode];
+ if (array_key_exists($formatCodeIndex, self::$flippedBuiltInFormats)) {
+ return self::$flippedBuiltInFormats[$formatCodeIndex];
}
return false;
@@ -389,428 +388,6 @@ class NumberFormat extends Supervisor
);
}
- /**
- * Search/replace values to convert Excel date/time format masks to PHP format masks.
- *
- * @var array
- */
- private static $dateFormatReplacements = [
- // first remove escapes related to non-format characters
- '\\' => '',
- // 12-hour suffix
- 'am/pm' => 'A',
- // 4-digit year
- 'e' => 'Y',
- 'yyyy' => 'Y',
- // 2-digit year
- 'yy' => 'y',
- // first letter of month - no php equivalent
- 'mmmmm' => 'M',
- // full month name
- 'mmmm' => 'F',
- // short month name
- 'mmm' => 'M',
- // mm is minutes if time, but can also be month w/leading zero
- // so we try to identify times be the inclusion of a : separator in the mask
- // It isn't perfect, but the best way I know how
- ':mm' => ':i',
- 'mm:' => 'i:',
- // month leading zero
- 'mm' => 'm',
- // month no leading zero
- 'm' => 'n',
- // full day of week name
- 'dddd' => 'l',
- // short day of week name
- 'ddd' => 'D',
- // days leading zero
- 'dd' => 'd',
- // days no leading zero
- 'd' => 'j',
- // seconds
- 'ss' => 's',
- // fractional seconds - no php equivalent
- '.s' => '',
- ];
-
- /**
- * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock).
- *
- * @var array
- */
- private static $dateFormatReplacements24 = [
- 'hh' => 'H',
- 'h' => 'G',
- ];
-
- /**
- * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock).
- *
- * @var array
- */
- private static $dateFormatReplacements12 = [
- 'hh' => 'h',
- 'h' => 'g',
- ];
-
- private static function setLowercaseCallback($matches)
- {
- return mb_strtolower($matches[0]);
- }
-
- private static function escapeQuotesCallback($matches)
- {
- return '\\' . implode('\\', str_split($matches[1]));
- }
-
- private static function formatAsDate(&$value, &$format): void
- {
- // strip off first part containing e.g. [$-F800] or [$USD-409]
- // general syntax: [$-]
- // language info is in hexadecimal
- // strip off chinese part like [DBNum1][$-804]
- $format = preg_replace('/^(\[[0-9A-Za-z]*\])*(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $format);
-
- // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case;
- // but we don't want to change any quoted strings
- $format = preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', ['self', 'setLowercaseCallback'], $format);
-
- // Only process the non-quoted blocks for date format characters
- $blocks = explode('"', $format);
- foreach ($blocks as $key => &$block) {
- if ($key % 2 == 0) {
- $block = strtr($block, self::$dateFormatReplacements);
- if (!strpos($block, 'A')) {
- // 24-hour time format
- // when [h]:mm format, the [h] should replace to the hours of the value * 24
- if (false !== strpos($block, '[h]')) {
- $hours = (int) ($value * 24);
- $block = str_replace('[h]', $hours, $block);
-
- continue;
- }
- $block = strtr($block, self::$dateFormatReplacements24);
- } else {
- // 12-hour time format
- $block = strtr($block, self::$dateFormatReplacements12);
- }
- }
- }
- $format = implode('"', $blocks);
-
- // escape any quoted characters so that DateTime format() will render them correctly
- $format = preg_replace_callback('/"(.*)"/U', ['self', 'escapeQuotesCallback'], $format);
-
- $dateObj = Date::excelToDateTimeObject($value);
- $value = $dateObj->format($format);
- }
-
- private static function formatAsPercentage(&$value, &$format): void
- {
- if ($format === self::FORMAT_PERCENTAGE) {
- $value = round((100 * $value), 0) . '%';
- } else {
- if (preg_match('/\.[#0]+/', $format, $m)) {
- $s = substr($m[0], 0, 1) . (strlen($m[0]) - 1);
- $format = str_replace($m[0], $s, $format);
- }
- if (preg_match('/^[#0]+/', $format, $m)) {
- $format = str_replace($m[0], strlen($m[0]), $format);
- }
- $format = '%' . str_replace('%', 'f%%', $format);
-
- $value = sprintf($format, 100 * $value);
- }
- }
-
- private static function formatAsFraction(&$value, &$format): void
- {
- $sign = ($value < 0) ? '-' : '';
-
- $integerPart = floor(abs($value));
- $decimalPart = trim(fmod(abs($value), 1), '0.');
- $decimalLength = strlen($decimalPart);
- $decimalDivisor = 10 ** $decimalLength;
-
- $GCD = MathTrig::GCD($decimalPart, $decimalDivisor);
-
- $adjustedDecimalPart = $decimalPart / $GCD;
- $adjustedDecimalDivisor = $decimalDivisor / $GCD;
-
- if ((strpos($format, '0') !== false)) {
- $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor";
- } elseif ((strpos($format, '#') !== false)) {
- if ($integerPart == 0) {
- $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor";
- } else {
- $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor";
- }
- } elseif ((substr($format, 0, 3) == '? ?')) {
- if ($integerPart == 0) {
- $integerPart = '';
- }
- $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor";
- } else {
- $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor;
- $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor";
- }
- }
-
- private static function mergeComplexNumberFormatMasks($numbers, $masks)
- {
- $decimalCount = strlen($numbers[1]);
- $postDecimalMasks = [];
-
- do {
- $tempMask = array_pop($masks);
- $postDecimalMasks[] = $tempMask;
- $decimalCount -= strlen($tempMask);
- } while ($decimalCount > 0);
-
- return [
- implode('.', $masks),
- implode('.', array_reverse($postDecimalMasks)),
- ];
- }
-
- private static function processComplexNumberFormatMask($number, $mask)
- {
- $result = $number;
- $maskingBlockCount = preg_match_all('/0+/', $mask, $maskingBlocks, PREG_OFFSET_CAPTURE);
-
- if ($maskingBlockCount > 1) {
- $maskingBlocks = array_reverse($maskingBlocks[0]);
-
- foreach ($maskingBlocks as $block) {
- $divisor = 1 . $block[0];
- $size = strlen($block[0]);
- $offset = $block[1];
-
- $blockValue = sprintf(
- '%0' . $size . 'd',
- fmod($number, $divisor)
- );
- $number = floor($number / $divisor);
- $mask = substr_replace($mask, $blockValue, $offset, $size);
- }
- if ($number > 0) {
- $mask = substr_replace($mask, $number, $offset, 0);
- }
- $result = $mask;
- }
-
- return $result;
- }
-
- private static function complexNumberFormatMask($number, $mask, $splitOnPoint = true)
- {
- $sign = ($number < 0.0);
- $number = abs($number);
-
- if ($splitOnPoint && strpos($mask, '.') !== false && strpos($number, '.') !== false) {
- $numbers = explode('.', $number);
- $masks = explode('.', $mask);
- if (count($masks) > 2) {
- $masks = self::mergeComplexNumberFormatMasks($numbers, $masks);
- }
- $result1 = self::complexNumberFormatMask($numbers[0], $masks[0], false);
- $result2 = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), false));
-
- return (($sign) ? '-' : '') . $result1 . '.' . $result2;
- }
-
- $result = self::processComplexNumberFormatMask($number, $mask);
-
- return (($sign) ? '-' : '') . $result;
- }
-
- private static function formatStraightNumericValue($value, $format, array $matches, $useThousands, $number_regex)
- {
- $left = $matches[1];
- $dec = $matches[2];
- $right = $matches[3];
-
- // minimun width of formatted number (including dot)
- $minWidth = strlen($left) + strlen($dec) + strlen($right);
- if ($useThousands) {
- $value = number_format(
- $value,
- strlen($right),
- StringHelper::getDecimalSeparator(),
- StringHelper::getThousandsSeparator()
- );
- $value = preg_replace($number_regex, $value, $format);
- } else {
- if (preg_match('/[0#]E[+-]0/i', $format)) {
- // Scientific format
- $value = sprintf('%5.2E', $value);
- } elseif (preg_match('/0([^\d\.]+)0/', $format) || substr_count($format, '.') > 1) {
- if ($value == (int) $value && substr_count($format, '.') === 1) {
- $value *= 10 ** strlen(explode('.', $format)[1]);
- }
- $value = self::complexNumberFormatMask($value, $format);
- } else {
- $sprintf_pattern = "%0$minWidth." . strlen($right) . 'f';
- $value = sprintf($sprintf_pattern, $value);
- $value = preg_replace($number_regex, $value, $format);
- }
- }
-
- return $value;
- }
-
- private static function formatAsNumber($value, $format)
- {
- // The "_" in this string has already been stripped out,
- // so this test is never true. Furthermore, testing
- // on Excel shows this format uses Euro symbol, not "EUR".
- //if ($format === self::FORMAT_CURRENCY_EUR_SIMPLE) {
- // return 'EUR ' . sprintf('%1.2f', $value);
- //}
-
- // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols
- $format = str_replace(['"', '*'], '', $format);
-
- // Find out if we need thousands separator
- // This is indicated by a comma enclosed by a digit placeholder:
- // #,# or 0,0
- $useThousands = preg_match('/(#,#|0,0)/', $format);
- if ($useThousands) {
- $format = preg_replace('/0,0/', '00', $format);
- $format = preg_replace('/#,#/', '##', $format);
- }
-
- // Scale thousands, millions,...
- // This is indicated by a number of commas after a digit placeholder:
- // #, or 0.0,,
- $scale = 1; // same as no scale
- $matches = [];
- if (preg_match('/(#|0)(,+)/', $format, $matches)) {
- $scale = 1000 ** strlen($matches[2]);
-
- // strip the commas
- $format = preg_replace('/0,+/', '0', $format);
- $format = preg_replace('/#,+/', '#', $format);
- }
-
- if (preg_match('/#?.*\?\/\?/', $format, $m)) {
- if ($value != (int) $value) {
- self::formatAsFraction($value, $format);
- }
- } else {
- // Handle the number itself
-
- // scale number
- $value = $value / $scale;
- // Strip #
- $format = preg_replace('/\\#/', '0', $format);
- // Remove locale code [$-###]
- $format = preg_replace('/\[\$\-.*\]/', '', $format);
-
- $n = '/\\[[^\\]]+\\]/';
- $m = preg_replace($n, '', $format);
- $number_regex = '/(0+)(\\.?)(0*)/';
- if (preg_match($number_regex, $m, $matches)) {
- $value = self::formatStraightNumericValue($value, $format, $matches, $useThousands, $number_regex);
- }
- }
-
- if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
- // Currency or Accounting
- $currencyCode = $m[1];
- [$currencyCode] = explode('-', $currencyCode);
- if ($currencyCode == '') {
- $currencyCode = StringHelper::getCurrencyCode();
- }
- $value = preg_replace('/\[\$([^\]]*)\]/u', $currencyCode, $value);
- }
-
- return $value;
- }
-
- private static function splitFormatCompare($value, $cond, $val, $dfcond, $dfval)
- {
- if (!$cond) {
- $cond = $dfcond;
- $val = $dfval;
- }
- switch ($cond) {
- case '>':
- return $value > $val;
-
- case '<':
- return $value < $val;
-
- case '<=':
- return $value <= $val;
-
- case '<>':
- return $value != $val;
-
- case '=':
- return $value == $val;
- }
-
- return $value >= $val;
- }
-
- private static function splitFormat($sections, $value)
- {
- // Extract the relevant section depending on whether number is positive, negative, or zero?
- // Text not supported yet.
- // Here is how the sections apply to various values in Excel:
- // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT]
- // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE]
- // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO]
- // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT]
- $cnt = count($sections);
- $color_regex = '/\\[(' . implode('|', Color::NAMED_COLORS) . ')\\]/';
- $cond_regex = '/\\[(>|>=|<|<=|=|<>)([+-]?\\d+([.]\\d+)?)\\]/';
- $colors = ['', '', '', '', ''];
- $condops = ['', '', '', '', ''];
- $condvals = [0, 0, 0, 0, 0];
- for ($idx = 0; $idx < $cnt; ++$idx) {
- if (preg_match($color_regex, $sections[$idx], $matches)) {
- $colors[$idx] = $matches[0];
- $sections[$idx] = preg_replace($color_regex, '', $sections[$idx]);
- }
- if (preg_match($cond_regex, $sections[$idx], $matches)) {
- $condops[$idx] = $matches[1];
- $condvals[$idx] = $matches[2];
- $sections[$idx] = preg_replace($cond_regex, '', $sections[$idx]);
- }
- }
- $color = $colors[0];
- $format = $sections[0];
- $absval = $value;
- switch ($cnt) {
- case 2:
- $absval = abs($value);
- if (!self::splitFormatCompare($value, $condops[0], $condvals[0], '>=', 0)) {
- $color = $colors[1];
- $format = $sections[1];
- }
-
- break;
- case 3:
- case 4:
- $absval = abs($value);
- if (!self::splitFormatCompare($value, $condops[0], $condvals[0], '>', 0)) {
- if (self::splitFormatCompare($value, $condops[1], $condvals[1], '<', 0)) {
- $color = $colors[1];
- $format = $sections[1];
- } else {
- $color = $colors[2];
- $format = $sections[2];
- }
- }
-
- break;
- }
-
- return [$color, $format, $absval];
- }
-
/**
* Convert a value in a pre-defined format to a PHP string.
*
@@ -822,53 +399,7 @@ class NumberFormat extends Supervisor
*/
public static function toFormattedString($value, $format, $callBack = null)
{
- // For now we do not treat strings although section 4 of a format code affects strings
- if (!is_numeric($value)) {
- return $value;
- }
-
- // For 'General' format code, we just pass the value although this is not entirely the way Excel does it,
- // it seems to round numbers to a total of 10 digits.
- if (($format === self::FORMAT_GENERAL) || ($format === self::FORMAT_TEXT)) {
- return $value;
- }
-
- // Convert any other escaped characters to quoted strings, e.g. (\T to "T")
- $format = preg_replace('/(\\\(((.)(?!((AM\/PM)|(A\/P))))|([^ ])))(?=(?:[^"]|"[^"]*")*$)/u', '"${2}"', $format);
-
- // Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal)
- $sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format);
-
- [$colors, $format, $value] = self::splitFormat($sections, $value);
-
- // In Excel formats, "_" is used to add spacing,
- // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space
- $format = preg_replace('/_./', ' ', $format);
-
- // Let's begin inspecting the format and converting the value to a formatted string
-
- // Check for date/time characters (not inside quotes)
- if (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format, $matches)) {
- // datetime format
- self::formatAsDate($value, $format);
- } else {
- if (substr($format, 0, 1) === '"' && substr($format, -1, 1) === '"') {
- $value = substr($format, 1, -1);
- } elseif (preg_match('/%$/', $format)) {
- // % number format
- self::formatAsPercentage($value, $format);
- } else {
- $value = self::formatAsNumber($value, $format);
- }
- }
-
- // Additional formatting provided by callback function
- if ($callBack !== null) {
- [$writerInstance, $function] = $callBack;
- $value = $writerInstance->$function($value, $colors);
- }
-
- return $value;
+ return NumberFormat\Formatter::toFormattedString($value, $format, $callBack);
}
protected function exportArray1(): array
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php
new file mode 100644
index 00000000000..7988143c510
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php
@@ -0,0 +1,12 @@
+ '',
+ // 12-hour suffix
+ 'am/pm' => 'A',
+ // 4-digit year
+ 'e' => 'Y',
+ 'yyyy' => 'Y',
+ // 2-digit year
+ 'yy' => 'y',
+ // first letter of month - no php equivalent
+ 'mmmmm' => 'M',
+ // full month name
+ 'mmmm' => 'F',
+ // short month name
+ 'mmm' => 'M',
+ // mm is minutes if time, but can also be month w/leading zero
+ // so we try to identify times be the inclusion of a : separator in the mask
+ // It isn't perfect, but the best way I know how
+ ':mm' => ':i',
+ 'mm:' => 'i:',
+ // month leading zero
+ 'mm' => 'm',
+ // month no leading zero
+ 'm' => 'n',
+ // full day of week name
+ 'dddd' => 'l',
+ // short day of week name
+ 'ddd' => 'D',
+ // days leading zero
+ 'dd' => 'd',
+ // days no leading zero
+ 'd' => 'j',
+ // seconds
+ 'ss' => 's',
+ // fractional seconds - no php equivalent
+ '.s' => '',
+ ];
+
+ /**
+ * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock).
+ *
+ * @var array
+ */
+ private static $dateFormatReplacements24 = [
+ 'hh' => 'H',
+ 'h' => 'G',
+ ];
+
+ /**
+ * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock).
+ *
+ * @var array
+ */
+ private static $dateFormatReplacements12 = [
+ 'hh' => 'h',
+ 'h' => 'g',
+ ];
+
+ public static function format($value, string $format): string
+ {
+ // strip off first part containing e.g. [$-F800] or [$USD-409]
+ // general syntax: [$-]
+ // language info is in hexadecimal
+ // strip off chinese part like [DBNum1][$-804]
+ $format = preg_replace('/^(\[DBNum\d\])*(\[\$[^\]]*\])/i', '', $format);
+
+ // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case;
+ // but we don't want to change any quoted strings
+ $format = preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', ['self', 'setLowercaseCallback'], $format);
+
+ // Only process the non-quoted blocks for date format characters
+ $blocks = explode('"', $format);
+ foreach ($blocks as $key => &$block) {
+ if ($key % 2 == 0) {
+ $block = strtr($block, self::$dateFormatReplacements);
+ if (!strpos($block, 'A')) {
+ // 24-hour time format
+ // when [h]:mm format, the [h] should replace to the hours of the value * 24
+ if (false !== strpos($block, '[h]')) {
+ $hours = (int) ($value * 24);
+ $block = str_replace('[h]', $hours, $block);
+
+ continue;
+ }
+ $block = strtr($block, self::$dateFormatReplacements24);
+ } else {
+ // 12-hour time format
+ $block = strtr($block, self::$dateFormatReplacements12);
+ }
+ }
+ }
+ $format = implode('"', $blocks);
+
+ // escape any quoted characters so that DateTime format() will render them correctly
+ $format = preg_replace_callback('/"(.*)"/U', ['self', 'escapeQuotesCallback'], $format);
+
+ $dateObj = Date::excelToDateTimeObject($value);
+ // If the colon preceding minute had been quoted, as happens in
+ // Excel 2003 XML formats, m will not have been changed to i above.
+ // Change it now.
+ $format = \preg_replace('/\\\\:m/', ':i', $format);
+
+ return $dateObj->format($format);
+ }
+
+ private static function setLowercaseCallback($matches): string
+ {
+ return mb_strtolower($matches[0]);
+ }
+
+ private static function escapeQuotesCallback($matches): string
+ {
+ return '\\' . implode('\\', str_split($matches[1]));
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php
new file mode 100644
index 00000000000..01407e64232
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php
@@ -0,0 +1,162 @@
+':
+ return $value > $val;
+
+ case '<':
+ return $value < $val;
+
+ case '<=':
+ return $value <= $val;
+
+ case '<>':
+ return $value != $val;
+
+ case '=':
+ return $value == $val;
+ }
+
+ return $value >= $val;
+ }
+
+ private static function splitFormat($sections, $value)
+ {
+ // Extract the relevant section depending on whether number is positive, negative, or zero?
+ // Text not supported yet.
+ // Here is how the sections apply to various values in Excel:
+ // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT]
+ // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE]
+ // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO]
+ // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT]
+ $cnt = count($sections);
+ $color_regex = '/\\[(' . implode('|', Color::NAMED_COLORS) . ')\\]/mui';
+ $cond_regex = '/\\[(>|>=|<|<=|=|<>)([+-]?\\d+([.]\\d+)?)\\]/';
+ $colors = ['', '', '', '', ''];
+ $condops = ['', '', '', '', ''];
+ $condvals = [0, 0, 0, 0, 0];
+ for ($idx = 0; $idx < $cnt; ++$idx) {
+ if (preg_match($color_regex, $sections[$idx], $matches)) {
+ $colors[$idx] = $matches[0];
+ $sections[$idx] = preg_replace($color_regex, '', $sections[$idx]);
+ }
+ if (preg_match($cond_regex, $sections[$idx], $matches)) {
+ $condops[$idx] = $matches[1];
+ $condvals[$idx] = $matches[2];
+ $sections[$idx] = preg_replace($cond_regex, '', $sections[$idx]);
+ }
+ }
+ $color = $colors[0];
+ $format = $sections[0];
+ $absval = $value;
+ switch ($cnt) {
+ case 2:
+ $absval = abs($value);
+ if (!self::splitFormatCompare($value, $condops[0], $condvals[0], '>=', 0)) {
+ $color = $colors[1];
+ $format = $sections[1];
+ }
+
+ break;
+ case 3:
+ case 4:
+ $absval = abs($value);
+ if (!self::splitFormatCompare($value, $condops[0], $condvals[0], '>', 0)) {
+ if (self::splitFormatCompare($value, $condops[1], $condvals[1], '<', 0)) {
+ $color = $colors[1];
+ $format = $sections[1];
+ } else {
+ $color = $colors[2];
+ $format = $sections[2];
+ }
+ }
+
+ break;
+ }
+
+ return [$color, $format, $absval];
+ }
+
+ /**
+ * Convert a value in a pre-defined format to a PHP string.
+ *
+ * @param mixed $value Value to format
+ * @param string $format Format code, see = NumberFormat::FORMAT_*
+ * @param array $callBack Callback function for additional formatting of string
+ *
+ * @return string Formatted string
+ */
+ public static function toFormattedString($value, $format, $callBack = null)
+ {
+ // For now we do not treat strings although section 4 of a format code affects strings
+ if (!is_numeric($value)) {
+ return $value;
+ }
+
+ // For 'General' format code, we just pass the value although this is not entirely the way Excel does it,
+ // it seems to round numbers to a total of 10 digits.
+ if (($format === NumberFormat::FORMAT_GENERAL) || ($format === NumberFormat::FORMAT_TEXT)) {
+ return $value;
+ }
+
+ $format = preg_replace_callback(
+ '/(["])(?:(?=(\\\\?))\\2.)*?\\1/u',
+ function ($matches) {
+ return str_replace('.', chr(0x00), $matches[0]);
+ },
+ $format
+ );
+
+ // Convert any other escaped characters to quoted strings, e.g. (\T to "T")
+ $format = preg_replace('/(\\\(((.)(?!((AM\/PM)|(A\/P))))|([^ ])))(?=(?:[^"]|"[^"]*")*$)/ui', '"${2}"', $format);
+
+ // Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal)
+ $sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format);
+
+ [$colors, $format, $value] = self::splitFormat($sections, $value);
+
+ // In Excel formats, "_" is used to add spacing,
+ // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space
+ $format = preg_replace('/_.?/ui', ' ', $format);
+
+ // Let's begin inspecting the format and converting the value to a formatted string
+
+ // Check for date/time characters (not inside quotes)
+ if (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format, $matches)) {
+ // datetime format
+ $value = DateFormatter::format($value, $format);
+ } else {
+ if (substr($format, 0, 1) === '"' && substr($format, -1, 1) === '"' && substr_count($format, '"') === 2) {
+ $value = substr($format, 1, -1);
+ } elseif (preg_match('/[0#, ]%/', $format)) {
+ // % number format
+ $value = PercentageFormatter::format($value, $format);
+ } else {
+ $value = NumberFormatter::format($value, $format);
+ }
+ }
+
+ // Additional formatting provided by callback function
+ if ($callBack !== null) {
+ [$writerInstance, $function] = $callBack;
+ $value = $writerInstance->$function($value, $colors);
+ }
+
+ $value = str_replace(chr(0x00), '.', $value);
+
+ return $value;
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php
new file mode 100644
index 00000000000..46f27cc33ff
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php
@@ -0,0 +1,64 @@
+ 0);
+
+ return [
+ implode('.', $masks),
+ implode('.', array_reverse($postDecimalMasks)),
+ ];
+ }
+
+ /**
+ * @param mixed $number
+ */
+ private static function processComplexNumberFormatMask($number, string $mask): string
+ {
+ /** @var string */
+ $result = $number;
+ $maskingBlockCount = preg_match_all('/0+/', $mask, $maskingBlocks, PREG_OFFSET_CAPTURE);
+
+ if ($maskingBlockCount > 1) {
+ $maskingBlocks = array_reverse($maskingBlocks[0]);
+
+ $offset = 0;
+ foreach ($maskingBlocks as $block) {
+ $size = strlen($block[0]);
+ $divisor = 10 ** $size;
+ $offset = $block[1];
+
+ /** @var float */
+ $numberFloat = $number;
+ $blockValue = sprintf("%0{$size}d", fmod($numberFloat, $divisor));
+ $number = floor($numberFloat / $divisor);
+ $mask = substr_replace($mask, $blockValue, $offset, $size);
+ }
+ /** @var string */
+ $numberString = $number;
+ if ($number > 0) {
+ $mask = substr_replace($mask, $numberString, $offset, 0);
+ }
+ $result = $mask;
+ }
+
+ return self::makeString($result);
+ }
+
+ /**
+ * @param mixed $number
+ */
+ private static function complexNumberFormatMask($number, string $mask, bool $splitOnPoint = true): string
+ {
+ $sign = ($number < 0.0) ? '-' : '';
+ /** @var float */
+ $numberFloat = $number;
+ $number = (string) abs($numberFloat);
+
+ if ($splitOnPoint && strpos($mask, '.') !== false && strpos($number, '.') !== false) {
+ $numbers = explode('.', $number);
+ $masks = explode('.', $mask);
+ if (count($masks) > 2) {
+ $masks = self::mergeComplexNumberFormatMasks($numbers, $masks);
+ }
+ $integerPart = self::complexNumberFormatMask($numbers[0], $masks[0], false);
+ $decimalPart = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), false));
+
+ return "{$sign}{$integerPart}.{$decimalPart}";
+ }
+
+ $result = self::processComplexNumberFormatMask($number, $mask);
+
+ return "{$sign}{$result}";
+ }
+
+ /**
+ * @param mixed $value
+ */
+ private static function formatStraightNumericValue($value, string $format, array $matches, bool $useThousands): string
+ {
+ /** @var float */
+ $valueFloat = $value;
+ $left = $matches[1];
+ $dec = $matches[2];
+ $right = $matches[3];
+
+ // minimun width of formatted number (including dot)
+ $minWidth = strlen($left) + strlen($dec) + strlen($right);
+ if ($useThousands) {
+ $value = number_format(
+ $valueFloat,
+ strlen($right),
+ StringHelper::getDecimalSeparator(),
+ StringHelper::getThousandsSeparator()
+ );
+
+ return self::pregReplace(self::NUMBER_REGEX, $value, $format);
+ }
+
+ if (preg_match('/[0#]E[+-]0/i', $format)) {
+ // Scientific format
+ return sprintf('%5.2E', $valueFloat);
+ } elseif (preg_match('/0([^\d\.]+)0/', $format) || substr_count($format, '.') > 1) {
+ if ($value == (int) $valueFloat && substr_count($format, '.') === 1) {
+ $value *= 10 ** strlen(explode('.', $format)[1]);
+ }
+
+ return self::complexNumberFormatMask($value, $format);
+ }
+
+ $sprintf_pattern = "%0$minWidth." . strlen($right) . 'f';
+ /** @var float */
+ $valueFloat = $value;
+ $value = sprintf($sprintf_pattern, round($valueFloat, strlen($right)));
+
+ return self::pregReplace(self::NUMBER_REGEX, $value, $format);
+ }
+
+ /**
+ * @param mixed $value
+ */
+ public static function format($value, string $format): string
+ {
+ // The "_" in this string has already been stripped out,
+ // so this test is never true. Furthermore, testing
+ // on Excel shows this format uses Euro symbol, not "EUR".
+ //if ($format === NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE) {
+ // return 'EUR ' . sprintf('%1.2f', $value);
+ //}
+
+ // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols
+ $format = self::makeString(str_replace(['"', '*'], '', $format));
+
+ // Find out if we need thousands separator
+ // This is indicated by a comma enclosed by a digit placeholder:
+ // #,# or 0,0
+ $useThousands = (bool) preg_match('/(#,#|0,0)/', $format);
+ if ($useThousands) {
+ $format = self::pregReplace('/0,0/', '00', $format);
+ $format = self::pregReplace('/#,#/', '##', $format);
+ }
+
+ // Scale thousands, millions,...
+ // This is indicated by a number of commas after a digit placeholder:
+ // #, or 0.0,,
+ $scale = 1; // same as no scale
+ $matches = [];
+ if (preg_match('/(#|0)(,+)/', $format, $matches)) {
+ $scale = 1000 ** strlen($matches[2]);
+
+ // strip the commas
+ $format = self::pregReplace('/0,+/', '0', $format);
+ $format = self::pregReplace('/#,+/', '#', $format);
+ }
+ if (preg_match('/#?.*\?\/\?/', $format, $m)) {
+ $value = FractionFormatter::format($value, $format);
+ } else {
+ // Handle the number itself
+
+ // scale number
+ $value = $value / $scale;
+ // Strip #
+ $format = self::pregReplace('/\\#/', '0', $format);
+ // Remove locale code [$-###]
+ $format = self::pregReplace('/\[\$\-.*\]/', '', $format);
+
+ $n = '/\\[[^\\]]+\\]/';
+ $m = self::pregReplace($n, '', $format);
+ if (preg_match(self::NUMBER_REGEX, $m, $matches)) {
+ // There are placeholders for digits, so inject digits from the value into the mask
+ $value = self::formatStraightNumericValue($value, $format, $matches, $useThousands);
+ } elseif ($format !== NumberFormat::FORMAT_GENERAL) {
+ // Yes, I know that this is basically just a hack;
+ // if there's no placeholders for digits, just return the format mask "as is"
+ $value = self::makeString(str_replace('?', '', $format));
+ }
+ }
+
+ if (preg_match('/\[\$(.*)\]/u', $format, $m)) {
+ // Currency or Accounting
+ $currencyCode = $m[1];
+ [$currencyCode] = explode('-', $currencyCode);
+ if ($currencyCode == '') {
+ $currencyCode = StringHelper::getCurrencyCode();
+ }
+ $value = self::pregReplace('/\[\$([^\]]*)\]/u', $currencyCode, (string) $value);
+ }
+
+ return (string) $value;
+ }
+
+ /**
+ * @param array|string $value
+ */
+ private static function makeString($value): string
+ {
+ return is_array($value) ? '' : "$value";
+ }
+
+ private static function pregReplace(string $pattern, string $replacement, string $subject): string
+ {
+ return self::makeString(preg_replace($pattern, $replacement, $subject) ?? '');
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php
new file mode 100644
index 00000000000..cf1731ec85a
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php
@@ -0,0 +1,42 @@
+parent->getSharedComponent()->getProtection();
+ /** @var Style */
+ $parent = $this->parent;
+
+ return $parent->getSharedComponent()->getProtection();
}
/**
@@ -80,20 +83,20 @@ class Protection extends Supervisor
* );
*
*
- * @param array $pStyles Array containing style information
+ * @param array $styleArray Array containing style information
*
* @return $this
*/
- public function applyFromArray(array $pStyles)
+ public function applyFromArray(array $styleArray)
{
if ($this->isSupervisor) {
- $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles));
+ $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
- if (isset($pStyles['locked'])) {
- $this->setLocked($pStyles['locked']);
+ if (isset($styleArray['locked'])) {
+ $this->setLocked($styleArray['locked']);
}
- if (isset($pStyles['hidden'])) {
- $this->setHidden($pStyles['hidden']);
+ if (isset($styleArray['hidden'])) {
+ $this->setHidden($styleArray['hidden']);
}
}
@@ -117,17 +120,17 @@ class Protection extends Supervisor
/**
* Set locked.
*
- * @param string $pValue see self::PROTECTION_*
+ * @param string $lockType see self::PROTECTION_*
*
* @return $this
*/
- public function setLocked($pValue)
+ public function setLocked($lockType)
{
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['locked' => $pValue]);
+ $styleArray = $this->getStyleArray(['locked' => $lockType]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->locked = $pValue;
+ $this->locked = $lockType;
}
return $this;
@@ -150,17 +153,17 @@ class Protection extends Supervisor
/**
* Set hidden.
*
- * @param string $pValue see self::PROTECTION_*
+ * @param string $hiddenType see self::PROTECTION_*
*
* @return $this
*/
- public function setHidden($pValue)
+ public function setHidden($hiddenType)
{
if ($this->isSupervisor) {
- $styleArray = $this->getStyleArray(['hidden' => $pValue]);
+ $styleArray = $this->getStyleArray(['hidden' => $hiddenType]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->hidden = $pValue;
+ $this->hidden = $hiddenType;
}
return $this;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php
index f7c1be23fc4..fdb15451bab 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php
@@ -63,6 +63,27 @@ class Style extends Supervisor
*/
protected $quotePrefix = false;
+ /**
+ * Internal cache for styles
+ * Used when applying style on range of cells (column or row) and cleared when
+ * all cells in range is styled.
+ *
+ * PhpSpreadsheet will always minimize the amount of styles used. So cells with
+ * same styles will reference the same Style instance. To check if two styles
+ * are similar Style::getHashCode() is used. This call is expensive. To minimize
+ * the need to call this method we can cache the internal PHP object id of the
+ * Style in the range. Style::getHashCode() will then only be called when we
+ * encounter a unique style.
+ *
+ * @see Style::applyFromArray()
+ * @see Style::getHashCode()
+ *
+ * @phpstan-var null|array{styleByHash: array, hashByObjId: array}
+ *
+ * @var array
+ */
+ private static $cachedStyles;
+
/**
* Create a new Style.
*
@@ -80,7 +101,7 @@ class Style extends Supervisor
// Initialise values
$this->font = new Font($isSupervisor, $isConditional);
$this->fill = new Fill($isSupervisor, $isConditional);
- $this->borders = new Borders($isSupervisor, $isConditional);
+ $this->borders = new Borders($isSupervisor);
$this->alignment = new Alignment($isSupervisor, $isConditional);
$this->numberFormat = new NumberFormat($isSupervisor, $isConditional);
$this->protection = new Protection($isSupervisor, $isConditional);
@@ -99,10 +120,8 @@ class Style extends Supervisor
/**
* Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor.
- *
- * @return Style
*/
- public function getSharedComponent()
+ public function getSharedComponent(): self
{
$activeSheet = $this->getActiveSheet();
$selectedCell = $this->getActiveCell(); // e.g. 'A1'
@@ -113,17 +132,15 @@ class Style extends Supervisor
$xfIndex = 0;
}
- return $this->parent->getCellXfByIndex($xfIndex);
+ return $activeSheet->getParent()->getCellXfByIndex($xfIndex);
}
/**
* Get parent. Only used for style supervisor.
- *
- * @return Spreadsheet
*/
- public function getParent()
+ public function getParent(): Spreadsheet
{
- return $this->parent;
+ return $this->getActiveSheet()->getParent();
}
/**
@@ -178,12 +195,12 @@ class Style extends Supervisor
* );
*
*
- * @param array $pStyles Array containing style information
- * @param bool $pAdvanced advanced mode for setting borders
+ * @param array $styleArray Array containing style information
+ * @param bool $advancedBorders advanced mode for setting borders
*
* @return $this
*/
- public function applyFromArray(array $pStyles, $pAdvanced = true)
+ public function applyFromArray(array $styleArray, $advancedBorders = true)
{
if ($this->isSupervisor) {
$pRange = $this->getSelectedCells();
@@ -202,66 +219,65 @@ class Style extends Supervisor
// Calculate range outer borders
$rangeStart = Coordinate::coordinateFromString($rangeA);
$rangeEnd = Coordinate::coordinateFromString($rangeB);
+ $rangeStartIndexes = Coordinate::indexesFromString($rangeA);
+ $rangeEndIndexes = Coordinate::indexesFromString($rangeB);
- // Translate column into index
- $rangeStart0 = $rangeStart[0];
- $rangeEnd0 = $rangeEnd[0];
- $rangeStart[0] = Coordinate::columnIndexFromString($rangeStart[0]);
- $rangeEnd[0] = Coordinate::columnIndexFromString($rangeEnd[0]);
+ $columnStart = $rangeStart[0];
+ $columnEnd = $rangeEnd[0];
// 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;
+ if ($rangeStartIndexes[0] > $rangeEndIndexes[0] && $rangeStartIndexes[1] > $rangeEndIndexes[1]) {
+ $tmp = $rangeStartIndexes;
+ $rangeStartIndexes = $rangeEndIndexes;
+ $rangeEndIndexes = $tmp;
}
// ADVANCED MODE:
- if ($pAdvanced && isset($pStyles['borders'])) {
+ if ($advancedBorders && isset($styleArray['borders'])) {
// 'allBorders' is a shorthand property for 'outline' and 'inside' and
// it applies to components that have not been set explicitly
- if (isset($pStyles['borders']['allBorders'])) {
+ if (isset($styleArray['borders']['allBorders'])) {
foreach (['outline', 'inside'] as $component) {
- if (!isset($pStyles['borders'][$component])) {
- $pStyles['borders'][$component] = $pStyles['borders']['allBorders'];
+ if (!isset($styleArray['borders'][$component])) {
+ $styleArray['borders'][$component] = $styleArray['borders']['allBorders'];
}
}
- unset($pStyles['borders']['allBorders']); // not needed any more
+ unset($styleArray['borders']['allBorders']); // not needed any more
}
// 'outline' is a shorthand property for 'top', 'right', 'bottom', 'left'
// it applies to components that have not been set explicitly
- if (isset($pStyles['borders']['outline'])) {
+ if (isset($styleArray['borders']['outline'])) {
foreach (['top', 'right', 'bottom', 'left'] as $component) {
- if (!isset($pStyles['borders'][$component])) {
- $pStyles['borders'][$component] = $pStyles['borders']['outline'];
+ if (!isset($styleArray['borders'][$component])) {
+ $styleArray['borders'][$component] = $styleArray['borders']['outline'];
}
}
- unset($pStyles['borders']['outline']); // not needed any more
+ unset($styleArray['borders']['outline']); // not needed any more
}
// 'inside' is a shorthand property for 'vertical' and 'horizontal'
// it applies to components that have not been set explicitly
- if (isset($pStyles['borders']['inside'])) {
+ if (isset($styleArray['borders']['inside'])) {
foreach (['vertical', 'horizontal'] as $component) {
- if (!isset($pStyles['borders'][$component])) {
- $pStyles['borders'][$component] = $pStyles['borders']['inside'];
+ if (!isset($styleArray['borders'][$component])) {
+ $styleArray['borders'][$component] = $styleArray['borders']['inside'];
}
}
- unset($pStyles['borders']['inside']); // not needed any more
+ unset($styleArray['borders']['inside']); // not needed any more
}
// width and height characteristics of selection, 1, 2, or 3 (for 3 or more)
- $xMax = min($rangeEnd[0] - $rangeStart[0] + 1, 3);
- $yMax = min($rangeEnd[1] - $rangeStart[1] + 1, 3);
+ $xMax = min($rangeEndIndexes[0] - $rangeStartIndexes[0] + 1, 3);
+ $yMax = min($rangeEndIndexes[1] - $rangeStartIndexes[1] + 1, 3);
// loop through up to 3 x 3 = 9 regions
for ($x = 1; $x <= $xMax; ++$x) {
// start column index for region
$colStart = ($x == 3) ?
- Coordinate::stringFromColumnIndex($rangeEnd[0])
- : Coordinate::stringFromColumnIndex($rangeStart[0] + $x - 1);
+ Coordinate::stringFromColumnIndex($rangeEndIndexes[0])
+ : Coordinate::stringFromColumnIndex($rangeStartIndexes[0] + $x - 1);
// end column index for region
$colEnd = ($x == 1) ?
- Coordinate::stringFromColumnIndex($rangeStart[0])
- : Coordinate::stringFromColumnIndex($rangeEnd[0] - $xMax + $x);
+ Coordinate::stringFromColumnIndex($rangeStartIndexes[0])
+ : Coordinate::stringFromColumnIndex($rangeEndIndexes[0] - $xMax + $x);
for ($y = 1; $y <= $yMax; ++$y) {
// which edges are touching the region
@@ -285,17 +301,17 @@ class Style extends Supervisor
// start row index for region
$rowStart = ($y == 3) ?
- $rangeEnd[1] : $rangeStart[1] + $y - 1;
+ $rangeEndIndexes[1] : $rangeStartIndexes[1] + $y - 1;
// end row index for region
$rowEnd = ($y == 1) ?
- $rangeStart[1] : $rangeEnd[1] - $yMax + $y;
+ $rangeStartIndexes[1] : $rangeEndIndexes[1] - $yMax + $y;
// build range for region
$range = $colStart . $rowStart . ':' . $colEnd . $rowEnd;
// retrieve relevant style array for region
- $regionStyles = $pStyles;
+ $regionStyles = $styleArray;
unset($regionStyles['borders']['inside']);
// what are the inner edges of the region when looking at the selection
@@ -307,8 +323,8 @@ class Style extends Supervisor
case 'top':
case 'bottom':
// should pick up 'horizontal' border property if set
- if (isset($pStyles['borders']['horizontal'])) {
- $regionStyles['borders'][$innerEdge] = $pStyles['borders']['horizontal'];
+ if (isset($styleArray['borders']['horizontal'])) {
+ $regionStyles['borders'][$innerEdge] = $styleArray['borders']['horizontal'];
} else {
unset($regionStyles['borders'][$innerEdge]);
}
@@ -317,8 +333,8 @@ class Style extends Supervisor
case 'left':
case 'right':
// should pick up 'vertical' border property if set
- if (isset($pStyles['borders']['vertical'])) {
- $regionStyles['borders'][$innerEdge] = $pStyles['borders']['vertical'];
+ if (isset($styleArray['borders']['vertical'])) {
+ $regionStyles['borders'][$innerEdge] = $styleArray['borders']['vertical'];
} else {
unset($regionStyles['borders'][$innerEdge]);
}
@@ -342,68 +358,75 @@ class Style extends Supervisor
// Selection type, inspect
if (preg_match('/^[A-Z]+1:[A-Z]+1048576$/', $pRange)) {
$selectionType = 'COLUMN';
+
+ // Enable caching of styles
+ self::$cachedStyles = ['hashByObjId' => [], 'styleByHash' => []];
} elseif (preg_match('/^A\d+:XFD\d+$/', $pRange)) {
$selectionType = 'ROW';
+
+ // Enable caching of styles
+ self::$cachedStyles = ['hashByObjId' => [], 'styleByHash' => []];
} else {
$selectionType = 'CELL';
}
// First loop through columns, rows, or cells to find out which styles are affected by this operation
- switch ($selectionType) {
- case 'COLUMN':
- $oldXfIndexes = [];
- for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
- $oldXfIndexes[$this->getActiveSheet()->getColumnDimensionByColumn($col)->getXfIndex()] = true;
- }
- foreach ($this->getActiveSheet()->getColumnIterator($rangeStart0, $rangeEnd0) as $columnIterator) {
- $cellIterator = $columnIterator->getCellIterator();
- $cellIterator->setIterateOnlyExistingCells(true);
- foreach ($cellIterator as $columnCell) {
- $columnCell->getStyle()->applyFromArray($pStyles);
- }
- }
-
- break;
- case 'ROW':
- $oldXfIndexes = [];
- for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
- if ($this->getActiveSheet()->getRowDimension($row)->getXfIndex() == null) {
- $oldXfIndexes[0] = true; // row without explicit style should be formatted based on default style
- } else {
- $oldXfIndexes[$this->getActiveSheet()->getRowDimension($row)->getXfIndex()] = true;
- }
- }
- foreach ($this->getActiveSheet()->getRowIterator((int) $rangeStart[1], (int) $rangeEnd[1]) as $rowIterator) {
- $cellIterator = $rowIterator->getCellIterator();
- $cellIterator->setIterateOnlyExistingCells(true);
- foreach ($cellIterator as $rowCell) {
- $rowCell->getStyle()->applyFromArray($pStyles);
- }
- }
-
- break;
- case 'CELL':
- $oldXfIndexes = [];
- for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
- for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
- $oldXfIndexes[$this->getActiveSheet()->getCellByColumnAndRow($col, $row)->getXfIndex()] = true;
- }
- }
-
- break;
- }
+ $oldXfIndexes = $this->getOldXfIndexes($selectionType, $rangeStartIndexes, $rangeEndIndexes, $columnStart, $columnEnd, $styleArray);
// clone each of the affected styles, apply the style array, and add the new styles to the workbook
$workbook = $this->getActiveSheet()->getParent();
+ $newXfIndexes = [];
foreach ($oldXfIndexes as $oldXfIndex => $dummy) {
$style = $workbook->getCellXfByIndex($oldXfIndex);
- $newStyle = clone $style;
- $newStyle->applyFromArray($pStyles);
- if ($existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode())) {
+ // $cachedStyles is set when applying style for a range of cells, either column or row
+ if (self::$cachedStyles === null) {
+ // Clone the old style and apply style-array
+ $newStyle = clone $style;
+ $newStyle->applyFromArray($styleArray);
+
+ // Look for existing style we can use instead (reduce memory usage)
+ $existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode());
+ } else {
+ // Style cache is stored by Style::getHashCode(). But calling this method is
+ // expensive. So we cache the php obj id -> hash.
+ $objId = spl_object_id($style);
+
+ // Look for the original HashCode
+ $styleHash = self::$cachedStyles['hashByObjId'][$objId] ?? null;
+ if ($styleHash === null) {
+ // This object_id is not cached, store the hashcode in case encounter again
+ $styleHash = self::$cachedStyles['hashByObjId'][$objId] = $style->getHashCode();
+ }
+
+ // Find existing style by hash.
+ $existingStyle = self::$cachedStyles['styleByHash'][$styleHash] ?? null;
+
+ if (!$existingStyle) {
+ // The old style combined with the new style array is not cached, so we create it now
+ $newStyle = clone $style;
+ $newStyle->applyFromArray($styleArray);
+
+ // Look for similar style in workbook to reduce memory usage
+ $existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode());
+
+ // Cache the new style by original hashcode
+ self::$cachedStyles['styleByHash'][$styleHash] = $existingStyle instanceof self ? $existingStyle : $newStyle;
+ }
+ }
+
+ if ($existingStyle) {
// there is already such cell Xf in our collection
$newXfIndexes[$oldXfIndex] = $existingStyle->getIndex();
} else {
+ if (!isset($newStyle)) {
+ // Handle bug in PHPStan, see https://github.com/phpstan/phpstan/issues/5805
+ // $newStyle should always be defined.
+ // This block might not be needed in the future
+ $newStyle = clone $style;
+ $newStyle->applyFromArray($styleArray);
+ }
+
// we don't have such a cell Xf, need to add
$workbook->addCellXf($newStyle);
$newXfIndexes[$oldXfIndex] = $newStyle->getIndex();
@@ -413,25 +436,31 @@ class Style extends Supervisor
// Loop through columns, rows, or cells again and update the XF index
switch ($selectionType) {
case 'COLUMN':
- for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
+ for ($col = $rangeStartIndexes[0]; $col <= $rangeEndIndexes[0]; ++$col) {
$columnDimension = $this->getActiveSheet()->getColumnDimensionByColumn($col);
$oldXfIndex = $columnDimension->getXfIndex();
$columnDimension->setXfIndex($newXfIndexes[$oldXfIndex]);
}
+ // Disable caching of styles
+ self::$cachedStyles = null;
+
break;
case 'ROW':
- for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
+ for ($row = $rangeStartIndexes[1]; $row <= $rangeEndIndexes[1]; ++$row) {
$rowDimension = $this->getActiveSheet()->getRowDimension($row);
- $oldXfIndex = $rowDimension->getXfIndex() === null ?
- 0 : $rowDimension->getXfIndex(); // row without explicit style should be formatted based on default style
+ // row without explicit style should be formatted based on default style
+ $oldXfIndex = $rowDimension->getXfIndex() ?? 0;
$rowDimension->setXfIndex($newXfIndexes[$oldXfIndex]);
}
+ // Disable caching of styles
+ self::$cachedStyles = null;
+
break;
case 'CELL':
- for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
- for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
+ for ($col = $rangeStartIndexes[0]; $col <= $rangeEndIndexes[0]; ++$col) {
+ for ($row = $rangeStartIndexes[1]; $row <= $rangeEndIndexes[1]; ++$row) {
$cell = $this->getActiveSheet()->getCellByColumnAndRow($col, $row);
$oldXfIndex = $cell->getXfIndex();
$cell->setXfIndex($newXfIndexes[$oldXfIndex]);
@@ -442,32 +471,83 @@ class Style extends Supervisor
}
} else {
// not a supervisor, just apply the style array directly on style object
- if (isset($pStyles['fill'])) {
- $this->getFill()->applyFromArray($pStyles['fill']);
+ if (isset($styleArray['fill'])) {
+ $this->getFill()->applyFromArray($styleArray['fill']);
}
- if (isset($pStyles['font'])) {
- $this->getFont()->applyFromArray($pStyles['font']);
+ if (isset($styleArray['font'])) {
+ $this->getFont()->applyFromArray($styleArray['font']);
}
- if (isset($pStyles['borders'])) {
- $this->getBorders()->applyFromArray($pStyles['borders']);
+ if (isset($styleArray['borders'])) {
+ $this->getBorders()->applyFromArray($styleArray['borders']);
}
- if (isset($pStyles['alignment'])) {
- $this->getAlignment()->applyFromArray($pStyles['alignment']);
+ if (isset($styleArray['alignment'])) {
+ $this->getAlignment()->applyFromArray($styleArray['alignment']);
}
- if (isset($pStyles['numberFormat'])) {
- $this->getNumberFormat()->applyFromArray($pStyles['numberFormat']);
+ if (isset($styleArray['numberFormat'])) {
+ $this->getNumberFormat()->applyFromArray($styleArray['numberFormat']);
}
- if (isset($pStyles['protection'])) {
- $this->getProtection()->applyFromArray($pStyles['protection']);
+ if (isset($styleArray['protection'])) {
+ $this->getProtection()->applyFromArray($styleArray['protection']);
}
- if (isset($pStyles['quotePrefix'])) {
- $this->quotePrefix = $pStyles['quotePrefix'];
+ if (isset($styleArray['quotePrefix'])) {
+ $this->quotePrefix = $styleArray['quotePrefix'];
}
}
return $this;
}
+ private function getOldXfIndexes(string $selectionType, array $rangeStart, array $rangeEnd, string $columnStart, string $columnEnd, array $styleArray): array
+ {
+ $oldXfIndexes = [];
+ switch ($selectionType) {
+ case 'COLUMN':
+ for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
+ $oldXfIndexes[$this->getActiveSheet()->getColumnDimensionByColumn($col)->getXfIndex()] = true;
+ }
+ foreach ($this->getActiveSheet()->getColumnIterator($columnStart, $columnEnd) as $columnIterator) {
+ $cellIterator = $columnIterator->getCellIterator();
+ $cellIterator->setIterateOnlyExistingCells(true);
+ foreach ($cellIterator as $columnCell) {
+ if ($columnCell !== null) {
+ $columnCell->getStyle()->applyFromArray($styleArray);
+ }
+ }
+ }
+
+ break;
+ case 'ROW':
+ for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
+ if ($this->getActiveSheet()->getRowDimension($row)->getXfIndex() === null) {
+ $oldXfIndexes[0] = true; // row without explicit style should be formatted based on default style
+ } else {
+ $oldXfIndexes[$this->getActiveSheet()->getRowDimension($row)->getXfIndex()] = true;
+ }
+ }
+ foreach ($this->getActiveSheet()->getRowIterator((int) $rangeStart[1], (int) $rangeEnd[1]) as $rowIterator) {
+ $cellIterator = $rowIterator->getCellIterator();
+ $cellIterator->setIterateOnlyExistingCells(true);
+ foreach ($cellIterator as $rowCell) {
+ if ($rowCell !== null) {
+ $rowCell->getStyle()->applyFromArray($styleArray);
+ }
+ }
+ }
+
+ break;
+ case 'CELL':
+ for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
+ for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
+ $oldXfIndexes[$this->getActiveSheet()->getCellByColumnAndRow($col, $row)->getXfIndex()] = true;
+ }
+ }
+
+ break;
+ }
+
+ return $oldXfIndexes;
+ }
+
/**
* Get Fill.
*
@@ -543,13 +623,13 @@ class Style extends Supervisor
/**
* Set Conditional Styles. Only used on supervisor.
*
- * @param Conditional[] $pValue Array of conditional styles
+ * @param Conditional[] $conditionalStyleArray Array of conditional styles
*
* @return $this
*/
- public function setConditionalStyles(array $pValue)
+ public function setConditionalStyles(array $conditionalStyleArray)
{
- $this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $pValue);
+ $this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $conditionalStyleArray);
return $this;
}
@@ -581,20 +661,20 @@ class Style extends Supervisor
/**
* Set quote prefix.
*
- * @param bool $pValue
+ * @param bool $quotePrefix
*
* @return $this
*/
- public function setQuotePrefix($pValue)
+ public function setQuotePrefix($quotePrefix)
{
- if ($pValue == '') {
- $pValue = false;
+ if ($quotePrefix == '') {
+ $quotePrefix = false;
}
if ($this->isSupervisor) {
- $styleArray = ['quotePrefix' => $pValue];
+ $styleArray = ['quotePrefix' => $quotePrefix];
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
- $this->quotePrefix = (bool) $pValue;
+ $this->quotePrefix = (bool) $quotePrefix;
}
return $this;
@@ -632,11 +712,11 @@ class Style extends Supervisor
/**
* Set own index in style collection.
*
- * @param int $pValue
+ * @param int $index
*/
- public function setIndex($pValue): void
+ public function setIndex($index): void
{
- $this->index = $pValue;
+ $this->index = $index;
}
protected function exportArray1(): array
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Supervisor.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Supervisor.php
index 7f655bef72a..8a5c350d058 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Supervisor.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Supervisor.php
@@ -18,7 +18,7 @@ abstract class Supervisor implements IComparable
/**
* Parent. Only used for supervisor.
*
- * @var Spreadsheet|Style
+ * @var Spreadsheet|Supervisor
*/
protected $parent;
@@ -45,7 +45,7 @@ abstract class Supervisor implements IComparable
/**
* Bind parent. Only used for supervisor.
*
- * @param Spreadsheet|Style $parent
+ * @param Spreadsheet|Supervisor $parent
* @param null|string $parentPropertyName
*
* @return $this
@@ -155,4 +155,21 @@ abstract class Supervisor implements IComparable
$exportedArray[$index] = $objOrValue;
}
}
+
+ /**
+ * Get the shared style component for the currently active cell in currently active sheet.
+ * Only used for style supervisor.
+ *
+ * @return mixed
+ */
+ abstract public function getSharedComponent();
+
+ /**
+ * Build style array from subcomponents.
+ *
+ * @param array $array
+ *
+ * @return array
+ */
+ abstract public function getStyleArray($array);
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php
index c2ded195c78..893243dfd02 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php
@@ -2,19 +2,22 @@
namespace PhpOffice\PhpSpreadsheet\Worksheet;
+use DateTime;
+use DateTimeZone;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
-use PhpOffice\PhpSpreadsheet\Calculation\DateTime;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
+use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Shared\Date;
+use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule;
class AutoFilter
{
/**
* Autofilter Worksheet.
*
- * @var Worksheet
+ * @var null|Worksheet
*/
private $workSheet;
@@ -32,22 +35,32 @@ class AutoFilter
*/
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 string $pRange Cell range (i.e. A1:E10)
- * @param Worksheet $pSheet
*/
- public function __construct($pRange = '', ?Worksheet $pSheet = null)
+ public function __construct(string $range = '', ?Worksheet $worksheet = null)
{
- $this->range = $pRange;
- $this->workSheet = $pSheet;
+ $this->range = $range;
+ $this->workSheet = $worksheet;
}
/**
* Get AutoFilter Parent Worksheet.
*
- * @return Worksheet
+ * @return null|Worksheet
*/
public function getParent()
{
@@ -57,13 +70,12 @@ class AutoFilter
/**
* Set AutoFilter Parent Worksheet.
*
- * @param Worksheet $pSheet
- *
* @return $this
*/
- public function setParent(?Worksheet $pSheet = null)
+ public function setParent(?Worksheet $worksheet = null)
{
- $this->workSheet = $pSheet;
+ $this->evaluated = false;
+ $this->workSheet = $worksheet;
return $this;
}
@@ -79,36 +91,46 @@ class AutoFilter
}
/**
- * Set AutoFilter Range.
- *
- * @param string $pRange Cell range (i.e. A1:E10)
- *
- * @return $this
+ * Set AutoFilter Cell Range.
*/
- public function setRange($pRange)
+ public function setRange(string $range): self
{
+ $this->evaluated = false;
// extract coordinate
- [$worksheet, $pRange] = Worksheet::extractSheetTitle($pRange, true);
-
- if (strpos($pRange, ':') !== false) {
- $this->range = $pRange;
- } elseif (empty($pRange)) {
+ [$worksheet, $range] = Worksheet::extractSheetTitle($range, true);
+ if (empty($range)) {
+ // Discard all column rules
+ $this->columns = [];
$this->range = '';
- } else {
+
+ return $this;
+ }
+
+ if (strpos($range, ':') === false) {
throw new PhpSpreadsheetException('Autofilter must be set on a range of cells.');
}
- if (empty($pRange)) {
- // Discard all column rules
- $this->columns = [];
- } else {
- // 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]);
- }
+ $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 = preg_replace('/\\d+$/', (string) $this->workSheet->getHighestRow(), $thisrange) ?? '';
+ if ($range !== $thisrange) {
+ $this->setRange($range);
}
}
@@ -150,44 +172,44 @@ class AutoFilter
/**
* Get a specified AutoFilter Column Offset within the defined AutoFilter range.
*
- * @param string $pColumn Column name (e.g. A)
+ * @param string $column Column name (e.g. A)
*
* @return int The offset of the specified column within the autofilter range
*/
- public function getColumnOffset($pColumn)
+ public function getColumnOffset($column)
{
- return $this->testColumnInRange($pColumn);
+ return $this->testColumnInRange($column);
}
/**
* Get a specified AutoFilter Column.
*
- * @param string $pColumn Column name (e.g. A)
+ * @param string $column Column name (e.g. A)
*
* @return AutoFilter\Column
*/
- public function getColumn($pColumn)
+ public function getColumn($column)
{
- $this->testColumnInRange($pColumn);
+ $this->testColumnInRange($column);
- if (!isset($this->columns[$pColumn])) {
- $this->columns[$pColumn] = new AutoFilter\Column($pColumn, $this);
+ if (!isset($this->columns[$column])) {
+ $this->columns[$column] = new AutoFilter\Column($column, $this);
}
- return $this->columns[$pColumn];
+ return $this->columns[$column];
}
/**
* Get a specified AutoFilter Column by it's offset.
*
- * @param int $pColumnOffset Column offset within range (starting from 0)
+ * @param int $columnOffset Column offset within range (starting from 0)
*
* @return AutoFilter\Column
*/
- public function getColumnByOffset($pColumnOffset)
+ public function getColumnByOffset($columnOffset)
{
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range);
- $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $pColumnOffset);
+ $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset);
return $this->getColumn($pColumn);
}
@@ -195,27 +217,28 @@ class AutoFilter
/**
* Set AutoFilter.
*
- * @param AutoFilter\Column|string $pColumn
+ * @param AutoFilter\Column|string $columnObjectOrString
* A simple string containing a Column ID like 'A' is permitted
*
* @return $this
*/
- public function setColumn($pColumn)
+ public function setColumn($columnObjectOrString)
{
- if ((is_string($pColumn)) && (!empty($pColumn))) {
- $column = $pColumn;
- } elseif (is_object($pColumn) && ($pColumn instanceof AutoFilter\Column)) {
- $column = $pColumn->getColumnIndex();
+ $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 PhpSpreadsheetException('Column is not within the autofilter range.');
}
$this->testColumnInRange($column);
- if (is_string($pColumn)) {
- $this->columns[$pColumn] = new AutoFilter\Column($pColumn, $this);
- } elseif (is_object($pColumn) && ($pColumn instanceof AutoFilter\Column)) {
- $pColumn->setParent($this);
- $this->columns[$column] = $pColumn;
+ if (is_string($columnObjectOrString)) {
+ $this->columns[$columnObjectOrString] = new AutoFilter\Column($columnObjectOrString, $this);
+ } else {
+ $columnObjectOrString->setParent($this);
+ $this->columns[$column] = $columnObjectOrString;
}
ksort($this->columns);
@@ -225,16 +248,17 @@ class AutoFilter
/**
* Clear a specified AutoFilter Column.
*
- * @param string $pColumn Column name (e.g. A)
+ * @param string $column Column name (e.g. A)
*
* @return $this
*/
- public function clearColumn($pColumn)
+ public function clearColumn($column)
{
- $this->testColumnInRange($pColumn);
+ $this->evaluated = false;
+ $this->testColumnInRange($column);
- if (isset($this->columns[$pColumn])) {
- unset($this->columns[$pColumn]);
+ if (isset($this->columns[$column])) {
+ unset($this->columns[$column]);
}
return $this;
@@ -254,6 +278,7 @@ class AutoFilter
*/
public function shiftColumn($fromColumn, $toColumn)
{
+ $this->evaluated = false;
$fromColumn = strtoupper($fromColumn);
$toColumn = strtoupper($toColumn);
@@ -304,20 +329,22 @@ class AutoFilter
if (($cellValue == '') || ($cellValue === null)) {
return $blanks;
}
+ $timeZone = new DateTimeZone('UTC');
if (is_numeric($cellValue)) {
- $dateValue = Date::excelToTimestamp($cellValue);
+ $dateTime = Date::excelToDateTimeObject((float) $cellValue, $timeZone);
+ $cellValue = (float) $cellValue;
if ($cellValue < 1) {
// Just the time part
- $dtVal = date('His', $dateValue);
+ $dtVal = $dateTime->format('His');
$dateSet = $dateSet['time'];
} elseif ($cellValue == floor($cellValue)) {
// Just the date part
- $dtVal = date('Ymd', $dateValue);
+ $dtVal = $dateTime->format('Ymd');
$dateSet = $dateSet['date'];
} else {
// date and time parts
- $dtVal = date('YmdHis', $dateValue);
+ $dtVal = $dateTime->format('YmdHis');
$dateSet = $dateSet['dateTime'];
}
foreach ($dateSet as $dateValue) {
@@ -341,6 +368,7 @@ class AutoFilter
*/
private static function filterTestInCustomDataSet($cellValue, $ruleSet)
{
+ /** @var array[] */
$dataSet = $ruleSet['filterRules'];
$join = $ruleSet['join'];
$customRuleForBlanks = $ruleSet['customRuleForBlanks'] ?? false;
@@ -353,43 +381,50 @@ class AutoFilter
}
$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($rule['value'])) {
+ if (is_numeric($ruleValue)) {
// Numeric values are tested using the appropriate operator
- switch ($rule['operator']) {
- case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL:
- $retVal = ($cellValue == $rule['value']);
+ $numericTest = is_numeric($cellValue);
+ switch ($ruleOperator) {
+ case Rule::AUTOFILTER_COLUMN_RULE_EQUAL:
+ $retVal = $numericTest && ($cellValue == $ruleValue);
break;
- case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL:
- $retVal = ($cellValue != $rule['value']);
+ case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL:
+ $retVal = !$numericTest || ($cellValue != $ruleValue);
break;
- case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN:
- $retVal = ($cellValue > $rule['value']);
+ case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN:
+ $retVal = $numericTest && ($cellValue > $ruleValue);
break;
- case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL:
- $retVal = ($cellValue >= $rule['value']);
+ case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL:
+ $retVal = $numericTest && ($cellValue >= $ruleValue);
break;
- case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN:
- $retVal = ($cellValue < $rule['value']);
+ case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN:
+ $retVal = $numericTest && ($cellValue < $ruleValue);
break;
- case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL:
- $retVal = ($cellValue <= $rule['value']);
+ case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL:
+ $retVal = $numericTest && ($cellValue <= $ruleValue);
break;
}
- } elseif ($rule['value'] == '') {
- switch ($rule['operator']) {
- case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL:
+ } elseif ($ruleValue == '') {
+ switch ($ruleOperator) {
+ case Rule::AUTOFILTER_COLUMN_RULE_EQUAL:
$retVal = (($cellValue == '') || ($cellValue === null));
break;
- case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL:
+ case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL:
$retVal = (($cellValue != '') && ($cellValue !== null));
break;
@@ -400,7 +435,32 @@ class AutoFilter
}
} else {
// String values are always tested for equality, factoring in for wildcards (hence a regexp test)
- $retVal = preg_match('/^' . $rule['value'] . '$/i', $cellValue);
+ 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) {
@@ -439,7 +499,8 @@ class AutoFilter
}
if (is_numeric($cellValue)) {
- $dateValue = date('m', Date::excelToTimestamp($cellValue));
+ $dateObject = Date::excelToDateTimeObject((float) $cellValue, new DateTimeZone('UTC'));
+ $dateValue = (int) $dateObject->format('m');
if (in_array($dateValue, $monthSet)) {
return true;
}
@@ -448,154 +509,286 @@ class AutoFilter
return false;
}
- /**
- * Search/Replace arrays to convert Excel wildcard syntax to a regexp syntax for preg_matching.
- *
- * @var array
- */
- private static $fromReplace = ['\*', '\?', '~~', '~.*', '~.?'];
+ 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);
- private static $toReplace = ['.*', '.', '~', '\*', '\?'];
+ 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
- * @param AutoFilter\Column $filterColumn
*
* @return mixed[]
*/
- private function dynamicFilterDateRange($dynamicRuleType, &$filterColumn)
+ private function dynamicFilterDateRange($dynamicRuleType, AutoFilter\Column &$filterColumn)
{
- $rDateType = Functions::getReturnDateType();
- Functions::setReturnDateType(Functions::RETURNDATE_PHP_NUMERIC);
- $val = $maxVal = null;
-
$ruleValues = [];
- $baseDate = DateTime::DATENOW();
+ $callBack = [__CLASS__, self::DATE_FUNCTIONS[$dynamicRuleType]]; // What if not found?
// Calculate start/end dates for the required date range based on current date
- switch ($dynamicRuleType) {
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK:
- $baseDate = strtotime('-7 days', $baseDate);
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK:
- $baseDate = strtotime('-7 days', $baseDate);
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH:
- $baseDate = strtotime('-1 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH:
- $baseDate = strtotime('+1 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER:
- $baseDate = strtotime('-3 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER:
- $baseDate = strtotime('+3 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR:
- $baseDate = strtotime('-1 year', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR:
- $baseDate = strtotime('+1 year', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
-
- break;
- }
-
- switch ($dynamicRuleType) {
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY:
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY:
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW:
- $maxVal = (int) Date::PHPtoExcel(strtotime('+1 day', $baseDate));
- $val = (int) Date::PHPToExcel($baseDate);
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE:
- $maxVal = (int) Date::PHPtoExcel(strtotime('+1 day', $baseDate));
- $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate)));
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR:
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR:
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR:
- $maxVal = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 31, 12, date('Y', $baseDate)));
- ++$maxVal;
- $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate)));
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER:
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER:
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER:
- $thisMonth = date('m', $baseDate);
- $thisQuarter = floor(--$thisMonth / 3);
- $maxVal = (int) Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), (1 + $thisQuarter) * 3, date('Y', $baseDate)));
- ++$maxVal;
- $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1 + $thisQuarter * 3, date('Y', $baseDate)));
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH:
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH:
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH:
- $maxVal = (int) Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), date('m', $baseDate), date('Y', $baseDate)));
- ++$maxVal;
- $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate)));
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK:
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK:
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK:
- $dayOfWeek = date('w', $baseDate);
- $val = (int) Date::PHPToExcel($baseDate) - $dayOfWeek;
- $maxVal = $val + 7;
-
- break;
- }
-
- switch ($dynamicRuleType) {
- // Adjust Today dates for Yesterday and Tomorrow
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY:
- --$maxVal;
- --$val;
-
- break;
- case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW:
- ++$maxVal;
- ++$val;
-
- break;
+ // 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]);
+ $filterColumn->setAttributes(['val' => $val, 'maxVal' => $maxval]);
// Set the rules for identifying rows for hide/show
- $ruleValues[] = ['operator' => AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val];
- $ruleValues[] = ['operator' => AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxVal];
- Functions::setReturnDateType($rDateType);
+ $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;
- $dataValues = Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false));
+ $retVal = null;
+ if ($this->workSheet !== null) {
+ $dataValues = Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false));
+ $dataValues = array_filter($dataValues);
- $dataValues = array_filter($dataValues);
- if ($ruleType == AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) {
- rsort($dataValues);
- } else {
- sort($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 array_pop(array_slice($dataValues, 0, $ruleValue));
+ return $retVal;
}
/**
@@ -605,6 +798,9 @@ class AutoFilter
*/
public function showHideRows()
{
+ if ($this->workSheet === null) {
+ return $this;
+ }
[$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range);
// The heading row should always be visible
@@ -628,7 +824,7 @@ class AutoFilter
if (count($ruleValues) != count($ruleDataSet)) {
$blanks = true;
}
- if ($ruleType == AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_FILTER) {
+ if ($ruleType == Rule::AUTOFILTER_RULETYPE_FILTER) {
// Filter on absolute values
$columnFilterTests[$columnID] = [
'method' => 'filterTestInSimpleDataSet',
@@ -642,42 +838,45 @@ class AutoFilter
'dateTime' => [],
];
foreach ($ruleDataSet as $ruleValue) {
+ if (!is_array($ruleValue)) {
+ continue;
+ }
$date = $time = '';
if (
- (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) &&
- ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '')
+ (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) &&
+ ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '')
) {
- $date .= sprintf('%04d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]);
+ $date .= sprintf('%04d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]);
}
if (
- (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) &&
- ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '')
+ (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) &&
+ ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '')
) {
- $date .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]);
+ $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]);
}
if (
- (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) &&
- ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '')
+ (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) &&
+ ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '')
) {
- $date .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]);
+ $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]);
}
if (
- (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) &&
- ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '')
+ (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) &&
+ ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '')
) {
- $time .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]);
+ $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]);
}
if (
- (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) &&
- ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '')
+ (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) &&
+ ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '')
) {
- $time .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]);
+ $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]);
}
if (
- (isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) &&
- ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '')
+ (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) &&
+ ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '')
) {
- $time .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]);
+ $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]);
}
$dateTime = $date . $time;
$arguments['date'][] = $date;
@@ -696,15 +895,14 @@ class AutoFilter
break;
case AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER:
- $customRuleForBlanks = false;
+ $customRuleForBlanks = true;
$ruleValues = [];
// Build a list of the filter value selections
foreach ($rules as $rule) {
$ruleValue = $rule->getValue();
- if (!is_numeric($ruleValue)) {
+ if (!is_array($ruleValue) && !is_numeric($ruleValue)) {
// Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards
- $ruleValue = preg_quote($ruleValue);
- $ruleValue = str_replace(self::$fromReplace, self::$toReplace, $ruleValue);
+ $ruleValue = WildcardMatch::wildcard($ruleValue);
if (trim($ruleValue) == '') {
$customRuleForBlanks = true;
$ruleValue = trim($ruleValue);
@@ -725,17 +923,18 @@ class AutoFilter
// We should only ever have one Dynamic Filter Rule anyway
$dynamicRuleType = $rule->getGrouping();
if (
- ($dynamicRuleType == AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) ||
- ($dynamicRuleType == AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE)
+ ($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] . ')';
- $average = Calculation::getInstance()->calculateFormula($averageFormula, null, $this->workSheet->getCell('A1'));
+ $spreadsheet = ($this->workSheet === null) ? null : $this->workSheet->getParent();
+ $average = Calculation::getInstance($spreadsheet)->calculateFormula($averageFormula, null, $this->workSheet->getCell('A1'));
// Set above/below rule based on greaterThan or LessTan
- $operator = ($dynamicRuleType === AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE)
- ? AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN
- : AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN;
+ $operator = ($dynamicRuleType === Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE)
+ ? Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN
+ : Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN;
$ruleValues[] = [
'operator' => $operator,
'value' => $average,
@@ -777,27 +976,30 @@ class AutoFilter
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 ($ruleOperator === AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) {
- $ruleValue = floor($ruleValue * ($dataRowCount / 100));
+ if (is_numeric($ruleValue) && $ruleOperator === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) {
+ $ruleValue = floor((float) $ruleValue * ($dataRowCount / 100));
}
- if ($ruleValue < 1) {
+ if (!is_array($ruleValue) && $ruleValue < 1) {
$ruleValue = 1;
}
- if ($ruleValue > 500) {
+ if (!is_array($ruleValue) && $ruleValue > 500) {
$ruleValue = 500;
}
- $maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1] + 1, $rangeEnd[1], $toptenRuleType, $ruleValue);
+ $maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1] + 1, (int) $rangeEnd[1], $toptenRuleType, $ruleValue);
- $operator = ($toptenRuleType == AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP)
- ? AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL
- : AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL;
+ $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',
@@ -815,19 +1017,18 @@ class AutoFilter
foreach ($columnFilterTests as $columnID => $columnFilterTest) {
$cellValue = $this->workSheet->getCell($columnID . $row)->getCalculatedValue();
// Execute the filter test
- $result = $result &&
- call_user_func_array(
- [self::class, $columnFilterTest['method']],
- [$cellValue, $columnFilterTest['arguments']]
- );
+ $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($row)->setVisible($result);
+ $this->workSheet->getRowDimension((int) $row)->setVisible($result);
}
+ $this->evaluated = true;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php
index 09584a7aaac..2e3ea65bf3b 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php
@@ -49,7 +49,7 @@ class Column
/**
* Autofilter.
*
- * @var AutoFilter
+ * @var null|AutoFilter
*/
private $parent;
@@ -77,27 +77,34 @@ class Column
/**
* Autofilter Column Rules.
*
- * @var array of Column\Rule
+ * @var Column\Rule[]
*/
private $ruleset = [];
/**
* Autofilter Column Dynamic Attributes.
*
- * @var array of mixed
+ * @var mixed[]
*/
private $attributes = [];
/**
* Create a new Column.
*
- * @param string $pColumn Column (e.g. A)
- * @param AutoFilter $pParent Autofilter for this column
+ * @param string $column Column (e.g. A)
+ * @param AutoFilter $parent Autofilter for this column
*/
- public function __construct($pColumn, ?AutoFilter $pParent = null)
+ public function __construct($column, ?AutoFilter $parent = null)
{
- $this->columnIndex = $pColumn;
- $this->parent = $pParent;
+ $this->columnIndex = $column;
+ $this->parent = $parent;
+ }
+
+ public function setEvaluatedFalse(): void
+ {
+ if ($this->parent !== null) {
+ $this->parent->setEvaluated(false);
+ }
}
/**
@@ -113,19 +120,20 @@ class Column
/**
* Set AutoFilter column index as string eg: 'A'.
*
- * @param string $pColumn Column (e.g. A)
+ * @param string $column Column (e.g. A)
*
* @return $this
*/
- public function setColumnIndex($pColumn)
+ public function setColumnIndex($column)
{
+ $this->setEvaluatedFalse();
// Uppercase coordinate
- $pColumn = strtoupper($pColumn);
+ $column = strtoupper($column);
if ($this->parent !== null) {
- $this->parent->testColumnInRange($pColumn);
+ $this->parent->testColumnInRange($column);
}
- $this->columnIndex = $pColumn;
+ $this->columnIndex = $column;
return $this;
}
@@ -133,7 +141,7 @@ class Column
/**
* Get this Column's AutoFilter Parent.
*
- * @return AutoFilter
+ * @return null|AutoFilter
*/
public function getParent()
{
@@ -143,13 +151,12 @@ class Column
/**
* Set this Column's AutoFilter Parent.
*
- * @param AutoFilter $pParent
- *
* @return $this
*/
- public function setParent(?AutoFilter $pParent = null)
+ public function setParent(?AutoFilter $parent = null)
{
- $this->parent = $pParent;
+ $this->setEvaluatedFalse();
+ $this->parent = $parent;
return $this;
}
@@ -167,17 +174,21 @@ class Column
/**
* Set AutoFilter Type.
*
- * @param string $pFilterType
+ * @param string $filterType
*
* @return $this
*/
- public function setFilterType($pFilterType)
+ public function setFilterType($filterType)
{
- if (!in_array($pFilterType, self::$filterTypes)) {
+ $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 = $pFilterType;
+ $this->filterType = $filterType;
return $this;
}
@@ -195,19 +206,20 @@ class Column
/**
* Set AutoFilter Multiple Rules And/Or.
*
- * @param string $pJoin And/Or
+ * @param string $join And/Or
*
* @return $this
*/
- public function setJoin($pJoin)
+ public function setJoin($join)
{
+ $this->setEvaluatedFalse();
// Lowercase And/Or
- $pJoin = strtolower($pJoin);
- if (!in_array($pJoin, self::$ruleJoins)) {
+ $join = strtolower($join);
+ if (!in_array($join, self::$ruleJoins)) {
throw new PhpSpreadsheetException('Invalid rule connection for column AutoFilter.');
}
- $this->join = $pJoin;
+ $this->join = $join;
return $this;
}
@@ -215,12 +227,13 @@ class Column
/**
* Set AutoFilter Attributes.
*
- * @param string[] $attributes
+ * @param mixed[] $attributes
*
* @return $this
*/
- public function setAttributes(array $attributes)
+ public function setAttributes($attributes)
{
+ $this->setEvaluatedFalse();
$this->attributes = $attributes;
return $this;
@@ -229,14 +242,15 @@ class Column
/**
* Set An AutoFilter Attribute.
*
- * @param string $pName Attribute Name
- * @param string $pValue Attribute Value
+ * @param string $name Attribute Name
+ * @param string $value Attribute Value
*
* @return $this
*/
- public function setAttribute($pName, $pValue)
+ public function setAttribute($name, $value)
{
- $this->attributes[$pName] = $pValue;
+ $this->setEvaluatedFalse();
+ $this->attributes[$name] = $value;
return $this;
}
@@ -244,7 +258,7 @@ class Column
/**
* Get AutoFilter Column Attributes.
*
- * @return string[]
+ * @return int[]|string[]
*/
public function getAttributes()
{
@@ -254,19 +268,24 @@ class Column
/**
* Get specific AutoFilter Column Attribute.
*
- * @param string $pName Attribute Name
+ * @param string $name Attribute Name
*
- * @return string
+ * @return null|int|string
*/
- public function getAttribute($pName)
+ public function getAttribute($name)
{
- if (isset($this->attributes[$pName])) {
- return $this->attributes[$pName];
+ if (isset($this->attributes[$name])) {
+ return $this->attributes[$name];
}
return null;
}
+ public function ruleCount(): int
+ {
+ return count($this->ruleset);
+ }
+
/**
* Get all AutoFilter Column Rules.
*
@@ -280,17 +299,17 @@ class Column
/**
* Get a specified AutoFilter Column Rule.
*
- * @param int $pIndex Rule index in the ruleset array
+ * @param int $index Rule index in the ruleset array
*
* @return Column\Rule
*/
- public function getRule($pIndex)
+ public function getRule($index)
{
- if (!isset($this->ruleset[$pIndex])) {
- $this->ruleset[$pIndex] = new Column\Rule($this);
+ if (!isset($this->ruleset[$index])) {
+ $this->ruleset[$index] = new Column\Rule($this);
}
- return $this->ruleset[$pIndex];
+ return $this->ruleset[$index];
}
/**
@@ -300,6 +319,10 @@ class Column
*/
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);
@@ -310,10 +333,11 @@ class Column
*
* @return $this
*/
- public function addRule(Column\Rule $pRule)
+ public function addRule(Column\Rule $rule)
{
- $pRule->setParent($this);
- $this->ruleset[] = $pRule;
+ $this->setEvaluatedFalse();
+ $rule->setParent($this);
+ $this->ruleset[] = $rule;
return $this;
}
@@ -322,14 +346,15 @@ class Column
* 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 $pIndex Rule index in the ruleset array
+ * @param int $index Rule index in the ruleset array
*
* @return $this
*/
- public function deleteRule($pIndex)
+ public function deleteRule($index)
{
- if (isset($this->ruleset[$pIndex])) {
- unset($this->ruleset[$pIndex]);
+ $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);
@@ -346,6 +371,7 @@ class Column
*/
public function clearRules()
{
+ $this->setEvaluatedFalse();
$this->ruleset = [];
$this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR);
@@ -370,8 +396,6 @@ class Column
$cloned->setParent($this); // attach the new cloned Rule to this new cloned Autofilter Cloned object
$this->ruleset[$k] = $cloned;
}
- } elseif (is_object($value)) {
- $this->$key = clone $value;
} else {
$this->$key = $value;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php
index 1aacb0cb8fe..408dfb3f06b 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php
@@ -13,7 +13,7 @@ class Rule
const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter';
const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter';
- private static $ruleTypes = [
+ private const RULE_TYPES = [
// Currently we're not handling
// colorFilter
// extLst
@@ -32,7 +32,7 @@ class Rule
const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute';
const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second';
- private static $dateTimeGroups = [
+ private const DATE_TIME_GROUPS = [
self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR,
self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH,
self::AUTOFILTER_RULETYPE_DATEGROUP_DAY,
@@ -88,7 +88,7 @@ class Rule
const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage';
const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage';
- private static $dynamicTypes = [
+ private const DYNAMIC_TYPES = [
self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY,
self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY,
self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW,
@@ -125,15 +125,7 @@ class Rule
self::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE,
];
- /*
- * The only valid filter rule operators for filter and customFilter types are:
- *
- *
- *
- *
- *
- *
- */
+ // 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';
@@ -141,7 +133,7 @@ class Rule
const AUTOFILTER_COLUMN_RULE_LESSTHAN = 'lessThan';
const AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL = 'lessThanOrEqual';
- private static $operators = [
+ private const OPERATORS = [
self::AUTOFILTER_COLUMN_RULE_EQUAL,
self::AUTOFILTER_COLUMN_RULE_NOTEQUAL,
self::AUTOFILTER_COLUMN_RULE_GREATERTHAN,
@@ -153,7 +145,7 @@ class Rule
const AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE = 'byValue';
const AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT = 'byPercent';
- private static $topTenValue = [
+ private const TOP_TEN_VALUE = [
self::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE,
self::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT,
];
@@ -161,49 +153,27 @@ class Rule
const AUTOFILTER_COLUMN_RULE_TOPTEN_TOP = 'top';
const AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM = 'bottom';
- private static $topTenType = [
+ private const TOP_TEN_TYPE = [
self::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP,
self::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM,
];
- // Rule Operators (Numeric, Boolean etc)
-// const AUTOFILTER_COLUMN_RULE_BETWEEN = 'between'; // greaterThanOrEqual 1 && lessThanOrEqual 2
+ // 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
-// const AUTOFILTER_COLUMN_RULE_TOPTEN = 'topTen'; // greaterThan calculated value
-// const AUTOFILTER_COLUMN_RULE_TOPTENPERCENT = 'topTenPercent'; // greaterThan calculated value
-// const AUTOFILTER_COLUMN_RULE_ABOVEAVERAGE = 'aboveAverage'; // Value is calculated as the average
-// const AUTOFILTER_COLUMN_RULE_BELOWAVERAGE = 'belowAverage'; // Value is calculated as the average
// 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*
+ // 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';
-// const AUTOFILTER_COLUMN_RULE_YESTERDAY = 'yesterday';
-// const AUTOFILTER_COLUMN_RULE_TODAY = 'today';
-// const AUTOFILTER_COLUMN_RULE_TOMORROW = 'tomorrow';
-// const AUTOFILTER_COLUMN_RULE_LASTWEEK = 'lastWeek';
-// const AUTOFILTER_COLUMN_RULE_THISWEEK = 'thisWeek';
-// const AUTOFILTER_COLUMN_RULE_NEXTWEEK = 'nextWeek';
-// const AUTOFILTER_COLUMN_RULE_LASTMONTH = 'lastMonth';
-// const AUTOFILTER_COLUMN_RULE_THISMONTH = 'thisMonth';
-// const AUTOFILTER_COLUMN_RULE_NEXTMONTH = 'nextMonth';
-// const AUTOFILTER_COLUMN_RULE_LASTQUARTER = 'lastQuarter';
-// const AUTOFILTER_COLUMN_RULE_THISQUARTER = 'thisQuarter';
-// const AUTOFILTER_COLUMN_RULE_NEXTQUARTER = 'nextQuarter';
-// const AUTOFILTER_COLUMN_RULE_LASTYEAR = 'lastYear';
-// const AUTOFILTER_COLUMN_RULE_THISYEAR = 'thisYear';
-// const AUTOFILTER_COLUMN_RULE_NEXTYEAR = 'nextYear';
-// const AUTOFILTER_COLUMN_RULE_YEARTODATE = 'yearToDate'; //
-// const AUTOFILTER_COLUMN_RULE_ALLDATESINMONTH = 'allDatesInMonth'; // for Month/February
-// const AUTOFILTER_COLUMN_RULE_ALLDATESINQUARTER = 'allDatesInQuarter'; // for Quarter 2
+ // const AUTOFILTER_COLUMN_RULE_BEFORE = 'lessThan';
+ // const AUTOFILTER_COLUMN_RULE_AFTER = 'greaterThan';
/**
* Autofilter Column.
*
- * @var Column
+ * @var ?Column
*/
private $parent;
@@ -217,7 +187,7 @@ class Rule
/**
* Autofilter Rule Value.
*
- * @var string
+ * @var int|int[]|string|string[]
*/
private $value = '';
@@ -237,12 +207,17 @@ class Rule
/**
* Create a new Rule.
- *
- * @param Column $pParent
*/
- public function __construct(?Column $pParent = null)
+ public function __construct(?Column $parent = null)
{
- $this->parent = $pParent;
+ $this->parent = $parent;
+ }
+
+ private function setEvaluatedFalse(): void
+ {
+ if ($this->parent !== null) {
+ $this->parent->setEvaluatedFalse();
+ }
}
/**
@@ -258,17 +233,18 @@ class Rule
/**
* Set AutoFilter Rule Type.
*
- * @param string $pRuleType see self::AUTOFILTER_RULETYPE_*
+ * @param string $ruleType see self::AUTOFILTER_RULETYPE_*
*
* @return $this
*/
- public function setRuleType($pRuleType)
+ public function setRuleType($ruleType)
{
- if (!in_array($pRuleType, self::$ruleTypes)) {
+ $this->setEvaluatedFalse();
+ if (!in_array($ruleType, self::RULE_TYPES)) {
throw new PhpSpreadsheetException('Invalid rule type for column AutoFilter Rule.');
}
- $this->ruleType = $pRuleType;
+ $this->ruleType = $ruleType;
return $this;
}
@@ -276,7 +252,7 @@ class Rule
/**
* Get AutoFilter Rule Value.
*
- * @return string
+ * @return int|int[]|string|string[]
*/
public function getValue()
{
@@ -286,31 +262,32 @@ class Rule
/**
* Set AutoFilter Rule Value.
*
- * @param string|string[] $pValue
+ * @param int|int[]|string|string[] $value
*
* @return $this
*/
- public function setValue($pValue)
+ public function setValue($value)
{
- if (is_array($pValue)) {
+ $this->setEvaluatedFalse();
+ if (is_array($value)) {
$grouping = -1;
- foreach ($pValue as $key => $value) {
+ foreach ($value as $key => $v) {
// Validate array entries
- if (!in_array($key, self::$dateTimeGroups)) {
+ if (!in_array($key, self::DATE_TIME_GROUPS)) {
// Remove any invalid entries from the value array
- unset($pValue[$key]);
+ unset($value[$key]);
} else {
// Work out what the dateTime grouping will be
- $grouping = max($grouping, array_search($key, self::$dateTimeGroups));
+ $grouping = max($grouping, array_search($key, self::DATE_TIME_GROUPS));
}
}
- if (count($pValue) == 0) {
+ 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::$dateTimeGroups[$grouping]);
+ $this->setGrouping(self::DATE_TIME_GROUPS[$grouping]);
}
- $this->value = $pValue;
+ $this->value = $value;
return $this;
}
@@ -328,22 +305,23 @@ class Rule
/**
* Set AutoFilter Rule Operator.
*
- * @param string $pOperator see self::AUTOFILTER_COLUMN_RULE_*
+ * @param string $operator see self::AUTOFILTER_COLUMN_RULE_*
*
* @return $this
*/
- public function setOperator($pOperator)
+ public function setOperator($operator)
{
- if (empty($pOperator)) {
- $pOperator = self::AUTOFILTER_COLUMN_RULE_EQUAL;
+ $this->setEvaluatedFalse();
+ if (empty($operator)) {
+ $operator = self::AUTOFILTER_COLUMN_RULE_EQUAL;
}
if (
- (!in_array($pOperator, self::$operators)) &&
- (!in_array($pOperator, self::$topTenValue))
+ (!in_array($operator, self::OPERATORS)) &&
+ (!in_array($operator, self::TOP_TEN_VALUE))
) {
throw new PhpSpreadsheetException('Invalid operator for column AutoFilter Rule.');
}
- $this->operator = $pOperator;
+ $this->operator = $operator;
return $this;
}
@@ -361,21 +339,22 @@ class Rule
/**
* Set AutoFilter Rule Grouping.
*
- * @param string $pGrouping
+ * @param string $grouping
*
* @return $this
*/
- public function setGrouping($pGrouping)
+ public function setGrouping($grouping)
{
+ $this->setEvaluatedFalse();
if (
- ($pGrouping !== null) &&
- (!in_array($pGrouping, self::$dateTimeGroups)) &&
- (!in_array($pGrouping, self::$dynamicTypes)) &&
- (!in_array($pGrouping, self::$topTenType))
+ ($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 rule type for column AutoFilter Rule.');
+ throw new PhpSpreadsheetException('Invalid grouping for column AutoFilter Rule.');
}
- $this->grouping = $pGrouping;
+ $this->grouping = $grouping;
return $this;
}
@@ -383,21 +362,22 @@ class Rule
/**
* Set AutoFilter Rule.
*
- * @param string $pOperator see self::AUTOFILTER_COLUMN_RULE_*
- * @param string|string[] $pValue
- * @param string $pGrouping
+ * @param string $operator see self::AUTOFILTER_COLUMN_RULE_*
+ * @param int|int[]|string|string[] $value
+ * @param string $grouping
*
* @return $this
*/
- public function setRule($pOperator, $pValue, $pGrouping = null)
+ public function setRule($operator, $value, $grouping = null)
{
- $this->setOperator($pOperator);
- $this->setValue($pValue);
+ $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 ($pGrouping !== null) {
- $this->setGrouping($pGrouping);
+ if ($grouping !== null) {
+ $this->setGrouping($grouping);
}
return $this;
@@ -406,7 +386,7 @@ class Rule
/**
* Get this Rule's AutoFilter Column Parent.
*
- * @return Column
+ * @return ?Column
*/
public function getParent()
{
@@ -416,13 +396,12 @@ class Rule
/**
* Set this Rule's AutoFilter Column Parent.
*
- * @param Column $pParent
- *
* @return $this
*/
- public function setParent(?Column $pParent = null)
+ public function setParent(?Column $parent = null)
{
- $this->parent = $pParent;
+ $this->setEvaluatedFalse();
+ $this->parent = $parent;
return $this;
}
@@ -435,11 +414,9 @@ class Rule
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
- if ($key == 'parent') {
+ if ($key == 'parent') { // this is only object
// Detach from autofilter column parent
$this->$key = null;
- } else {
- $this->$key = clone $value;
}
} else {
$this->$key = $value;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php
index be2f23df7d2..46f061589f8 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php
@@ -39,7 +39,7 @@ class BaseDrawing implements IComparable
/**
* Worksheet.
*
- * @var Worksheet
+ * @var null|Worksheet
*/
protected $worksheet;
@@ -106,6 +106,13 @@ class BaseDrawing implements IComparable
*/
private $hyperlink;
+ /**
+ * Image type.
+ *
+ * @var int
+ */
+ protected $type;
+
/**
* Create a new BaseDrawing.
*/
@@ -123,6 +130,7 @@ class BaseDrawing implements IComparable
$this->resizeProportional = true;
$this->rotation = 0;
$this->shadow = new Drawing\Shadow();
+ $this->type = IMAGETYPE_UNKNOWN;
// Set image index
++self::$imageCounter;
@@ -152,13 +160,13 @@ class BaseDrawing implements IComparable
/**
* Set Name.
*
- * @param string $pValue
+ * @param string $name
*
* @return $this
*/
- public function setName($pValue)
+ public function setName($name)
{
- $this->name = $pValue;
+ $this->name = $name;
return $this;
}
@@ -190,7 +198,7 @@ class BaseDrawing implements IComparable
/**
* Get Worksheet.
*
- * @return Worksheet
+ * @return null|Worksheet
*/
public function getWorksheet()
{
@@ -200,20 +208,19 @@ class BaseDrawing implements IComparable
/**
* Set Worksheet.
*
- * @param Worksheet $pValue
- * @param bool $pOverrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet?
+ * @param bool $overrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet?
*
* @return $this
*/
- public function setWorksheet(?Worksheet $pValue = null, $pOverrideOld = false)
+ public function setWorksheet(?Worksheet $worksheet = null, $overrideOld = false)
{
if ($this->worksheet === null) {
// Add drawing to \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
- $this->worksheet = $pValue;
+ $this->worksheet = $worksheet;
$this->worksheet->getCell($this->coordinates);
$this->worksheet->getDrawingCollection()->append($this);
} else {
- if ($pOverrideOld) {
+ if ($overrideOld) {
// Remove drawing from old \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
$iterator = $this->worksheet->getDrawingCollection()->getIterator();
@@ -227,7 +234,7 @@ class BaseDrawing implements IComparable
}
// Set new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
- $this->setWorksheet($pValue);
+ $this->setWorksheet($worksheet);
} else {
throw new PhpSpreadsheetException('A Worksheet has already been assigned. Drawings can only exist on one \\PhpOffice\\PhpSpreadsheet\\Worksheet.');
}
@@ -249,13 +256,13 @@ class BaseDrawing implements IComparable
/**
* Set Coordinates.
*
- * @param string $pValue eg: 'A1'
+ * @param string $coordinates eg: 'A1'
*
* @return $this
*/
- public function setCoordinates($pValue)
+ public function setCoordinates($coordinates)
{
- $this->coordinates = $pValue;
+ $this->coordinates = $coordinates;
return $this;
}
@@ -273,13 +280,13 @@ class BaseDrawing implements IComparable
/**
* Set OffsetX.
*
- * @param int $pValue
+ * @param int $offsetX
*
* @return $this
*/
- public function setOffsetX($pValue)
+ public function setOffsetX($offsetX)
{
- $this->offsetX = $pValue;
+ $this->offsetX = $offsetX;
return $this;
}
@@ -297,13 +304,13 @@ class BaseDrawing implements IComparable
/**
* Set OffsetY.
*
- * @param int $pValue
+ * @param int $offsetY
*
* @return $this
*/
- public function setOffsetY($pValue)
+ public function setOffsetY($offsetY)
{
- $this->offsetY = $pValue;
+ $this->offsetY = $offsetY;
return $this;
}
@@ -321,20 +328,20 @@ class BaseDrawing implements IComparable
/**
* Set Width.
*
- * @param int $pValue
+ * @param int $width
*
* @return $this
*/
- public function setWidth($pValue)
+ public function setWidth($width)
{
// Resize proportional?
- if ($this->resizeProportional && $pValue != 0) {
+ if ($this->resizeProportional && $width != 0) {
$ratio = $this->height / ($this->width != 0 ? $this->width : 1);
- $this->height = round($ratio * $pValue);
+ $this->height = (int) round($ratio * $width);
}
// Set width
- $this->width = $pValue;
+ $this->width = $width;
return $this;
}
@@ -352,20 +359,20 @@ class BaseDrawing implements IComparable
/**
* Set Height.
*
- * @param int $pValue
+ * @param int $height
*
* @return $this
*/
- public function setHeight($pValue)
+ public function setHeight($height)
{
// Resize proportional?
- if ($this->resizeProportional && $pValue != 0) {
+ if ($this->resizeProportional && $height != 0) {
$ratio = $this->width / ($this->height != 0 ? $this->height : 1);
- $this->width = round($ratio * $pValue);
+ $this->width = (int) round($ratio * $height);
}
// Set height
- $this->height = $pValue;
+ $this->height = $height;
return $this;
}
@@ -379,12 +386,12 @@ class BaseDrawing implements IComparable
* $objDrawing->setWidthAndHeight(160,120);
*
*
- * @author Vincent@luo MSN:kele_100@hotmail.com
- *
* @param int $width
* @param int $height
*
* @return $this
+ *
+ * @author Vincent@luo MSN:kele_100@hotmail.com
*/
public function setWidthAndHeight($width, $height)
{
@@ -392,10 +399,10 @@ class BaseDrawing implements IComparable
$yratio = $height / ($this->height != 0 ? $this->height : 1);
if ($this->resizeProportional && !($width == 0 || $height == 0)) {
if (($xratio * $this->height) < $height) {
- $this->height = ceil($xratio * $this->height);
+ $this->height = (int) ceil($xratio * $this->height);
$this->width = $width;
} else {
- $this->width = ceil($yratio * $this->width);
+ $this->width = (int) ceil($yratio * $this->width);
$this->height = $height;
}
} else {
@@ -419,13 +426,13 @@ class BaseDrawing implements IComparable
/**
* Set ResizeProportional.
*
- * @param bool $pValue
+ * @param bool $resizeProportional
*
* @return $this
*/
- public function setResizeProportional($pValue)
+ public function setResizeProportional($resizeProportional)
{
- $this->resizeProportional = $pValue;
+ $this->resizeProportional = $resizeProportional;
return $this;
}
@@ -443,13 +450,13 @@ class BaseDrawing implements IComparable
/**
* Set Rotation.
*
- * @param int $pValue
+ * @param int $rotation
*
* @return $this
*/
- public function setRotation($pValue)
+ public function setRotation($rotation)
{
- $this->rotation = $pValue;
+ $this->rotation = $rotation;
return $this;
}
@@ -467,13 +474,11 @@ class BaseDrawing implements IComparable
/**
* Set Shadow.
*
- * @param Drawing\Shadow $pValue
- *
* @return $this
*/
- public function setShadow(?Drawing\Shadow $pValue = null)
+ public function setShadow(?Drawing\Shadow $shadow = null)
{
- $this->shadow = $pValue;
+ $this->shadow = $shadow;
return $this;
}
@@ -517,9 +522,9 @@ class BaseDrawing implements IComparable
}
}
- public function setHyperlink(?Hyperlink $pHyperlink = null): void
+ public function setHyperlink(?Hyperlink $hyperlink = null): void
{
- $this->hyperlink = $pHyperlink;
+ $this->hyperlink = $hyperlink;
}
/**
@@ -529,4 +534,28 @@ class BaseDrawing implements IComparable
{
return $this->hyperlink;
}
+
+ /**
+ * Set Fact Sizes and Type of Image.
+ */
+ protected function setSizesAndType(string $path): void
+ {
+ if ($this->width == 0 && $this->height == 0 && $this->type == IMAGETYPE_UNKNOWN) {
+ $imageData = getimagesize($path);
+
+ if (is_array($imageData)) {
+ $this->width = $imageData[0];
+ $this->height = $imageData[1];
+ $this->type = $imageData[2];
+ }
+ }
+ }
+
+ /**
+ * Get Image Type.
+ */
+ public function getType(): int
+ {
+ return $this->type;
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php
index 45f76cab371..444e3b1fae5 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php
@@ -3,7 +3,12 @@
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use Iterator;
+use PhpOffice\PhpSpreadsheet\Cell\Cell;
+/**
+ * @template TKey
+ * @implements Iterator
+ */
abstract class CellIterator implements Iterator
{
/**
@@ -25,15 +30,14 @@ abstract class CellIterator implements Iterator
*/
public function __destruct()
{
+ // @phpstan-ignore-next-line
$this->worksheet = null;
}
/**
* Get loop only existing cells.
- *
- * @return bool
*/
- public function getIterateOnlyExistingCells()
+ public function getIterateOnlyExistingCells(): bool
{
return $this->onlyExistingCells;
}
@@ -45,10 +49,8 @@ abstract class CellIterator implements Iterator
/**
* Set the iterator to loop only existing cells.
- *
- * @param bool $value
*/
- public function setIterateOnlyExistingCells($value): void
+ public function setIterateOnlyExistingCells(bool $value): void
{
$this->onlyExistingCells = (bool) $value;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php
index 410e80735a2..b6f30f1f984 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php
@@ -21,7 +21,6 @@ class Column
/**
* Create a new column.
*
- * @param Worksheet $parent
* @param string $columnIndex
*/
public function __construct(?Worksheet $parent = null, $columnIndex = 'A')
@@ -36,15 +35,14 @@ class Column
*/
public function __destruct()
{
+ // @phpstan-ignore-next-line
$this->parent = null;
}
/**
* Get column index as string eg: 'A'.
- *
- * @return string
*/
- public function getColumnIndex()
+ public function getColumnIndex(): string
{
return $this->columnIndex;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php
index 714ee7ce3bf..9d0be5bd470 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php
@@ -2,9 +2,13 @@
namespace PhpOffice\PhpSpreadsheet\Worksheet;
+use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
+/**
+ * @extends CellIterator
+ */
class ColumnCellIterator extends CellIterator
{
/**
@@ -17,7 +21,7 @@ class ColumnCellIterator extends CellIterator
/**
* Column index.
*
- * @var string
+ * @var int
*/
private $columnIndex;
@@ -43,7 +47,7 @@ class ColumnCellIterator extends CellIterator
* @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 = null, $columnIndex = 'A', $startRow = 1, $endRow = null)
+ public function __construct(Worksheet $subject, $columnIndex = 'A', $startRow = 1, $endRow = null)
{
// Set subject
$this->worksheet = $subject;
@@ -59,7 +63,7 @@ class ColumnCellIterator extends CellIterator
*
* @return $this
*/
- public function resetStart($startRow = 1)
+ public function resetStart(int $startRow = 1)
{
$this->startRow = $startRow;
$this->adjustForExistingOnlyRange();
@@ -77,7 +81,7 @@ class ColumnCellIterator extends CellIterator
*/
public function resetEnd($endRow = null)
{
- $this->endRow = ($endRow) ? $endRow : $this->worksheet->getHighestRow();
+ $this->endRow = $endRow ?: $this->worksheet->getHighestRow();
$this->adjustForExistingOnlyRange();
return $this;
@@ -90,7 +94,7 @@ class ColumnCellIterator extends CellIterator
*
* @return $this
*/
- public function seek($row = 1)
+ public function seek(int $row = 1)
{
if ($this->onlyExistingCells && !($this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $row))) {
throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist');
@@ -113,20 +117,16 @@ class ColumnCellIterator extends CellIterator
/**
* Return the current cell in this worksheet column.
- *
- * @return \PhpOffice\PhpSpreadsheet\Cell\Cell
*/
- public function current()
+ public function current(): ?Cell
{
return $this->worksheet->getCellByColumnAndRow($this->columnIndex, $this->currentRow);
}
/**
* Return the current iterator key.
- *
- * @return int
*/
- public function key()
+ public function key(): int
{
return $this->currentRow;
}
@@ -161,10 +161,8 @@ class ColumnCellIterator extends CellIterator
/**
* Indicate if more rows exist in the worksheet range of rows that we're iterating.
- *
- * @return bool
*/
- public function valid()
+ public function valid(): bool
{
return $this->currentRow <= $this->endRow && $this->currentRow >= $this->startRow;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php
index 4e87a344c80..8a48f470c15 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php
@@ -2,6 +2,8 @@
namespace PhpOffice\PhpSpreadsheet\Worksheet;
+use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension;
+
class ColumnDimension extends Dimension
{
/**
@@ -30,12 +32,12 @@ class ColumnDimension extends Dimension
/**
* Create a new ColumnDimension.
*
- * @param string $pIndex Character column index
+ * @param string $index Character column index
*/
- public function __construct($pIndex = 'A')
+ public function __construct($index = 'A')
{
// Initialise values
- $this->columnIndex = $pIndex;
+ $this->columnIndex = $index;
// set dimension as unformatted by default
parent::__construct(0);
@@ -43,10 +45,8 @@ class ColumnDimension extends Dimension
/**
* Get column index as string eg: 'A'.
- *
- * @return string
*/
- public function getColumnIndex()
+ public function getColumnIndex(): string
{
return $this->columnIndex;
}
@@ -54,13 +54,11 @@ class ColumnDimension extends Dimension
/**
* Set column index as string eg: 'A'.
*
- * @param string $pValue
- *
* @return $this
*/
- public function setColumnIndex($pValue)
+ public function setColumnIndex(string $index)
{
- $this->columnIndex = $pValue;
+ $this->columnIndex = $index;
return $this;
}
@@ -68,33 +66,39 @@ class ColumnDimension extends Dimension
/**
* Get Width.
*
- * @return float
+ * Each unit of column width is equal to the width of one character in the default font size.
+ * By default, this will be the return value; but this method also accepts a unit of measure argument and will
+ * return the value converted to the specified UoM using an approximation method.
*/
- public function getWidth()
+ public function getWidth(?string $unitOfMeasure = null): float
{
- return $this->width;
+ return ($unitOfMeasure === null || $this->width < 0)
+ ? $this->width
+ : (new CssDimension((string) $this->width))->toUnit($unitOfMeasure);
}
/**
* Set Width.
*
- * @param float $pValue
+ * Each unit of column width is equal to the width of one character in the default font size.
+ * By default, this will be the unit of measure for the passed value; but this method accepts a unit of measure
+ * argument, and will convert the value from the specified UoM using an approximation method.
*
* @return $this
*/
- public function setWidth($pValue)
+ public function setWidth(float $width, ?string $unitOfMeasure = null)
{
- $this->width = $pValue;
+ $this->width = ($unitOfMeasure === null || $width < 0)
+ ? $width
+ : (new CssDimension("{$width}{$unitOfMeasure}"))->width();
return $this;
}
/**
* Get Auto Size.
- *
- * @return bool
*/
- public function getAutoSize()
+ public function getAutoSize(): bool
{
return $this->autoSize;
}
@@ -102,13 +106,11 @@ class ColumnDimension extends Dimension
/**
* Set Auto Size.
*
- * @param bool $pValue
- *
* @return $this
*/
- public function setAutoSize($pValue)
+ public function setAutoSize(bool $autosizeEnabled)
{
- $this->autoSize = $pValue;
+ $this->autoSize = $autosizeEnabled;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php
index d0bb20cc968..b64ae5a4839 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php
@@ -7,6 +7,9 @@ use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
+/**
+ * @implements Iterator
+ */
class ColumnIterator implements Iterator
{
/**
@@ -57,6 +60,7 @@ class ColumnIterator implements Iterator
*/
public function __destruct()
{
+ // @phpstan-ignore-next-line
$this->worksheet = null;
}
@@ -67,11 +71,13 @@ class ColumnIterator implements Iterator
*
* @return $this
*/
- public function resetStart($startColumn = 'A')
+ 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()})");
+ throw new Exception(
+ "Start column ({$startColumn}) is beyond highest column ({$this->worksheet->getHighestColumn()})"
+ );
}
$this->startColumnIndex = $startColumnIndex;
@@ -92,7 +98,7 @@ class ColumnIterator implements Iterator
*/
public function resetEnd($endColumn = null)
{
- $endColumn = $endColumn ? $endColumn : $this->worksheet->getHighestColumn();
+ $endColumn = $endColumn ?: $this->worksheet->getHighestColumn();
$this->endColumnIndex = Coordinate::columnIndexFromString($endColumn);
return $this;
@@ -105,11 +111,13 @@ class ColumnIterator implements Iterator
*
* @return $this
*/
- public function seek($column = 'A')
+ 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})");
+ throw new PhpSpreadsheetException(
+ "Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})"
+ );
}
$this->currentColumnIndex = $column;
@@ -126,20 +134,16 @@ class ColumnIterator implements Iterator
/**
* Return the current column in this worksheet.
- *
- * @return Column
*/
- public function current()
+ public function current(): Column
{
return new Column($this->worksheet, Coordinate::stringFromColumnIndex($this->currentColumnIndex));
}
/**
* Return the current iterator key.
- *
- * @return string
*/
- public function key()
+ public function key(): string
{
return Coordinate::stringFromColumnIndex($this->currentColumnIndex);
}
@@ -162,10 +166,8 @@ class ColumnIterator implements Iterator
/**
* Indicate if more columns exist in the worksheet range of columns that we're iterating.
- *
- * @return bool
*/
- public function valid()
+ public function valid(): bool
{
return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php
index a27daf092d9..894ac19ed49 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php
@@ -47,10 +47,8 @@ abstract class Dimension
/**
* Get Visible.
- *
- * @return bool
*/
- public function getVisible()
+ public function getVisible(): bool
{
return $this->visible;
}
@@ -58,23 +56,19 @@ abstract class Dimension
/**
* Set Visible.
*
- * @param bool $pValue
- *
* @return $this
*/
- public function setVisible($pValue)
+ public function setVisible(bool $visible)
{
- $this->visible = (bool) $pValue;
+ $this->visible = $visible;
return $this;
}
/**
* Get Outline Level.
- *
- * @return int
*/
- public function getOutlineLevel()
+ public function getOutlineLevel(): int
{
return $this->outlineLevel;
}
@@ -83,27 +77,23 @@ abstract class Dimension
* Set Outline Level.
* Value must be between 0 and 7.
*
- * @param int $pValue
- *
* @return $this
*/
- public function setOutlineLevel($pValue)
+ public function setOutlineLevel(int $level)
{
- if ($pValue < 0 || $pValue > 7) {
+ if ($level < 0 || $level > 7) {
throw new PhpSpreadsheetException('Outline level must range between 0 and 7.');
}
- $this->outlineLevel = $pValue;
+ $this->outlineLevel = $level;
return $this;
}
/**
* Get Collapsed.
- *
- * @return bool
*/
- public function getCollapsed()
+ public function getCollapsed(): bool
{
return $this->collapsed;
}
@@ -111,13 +101,11 @@ abstract class Dimension
/**
* Set Collapsed.
*
- * @param bool $pValue
- *
* @return $this
*/
- public function setCollapsed($pValue)
+ public function setCollapsed(bool $collapsed)
{
- $this->collapsed = (bool) $pValue;
+ $this->collapsed = $collapsed;
return $this;
}
@@ -127,7 +115,7 @@ abstract class Dimension
*
* @return int
*/
- public function getXfIndex()
+ public function getXfIndex(): ?int
{
return $this->xfIndex;
}
@@ -135,13 +123,11 @@ abstract class Dimension
/**
* Set index to cellXf.
*
- * @param int $pValue
- *
* @return $this
*/
- public function setXfIndex($pValue)
+ public function setXfIndex(int $XfIndex)
{
- $this->xfIndex = $pValue;
+ $this->xfIndex = $XfIndex;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php
index 1f1dae93abe..f62873bbae4 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php
@@ -3,9 +3,17 @@
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.
*
@@ -13,6 +21,13 @@ class Drawing extends BaseDrawing
*/
private $path;
+ /**
+ * Whether or not we are dealing with a URL.
+ *
+ * @var bool
+ */
+ private $isUrl;
+
/**
* Create a new Drawing.
*/
@@ -20,6 +35,7 @@ class Drawing extends BaseDrawing
{
// Initialise values
$this->path = '';
+ $this->isUrl = false;
// Initialize parent
parent::__construct();
@@ -37,15 +53,10 @@ class Drawing extends BaseDrawing
/**
* Get indexed filename (using image index).
- *
- * @return string
*/
- public function getIndexedFilename()
+ public function getIndexedFilename(): string
{
- $fileName = $this->getFilename();
- $fileName = str_replace(' ', '_', $fileName);
-
- return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension();
+ return md5($this->path) . '.' . $this->getExtension();
}
/**
@@ -60,6 +71,20 @@ class Drawing extends BaseDrawing
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.
*
@@ -73,31 +98,68 @@ class Drawing extends BaseDrawing
/**
* Set Path.
*
- * @param string $pValue File path
- * @param bool $pVerifyFile Verify file
+ * @param string $path File path
+ * @param bool $verifyFile Verify file
+ * @param ZipArchive $zip Zip archive instance
*
* @return $this
*/
- public function setPath($pValue, $pVerifyFile = true)
+ public function setPath($path, $verifyFile = true, $zip = null)
{
- if ($pVerifyFile) {
- if (file_exists($pValue)) {
- $this->path = $pValue;
-
- if ($this->width == 0 && $this->height == 0) {
- // Get width/height
- [$this->width, $this->height] = getimagesize($pValue);
+ if ($verifyFile) {
+ // 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 $pValue not found!");
+ throw new PhpSpreadsheetException("File $path not found!");
}
} else {
- $this->path = $pValue;
+ $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.
*
@@ -111,4 +173,42 @@ class Drawing extends BaseDrawing
__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 is_string($result) ? $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]);
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php
index 01ffed94d2f..a461a51bb2e 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php
@@ -52,7 +52,7 @@ class Shadow implements IComparable
/**
* Shadow alignment.
*
- * @var int
+ * @var string
*/
private $alignment;
@@ -98,13 +98,13 @@ class Shadow implements IComparable
/**
* Set Visible.
*
- * @param bool $pValue
+ * @param bool $visible
*
* @return $this
*/
- public function setVisible($pValue)
+ public function setVisible($visible)
{
- $this->visible = $pValue;
+ $this->visible = $visible;
return $this;
}
@@ -122,13 +122,13 @@ class Shadow implements IComparable
/**
* Set Blur radius.
*
- * @param int $pValue
+ * @param int $blurRadius
*
* @return $this
*/
- public function setBlurRadius($pValue)
+ public function setBlurRadius($blurRadius)
{
- $this->blurRadius = $pValue;
+ $this->blurRadius = $blurRadius;
return $this;
}
@@ -146,13 +146,13 @@ class Shadow implements IComparable
/**
* Set Shadow distance.
*
- * @param int $pValue
+ * @param int $distance
*
* @return $this
*/
- public function setDistance($pValue)
+ public function setDistance($distance)
{
- $this->distance = $pValue;
+ $this->distance = $distance;
return $this;
}
@@ -170,13 +170,13 @@ class Shadow implements IComparable
/**
* Set Shadow direction (in degrees).
*
- * @param int $pValue
+ * @param int $direction
*
* @return $this
*/
- public function setDirection($pValue)
+ public function setDirection($direction)
{
- $this->direction = $pValue;
+ $this->direction = $direction;
return $this;
}
@@ -184,7 +184,7 @@ class Shadow implements IComparable
/**
* Get Shadow alignment.
*
- * @return int
+ * @return string
*/
public function getAlignment()
{
@@ -194,13 +194,13 @@ class Shadow implements IComparable
/**
* Set Shadow alignment.
*
- * @param int $pValue
+ * @param string $alignment
*
* @return $this
*/
- public function setAlignment($pValue)
+ public function setAlignment($alignment)
{
- $this->alignment = $pValue;
+ $this->alignment = $alignment;
return $this;
}
@@ -218,13 +218,11 @@ class Shadow implements IComparable
/**
* Set Color.
*
- * @param Color $pValue
- *
* @return $this
*/
- public function setColor(?Color $pValue = null)
+ public function setColor(?Color $color = null)
{
- $this->color = $pValue;
+ $this->color = $color;
return $this;
}
@@ -242,13 +240,13 @@ class Shadow implements IComparable
/**
* Set Alpha.
*
- * @param int $pValue
+ * @param int $alpha
*
* @return $this
*/
- public function setAlpha($pValue)
+ public function setAlpha($alpha)
{
- $this->alpha = $pValue;
+ $this->alpha = $alpha;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php
index cc37e7f5df9..c3504d831be 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php
@@ -170,13 +170,13 @@ class HeaderFooter
/**
* Set OddHeader.
*
- * @param string $pValue
+ * @param string $oddHeader
*
* @return $this
*/
- public function setOddHeader($pValue)
+ public function setOddHeader($oddHeader)
{
- $this->oddHeader = $pValue;
+ $this->oddHeader = $oddHeader;
return $this;
}
@@ -194,13 +194,13 @@ class HeaderFooter
/**
* Set OddFooter.
*
- * @param string $pValue
+ * @param string $oddFooter
*
* @return $this
*/
- public function setOddFooter($pValue)
+ public function setOddFooter($oddFooter)
{
- $this->oddFooter = $pValue;
+ $this->oddFooter = $oddFooter;
return $this;
}
@@ -218,13 +218,13 @@ class HeaderFooter
/**
* Set EvenHeader.
*
- * @param string $pValue
+ * @param string $eventHeader
*
* @return $this
*/
- public function setEvenHeader($pValue)
+ public function setEvenHeader($eventHeader)
{
- $this->evenHeader = $pValue;
+ $this->evenHeader = $eventHeader;
return $this;
}
@@ -242,13 +242,13 @@ class HeaderFooter
/**
* Set EvenFooter.
*
- * @param string $pValue
+ * @param string $evenFooter
*
* @return $this
*/
- public function setEvenFooter($pValue)
+ public function setEvenFooter($evenFooter)
{
- $this->evenFooter = $pValue;
+ $this->evenFooter = $evenFooter;
return $this;
}
@@ -266,13 +266,13 @@ class HeaderFooter
/**
* Set FirstHeader.
*
- * @param string $pValue
+ * @param string $firstHeader
*
* @return $this
*/
- public function setFirstHeader($pValue)
+ public function setFirstHeader($firstHeader)
{
- $this->firstHeader = $pValue;
+ $this->firstHeader = $firstHeader;
return $this;
}
@@ -290,13 +290,13 @@ class HeaderFooter
/**
* Set FirstFooter.
*
- * @param string $pValue
+ * @param string $firstFooter
*
* @return $this
*/
- public function setFirstFooter($pValue)
+ public function setFirstFooter($firstFooter)
{
- $this->firstFooter = $pValue;
+ $this->firstFooter = $firstFooter;
return $this;
}
@@ -314,13 +314,13 @@ class HeaderFooter
/**
* Set DifferentOddEven.
*
- * @param bool $pValue
+ * @param bool $differentOddEvent
*
* @return $this
*/
- public function setDifferentOddEven($pValue)
+ public function setDifferentOddEven($differentOddEvent)
{
- $this->differentOddEven = $pValue;
+ $this->differentOddEven = $differentOddEvent;
return $this;
}
@@ -338,13 +338,13 @@ class HeaderFooter
/**
* Set DifferentFirst.
*
- * @param bool $pValue
+ * @param bool $differentFirst
*
* @return $this
*/
- public function setDifferentFirst($pValue)
+ public function setDifferentFirst($differentFirst)
{
- $this->differentFirst = $pValue;
+ $this->differentFirst = $differentFirst;
return $this;
}
@@ -362,13 +362,13 @@ class HeaderFooter
/**
* Set ScaleWithDocument.
*
- * @param bool $pValue
+ * @param bool $scaleWithDocument
*
* @return $this
*/
- public function setScaleWithDocument($pValue)
+ public function setScaleWithDocument($scaleWithDocument)
{
- $this->scaleWithDocument = $pValue;
+ $this->scaleWithDocument = $scaleWithDocument;
return $this;
}
@@ -386,13 +386,13 @@ class HeaderFooter
/**
* Set AlignWithMargins.
*
- * @param bool $pValue
+ * @param bool $alignWithMargins
*
* @return $this
*/
- public function setAlignWithMargins($pValue)
+ public function setAlignWithMargins($alignWithMargins)
{
- $this->alignWithMargins = $pValue;
+ $this->alignWithMargins = $alignWithMargins;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php
index 6cfed37a475..dc082043e45 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php
@@ -4,6 +4,9 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
+/**
+ * @implements \Iterator
+ */
class Iterator implements \Iterator
{
/**
@@ -29,14 +32,6 @@ class Iterator implements \Iterator
$this->subject = $subject;
}
- /**
- * Destructor.
- */
- public function __destruct()
- {
- $this->subject = null;
- }
-
/**
* Rewind iterator.
*/
@@ -47,20 +42,16 @@ class Iterator implements \Iterator
/**
* Current Worksheet.
- *
- * @return Worksheet
*/
- public function current()
+ public function current(): Worksheet
{
return $this->subject->getSheet($this->position);
}
/**
* Current key.
- *
- * @return int
*/
- public function key()
+ public function key(): int
{
return $this->position;
}
@@ -75,10 +66,8 @@ class Iterator implements \Iterator
/**
* Are there more Worksheet instances available?
- *
- * @return bool
*/
- public function valid()
+ public function valid(): bool
{
return $this->position < $this->subject->getSheetCount() && $this->position >= 0;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php
index fb002114fd9..91acbb7b8f4 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php
@@ -3,6 +3,7 @@
namespace PhpOffice\PhpSpreadsheet\Worksheet;
use GdImage;
+use PhpOffice\PhpSpreadsheet\Exception;
class MemoryDrawing extends BaseDrawing
{
@@ -21,7 +22,7 @@ class MemoryDrawing extends BaseDrawing
/**
* Image resource.
*
- * @var GdImage|resource
+ * @var null|GdImage|resource
*/
private $imageResource;
@@ -52,7 +53,6 @@ class MemoryDrawing extends BaseDrawing
public function __construct()
{
// Initialise values
- $this->imageResource = null;
$this->renderingFunction = self::RENDERING_DEFAULT;
$this->mimeType = self::MIMETYPE_DEFAULT;
$this->uniqueName = md5(mt_rand(0, 9999) . time() . mt_rand(0, 9999));
@@ -61,10 +61,71 @@ class MemoryDrawing extends BaseDrawing
parent::__construct();
}
+ public function __destruct()
+ {
+ if ($this->imageResource) {
+ imagedestroy($this->imageResource);
+ $this->imageResource = null;
+ }
+ }
+
+ public function __clone()
+ {
+ parent::__clone();
+ $this->cloneResource();
+ }
+
+ private function cloneResource(): void
+ {
+ if (!$this->imageResource) {
+ return;
+ }
+
+ $width = imagesx($this->imageResource);
+ $height = 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;
+ }
+
/**
* Get image resource.
*
- * @return GdImage|resource
+ * @return null|GdImage|resource
*/
public function getImageResource()
{
@@ -141,10 +202,8 @@ class MemoryDrawing extends BaseDrawing
/**
* Get indexed filename (using image index).
- *
- * @return string
*/
- public function getIndexedFilename()
+ public function getIndexedFilename(): string
{
$extension = strtolower($this->getMimeType());
$extension = explode('/', $extension);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php
index a8297933ade..34e1145e04a 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php
@@ -66,13 +66,13 @@ class PageMargins
/**
* Set Left.
*
- * @param float $pValue
+ * @param float $left
*
* @return $this
*/
- public function setLeft($pValue)
+ public function setLeft($left)
{
- $this->left = $pValue;
+ $this->left = $left;
return $this;
}
@@ -90,13 +90,13 @@ class PageMargins
/**
* Set Right.
*
- * @param float $pValue
+ * @param float $right
*
* @return $this
*/
- public function setRight($pValue)
+ public function setRight($right)
{
- $this->right = $pValue;
+ $this->right = $right;
return $this;
}
@@ -114,13 +114,13 @@ class PageMargins
/**
* Set Top.
*
- * @param float $pValue
+ * @param float $top
*
* @return $this
*/
- public function setTop($pValue)
+ public function setTop($top)
{
- $this->top = $pValue;
+ $this->top = $top;
return $this;
}
@@ -138,13 +138,13 @@ class PageMargins
/**
* Set Bottom.
*
- * @param float $pValue
+ * @param float $bottom
*
* @return $this
*/
- public function setBottom($pValue)
+ public function setBottom($bottom)
{
- $this->bottom = $pValue;
+ $this->bottom = $bottom;
return $this;
}
@@ -162,13 +162,13 @@ class PageMargins
/**
* Set Header.
*
- * @param float $pValue
+ * @param float $header
*
* @return $this
*/
- public function setHeader($pValue)
+ public function setHeader($header)
{
- $this->header = $pValue;
+ $this->header = $header;
return $this;
}
@@ -186,13 +186,13 @@ class PageMargins
/**
* Set Footer.
*
- * @param float $pValue
+ * @param float $footer
*
* @return $this
*/
- public function setFooter($pValue)
+ public function setFooter($footer)
{
- $this->footer = $pValue;
+ $this->footer = $footer;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php
index d1a22a7b0a5..9640782877e 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php
@@ -160,18 +160,32 @@ class PageSetup
const PAGEORDER_DOWN_THEN_OVER = 'downThenOver';
/**
- * Paper size.
+ * Paper size default.
*
* @var int
*/
- private $paperSize = self::PAPERSIZE_LETTER;
+ 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 = self::ORIENTATION_DEFAULT;
+ private $orientation;
/**
* Scale (Print Scale).
@@ -238,7 +252,7 @@ class PageSetup
/**
* Print area.
*
- * @var string
+ * @var null|string
*/
private $printArea;
@@ -256,6 +270,7 @@ class PageSetup
*/
public function __construct()
{
+ $this->orientation = self::$orientationDefault;
}
/**
@@ -265,23 +280,39 @@ class PageSetup
*/
public function getPaperSize()
{
- return $this->paperSize;
+ return $this->paperSize ?? self::$paperSizeDefault;
}
/**
* Set Paper Size.
*
- * @param int $pValue see self::PAPERSIZE_*
+ * @param int $paperSize see self::PAPERSIZE_*
*
* @return $this
*/
- public function setPaperSize($pValue)
+ public function setPaperSize($paperSize)
{
- $this->paperSize = $pValue;
+ $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.
*
@@ -295,17 +326,31 @@ class PageSetup
/**
* Set Orientation.
*
- * @param string $pValue see self::ORIENTATION_*
+ * @param string $orientation see self::ORIENTATION_*
*
* @return $this
*/
- public function setOrientation($pValue)
+ public function setOrientation($orientation)
{
- $this->orientation = $pValue;
+ 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.
*
@@ -321,18 +366,18 @@ class PageSetup
* Print scaling. Valid values range from 10 to 400
* This setting is overridden when fitToWidth and/or fitToHeight are in use.
*
- * @param null|int $pValue
- * @param bool $pUpdate Update fitToPage so scaling applies rather than fitToHeight / fitToWidth
+ * @param null|int $scale
+ * @param bool $update Update fitToPage so scaling applies rather than fitToHeight / fitToWidth
*
* @return $this
*/
- public function setScale($pValue, $pUpdate = true)
+ 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 (($pValue >= 0) || $pValue === null) {
- $this->scale = $pValue;
- if ($pUpdate) {
+ if (($scale >= 0) || $scale === null) {
+ $this->scale = $scale;
+ if ($update) {
$this->fitToPage = false;
}
} else {
@@ -355,13 +400,13 @@ class PageSetup
/**
* Set Fit To Page.
*
- * @param bool $pValue
+ * @param bool $fitToPage
*
* @return $this
*/
- public function setFitToPage($pValue)
+ public function setFitToPage($fitToPage)
{
- $this->fitToPage = $pValue;
+ $this->fitToPage = $fitToPage;
return $this;
}
@@ -379,15 +424,15 @@ class PageSetup
/**
* Set Fit To Height.
*
- * @param null|int $pValue
- * @param bool $pUpdate Update fitToPage so it applies rather than scaling
+ * @param null|int $fitToHeight
+ * @param bool $update Update fitToPage so it applies rather than scaling
*
* @return $this
*/
- public function setFitToHeight($pValue, $pUpdate = true)
+ public function setFitToHeight($fitToHeight, $update = true)
{
- $this->fitToHeight = $pValue;
- if ($pUpdate) {
+ $this->fitToHeight = $fitToHeight;
+ if ($update) {
$this->fitToPage = true;
}
@@ -407,15 +452,15 @@ class PageSetup
/**
* Set Fit To Width.
*
- * @param null|int $pValue
- * @param bool $pUpdate Update fitToPage so it applies rather than scaling
+ * @param null|int $value
+ * @param bool $update Update fitToPage so it applies rather than scaling
*
* @return $this
*/
- public function setFitToWidth($pValue, $pUpdate = true)
+ public function setFitToWidth($value, $update = true)
{
- $this->fitToWidth = $pValue;
- if ($pUpdate) {
+ $this->fitToWidth = $value;
+ if ($update) {
$this->fitToPage = true;
}
@@ -451,13 +496,13 @@ class PageSetup
/**
* Set Columns to repeat at left.
*
- * @param array $pValue Containing start column and end column, empty array if option unset
+ * @param array $columnsToRepeatAtLeft Containing start column and end column, empty array if option unset
*
* @return $this
*/
- public function setColumnsToRepeatAtLeft(array $pValue)
+ public function setColumnsToRepeatAtLeft(array $columnsToRepeatAtLeft)
{
- $this->columnsToRepeatAtLeft = $pValue;
+ $this->columnsToRepeatAtLeft = $columnsToRepeatAtLeft;
return $this;
}
@@ -465,14 +510,14 @@ class PageSetup
/**
* Set Columns to repeat at left by start and end.
*
- * @param string $pStart eg: 'A'
- * @param string $pEnd eg: 'B'
+ * @param string $start eg: 'A'
+ * @param string $end eg: 'B'
*
* @return $this
*/
- public function setColumnsToRepeatAtLeftByStartAndEnd($pStart, $pEnd)
+ public function setColumnsToRepeatAtLeftByStartAndEnd($start, $end)
{
- $this->columnsToRepeatAtLeft = [$pStart, $pEnd];
+ $this->columnsToRepeatAtLeft = [$start, $end];
return $this;
}
@@ -506,13 +551,13 @@ class PageSetup
/**
* Set Rows to repeat at top.
*
- * @param array $pValue Containing start column and end column, empty array if option unset
+ * @param array $rowsToRepeatAtTop Containing start column and end column, empty array if option unset
*
* @return $this
*/
- public function setRowsToRepeatAtTop(array $pValue)
+ public function setRowsToRepeatAtTop(array $rowsToRepeatAtTop)
{
- $this->rowsToRepeatAtTop = $pValue;
+ $this->rowsToRepeatAtTop = $rowsToRepeatAtTop;
return $this;
}
@@ -520,14 +565,14 @@ class PageSetup
/**
* Set Rows to repeat at top by start and end.
*
- * @param int $pStart eg: 1
- * @param int $pEnd eg: 1
+ * @param int $start eg: 1
+ * @param int $end eg: 1
*
* @return $this
*/
- public function setRowsToRepeatAtTopByStartAndEnd($pStart, $pEnd)
+ public function setRowsToRepeatAtTopByStartAndEnd($start, $end)
{
- $this->rowsToRepeatAtTop = [$pStart, $pEnd];
+ $this->rowsToRepeatAtTop = [$start, $end];
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php
index ba3af0a799e..4d44d8e5d67 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php
@@ -202,13 +202,13 @@ class Protection
/**
* Set Sheet.
*
- * @param bool $pValue
+ * @param bool $sheet
*
* @return $this
*/
- public function setSheet($pValue)
+ public function setSheet($sheet)
{
- $this->sheet = $pValue;
+ $this->sheet = $sheet;
return $this;
}
@@ -226,13 +226,13 @@ class Protection
/**
* Set Objects.
*
- * @param bool $pValue
+ * @param bool $objects
*
* @return $this
*/
- public function setObjects($pValue)
+ public function setObjects($objects)
{
- $this->objects = $pValue;
+ $this->objects = $objects;
return $this;
}
@@ -250,13 +250,13 @@ class Protection
/**
* Set Scenarios.
*
- * @param bool $pValue
+ * @param bool $scenarios
*
* @return $this
*/
- public function setScenarios($pValue)
+ public function setScenarios($scenarios)
{
- $this->scenarios = $pValue;
+ $this->scenarios = $scenarios;
return $this;
}
@@ -274,13 +274,13 @@ class Protection
/**
* Set FormatCells.
*
- * @param bool $pValue
+ * @param bool $formatCells
*
* @return $this
*/
- public function setFormatCells($pValue)
+ public function setFormatCells($formatCells)
{
- $this->formatCells = $pValue;
+ $this->formatCells = $formatCells;
return $this;
}
@@ -298,13 +298,13 @@ class Protection
/**
* Set FormatColumns.
*
- * @param bool $pValue
+ * @param bool $formatColumns
*
* @return $this
*/
- public function setFormatColumns($pValue)
+ public function setFormatColumns($formatColumns)
{
- $this->formatColumns = $pValue;
+ $this->formatColumns = $formatColumns;
return $this;
}
@@ -322,13 +322,13 @@ class Protection
/**
* Set FormatRows.
*
- * @param bool $pValue
+ * @param bool $formatRows
*
* @return $this
*/
- public function setFormatRows($pValue)
+ public function setFormatRows($formatRows)
{
- $this->formatRows = $pValue;
+ $this->formatRows = $formatRows;
return $this;
}
@@ -346,13 +346,13 @@ class Protection
/**
* Set InsertColumns.
*
- * @param bool $pValue
+ * @param bool $insertColumns
*
* @return $this
*/
- public function setInsertColumns($pValue)
+ public function setInsertColumns($insertColumns)
{
- $this->insertColumns = $pValue;
+ $this->insertColumns = $insertColumns;
return $this;
}
@@ -370,13 +370,13 @@ class Protection
/**
* Set InsertRows.
*
- * @param bool $pValue
+ * @param bool $insertRows
*
* @return $this
*/
- public function setInsertRows($pValue)
+ public function setInsertRows($insertRows)
{
- $this->insertRows = $pValue;
+ $this->insertRows = $insertRows;
return $this;
}
@@ -394,13 +394,13 @@ class Protection
/**
* Set InsertHyperlinks.
*
- * @param bool $pValue
+ * @param bool $insertHyperLinks
*
* @return $this
*/
- public function setInsertHyperlinks($pValue)
+ public function setInsertHyperlinks($insertHyperLinks)
{
- $this->insertHyperlinks = $pValue;
+ $this->insertHyperlinks = $insertHyperLinks;
return $this;
}
@@ -418,13 +418,13 @@ class Protection
/**
* Set DeleteColumns.
*
- * @param bool $pValue
+ * @param bool $deleteColumns
*
* @return $this
*/
- public function setDeleteColumns($pValue)
+ public function setDeleteColumns($deleteColumns)
{
- $this->deleteColumns = $pValue;
+ $this->deleteColumns = $deleteColumns;
return $this;
}
@@ -442,13 +442,13 @@ class Protection
/**
* Set DeleteRows.
*
- * @param bool $pValue
+ * @param bool $deleteRows
*
* @return $this
*/
- public function setDeleteRows($pValue)
+ public function setDeleteRows($deleteRows)
{
- $this->deleteRows = $pValue;
+ $this->deleteRows = $deleteRows;
return $this;
}
@@ -466,13 +466,13 @@ class Protection
/**
* Set SelectLockedCells.
*
- * @param bool $pValue
+ * @param bool $selectLockedCells
*
* @return $this
*/
- public function setSelectLockedCells($pValue)
+ public function setSelectLockedCells($selectLockedCells)
{
- $this->selectLockedCells = $pValue;
+ $this->selectLockedCells = $selectLockedCells;
return $this;
}
@@ -490,13 +490,13 @@ class Protection
/**
* Set Sort.
*
- * @param bool $pValue
+ * @param bool $sort
*
* @return $this
*/
- public function setSort($pValue)
+ public function setSort($sort)
{
- $this->sort = $pValue;
+ $this->sort = $sort;
return $this;
}
@@ -514,13 +514,13 @@ class Protection
/**
* Set AutoFilter.
*
- * @param bool $pValue
+ * @param bool $autoFilter
*
* @return $this
*/
- public function setAutoFilter($pValue)
+ public function setAutoFilter($autoFilter)
{
- $this->autoFilter = $pValue;
+ $this->autoFilter = $autoFilter;
return $this;
}
@@ -538,13 +538,13 @@ class Protection
/**
* Set PivotTables.
*
- * @param bool $pValue
+ * @param bool $pivotTables
*
* @return $this
*/
- public function setPivotTables($pValue)
+ public function setPivotTables($pivotTables)
{
- $this->pivotTables = $pValue;
+ $this->pivotTables = $pivotTables;
return $this;
}
@@ -562,13 +562,13 @@ class Protection
/**
* Set SelectUnlockedCells.
*
- * @param bool $pValue
+ * @param bool $selectUnlockedCells
*
* @return $this
*/
- public function setSelectUnlockedCells($pValue)
+ public function setSelectUnlockedCells($selectUnlockedCells)
{
- $this->selectUnlockedCells = $pValue;
+ $this->selectUnlockedCells = $selectUnlockedCells;
return $this;
}
@@ -586,20 +586,20 @@ class Protection
/**
* Set Password.
*
- * @param string $pValue
- * @param bool $pAlreadyHashed If the password has already been hashed, set this to true
+ * @param string $password
+ * @param bool $alreadyHashed If the password has already been hashed, set this to true
*
* @return $this
*/
- public function setPassword($pValue, $pAlreadyHashed = false)
+ public function setPassword($password, $alreadyHashed = false)
{
- if (!$pAlreadyHashed) {
+ if (!$alreadyHashed) {
$salt = $this->generateSalt();
$this->setSalt($salt);
- $pValue = PasswordHasher::hashPassword($pValue, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount());
+ $password = PasswordHasher::hashPassword($password, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount());
}
- $this->password = $pValue;
+ $this->password = $password;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php
index 4f48a34618b..b59333568f5 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php
@@ -21,7 +21,6 @@ class Row
/**
* Create a new row.
*
- * @param Worksheet $worksheet
* @param int $rowIndex
*/
public function __construct(?Worksheet $worksheet = null, $rowIndex = 1)
@@ -36,15 +35,14 @@ class Row
*/
public function __destruct()
{
+ // @phpstan-ignore-next-line
$this->worksheet = null;
}
/**
* Get row index.
- *
- * @return int
*/
- public function getRowIndex()
+ public function getRowIndex(): int
{
return $this->rowIndex;
}
@@ -64,10 +62,8 @@ class Row
/**
* Returns bound worksheet.
- *
- * @return Worksheet
*/
- public function getWorksheet()
+ public function getWorksheet(): Worksheet
{
return $this->worksheet;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php
index 9b9d54eb611..a78765bd328 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php
@@ -2,9 +2,13 @@
namespace PhpOffice\PhpSpreadsheet\Worksheet;
+use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
+/**
+ * @extends CellIterator
+ */
class RowCellIterator extends CellIterator
{
/**
@@ -43,7 +47,7 @@ class RowCellIterator extends CellIterator
* @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 = null, $rowIndex = 1, $startColumn = 'A', $endColumn = null)
+ public function __construct(Worksheet $worksheet, $rowIndex = 1, $startColumn = 'A', $endColumn = null)
{
// Set subject and row index
$this->worksheet = $worksheet;
@@ -59,7 +63,7 @@ class RowCellIterator extends CellIterator
*
* @return $this
*/
- public function resetStart($startColumn = 'A')
+ public function resetStart(string $startColumn = 'A')
{
$this->startColumnIndex = Coordinate::columnIndexFromString($startColumn);
$this->adjustForExistingOnlyRange();
@@ -77,7 +81,7 @@ class RowCellIterator extends CellIterator
*/
public function resetEnd($endColumn = null)
{
- $endColumn = $endColumn ? $endColumn : $this->worksheet->getHighestColumn();
+ $endColumn = $endColumn ?: $this->worksheet->getHighestColumn();
$this->endColumnIndex = Coordinate::columnIndexFromString($endColumn);
$this->adjustForExistingOnlyRange();
@@ -91,7 +95,7 @@ class RowCellIterator extends CellIterator
*
* @return $this
*/
- public function seek($column = 'A')
+ public function seek(string $column = 'A')
{
$columnx = $column;
$column = Coordinate::columnIndexFromString($column);
@@ -116,20 +120,16 @@ class RowCellIterator extends CellIterator
/**
* Return the current cell in this worksheet row.
- *
- * @return \PhpOffice\PhpSpreadsheet\Cell\Cell
*/
- public function current()
+ public function current(): ?Cell
{
return $this->worksheet->getCellByColumnAndRow($this->currentColumnIndex, $this->rowIndex);
}
/**
* Return the current iterator key.
- *
- * @return string
*/
- public function key()
+ public function key(): string
{
return Coordinate::stringFromColumnIndex($this->currentColumnIndex);
}
@@ -156,20 +156,16 @@ class RowCellIterator extends CellIterator
/**
* Indicate if more columns exist in the worksheet range of columns that we're iterating.
- *
- * @return bool
*/
- public function valid()
+ public function valid(): bool
{
return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex;
}
/**
* Return the current iterator position.
- *
- * @return int
*/
- public function getCurrentColumnIndex()
+ public function getCurrentColumnIndex(): int
{
return $this->currentColumnIndex;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php
index c4a87bdb558..1d8aada85d1 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php
@@ -2,6 +2,8 @@
namespace PhpOffice\PhpSpreadsheet\Worksheet;
+use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension;
+
class RowDimension extends Dimension
{
/**
@@ -30,12 +32,12 @@ class RowDimension extends Dimension
/**
* Create a new RowDimension.
*
- * @param int $pIndex Numeric row index
+ * @param int $index Numeric row index
*/
- public function __construct($pIndex = 0)
+ public function __construct($index = 0)
{
// Initialise values
- $this->rowIndex = $pIndex;
+ $this->rowIndex = $index;
// set dimension as unformatted by default
parent::__construct(null);
@@ -43,10 +45,8 @@ class RowDimension extends Dimension
/**
* Get Row Index.
- *
- * @return int
*/
- public function getRowIndex()
+ public function getRowIndex(): int
{
return $this->rowIndex;
}
@@ -54,47 +54,51 @@ class RowDimension extends Dimension
/**
* Set Row Index.
*
- * @param int $pValue
- *
* @return $this
*/
- public function setRowIndex($pValue)
+ public function setRowIndex(int $index)
{
- $this->rowIndex = $pValue;
+ $this->rowIndex = $index;
return $this;
}
/**
* Get Row Height.
+ * By default, this will be in points; but this method accepts a unit of measure
+ * argument, and will convert the value to the specified UoM.
*
* @return float
*/
- public function getRowHeight()
+ public function getRowHeight(?string $unitOfMeasure = null)
{
- return $this->height;
+ return ($unitOfMeasure === null || $this->height < 0)
+ ? $this->height
+ : (new CssDimension($this->height . CssDimension::UOM_POINTS))->toUnit($unitOfMeasure);
}
/**
* Set Row Height.
*
- * @param float $pValue
+ * @param float $height in points
+ * By default, this will be the passed argument value; but this method accepts a unit of measure
+ * argument, and will convert the passed argument value to points from the specified UoM
*
* @return $this
*/
- public function setRowHeight($pValue)
+ public function setRowHeight($height, ?string $unitOfMeasure = null)
{
- $this->height = $pValue;
+ $this->height = ($unitOfMeasure === null || $height < 0)
+ ? $height
+ : (new CssDimension("{$height}{$unitOfMeasure}"))->height();
return $this;
}
/**
* Get ZeroHeight.
- *
- * @return bool
*/
- public function getZeroHeight()
+ public function getZeroHeight(): bool
{
return $this->zeroHeight;
}
@@ -102,13 +106,11 @@ class RowDimension extends Dimension
/**
* Set ZeroHeight.
*
- * @param bool $pValue
- *
* @return $this
*/
- public function setZeroHeight($pValue)
+ public function setZeroHeight(bool $zeroHeight)
{
- $this->zeroHeight = $pValue;
+ $this->zeroHeight = $zeroHeight;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php
index 4254253313b..5c51bfeeabe 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php
@@ -5,6 +5,9 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet;
use Iterator;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
+/**
+ * @implements Iterator
+ */
class RowIterator implements Iterator
{
/**
@@ -50,14 +53,6 @@ class RowIterator implements Iterator
$this->resetStart($startRow);
}
- /**
- * Destructor.
- */
- public function __destruct()
- {
- $this->subject = null;
- }
-
/**
* (Re)Set the start row and the current row pointer.
*
@@ -65,10 +60,12 @@ class RowIterator implements Iterator
*
* @return $this
*/
- public function resetStart($startRow = 1)
+ public function resetStart(int $startRow = 1)
{
if ($startRow > $this->subject->getHighestRow()) {
- throw new PhpSpreadsheetException("Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})");
+ throw new PhpSpreadsheetException(
+ "Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})"
+ );
}
$this->startRow = $startRow;
@@ -89,7 +86,7 @@ class RowIterator implements Iterator
*/
public function resetEnd($endRow = null)
{
- $this->endRow = ($endRow) ? $endRow : $this->subject->getHighestRow();
+ $this->endRow = $endRow ?: $this->subject->getHighestRow();
return $this;
}
@@ -101,7 +98,7 @@ class RowIterator implements Iterator
*
* @return $this
*/
- public function seek($row = 1)
+ 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})");
@@ -121,20 +118,16 @@ class RowIterator implements Iterator
/**
* Return the current row in this worksheet.
- *
- * @return Row
*/
- public function current()
+ public function current(): Row
{
return new Row($this->subject, $this->position);
}
/**
* Return the current iterator key.
- *
- * @return int
*/
- public function key()
+ public function key(): int
{
return $this->position;
}
@@ -157,10 +150,8 @@ class RowIterator implements Iterator
/**
* Indicate if more rows exist in the worksheet range of rows that we're iterating.
- *
- * @return bool
*/
- public function valid()
+ public function valid(): bool
{
return $this->position <= $this->endRow && $this->position >= $this->startRow;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php
index 2f7d3812be9..80c4433ca13 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php
@@ -75,16 +75,16 @@ class SheetView
* Set ZoomScale.
* Valid values range from 10 to 400.
*
- * @param int $pValue
+ * @param int $zoomScale
*
* @return $this
*/
- public function setZoomScale($pValue)
+ 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 (($pValue >= 1) || $pValue === null) {
- $this->zoomScale = $pValue;
+ if (($zoomScale >= 1) || $zoomScale === null) {
+ $this->zoomScale = $zoomScale;
} else {
throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.');
}
@@ -106,14 +106,14 @@ class SheetView
* Set ZoomScale.
* Valid values range from 10 to 400.
*
- * @param int $pValue
+ * @param int $zoomScaleNormal
*
* @return $this
*/
- public function setZoomScaleNormal($pValue)
+ public function setZoomScaleNormal($zoomScaleNormal)
{
- if (($pValue >= 1) || $pValue === null) {
- $this->zoomScaleNormal = $pValue;
+ if (($zoomScaleNormal >= 1) || $zoomScaleNormal === null) {
+ $this->zoomScaleNormal = $zoomScaleNormal;
} else {
throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.');
}
@@ -124,11 +124,11 @@ class SheetView
/**
* Set ShowZeroes setting.
*
- * @param bool $pValue
+ * @param bool $showZeros
*/
- public function setShowZeros($pValue): void
+ public function setShowZeros($showZeros): void
{
- $this->showZeros = $pValue;
+ $this->showZeros = $showZeros;
}
/**
@@ -157,18 +157,18 @@ class SheetView
* 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT
* 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW
*
- * @param string $pValue
+ * @param string $sheetViewType
*
* @return $this
*/
- public function setView($pValue)
+ public function setView($sheetViewType)
{
// MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview' via the user interface
- if ($pValue === null) {
- $pValue = self::SHEETVIEW_NORMAL;
+ if ($sheetViewType === null) {
+ $sheetViewType = self::SHEETVIEW_NORMAL;
}
- if (in_array($pValue, self::$sheetViewTypes)) {
- $this->sheetviewType = $pValue;
+ if (in_array($sheetViewType, self::$sheetViewTypes)) {
+ $this->sheetviewType = $sheetViewType;
} else {
throw new PhpSpreadsheetException('Invalid sheetview layout type.');
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php
index 19833b71e50..ca8c3dfe429 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php
@@ -96,16 +96,16 @@ class Worksheet implements IComparable
/**
* Collection of drawings.
*
- * @var BaseDrawing[]
+ * @var ArrayObject
*/
private $drawingCollection;
/**
* Collection of Chart objects.
*
- * @var Chart[]
+ * @var ArrayObject
*/
- private $chartCollection = [];
+ private $chartCollection;
/**
* Worksheet title.
@@ -180,7 +180,7 @@ class Worksheet implements IComparable
/**
* Collection of breaks.
*
- * @var array
+ * @var int[]
*/
private $breaks = [];
@@ -194,7 +194,7 @@ class Worksheet implements IComparable
/**
* Collection of protected cell ranges.
*
- * @var array
+ * @var string[]
*/
private $protectedCells = [];
@@ -278,9 +278,9 @@ class Worksheet implements IComparable
/**
* Cached highest column.
*
- * @var string
+ * @var int
*/
- private $cachedHighestColumn = 'A';
+ private $cachedHighestColumn = 1;
/**
* Cached highest row.
@@ -313,7 +313,7 @@ class Worksheet implements IComparable
/**
* Tab color.
*
- * @var Color
+ * @var null|Color
*/
private $tabColor;
@@ -341,14 +341,13 @@ class Worksheet implements IComparable
/**
* Create a new worksheet.
*
- * @param Spreadsheet $parent
- * @param string $pTitle
+ * @param string $title
*/
- public function __construct(?Spreadsheet $parent = null, $pTitle = 'Worksheet')
+ public function __construct(?Spreadsheet $parent = null, $title = 'Worksheet')
{
// Set parent and title
$this->parent = $parent;
- $this->setTitle($pTitle, false);
+ $this->setTitle($title, false);
// setTitle can change $pTitle
$this->setCodeName($this->getTitle());
$this->setSheetState(self::SHEETSTATE_VISIBLE);
@@ -372,7 +371,7 @@ class Worksheet implements IComparable
$this->defaultRowDimension = new RowDimension(null);
// Default column dimension
$this->defaultColumnDimension = new ColumnDimension(null);
- $this->autoFilter = new AutoFilter(null, $this);
+ $this->autoFilter = new AutoFilter('', $this);
}
/**
@@ -383,9 +382,11 @@ class Worksheet implements IComparable
{
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
+ // @phpstan-ignore-next-line
$this->parent = null;
}
@@ -397,6 +398,7 @@ class Worksheet implements IComparable
Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title);
$this->disconnectCells();
+ $this->rowDimensions = [];
}
/**
@@ -422,53 +424,53 @@ class Worksheet implements IComparable
/**
* Check sheet code name for valid Excel syntax.
*
- * @param string $pValue The string to check
+ * @param string $sheetCodeName The string to check
*
* @return string The valid string
*/
- private static function checkSheetCodeName($pValue)
+ private static function checkSheetCodeName($sheetCodeName)
{
- $CharCount = Shared\StringHelper::countCharacters($pValue);
- if ($CharCount == 0) {
+ $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, '', $pValue) !== $pValue) ||
- (Shared\StringHelper::substring($pValue, -1, 1) == '\'') ||
- (Shared\StringHelper::substring($pValue, 0, 1) == '\'')
+ (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) {
+ if ($charCount > self::SHEET_TITLE_MAXIMUM_LENGTH) {
throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.');
}
- return $pValue;
+ return $sheetCodeName;
}
/**
* Check sheet title for valid Excel syntax.
*
- * @param string $pValue The string to check
+ * @param string $sheetTitle The string to check
*
* @return string The valid string
*/
- private static function checkSheetTitle($pValue)
+ private static function checkSheetTitle($sheetTitle)
{
// Some of the printable ASCII characters are invalid: * : / \ ? [ ]
- if (str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) {
+ 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($pValue) > self::SHEET_TITLE_MAXIMUM_LENGTH) {
+ 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 $pValue;
+ return $sheetTitle;
}
/**
@@ -534,7 +536,7 @@ class Worksheet implements IComparable
/**
* Get collection of drawings.
*
- * @return BaseDrawing[]
+ * @return ArrayObject
*/
public function getDrawingCollection()
{
@@ -544,7 +546,7 @@ class Worksheet implements IComparable
/**
* Get collection of charts.
*
- * @return Chart[]
+ * @return ArrayObject
*/
public function getChartCollection()
{
@@ -554,21 +556,21 @@ class Worksheet implements IComparable
/**
* Add chart.
*
- * @param null|int $iChartIndex Index where chart should go (0,1,..., or null for last)
+ * @param null|int $chartIndex Index where chart should go (0,1,..., or null for last)
*
* @return Chart
*/
- public function addChart(Chart $pChart, $iChartIndex = null)
+ public function addChart(Chart $chart, $chartIndex = null)
{
- $pChart->setWorksheet($this);
- if ($iChartIndex === null) {
- $this->chartCollection[] = $pChart;
+ $chart->setWorksheet($this);
+ if ($chartIndex === null) {
+ $this->chartCollection[] = $chart;
} else {
// Insert the chart at the requested index
- array_splice($this->chartCollection, $iChartIndex, 0, [$pChart]);
+ array_splice($this->chartCollection, $chartIndex, 0, [$chart]);
}
- return $pChart;
+ return $chart;
}
/**
@@ -728,7 +730,7 @@ class Worksheet implements IComparable
// loop through all cells in the worksheet
foreach ($this->getCoordinates(false) as $coordinate) {
- $cell = $this->getCell($coordinate, false);
+ $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()]);
@@ -754,15 +756,17 @@ class Worksheet implements IComparable
$this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()
);
- $autoSizes[$this->cellCollection->getCurrentColumn()] = max(
- (float) $autoSizes[$this->cellCollection->getCurrentColumn()],
- (float) Shared\Font::calculateColumnWidth(
- $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),
- $cellValue,
- $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(),
- $this->getParent()->getDefaultStyle()->getFont()
- )
- );
+ if ($cellValue !== null && $cellValue !== '') {
+ $autoSizes[$this->cellCollection->getCurrentColumn()] = max(
+ (float) $autoSizes[$this->cellCollection->getCurrentColumn()],
+ (float) Shared\Font::calculateColumnWidth(
+ $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(),
+ $cellValue,
+ $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(),
+ $this->getParent()->getDefaultStyle()->getFont()
+ )
+ );
+ }
}
}
}
@@ -824,7 +828,7 @@ class Worksheet implements IComparable
/**
* Set title.
*
- * @param string $pValue String containing the dimension of this worksheet
+ * @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
@@ -835,10 +839,10 @@ class Worksheet implements IComparable
*
* @return $this
*/
- public function setTitle($pValue, $updateFormulaCellReferences = true, $validate = true)
+ public function setTitle($title, $updateFormulaCellReferences = true, $validate = true)
{
// Is this a 'rename' or not?
- if ($this->getTitle() == $pValue) {
+ if ($this->getTitle() == $title) {
return $this;
}
@@ -847,37 +851,37 @@ class Worksheet implements IComparable
if ($validate) {
// Syntax check
- self::checkSheetTitle($pValue);
+ self::checkSheetTitle($title);
if ($this->parent) {
// Is there already such sheet name?
- if ($this->parent->sheetNameExists($pValue)) {
+ if ($this->parent->sheetNameExists($title)) {
// Use name, but append with lowest possible integer
- if (Shared\StringHelper::countCharacters($pValue) > 29) {
- $pValue = Shared\StringHelper::substring($pValue, 0, 29);
+ if (Shared\StringHelper::countCharacters($title) > 29) {
+ $title = Shared\StringHelper::substring($title, 0, 29);
}
$i = 1;
- while ($this->parent->sheetNameExists($pValue . ' ' . $i)) {
+ while ($this->parent->sheetNameExists($title . ' ' . $i)) {
++$i;
if ($i == 10) {
- if (Shared\StringHelper::countCharacters($pValue) > 28) {
- $pValue = Shared\StringHelper::substring($pValue, 0, 28);
+ if (Shared\StringHelper::countCharacters($title) > 28) {
+ $title = Shared\StringHelper::substring($title, 0, 28);
}
} elseif ($i == 100) {
- if (Shared\StringHelper::countCharacters($pValue) > 27) {
- $pValue = Shared\StringHelper::substring($pValue, 0, 27);
+ if (Shared\StringHelper::countCharacters($title) > 27) {
+ $title = Shared\StringHelper::substring($title, 0, 27);
}
}
}
- $pValue .= " $i";
+ $title .= " $i";
}
}
}
// Set title
- $this->title = $pValue;
+ $this->title = $title;
$this->dirty = true;
if ($this->parent && $this->parent->getCalculationEngine()) {
@@ -932,9 +936,9 @@ class Worksheet implements IComparable
*
* @return $this
*/
- public function setPageSetup(PageSetup $pValue)
+ public function setPageSetup(PageSetup $pageSetup)
{
- $this->pageSetup = $pValue;
+ $this->pageSetup = $pageSetup;
return $this;
}
@@ -954,9 +958,9 @@ class Worksheet implements IComparable
*
* @return $this
*/
- public function setPageMargins(PageMargins $pValue)
+ public function setPageMargins(PageMargins $pageMargins)
{
- $this->pageMargins = $pValue;
+ $this->pageMargins = $pageMargins;
return $this;
}
@@ -976,9 +980,9 @@ class Worksheet implements IComparable
*
* @return $this
*/
- public function setHeaderFooter(HeaderFooter $pValue)
+ public function setHeaderFooter(HeaderFooter $headerFooter)
{
- $this->headerFooter = $pValue;
+ $this->headerFooter = $headerFooter;
return $this;
}
@@ -998,9 +1002,9 @@ class Worksheet implements IComparable
*
* @return $this
*/
- public function setSheetView(SheetView $pValue)
+ public function setSheetView(SheetView $sheetView)
{
- $this->sheetView = $pValue;
+ $this->sheetView = $sheetView;
return $this;
}
@@ -1020,9 +1024,9 @@ class Worksheet implements IComparable
*
* @return $this
*/
- public function setProtection(Protection $pValue)
+ public function setProtection(Protection $protection)
{
- $this->protection = $pValue;
+ $this->protection = $protection;
$this->dirty = true;
return $this;
@@ -1031,15 +1035,15 @@ class Worksheet implements IComparable
/**
* Get highest worksheet column.
*
- * @param string $row Return the data highest column for the specified row,
+ * @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 $this->cachedHighestColumn;
+ if (empty($row)) {
+ return Coordinate::stringFromColumnIndex($this->cachedHighestColumn);
}
return $this->getHighestDataColumn($row);
@@ -1048,7 +1052,7 @@ class Worksheet implements IComparable
/**
* Get highest worksheet column that contains data.
*
- * @param string $row Return the highest data column for the specified row,
+ * @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
@@ -1061,7 +1065,7 @@ class Worksheet implements IComparable
/**
* Get highest worksheet row.
*
- * @param string $column Return the highest data row for the specified column,
+ * @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
@@ -1078,7 +1082,7 @@ class Worksheet implements IComparable
/**
* Get highest worksheet row that contains data.
*
- * @param string $column Return the highest data row for the specified column,
+ * @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
@@ -1101,14 +1105,14 @@ class Worksheet implements IComparable
/**
* Set a cell value.
*
- * @param string $pCoordinate Coordinate of the cell, eg: 'A1'
- * @param mixed $pValue Value of the cell
+ * @param string $coordinate Coordinate of the cell, eg: 'A1'
+ * @param mixed $value Value of the cell
*
* @return $this
*/
- public function setCellValue($pCoordinate, $pValue)
+ public function setCellValue($coordinate, $value)
{
- $this->getCell($pCoordinate)->setValue($pValue);
+ $this->getCell($coordinate)->setValue($value);
return $this;
}
@@ -1132,16 +1136,16 @@ class Worksheet implements IComparable
/**
* Set a cell value.
*
- * @param string $pCoordinate Coordinate of the cell, eg: 'A1'
- * @param mixed $pValue Value of the cell
- * @param string $pDataType Explicit data type, see DataType::TYPE_*
+ * @param string $coordinate Coordinate of the cell, eg: 'A1'
+ * @param mixed $value Value of the cell
+ * @param string $dataType Explicit data type, see DataType::TYPE_*
*
* @return $this
*/
- public function setCellValueExplicit($pCoordinate, $pValue, $pDataType)
+ public function setCellValueExplicit($coordinate, $value, $dataType)
{
// Set value
- $this->getCell($pCoordinate)->setValueExplicit($pValue, $pDataType);
+ $this->getCell($coordinate)->setValueExplicit($value, $dataType);
return $this;
}
@@ -1166,50 +1170,94 @@ class Worksheet implements IComparable
/**
* Get cell at a specific coordinate.
*
- * @param string $pCoordinate Coordinate of the cell, eg: 'A1'
- * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't
- * already exist, or a null should be returned instead
+ * @param string $coordinate Coordinate of the cell, eg: 'A1'
*
- * @return null|Cell Cell that was found/created or null
+ * @return Cell Cell that was found or created
*/
- public function getCell($pCoordinate, $createIfNotExists = true)
+ public function getCell(string $coordinate): Cell
{
- // Uppercase coordinate
- $pCoordinateUpper = strtoupper($pCoordinate);
+ // Shortcut for increased performance for the vast majority of simple cases
+ if ($this->cellCollection->has($coordinate)) {
+ /** @var Cell $cell */
+ $cell = $this->cellCollection->get($coordinate);
- // Check cell collection
- if ($this->cellCollection->has($pCoordinateUpper)) {
- return $this->cellCollection->get($pCoordinateUpper);
+ return $cell;
}
+ /** @var Worksheet $sheet */
+ [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($coordinate);
+ $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($pCoordinate, '!') !== false) {
- $worksheetReference = self::extractSheetTitle($pCoordinate, true);
+ if (strpos($coordinate, '!') !== false) {
+ $worksheetReference = self::extractSheetTitle($coordinate, true);
- return $this->parent->getSheetByName($worksheetReference[0])->getCell(strtoupper($worksheetReference[1]), $createIfNotExists);
- }
+ $sheet = $this->parent->getSheetByName($worksheetReference[0]);
+ $finalCoordinate = strtoupper($worksheetReference[1]);
- // Named range?
- if (
- (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) &&
- (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $pCoordinate, $matches))
+ if (!$sheet) {
+ 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 . '$/i', $coordinate)
) {
- $namedRange = DefinedName::resolveName($pCoordinate, $this);
+ // Named range?
+ $namedRange = $this->validateNamedRange($coordinate, true);
if ($namedRange !== null) {
- $pCoordinate = $namedRange->getValue();
+ $sheet = $namedRange->getWorksheet();
+ if (!$sheet) {
+ throw new Exception('Sheet not found for named range: ' . $namedRange->getName());
+ }
- return $namedRange->getWorksheet()->getCell($pCoordinate, $createIfNotExists);
+ $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!');
+ $finalCoordinate = str_replace('$', '', $cellCoordinate);
}
}
- if (Coordinate::coordinateIsRange($pCoordinate)) {
- throw new Exception('Cell coordinate can not be a range of cells.');
- } elseif (strpos($pCoordinate, '$') !== false) {
+ if (!$sheet || !$finalCoordinate) {
+ $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.');
}
- // Create new cell object, if required
- return $createIfNotExists ? $this->createNewCell($pCoordinateUpper) : null;
+ 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;
}
/**
@@ -1217,50 +1265,52 @@ class Worksheet implements IComparable
*
* @param int $columnIndex Numeric column coordinate of the cell
* @param int $row Numeric row coordinate of the cell
- * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't
- * already exist, or a null should be returned instead
*
- * @return null|Cell Cell that was found/created or null
+ * @return Cell Cell that was found/created or null
*/
- public function getCellByColumnAndRow($columnIndex, $row, $createIfNotExists = true)
+ public function getCellByColumnAndRow($columnIndex, $row): Cell
{
$columnLetter = Coordinate::stringFromColumnIndex($columnIndex);
$coordinate = $columnLetter . $row;
if ($this->cellCollection->has($coordinate)) {
- return $this->cellCollection->get($coordinate);
+ /** @var Cell $cell */
+ $cell = $this->cellCollection->get($coordinate);
+
+ return $cell;
}
// Create new cell object, if required
- return $createIfNotExists ? $this->createNewCell($coordinate) : null;
+ return $this->createNewCell($coordinate);
}
/**
* Create a new cell at the specified coordinate.
*
- * @param string $pCoordinate Coordinate of the cell
+ * @param string $coordinate Coordinate of the cell
*
* @return Cell Cell that was created
*/
- private function createNewCell($pCoordinate)
+ private function createNewCell($coordinate)
{
$cell = new Cell(null, DataType::TYPE_NULL, $this);
- $this->cellCollection->add($pCoordinate, $cell);
+ $this->cellCollection->add($coordinate, $cell);
$this->cellCollectionIsSorted = false;
// Coordinates
- $aCoordinates = Coordinate::coordinateFromString($pCoordinate);
- if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($aCoordinates[0])) {
- $this->cachedHighestColumn = $aCoordinates[0];
+ [$column, $row] = Coordinate::coordinateFromString($coordinate);
+ $aIndexes = Coordinate::indexesFromString($coordinate);
+ if ($this->cachedHighestColumn < $aIndexes[0]) {
+ $this->cachedHighestColumn = $aIndexes[0];
}
- if ($aCoordinates[1] > $this->cachedHighestRow) {
- $this->cachedHighestRow = $aCoordinates[1];
+ if ($aIndexes[1] > $this->cachedHighestRow) {
+ $this->cachedHighestRow = $aIndexes[1];
}
// Cell needs appropriate xfIndex from dimensions records
// but don't create dimension records if they don't already exist
- $rowDimension = $this->getRowDimension($aCoordinates[1], false);
- $columnDimension = $this->getColumnDimension($aCoordinates[0], false);
+ $rowDimension = $this->rowDimensions[$row] ?? null;
+ $columnDimension = $this->columnDimensions[$column] ?? null;
if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) {
// then there is a row dimension with explicit style, assign it to the cell
@@ -1276,50 +1326,16 @@ class Worksheet implements IComparable
/**
* Does the cell at a specific coordinate exist?
*
- * @param string $pCoordinate Coordinate of the cell eg: 'A1'
+ * @param string $coordinate Coordinate of the cell eg: 'A1'
*
* @return bool
*/
- public function cellExists($pCoordinate)
+ public function cellExists($coordinate)
{
- // Worksheet reference?
- if (strpos($pCoordinate, '!') !== false) {
- $worksheetReference = self::extractSheetTitle($pCoordinate, true);
+ /** @var Worksheet $sheet */
+ [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($coordinate);
- return $this->parent->getSheetByName($worksheetReference[0])->cellExists(strtoupper($worksheetReference[1]));
- }
-
- // Named range?
- if (
- (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) &&
- (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $pCoordinate, $matches))
- ) {
- $namedRange = DefinedName::resolveName($pCoordinate, $this);
- if ($namedRange !== null) {
- $pCoordinate = $namedRange->getValue();
- if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) {
- if (!$namedRange->getLocalOnly()) {
- return $namedRange->getWorksheet()->cellExists($pCoordinate);
- }
-
- throw new Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle());
- }
- } else {
- return false;
- }
- }
-
- // Uppercase coordinate
- $pCoordinate = strtoupper($pCoordinate);
-
- if (Coordinate::coordinateIsRange($pCoordinate)) {
- throw new Exception('Cell coordinate can not be a range of cells.');
- } elseif (strpos($pCoordinate, '$') !== false) {
- throw new Exception('Cell coordinate must not be absolute.');
- }
-
- // Cell exists?
- return $this->cellCollection->has($pCoordinate);
+ return $sheet->cellCollection->has($finalCoordinate);
}
/**
@@ -1338,65 +1354,49 @@ class Worksheet implements IComparable
/**
* Get row dimension at a specific row.
*
- * @param int $pRow Numeric index of the row
- * @param bool $create
- *
- * @return RowDimension
+ * @param int $row Numeric index of the row
*/
- public function getRowDimension($pRow, $create = true)
+ public function getRowDimension(int $row): RowDimension
{
- // Found
- $found = null;
-
// Get row dimension
- if (!isset($this->rowDimensions[$pRow])) {
- if (!$create) {
- return null;
- }
- $this->rowDimensions[$pRow] = new RowDimension($pRow);
+ if (!isset($this->rowDimensions[$row])) {
+ $this->rowDimensions[$row] = new RowDimension($row);
- $this->cachedHighestRow = max($this->cachedHighestRow, $pRow);
+ $this->cachedHighestRow = max($this->cachedHighestRow, $row);
}
- return $this->rowDimensions[$pRow];
+ return $this->rowDimensions[$row];
}
/**
* Get column dimension at a specific column.
*
- * @param string $pColumn String index of the column eg: 'A'
- * @param bool $create
- *
- * @return ColumnDimension
+ * @param string $column String index of the column eg: 'A'
*/
- public function getColumnDimension($pColumn, $create = true)
+ public function getColumnDimension(string $column): ColumnDimension
{
// Uppercase coordinate
- $pColumn = strtoupper($pColumn);
+ $column = strtoupper($column);
// Fetch dimensions
- if (!isset($this->columnDimensions[$pColumn])) {
- if (!$create) {
- return null;
- }
- $this->columnDimensions[$pColumn] = new ColumnDimension($pColumn);
+ if (!isset($this->columnDimensions[$column])) {
+ $this->columnDimensions[$column] = new ColumnDimension($column);
- if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($pColumn)) {
- $this->cachedHighestColumn = $pColumn;
+ $columnIndex = Coordinate::columnIndexFromString($column);
+ if ($this->cachedHighestColumn < $columnIndex) {
+ $this->cachedHighestColumn = $columnIndex;
}
}
- return $this->columnDimensions[$pColumn];
+ 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
- *
- * @return ColumnDimension
*/
- public function getColumnDimensionByColumn($columnIndex)
+ public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension
{
return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex));
}
@@ -1414,17 +1414,17 @@ class Worksheet implements IComparable
/**
* Get style for cell.
*
- * @param string $pCellCoordinate Cell coordinate (or range) to get style for, eg: 'A1'
+ * @param string $cellCoordinate Cell coordinate (or range) to get style for, eg: 'A1'
*
* @return Style
*/
- public function getStyle($pCellCoordinate)
+ public function getStyle($cellCoordinate)
{
// set this sheet as active
$this->parent->setActiveSheetIndex($this->parent->getIndex($this));
// set cell coordinate as active
- $this->setSelectedCells($pCellCoordinate);
+ $this->setSelectedCells($cellCoordinate);
return $this->parent->getCellXfSupervisor();
}
@@ -1432,42 +1432,69 @@ class Worksheet implements IComparable
/**
* Get conditional styles for a cell.
*
- * @param string $pCoordinate eg: 'A1'
+ * @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($pCoordinate)
+ public function getConditionalStyles($coordinate)
{
- $pCoordinate = strtoupper($pCoordinate);
- if (!isset($this->conditionalStylesCollection[$pCoordinate])) {
- $this->conditionalStylesCollection[$pCoordinate] = [];
+ $coordinate = strtoupper($coordinate);
+ if (strpos($coordinate, ':') !== false) {
+ return $this->conditionalStylesCollection[$coordinate] ?? [];
}
- return $this->conditionalStylesCollection[$pCoordinate];
+ $cell = $this->getCell($coordinate);
+ foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) {
+ if ($cell->isInRange($conditionalRange)) {
+ return $this->conditionalStylesCollection[$conditionalRange];
+ }
+ }
+
+ return [];
}
/**
* Do conditional styles exist for this cell?
*
- * @param string $pCoordinate eg: 'A1'
+ * @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.
*
* @return bool
*/
- public function conditionalStylesExists($pCoordinate)
+ public function conditionalStylesExists($coordinate)
{
- return isset($this->conditionalStylesCollection[strtoupper($pCoordinate)]);
+ $coordinate = strtoupper($coordinate);
+ if (strpos($coordinate, ':') !== false) {
+ return isset($this->conditionalStylesCollection[strtoupper($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 $pCoordinate eg: 'A1'
+ * @param string $coordinate eg: 'A1'
*
* @return $this
*/
- public function removeConditionalStyles($pCoordinate)
+ public function removeConditionalStyles($coordinate)
{
- unset($this->conditionalStylesCollection[strtoupper($pCoordinate)]);
+ unset($this->conditionalStylesCollection[strtoupper($coordinate)]);
return $this;
}
@@ -1485,14 +1512,14 @@ class Worksheet implements IComparable
/**
* Set conditional styles.
*
- * @param string $pCoordinate eg: 'A1'
- * @param $pValue Conditional[]
+ * @param string $coordinate eg: 'A1'
+ * @param Conditional[] $styles
*
* @return $this
*/
- public function setConditionalStyles($pCoordinate, $pValue)
+ public function setConditionalStyles($coordinate, $styles)
{
- $this->conditionalStylesCollection[strtoupper($pCoordinate)] = $pValue;
+ $this->conditionalStylesCollection[strtoupper($coordinate)] = $styles;
return $this;
}
@@ -1523,26 +1550,26 @@ class Worksheet implements IComparable
*
* Please note that this will overwrite existing cell styles for cells in range!
*
- * @param Style $pCellStyle Cell style to duplicate
- * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
+ * @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 $pCellStyle, $pRange)
+ public function duplicateStyle(Style $style, $range)
{
// Add the style to the workbook if necessary
$workbook = $this->parent;
- if ($existingStyle = $this->parent->getCellXfByHashCode($pCellStyle->getHashCode())) {
+ if ($existingStyle = $this->parent->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($pCellStyle);
- $xfIndex = $pCellStyle->getIndex();
+ $workbook->addCellXf($style);
+ $xfIndex = $style->getIndex();
}
// Calculate range outer borders
- [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange . ':' . $pRange);
+ [$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]) {
@@ -1566,21 +1593,21 @@ class Worksheet implements IComparable
*
* Please note that this will overwrite existing cell styles for cells in range!
*
- * @param Conditional[] $pCellStyle Cell style to duplicate
- * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
+ * @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 $pCellStyle, $pRange = '')
+ public function duplicateConditionalStyle(array $styles, $range = '')
{
- foreach ($pCellStyle as $cellStyle) {
+ 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($pRange . ':' . $pRange);
+ [$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]) {
@@ -1592,7 +1619,7 @@ class Worksheet implements IComparable
// 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, $pCellStyle);
+ $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $styles);
}
}
@@ -1602,23 +1629,23 @@ class Worksheet implements IComparable
/**
* Set break on a cell.
*
- * @param string $pCoordinate Cell coordinate (e.g. A1)
- * @param int $pBreak Break type (type of Worksheet::BREAK_*)
+ * @param string $coordinate Cell coordinate (e.g. A1)
+ * @param int $break Break type (type of Worksheet::BREAK_*)
*
* @return $this
*/
- public function setBreak($pCoordinate, $pBreak)
+ public function setBreak($coordinate, $break)
{
// Uppercase coordinate
- $pCoordinate = strtoupper($pCoordinate);
+ $coordinate = strtoupper($coordinate);
- if ($pCoordinate != '') {
- if ($pBreak == self::BREAK_NONE) {
- if (isset($this->breaks[$pCoordinate])) {
- unset($this->breaks[$pCoordinate]);
+ if ($coordinate != '') {
+ if ($break == self::BREAK_NONE) {
+ if (isset($this->breaks[$coordinate])) {
+ unset($this->breaks[$coordinate]);
}
} else {
- $this->breaks[$pCoordinate] = $pBreak;
+ $this->breaks[$coordinate] = $break;
}
} else {
throw new Exception('No cell coordinate specified.');
@@ -1644,7 +1671,7 @@ class Worksheet implements IComparable
/**
* Get breaks.
*
- * @return array[]
+ * @return int[]
*/
public function getBreaks()
{
@@ -1654,22 +1681,22 @@ class Worksheet implements IComparable
/**
* Set merge on a cell range.
*
- * @param string $pRange Cell range (e.g. A1:E1)
+ * @param string $range Cell range (e.g. A1:E1)
*
* @return $this
*/
- public function mergeCells($pRange)
+ public function mergeCells($range)
{
// Uppercase coordinate
- $pRange = strtoupper($pRange);
+ $range = strtoupper($range);
- if (strpos($pRange, ':') !== false) {
- $this->mergeCells[$pRange] = $pRange;
+ if (strpos($range, ':') !== false) {
+ $this->mergeCells[$range] = $range;
// make sure cells are created
// get the cells in the range
- $aReferences = Coordinate::extractAllCellReferencesInRange($pRange);
+ $aReferences = Coordinate::extractAllCellReferencesInRange($range);
// create upper left cell if it does not already exist
$upperLeft = $aReferences[0];
@@ -1711,20 +1738,20 @@ class Worksheet implements IComparable
/**
* Remove merge on a cell range.
*
- * @param string $pRange Cell range (e.g. A1:E1)
+ * @param string $range Cell range (e.g. A1:E1)
*
* @return $this
*/
- public function unmergeCells($pRange)
+ public function unmergeCells($range)
{
// Uppercase coordinate
- $pRange = strtoupper($pRange);
+ $range = strtoupper($range);
- if (strpos($pRange, ':') !== false) {
- if (isset($this->mergeCells[$pRange])) {
- unset($this->mergeCells[$pRange]);
+ if (strpos($range, ':') !== false) {
+ if (isset($this->mergeCells[$range])) {
+ unset($this->mergeCells[$range]);
} else {
- throw new Exception('Cell range ' . $pRange . ' not known as merged.');
+ throw new Exception('Cell range ' . $range . ' not known as merged.');
}
} else {
throw new Exception('Merge can only be removed from a range of cells.');
@@ -1764,13 +1791,13 @@ class Worksheet implements IComparable
* Set merge cells array for the entire sheet. Use instead mergeCells() to merge
* a single cell range.
*
- * @param string[] $pValue
+ * @param string[] $mergeCells
*
* @return $this
*/
- public function setMergeCells(array $pValue)
+ public function setMergeCells(array $mergeCells)
{
- $this->mergeCells = $pValue;
+ $this->mergeCells = $mergeCells;
return $this;
}
@@ -1778,21 +1805,21 @@ class Worksheet implements IComparable
/**
* Set protection on a cell range.
*
- * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1)
- * @param string $pPassword Password to unlock the protection
- * @param bool $pAlreadyHashed If the password has already been hashed, set this to true
+ * @param string $range Cell (e.g. A1) or cell range (e.g. A1:E1)
+ * @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($pRange, $pPassword, $pAlreadyHashed = false)
+ public function protectCells($range, $password, $alreadyHashed = false)
{
// Uppercase coordinate
- $pRange = strtoupper($pRange);
+ $range = strtoupper($range);
- if (!$pAlreadyHashed) {
- $pPassword = Shared\PasswordHasher::hashPassword($pPassword);
+ if (!$alreadyHashed) {
+ $password = Shared\PasswordHasher::hashPassword($password);
}
- $this->protectedCells[$pRange] = $pPassword;
+ $this->protectedCells[$range] = $password;
return $this;
}
@@ -1819,19 +1846,19 @@ class Worksheet implements IComparable
/**
* Remove protection on a cell range.
*
- * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1)
+ * @param string $range Cell (e.g. A1) or cell range (e.g. A1:E1)
*
* @return $this
*/
- public function unprotectCells($pRange)
+ public function unprotectCells($range)
{
// Uppercase coordinate
- $pRange = strtoupper($pRange);
+ $range = strtoupper($range);
- if (isset($this->protectedCells[$pRange])) {
- unset($this->protectedCells[$pRange]);
+ if (isset($this->protectedCells[$range])) {
+ unset($this->protectedCells[$range]);
} else {
- throw new Exception('Cell range ' . $pRange . ' not known as protected.');
+ throw new Exception('Cell range ' . $range . ' not known as protected.');
}
return $this;
@@ -1857,7 +1884,7 @@ class Worksheet implements IComparable
/**
* Get protected cells.
*
- * @return array[]
+ * @return string[]
*/
public function getProtectedCells()
{
@@ -1877,17 +1904,17 @@ class Worksheet implements IComparable
/**
* Set AutoFilter.
*
- * @param AutoFilter|string $pValue
+ * @param AutoFilter|string $autoFilterOrRange
* A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility
*
* @return $this
*/
- public function setAutoFilter($pValue)
+ public function setAutoFilter($autoFilterOrRange)
{
- if (is_string($pValue)) {
- $this->autoFilter->setRange($pValue);
- } elseif (is_object($pValue) && ($pValue instanceof AutoFilter)) {
- $this->autoFilter = $pValue;
+ if (is_string($autoFilterOrRange)) {
+ $this->autoFilter->setRange($autoFilterOrRange);
+ } elseif (is_object($autoFilterOrRange) && ($autoFilterOrRange instanceof AutoFilter)) {
+ $this->autoFilter = $autoFilterOrRange;
}
return $this;
@@ -1914,12 +1941,10 @@ class Worksheet implements IComparable
/**
* Remove autofilter.
- *
- * @return $this
*/
- public function removeAutoFilter()
+ public function removeAutoFilter(): self
{
- $this->autoFilter->setRange(null);
+ $this->autoFilter->setRange('');
return $this;
}
@@ -1927,7 +1952,7 @@ class Worksheet implements IComparable
/**
* Get Freeze Pane.
*
- * @return string
+ * @return null|string
*/
public function getFreezePane()
{
@@ -1965,6 +1990,13 @@ class Worksheet implements IComparable
return $this;
}
+ public function setTopLeftCell(string $topLeftCell): self
+ {
+ $this->topLeftCell = $topLeftCell;
+
+ return $this;
+ }
+
/**
* Freeze Pane by using numeric cell coordinates.
*
@@ -1991,7 +2023,7 @@ class Worksheet implements IComparable
/**
* Get the default position of the right bottom pane.
*
- * @return int
+ * @return null|string
*/
public function getTopLeftCell()
{
@@ -2001,16 +2033,16 @@ class Worksheet implements IComparable
/**
* Insert a new row, updating all possible related data.
*
- * @param int $pBefore Insert before this one
- * @param int $pNumRows Number of rows to insert
+ * @param int $before Insert before this one
+ * @param int $numberOfRows Number of rows to insert
*
* @return $this
*/
- public function insertNewRowBefore($pBefore, $pNumRows = 1)
+ public function insertNewRowBefore($before, $numberOfRows = 1)
{
- if ($pBefore >= 1) {
+ if ($before >= 1) {
$objReferenceHelper = ReferenceHelper::getInstance();
- $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this);
+ $objReferenceHelper->insertNewBefore('A' . $before, 0, $numberOfRows, $this);
} else {
throw new Exception('Rows can only be inserted before at least row 1.');
}
@@ -2021,16 +2053,16 @@ class Worksheet implements IComparable
/**
* Insert a new column, updating all possible related data.
*
- * @param string $pBefore Insert before this one, eg: 'A'
- * @param int $pNumCols Number of columns to insert
+ * @param string $before Insert before this one, eg: 'A'
+ * @param int $numberOfColumns Number of columns to insert
*
* @return $this
*/
- public function insertNewColumnBefore($pBefore, $pNumCols = 1)
+ public function insertNewColumnBefore($before, $numberOfColumns = 1)
{
- if (!is_numeric($pBefore)) {
+ if (!is_numeric($before)) {
$objReferenceHelper = ReferenceHelper::getInstance();
- $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this);
+ $objReferenceHelper->insertNewBefore($before . '1', $numberOfColumns, 0, $this);
} else {
throw new Exception('Column references should not be numeric.');
}
@@ -2042,14 +2074,14 @@ class Worksheet implements IComparable
* Insert a new column, updating all possible related data.
*
* @param int $beforeColumnIndex Insert before this one (numeric column coordinate of the cell)
- * @param int $pNumCols Number of columns to insert
+ * @param int $numberOfColumns Number of columns to insert
*
* @return $this
*/
- public function insertNewColumnBeforeByIndex($beforeColumnIndex, $pNumCols = 1)
+ public function insertNewColumnBeforeByIndex($beforeColumnIndex, $numberOfColumns = 1)
{
if ($beforeColumnIndex >= 1) {
- return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $pNumCols);
+ return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $numberOfColumns);
}
throw new Exception('Columns can only be inserted before at least column A (1).');
@@ -2058,29 +2090,29 @@ class Worksheet implements IComparable
/**
* Delete a row, updating all possible related data.
*
- * @param int $pRow Remove starting with this one
- * @param int $pNumRows Number of rows to remove
+ * @param int $row Remove starting with this one
+ * @param int $numberOfRows Number of rows to remove
*
* @return $this
*/
- public function removeRow($pRow, $pNumRows = 1)
+ public function removeRow($row, $numberOfRows = 1)
{
- if ($pRow < 1) {
+ if ($row < 1) {
throw new Exception('Rows to be deleted should at least start from row 1.');
}
$highestRow = $this->getHighestDataRow();
$removedRowsCounter = 0;
- for ($r = 0; $r < $pNumRows; ++$r) {
- if ($pRow + $r <= $highestRow) {
- $this->getCellCollection()->removeRow($pRow + $r);
+ for ($r = 0; $r < $numberOfRows; ++$r) {
+ if ($row + $r <= $highestRow) {
+ $this->getCellCollection()->removeRow($row + $r);
++$removedRowsCounter;
}
}
$objReferenceHelper = ReferenceHelper::getInstance();
- $objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this);
+ $objReferenceHelper->insertNewBefore('A' . ($row + $numberOfRows), 0, -$numberOfRows, $this);
for ($r = 0; $r < $removedRowsCounter; ++$r) {
$this->getCellCollection()->removeRow($highestRow);
--$highestRow;
@@ -2092,32 +2124,32 @@ class Worksheet implements IComparable
/**
* Remove a column, updating all possible related data.
*
- * @param string $pColumn Remove starting with this one, eg: 'A'
- * @param int $pNumCols Number of columns to remove
+ * @param string $column Remove starting with this one, eg: 'A'
+ * @param int $numberOfColumns Number of columns to remove
*
* @return $this
*/
- public function removeColumn($pColumn, $pNumCols = 1)
+ public function removeColumn($column, $numberOfColumns = 1)
{
- if (is_numeric($pColumn)) {
+ if (is_numeric($column)) {
throw new Exception('Column references should not be numeric.');
}
$highestColumn = $this->getHighestDataColumn();
$highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
- $pColumnIndex = Coordinate::columnIndexFromString($pColumn);
+ $pColumnIndex = Coordinate::columnIndexFromString($column);
if ($pColumnIndex > $highestColumnIndex) {
return $this;
}
- $pColumn = Coordinate::stringFromColumnIndex($pColumnIndex + $pNumCols);
+ $column = Coordinate::stringFromColumnIndex($pColumnIndex + $numberOfColumns);
$objReferenceHelper = ReferenceHelper::getInstance();
- $objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this);
+ $objReferenceHelper->insertNewBefore($column . '1', -$numberOfColumns, 0, $this);
$maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1;
- for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $pNumCols); $c < $n; ++$c) {
+ for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) {
$this->getCellCollection()->removeColumn($highestColumn);
$highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1);
}
@@ -2157,13 +2189,13 @@ class Worksheet implements IComparable
/**
* Set show gridlines.
*
- * @param bool $pValue Show gridlines (true/false)
+ * @param bool $showGridLines Show gridlines (true/false)
*
* @return $this
*/
- public function setShowGridlines($pValue)
+ public function setShowGridlines($showGridLines)
{
- $this->showGridlines = $pValue;
+ $this->showGridlines = $showGridLines;
return $this;
}
@@ -2181,13 +2213,13 @@ class Worksheet implements IComparable
/**
* Set print gridlines.
*
- * @param bool $pValue Print gridlines (true/false)
+ * @param bool $printGridLines Print gridlines (true/false)
*
* @return $this
*/
- public function setPrintGridlines($pValue)
+ public function setPrintGridlines($printGridLines)
{
- $this->printGridlines = $pValue;
+ $this->printGridlines = $printGridLines;
return $this;
}
@@ -2205,13 +2237,13 @@ class Worksheet implements IComparable
/**
* Set show row and column headers.
*
- * @param bool $pValue Show row and column headers (true/false)
+ * @param bool $showRowColHeaders Show row and column headers (true/false)
*
* @return $this
*/
- public function setShowRowColHeaders($pValue)
+ public function setShowRowColHeaders($showRowColHeaders)
{
- $this->showRowColHeaders = $pValue;
+ $this->showRowColHeaders = $showRowColHeaders;
return $this;
}
@@ -2229,13 +2261,13 @@ class Worksheet implements IComparable
/**
* Set show summary below.
*
- * @param bool $pValue Show summary below (true/false)
+ * @param bool $showSummaryBelow Show summary below (true/false)
*
* @return $this
*/
- public function setShowSummaryBelow($pValue)
+ public function setShowSummaryBelow($showSummaryBelow)
{
- $this->showSummaryBelow = $pValue;
+ $this->showSummaryBelow = $showSummaryBelow;
return $this;
}
@@ -2253,13 +2285,13 @@ class Worksheet implements IComparable
/**
* Set show summary right.
*
- * @param bool $pValue Show summary right (true/false)
+ * @param bool $showSummaryRight Show summary right (true/false)
*
* @return $this
*/
- public function setShowSummaryRight($pValue)
+ public function setShowSummaryRight($showSummaryRight)
{
- $this->showSummaryRight = $pValue;
+ $this->showSummaryRight = $showSummaryRight;
return $this;
}
@@ -2277,13 +2309,13 @@ class Worksheet implements IComparable
/**
* Set comments array for the entire sheet.
*
- * @param Comment[] $pValue
+ * @param Comment[] $comments
*
* @return $this
*/
- public function setComments(array $pValue)
+ public function setComments(array $comments)
{
- $this->comments = $pValue;
+ $this->comments = $comments;
return $this;
}
@@ -2291,31 +2323,31 @@ class Worksheet implements IComparable
/**
* Get comment for cell.
*
- * @param string $pCellCoordinate Cell coordinate to get comment for, eg: 'A1'
+ * @param string $cellCoordinate Cell coordinate to get comment for, eg: 'A1'
*
* @return Comment
*/
- public function getComment($pCellCoordinate)
+ public function getComment($cellCoordinate)
{
// Uppercase coordinate
- $pCellCoordinate = strtoupper($pCellCoordinate);
+ $cellCoordinate = strtoupper($cellCoordinate);
- if (Coordinate::coordinateIsRange($pCellCoordinate)) {
+ if (Coordinate::coordinateIsRange($cellCoordinate)) {
throw new Exception('Cell coordinate string can not be a range of cells.');
- } elseif (strpos($pCellCoordinate, '$') !== false) {
+ } elseif (strpos($cellCoordinate, '$') !== false) {
throw new Exception('Cell coordinate string must not be absolute.');
- } elseif ($pCellCoordinate == '') {
+ } elseif ($cellCoordinate == '') {
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[$pCellCoordinate])) {
- return $this->comments[$pCellCoordinate];
+ if (isset($this->comments[$cellCoordinate])) {
+ return $this->comments[$cellCoordinate];
}
// If not, create a new comment.
$newComment = new Comment();
- $this->comments[$pCellCoordinate] = $newComment;
+ $this->comments[$cellCoordinate] = $newComment;
return $newComment;
}
@@ -2356,46 +2388,81 @@ class Worksheet implements IComparable
/**
* Selected cell.
*
- * @param string $pCoordinate Cell (i.e. A1)
+ * @param string $coordinate Cell (i.e. A1)
*
* @return $this
*/
- public function setSelectedCell($pCoordinate)
+ public function setSelectedCell($coordinate)
{
- return $this->setSelectedCells($pCoordinate);
+ return $this->setSelectedCells($coordinate);
+ }
+
+ /**
+ * Sigh - Phpstan thinks, correctly, that preg_replace can return null.
+ * But Scrutinizer doesn't. Try to satisfy both.
+ *
+ * @param mixed $str
+ */
+ private static function ensureString($str): string
+ {
+ return is_string($str) ? $str : '';
+ }
+
+ public static function pregReplace(string $pattern, string $replacement, string $subject): string
+ {
+ return self::ensureString(preg_replace($pattern, $replacement, $subject));
+ }
+
+ private function tryDefinedName(string $coordinate): string
+ {
+ // Uppercase coordinate
+ $coordinate = strtoupper($coordinate);
+ // Eliminate leading equal sign
+ $coordinate = self::pregReplace('/^=/', '', $coordinate);
+ $defined = $this->parent->getDefinedName($coordinate, $this);
+ if ($defined !== null) {
+ if ($defined->getWorksheet() === $this && !$defined->isFormula()) {
+ $coordinate = self::pregReplace('/^=/', '', $defined->getValue());
+ }
+ }
+
+ return $coordinate;
}
/**
* Select a range of cells.
*
- * @param string $pCoordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6'
+ * @param string $coordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6'
*
* @return $this
*/
- public function setSelectedCells($pCoordinate)
+ public function setSelectedCells($coordinate)
{
- // Uppercase coordinate
- $pCoordinate = strtoupper($pCoordinate);
+ $originalCoordinate = $coordinate;
+ $coordinate = $this->tryDefinedName($coordinate);
// Convert 'A' to 'A:A'
- $pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate);
+ $coordinate = self::pregReplace('/^([A-Z]+)$/', '${1}:${1}', $coordinate);
// Convert '1' to '1:1'
- $pCoordinate = preg_replace('/^(\d+)$/', '${1}:${1}', $pCoordinate);
+ $coordinate = self::pregReplace('/^(\d+)$/', '${1}:${1}', $coordinate);
// Convert 'A:C' to 'A1:C1048576'
- $pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate);
+ $coordinate = self::pregReplace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $coordinate);
// Convert '1:3' to 'A1:XFD3'
- $pCoordinate = preg_replace('/^(\d+):(\d+)$/', 'A${1}:XFD${2}', $pCoordinate);
+ $coordinate = self::pregReplace('/^(\d+):(\d+)$/', 'A${1}:XFD${2}', $coordinate);
+ if (preg_match('/^\\$?[A-Z]{1,3}\\$?\d{1,7}(:\\$?[A-Z]{1,3}\\$?\d{1,7})?$/', $coordinate) !== 1) {
+ throw new Exception("Invalid setSelectedCells $originalCoordinate $coordinate");
+ }
- if (Coordinate::coordinateIsRange($pCoordinate)) {
- [$first] = Coordinate::splitRange($pCoordinate);
+ if (Coordinate::coordinateIsRange($coordinate)) {
+ [$first] = Coordinate::splitRange($coordinate);
$this->activeCell = $first[0];
} else {
- $this->activeCell = $pCoordinate;
+ $this->activeCell = $coordinate;
}
- $this->selectedCells = $pCoordinate;
+ $this->selectedCells = $coordinate;
return $this;
}
@@ -2483,7 +2550,7 @@ class Worksheet implements IComparable
/**
* Create array from a range of cells.
*
- * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
+ * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1")
* @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?
@@ -2492,12 +2559,12 @@ class Worksheet implements IComparable
*
* @return array
*/
- public function rangeToArray($pRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
+ public function rangeToArray($range, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
{
// Returnvalue
$returnValue = [];
// Identify the range that we need to extract from the worksheet
- [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange);
+ [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
$minCol = Coordinate::stringFromColumnIndex($rangeStart[0]);
$minRow = $rangeStart[1];
$maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]);
@@ -2550,10 +2617,42 @@ class Worksheet implements IComparable
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() && $this->getHashCode() !== $namedRange->getWorksheet()->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 $pNamedRange Name of the Named Range
+ * @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?
@@ -2562,17 +2661,14 @@ class Worksheet implements IComparable
*
* @return array
*/
- public function namedRangeToArray($pNamedRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
+ public function namedRangeToArray(string $definedName, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false)
{
- $namedRange = DefinedName::resolveName($pNamedRange, $this);
- if ($namedRange !== null) {
- $pWorkSheet = $namedRange->getWorksheet();
- $pCellRange = $namedRange->getValue();
+ $namedRange = $this->validateNamedRange($definedName);
+ $workSheet = $namedRange->getWorksheet();
+ $cellRange = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!');
+ $cellRange = str_replace('$', '', $cellRange);
- return $pWorkSheet->rangeToArray($pCellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
- }
-
- throw new Exception('Named Range ' . $pNamedRange . ' does not exist.');
+ return $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef);
}
/**
@@ -2652,9 +2748,9 @@ class Worksheet implements IComparable
// Cache values
if ($highestColumn < 1) {
- $this->cachedHighestColumn = 'A';
+ $this->cachedHighestColumn = 1;
} else {
- $this->cachedHighestColumn = Coordinate::stringFromColumnIndex($highestColumn);
+ $this->cachedHighestColumn = $highestColumn;
}
$this->cachedHighestRow = $highestRow;
@@ -2683,58 +2779,58 @@ class Worksheet implements IComparable
* Example: extractSheetTitle("testSheet!A1") ==> 'A1'
* Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1'];
*
- * @param string $pRange Range to extract title from
+ * @param string $range Range to extract title from
* @param bool $returnRange Return range? (see example)
*
* @return mixed
*/
- public static function extractSheetTitle($pRange, $returnRange = false)
+ public static function extractSheetTitle($range, $returnRange = false)
{
// Sheet title included?
- if (($sep = strrpos($pRange, '!')) === false) {
- return $returnRange ? ['', $pRange] : '';
+ if (($sep = strrpos($range, '!')) === false) {
+ return $returnRange ? ['', $range] : '';
}
if ($returnRange) {
- return [substr($pRange, 0, $sep), substr($pRange, $sep + 1)];
+ return [substr($range, 0, $sep), substr($range, $sep + 1)];
}
- return substr($pRange, $sep + 1);
+ return substr($range, $sep + 1);
}
/**
* Get hyperlink.
*
- * @param string $pCellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
+ * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1'
*
* @return Hyperlink
*/
- public function getHyperlink($pCellCoordinate)
+ public function getHyperlink($cellCoordinate)
{
// return hyperlink if we already have one
- if (isset($this->hyperlinkCollection[$pCellCoordinate])) {
- return $this->hyperlinkCollection[$pCellCoordinate];
+ if (isset($this->hyperlinkCollection[$cellCoordinate])) {
+ return $this->hyperlinkCollection[$cellCoordinate];
}
// else create hyperlink
- $this->hyperlinkCollection[$pCellCoordinate] = new Hyperlink();
+ $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink();
- return $this->hyperlinkCollection[$pCellCoordinate];
+ return $this->hyperlinkCollection[$cellCoordinate];
}
/**
* Set hyperlink.
*
- * @param string $pCellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
+ * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1'
*
* @return $this
*/
- public function setHyperlink($pCellCoordinate, ?Hyperlink $pHyperlink = null)
+ public function setHyperlink($cellCoordinate, ?Hyperlink $hyperlink = null)
{
- if ($pHyperlink === null) {
- unset($this->hyperlinkCollection[$pCellCoordinate]);
+ if ($hyperlink === null) {
+ unset($this->hyperlinkCollection[$cellCoordinate]);
} else {
- $this->hyperlinkCollection[$pCellCoordinate] = $pHyperlink;
+ $this->hyperlinkCollection[$cellCoordinate] = $hyperlink;
}
return $this;
@@ -2743,13 +2839,13 @@ class Worksheet implements IComparable
/**
* Hyperlink at a specific coordinate exists?
*
- * @param string $pCoordinate eg: 'A1'
+ * @param string $coordinate eg: 'A1'
*
* @return bool
*/
- public function hyperlinkExists($pCoordinate)
+ public function hyperlinkExists($coordinate)
{
- return isset($this->hyperlinkCollection[$pCoordinate]);
+ return isset($this->hyperlinkCollection[$coordinate]);
}
/**
@@ -2765,36 +2861,36 @@ class Worksheet implements IComparable
/**
* Get data validation.
*
- * @param string $pCellCoordinate Cell coordinate to get data validation for, eg: 'A1'
+ * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1'
*
* @return DataValidation
*/
- public function getDataValidation($pCellCoordinate)
+ public function getDataValidation($cellCoordinate)
{
// return data validation if we already have one
- if (isset($this->dataValidationCollection[$pCellCoordinate])) {
- return $this->dataValidationCollection[$pCellCoordinate];
+ if (isset($this->dataValidationCollection[$cellCoordinate])) {
+ return $this->dataValidationCollection[$cellCoordinate];
}
// else create data validation
- $this->dataValidationCollection[$pCellCoordinate] = new DataValidation();
+ $this->dataValidationCollection[$cellCoordinate] = new DataValidation();
- return $this->dataValidationCollection[$pCellCoordinate];
+ return $this->dataValidationCollection[$cellCoordinate];
}
/**
* Set data validation.
*
- * @param string $pCellCoordinate Cell coordinate to insert data validation, eg: 'A1'
+ * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1'
*
* @return $this
*/
- public function setDataValidation($pCellCoordinate, ?DataValidation $pDataValidation = null)
+ public function setDataValidation($cellCoordinate, ?DataValidation $dataValidation = null)
{
- if ($pDataValidation === null) {
- unset($this->dataValidationCollection[$pCellCoordinate]);
+ if ($dataValidation === null) {
+ unset($this->dataValidationCollection[$cellCoordinate]);
} else {
- $this->dataValidationCollection[$pCellCoordinate] = $pDataValidation;
+ $this->dataValidationCollection[$cellCoordinate] = $dataValidation;
}
return $this;
@@ -2803,13 +2899,13 @@ class Worksheet implements IComparable
/**
* Data validation at a specific coordinate exists?
*
- * @param string $pCoordinate eg: 'A1'
+ * @param string $coordinate eg: 'A1'
*
* @return bool
*/
- public function dataValidationExists($pCoordinate)
+ public function dataValidationExists($coordinate)
{
- return isset($this->dataValidationCollection[$pCoordinate]);
+ return isset($this->dataValidationCollection[$coordinate]);
}
/**
@@ -2880,7 +2976,6 @@ class Worksheet implements IComparable
public function resetTabColor()
{
$this->tabColor = null;
- $this->tabColor = null;
return $this;
}
@@ -2910,6 +3005,7 @@ class Worksheet implements IComparable
*/
public function __clone()
{
+ // @phpstan-ignore-next-line
foreach ($this as $key => $val) {
if ($key == 'parent') {
continue;
@@ -2942,57 +3038,57 @@ class Worksheet implements IComparable
/**
* Define the code name of the sheet.
*
- * @param string $pValue Same rule as Title minus space not allowed (but, like Excel, change
+ * @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($pValue, $validate = true)
+ public function setCodeName($codeName, $validate = true)
{
// Is this a 'rename' or not?
- if ($this->getCodeName() == $pValue) {
+ if ($this->getCodeName() == $codeName) {
return $this;
}
if ($validate) {
- $pValue = str_replace(' ', '_', $pValue); //Excel does this automatically without flinching, we are doing the same
+ $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($pValue);
+ 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->getParent()) {
// Is there already such sheet name?
- if ($this->getParent()->sheetCodeNameExists($pValue)) {
+ if ($this->getParent()->sheetCodeNameExists($codeName)) {
// Use name, but append with lowest possible integer
- if (Shared\StringHelper::countCharacters($pValue) > 29) {
- $pValue = Shared\StringHelper::substring($pValue, 0, 29);
+ if (Shared\StringHelper::countCharacters($codeName) > 29) {
+ $codeName = Shared\StringHelper::substring($codeName, 0, 29);
}
$i = 1;
- while ($this->getParent()->sheetCodeNameExists($pValue . '_' . $i)) {
+ while ($this->getParent()->sheetCodeNameExists($codeName . '_' . $i)) {
++$i;
if ($i == 10) {
- if (Shared\StringHelper::countCharacters($pValue) > 28) {
- $pValue = Shared\StringHelper::substring($pValue, 0, 28);
+ if (Shared\StringHelper::countCharacters($codeName) > 28) {
+ $codeName = Shared\StringHelper::substring($codeName, 0, 28);
}
} elseif ($i == 100) {
- if (Shared\StringHelper::countCharacters($pValue) > 27) {
- $pValue = Shared\StringHelper::substring($pValue, 0, 27);
+ if (Shared\StringHelper::countCharacters($codeName) > 27) {
+ $codeName = Shared\StringHelper::substring($codeName, 0, 27);
}
}
}
- $pValue .= '_' . $i; // ok, we have a valid name
+ $codeName .= '_' . $i; // ok, we have a valid name
}
}
}
- $this->codeName = $pValue;
+ $this->codeName = $codeName;
return $this;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/BaseWriter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/BaseWriter.php
index afda5c433ed..7811a2a0edc 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/BaseWriter.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/BaseWriter.php
@@ -6,7 +6,7 @@ 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;.
+ * Identifies whether the Writer should write definitions for any charts that exist in the PhpSpreadsheet object.
*
* @var bool
*/
@@ -50,9 +50,9 @@ abstract class BaseWriter implements IWriter
return $this->includeCharts;
}
- public function setIncludeCharts($pValue)
+ public function setIncludeCharts($includeCharts)
{
- $this->includeCharts = (bool) $pValue;
+ $this->includeCharts = (bool) $includeCharts;
return $this;
}
@@ -62,9 +62,9 @@ abstract class BaseWriter implements IWriter
return $this->preCalculateFormulas;
}
- public function setPreCalculateFormulas($pValue)
+ public function setPreCalculateFormulas($precalculateFormulas)
{
- $this->preCalculateFormulas = (bool) $pValue;
+ $this->preCalculateFormulas = (bool) $precalculateFormulas;
return $this;
}
@@ -74,15 +74,15 @@ abstract class BaseWriter implements IWriter
return $this->useDiskCaching;
}
- public function setUseDiskCaching($pValue, $pDirectory = null)
+ public function setUseDiskCaching($useDiskCache, $cacheDirectory = null)
{
- $this->useDiskCaching = $pValue;
+ $this->useDiskCaching = $useDiskCache;
- if ($pDirectory !== null) {
- if (is_dir($pDirectory)) {
- $this->diskCachingDirectory = $pDirectory;
+ if ($cacheDirectory !== null) {
+ if (is_dir($cacheDirectory)) {
+ $this->diskCachingDirectory = $cacheDirectory;
} else {
- throw new Exception("Directory does not exist: $pDirectory");
+ throw new Exception("Directory does not exist: $cacheDirectory");
}
}
@@ -94,6 +94,13 @@ abstract class BaseWriter implements IWriter
return $this->diskCachingDirectory;
}
+ protected function processFlags(int $flags): void
+ {
+ if (((bool) ($flags & self::SAVE_WITH_CHARTS)) === true) {
+ $this->setIncludeCharts(true);
+ }
+ }
+
/**
* Open file handle.
*
@@ -108,7 +115,12 @@ abstract class BaseWriter implements IWriter
return;
}
- $fileHandle = $filename ? fopen($filename, 'wb+') : false;
+ $mode = 'wb+';
+ $scheme = parse_url($filename, PHP_URL_SCHEME);
+ if ($scheme === 's3') {
+ $mode = 'w';
+ }
+ $fileHandle = $filename ? fopen($filename, $mode) : false;
if ($fileHandle === false) {
throw new Exception('Could not open file "' . $filename . '" for writing.');
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Csv.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Csv.php
index 74f286361b9..0f385de132e 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Csv.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Csv.php
@@ -64,6 +64,13 @@ class Csv extends BaseWriter
*/
private $excelCompatibility = false;
+ /**
+ * Output encoding.
+ *
+ * @var string
+ */
+ private $outputEncoding = '';
+
/**
* Create a new CSV.
*
@@ -77,10 +84,12 @@ class Csv extends BaseWriter
/**
* Save PhpSpreadsheet to file.
*
- * @param resource|string $pFilename
+ * @param resource|string $filename
*/
- public function save($pFilename): void
+ public function save($filename, int $flags = 0): void
{
+ $this->processFlags($flags);
+
// Fetch sheet
$sheet = $this->spreadsheet->getSheet($this->sheetIndex);
@@ -90,7 +99,7 @@ class Csv extends BaseWriter
Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE);
// Open file
- $this->openFileHandle($pFilename);
+ $this->openFileHandle($filename);
if ($this->excelCompatibility) {
$this->setUseBOM(true); // Enforce UTF-8 BOM Header
@@ -140,13 +149,13 @@ class Csv extends BaseWriter
/**
* Set delimiter.
*
- * @param string $pValue Delimiter, defaults to ','
+ * @param string $delimiter Delimiter, defaults to ','
*
* @return $this
*/
- public function setDelimiter($pValue)
+ public function setDelimiter($delimiter)
{
- $this->delimiter = $pValue;
+ $this->delimiter = $delimiter;
return $this;
}
@@ -164,13 +173,13 @@ class Csv extends BaseWriter
/**
* Set enclosure.
*
- * @param string $pValue Enclosure, defaults to "
+ * @param string $enclosure Enclosure, defaults to "
*
* @return $this
*/
- public function setEnclosure($pValue = '"')
+ public function setEnclosure($enclosure = '"')
{
- $this->enclosure = $pValue;
+ $this->enclosure = $enclosure;
return $this;
}
@@ -188,13 +197,13 @@ class Csv extends BaseWriter
/**
* Set line ending.
*
- * @param string $pValue Line ending, defaults to OS line ending (PHP_EOL)
+ * @param string $lineEnding Line ending, defaults to OS line ending (PHP_EOL)
*
* @return $this
*/
- public function setLineEnding($pValue)
+ public function setLineEnding($lineEnding)
{
- $this->lineEnding = $pValue;
+ $this->lineEnding = $lineEnding;
return $this;
}
@@ -212,13 +221,13 @@ class Csv extends BaseWriter
/**
* Set whether BOM should be used.
*
- * @param bool $pValue Use UTF-8 byte-order mark? Defaults to false
+ * @param bool $useBOM Use UTF-8 byte-order mark? Defaults to false
*
* @return $this
*/
- public function setUseBOM($pValue)
+ public function setUseBOM($useBOM)
{
- $this->useBOM = $pValue;
+ $this->useBOM = $useBOM;
return $this;
}
@@ -236,13 +245,13 @@ class Csv extends BaseWriter
/**
* Set whether a separator line should be included as the first line of the file.
*
- * @param bool $pValue Use separator line? Defaults to false
+ * @param bool $includeSeparatorLine Use separator line? Defaults to false
*
* @return $this
*/
- public function setIncludeSeparatorLine($pValue)
+ public function setIncludeSeparatorLine($includeSeparatorLine)
{
- $this->includeSeparatorLine = $pValue;
+ $this->includeSeparatorLine = $includeSeparatorLine;
return $this;
}
@@ -260,14 +269,14 @@ class Csv extends BaseWriter
/**
* Set whether the file should be saved with full Excel Compatibility.
*
- * @param bool $pValue Set the file to be written as a fully Excel compatible csv file
+ * @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
*
* @return $this
*/
- public function setExcelCompatibility($pValue)
+ public function setExcelCompatibility($excelCompatibility)
{
- $this->excelCompatibility = $pValue;
+ $this->excelCompatibility = $excelCompatibility;
return $this;
}
@@ -285,17 +294,42 @@ class Csv extends BaseWriter
/**
* Set sheet index.
*
- * @param int $pValue Sheet index
+ * @param int $sheetIndex Sheet index
*
* @return $this
*/
- public function setSheetIndex($pValue)
+ public function setSheetIndex($sheetIndex)
{
- $this->sheetIndex = $pValue;
+ $this->sheetIndex = $sheetIndex;
return $this;
}
+ /**
+ * Get output encoding.
+ *
+ * @return string
+ */
+ public function getOutputEncoding()
+ {
+ return $this->outputEncoding;
+ }
+
+ /**
+ * Set output encoding.
+ *
+ * @param string $outputEnconding Output encoding
+ *
+ * @return $this
+ */
+ public function setOutputEncoding($outputEnconding)
+ {
+ $this->outputEncoding = $outputEnconding;
+
+ return $this;
+ }
+
+ /** @var bool */
private $enclosureRequired = true;
public function setEnclosureRequired(bool $value): self
@@ -310,13 +344,27 @@ class Csv extends BaseWriter
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 $pFileHandle PHP filehandle
- * @param array $pValues Array containing values in a row
+ * @param resource $fileHandle PHP filehandle
+ * @param array $values Array containing values in a row
*/
- private function writeLine($pFileHandle, array $pValues): void
+ private function writeLine($fileHandle, array $values): void
{
// No leading delimiter
$delimiter = '';
@@ -324,7 +372,8 @@ class Csv extends BaseWriter
// Build the line
$line = '';
- foreach ($pValues as $element) {
+ foreach ($values as $element) {
+ $element = self::elementToString($element);
// Add delimiter
$line .= $delimiter;
$delimiter = $this->delimiter;
@@ -347,6 +396,9 @@ class Csv extends BaseWriter
$line .= $this->lineEnding;
// Write to file
- fwrite($pFileHandle, $line);
+ if ($this->outputEncoding != '') {
+ $line = mb_convert_encoding($line, $this->outputEncoding);
+ }
+ fwrite($fileHandle, $line);
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Html.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Html.php
index e9de2ce688c..9169d43bb50 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Html.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Html.php
@@ -9,6 +9,7 @@ use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\RichText\Run;
+use PhpOffice\PhpSpreadsheet\Settings;
use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Shared\Font as SharedFont;
@@ -37,7 +38,7 @@ class Html extends BaseWriter
/**
* Sheet index to write.
*
- * @var int
+ * @var null|int
*/
private $sheetIndex = 0;
@@ -151,12 +152,14 @@ class Html extends BaseWriter
/**
* Save Spreadsheet to file.
*
- * @param resource|string $pFilename
+ * @param resource|string $filename
*/
- public function save($pFilename): void
+ public function save($filename, int $flags = 0): void
{
+ $this->processFlags($flags);
+
// Open file
- $this->openFileHandle($pFilename);
+ $this->openFileHandle($filename);
// Write html
fwrite($this->fileHandle, $this->generateHTMLAll());
@@ -288,10 +291,8 @@ class Html extends BaseWriter
/**
* Get sheet index.
- *
- * @return int
*/
- public function getSheetIndex()
+ public function getSheetIndex(): ?int
{
return $this->sheetIndex;
}
@@ -299,13 +300,13 @@ class Html extends BaseWriter
/**
* Set sheet index.
*
- * @param int $pValue Sheet index
+ * @param int $sheetIndex Sheet index
*
* @return $this
*/
- public function setSheetIndex($pValue)
+ public function setSheetIndex($sheetIndex)
{
- $this->sheetIndex = $pValue;
+ $this->sheetIndex = $sheetIndex;
return $this;
}
@@ -323,13 +324,13 @@ class Html extends BaseWriter
/**
* Set sheet index.
*
- * @param bool $pValue Flag indicating whether the sheet navigation block should be generated or not
+ * @param bool $generateSheetNavigationBlock Flag indicating whether the sheet navigation block should be generated or not
*
* @return $this
*/
- public function setGenerateSheetNavigationBlock($pValue)
+ public function setGenerateSheetNavigationBlock($generateSheetNavigationBlock)
{
- $this->generateSheetNavigationBlock = (bool) $pValue;
+ $this->generateSheetNavigationBlock = (bool) $generateSheetNavigationBlock;
return $this;
}
@@ -348,17 +349,21 @@ class Html extends BaseWriter
private static function generateMeta($val, $desc)
{
- return $val ? (' ' . PHP_EOL) : '';
+ return $val
+ ? (' ' . PHP_EOL)
+ : '';
}
+ public const BODY_LINE = ' ' . PHP_EOL;
+
/**
* Generate HTML header.
*
- * @param bool $pIncludeStyles Include styles?
+ * @param bool $includeStyles Include styles?
*
* @return string
*/
- public function generateHTMLHeader($pIncludeStyles = false)
+ public function generateHTMLHeader($includeStyles = false)
{
// Construct HTML
$properties = $this->spreadsheet->getProperties();
@@ -367,7 +372,7 @@ class Html extends BaseWriter
$html .= ' ' . PHP_EOL;
$html .= ' ' . PHP_EOL;
$html .= ' ' . PHP_EOL;
- $html .= ' ' . htmlspecialchars($properties->getTitle()) . '' . PHP_EOL;
+ $html .= ' ' . htmlspecialchars($properties->getTitle(), Settings::htmlEntityFlags()) . '' . PHP_EOL;
$html .= self::generateMeta($properties->getCreator(), 'author');
$html .= self::generateMeta($properties->getTitle(), 'title');
$html .= self::generateMeta($properties->getDescription(), 'description');
@@ -377,11 +382,11 @@ class Html extends BaseWriter
$html .= self::generateMeta($properties->getCompany(), 'company');
$html .= self::generateMeta($properties->getManager(), 'manager');
- $html .= $pIncludeStyles ? $this->generateStyles(true) : $this->generatePageDeclarations(true);
+ $html .= $includeStyles ? $this->generateStyles(true) : $this->generatePageDeclarations(true);
$html .= ' ' . PHP_EOL;
$html .= '' . PHP_EOL;
- $html .= ' ' . PHP_EOL;
+ $html .= self::BODY_LINE;
return $html;
}
@@ -453,10 +458,8 @@ class Html extends BaseWriter
// Get worksheet dimension
[$min, $max] = explode(':', $sheet->calculateWorksheetDataDimension());
- [$minCol, $minRow] = Coordinate::coordinateFromString($min);
- $minCol = Coordinate::columnIndexFromString($minCol);
- [$maxCol, $maxRow] = Coordinate::coordinateFromString($max);
- $maxCol = Coordinate::columnIndexFromString($maxCol);
+ [$minCol, $minRow] = Coordinate::indexesFromString($min);
+ [$maxCol, $maxRow] = Coordinate::indexesFromString($max);
[$theadStart, $theadEnd, $tbodyStart] = $this->generateSheetStarts($sheet, $minRow);
@@ -548,20 +551,19 @@ class Html extends BaseWriter
* Jpgraph code issuing warnings. So, don't measure
* code coverage for this function till that is fixed.
*
- * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
* @param int $row Row to check for charts
*
* @return array
*
* @codeCoverageIgnore
*/
- private function extendRowsForCharts(Worksheet $pSheet, int $row)
+ private function extendRowsForCharts(Worksheet $worksheet, int $row)
{
$rowMax = $row;
$colMax = 'A';
$anyfound = false;
if ($this->includeCharts) {
- foreach ($pSheet->getChartCollection() as $chart) {
+ foreach ($worksheet->getChartCollection() as $chart) {
if ($chart instanceof Chart) {
$anyfound = true;
$chartCoordinates = $chart->getTopLeftPosition();
@@ -580,11 +582,11 @@ class Html extends BaseWriter
return [$rowMax, $colMax, $anyfound];
}
- private function extendRowsForChartsAndImages(Worksheet $pSheet, int $row): string
+ private function extendRowsForChartsAndImages(Worksheet $worksheet, int $row): string
{
- [$rowMax, $colMax, $anyfound] = $this->extendRowsForCharts($pSheet, $row);
+ [$rowMax, $colMax, $anyfound] = $this->extendRowsForCharts($worksheet, $row);
- foreach ($pSheet->getDrawingCollection() as $drawing) {
+ foreach ($worksheet->getDrawingCollection() as $drawing) {
$anyfound = true;
$imageTL = Coordinate::coordinateFromString($drawing->getCoordinates());
$imageCol = Coordinate::columnIndexFromString($imageTL[0]);
@@ -607,8 +609,8 @@ class Html extends BaseWriter
while ($row <= $rowMax) {
$html .= '';
for ($col = 'A'; $col != $colMax; ++$col) {
- $htmlx = $this->writeImageInCell($pSheet, $col . $row);
- $htmlx .= $this->includeCharts ? $this->writeChartInCell($pSheet, $col . $row) : '';
+ $htmlx = $this->writeImageInCell($worksheet, $col . $row);
+ $htmlx .= $this->includeCharts ? $this->writeChartInCell($worksheet, $col . $row) : '';
if ($htmlx) {
$html .= "| $htmlx | ";
} else {
@@ -642,18 +644,18 @@ class Html extends BaseWriter
/**
* Generate image tag in cell.
*
- * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
+ * @param Worksheet $worksheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
* @param string $coordinates Cell coordinates
*
* @return string
*/
- private function writeImageInCell(Worksheet $pSheet, $coordinates)
+ private function writeImageInCell(Worksheet $worksheet, $coordinates)
{
// Construct HTML
$html = '';
// Write images
- foreach ($pSheet->getDrawingCollection() as $drawing) {
+ foreach ($worksheet->getDrawingCollection() as $drawing) {
if ($drawing->getCoordinates() != $coordinates) {
continue;
}
@@ -672,7 +674,7 @@ class Html extends BaseWriter
$filename = preg_replace('@^[.]([^/])@', '$1', $filename);
// Convert UTF8 data to PCDATA
- $filename = htmlspecialchars($filename);
+ $filename = htmlspecialchars($filename, Settings::htmlEntityFlags());
$html .= PHP_EOL;
$imageData = self::winFileToUrl($filename);
@@ -692,18 +694,21 @@ class Html extends BaseWriter
$drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="' .
$imageData . '" alt="' . $filedesc . '" />';
} elseif ($drawing instanceof MemoryDrawing) {
- ob_start(); // Let's start output buffering.
- imagepng($drawing->getImageResource()); // This will normally output the image, but because of ob_start(), it won't.
- $contents = ob_get_contents(); // Instead, output above is saved to $contents
- ob_end_clean(); // End the output buffer.
+ $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 = ob_get_contents(); // Instead, output above is saved to $contents
+ ob_end_clean(); // End the output buffer.
- $dataUri = 'data:image/jpeg;base64,' . base64_encode($contents);
+ $dataUri = 'data:image/jpeg;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 .= '
';
+ // 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 .= '
';
+ }
}
}
@@ -718,32 +723,27 @@ class Html extends BaseWriter
* Jpgraph code issuing warnings. So, don't measure
* code coverage for this function till that is fixed.
*
- * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
- * @param string $coordinates Cell coordinates
- *
- * @return string
- *
* @codeCoverageIgnore
*/
- private function writeChartInCell(Worksheet $pSheet, $coordinates)
+ private function writeChartInCell(Worksheet $worksheet, string $coordinates): string
{
// Construct HTML
$html = '';
// Write charts
- foreach ($pSheet->getChartCollection() as $chart) {
+ 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;
+ return '';
}
$html .= PHP_EOL;
$imageDetails = getimagesize($chartFileName);
$filedesc = $chart->getTitle();
- $filedesc = $filedesc ? self::getChartCaption($filedesc->getCaption()) : '';
+ $filedesc = $filedesc ? $filedesc->getCaptionText() : '';
$filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded chart';
if ($fp = fopen($chartFileName, 'rb', 0)) {
$picture = fread($fp, filesize($chartFileName));
@@ -764,27 +764,6 @@ class Html extends BaseWriter
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.
- * However, that test is suppressed due to out-of-date
- * Jpgraph code issuing warnings. So, don't measure
- * code coverage for this function till that is fixed.
- * Caption is described in documentation as fixed,
- * but in 32_Chart it is somehow an array of RichText.
- *
- * @param mixed $cap
- *
- * @return string
- *
- * @codeCoverageIgnore
- */
- private static function getChartCaption($cap)
- {
- return is_array($cap) ? implode(' ', $cap) : $cap;
- }
-
/**
* Generate CSS styles.
*
@@ -995,36 +974,34 @@ class Html extends BaseWriter
*
* @return array
*/
- private function createCSSStyle(Style $pStyle)
+ private function createCSSStyle(Style $style)
{
// Create CSS
return array_merge(
- $this->createCSSStyleAlignment($pStyle->getAlignment()),
- $this->createCSSStyleBorders($pStyle->getBorders()),
- $this->createCSSStyleFont($pStyle->getFont()),
- $this->createCSSStyleFill($pStyle->getFill())
+ $this->createCSSStyleAlignment($style->getAlignment()),
+ $this->createCSSStyleBorders($style->getBorders()),
+ $this->createCSSStyleFont($style->getFont()),
+ $this->createCSSStyleFill($style->getFill())
);
}
/**
- * Create CSS style (\PhpOffice\PhpSpreadsheet\Style\Alignment).
- *
- * @param Alignment $pStyle \PhpOffice\PhpSpreadsheet\Style\Alignment
+ * Create CSS style.
*
* @return array
*/
- private function createCSSStyleAlignment(Alignment $pStyle)
+ private function createCSSStyleAlignment(Alignment $alignment)
{
// Construct CSS
$css = [];
// Create CSS
- $css['vertical-align'] = $this->mapVAlign($pStyle->getVertical());
- $textAlign = $this->mapHAlign($pStyle->getHorizontal());
+ $css['vertical-align'] = $this->mapVAlign($alignment->getVertical());
+ $textAlign = $this->mapHAlign($alignment->getHorizontal());
if ($textAlign) {
$css['text-align'] = $textAlign;
if (in_array($textAlign, ['left', 'right'])) {
- $css['padding-' . $textAlign] = (string) ((int) $pStyle->getIndent() * 9) . 'px';
+ $css['padding-' . $textAlign] = (string) ((int) $alignment->getIndent() * 9) . 'px';
}
}
@@ -1032,88 +1009,88 @@ class Html extends BaseWriter
}
/**
- * Create CSS style (\PhpOffice\PhpSpreadsheet\Style\Font).
+ * Create CSS style.
*
* @return array
*/
- private function createCSSStyleFont(Font $pStyle)
+ private function createCSSStyleFont(Font $font)
{
// Construct CSS
$css = [];
// Create CSS
- if ($pStyle->getBold()) {
+ if ($font->getBold()) {
$css['font-weight'] = 'bold';
}
- if ($pStyle->getUnderline() != Font::UNDERLINE_NONE && $pStyle->getStrikethrough()) {
+ if ($font->getUnderline() != Font::UNDERLINE_NONE && $font->getStrikethrough()) {
$css['text-decoration'] = 'underline line-through';
- } elseif ($pStyle->getUnderline() != Font::UNDERLINE_NONE) {
+ } elseif ($font->getUnderline() != Font::UNDERLINE_NONE) {
$css['text-decoration'] = 'underline';
- } elseif ($pStyle->getStrikethrough()) {
+ } elseif ($font->getStrikethrough()) {
$css['text-decoration'] = 'line-through';
}
- if ($pStyle->getItalic()) {
+ if ($font->getItalic()) {
$css['font-style'] = 'italic';
}
- $css['color'] = '#' . $pStyle->getColor()->getRGB();
- $css['font-family'] = '\'' . $pStyle->getName() . '\'';
- $css['font-size'] = $pStyle->getSize() . 'pt';
+ $css['color'] = '#' . $font->getColor()->getRGB();
+ $css['font-family'] = '\'' . $font->getName() . '\'';
+ $css['font-size'] = $font->getSize() . 'pt';
return $css;
}
/**
- * Create CSS style (Borders).
+ * Create CSS style.
*
- * @param Borders $pStyle Borders
+ * @param Borders $borders Borders
*
* @return array
*/
- private function createCSSStyleBorders(Borders $pStyle)
+ private function createCSSStyleBorders(Borders $borders)
{
// Construct CSS
$css = [];
// Create CSS
- $css['border-bottom'] = $this->createCSSStyleBorder($pStyle->getBottom());
- $css['border-top'] = $this->createCSSStyleBorder($pStyle->getTop());
- $css['border-left'] = $this->createCSSStyleBorder($pStyle->getLeft());
- $css['border-right'] = $this->createCSSStyleBorder($pStyle->getRight());
+ $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 (Border).
+ * Create CSS style.
*
- * @param Border $pStyle Border
+ * @param Border $border Border
*
* @return string
*/
- private function createCSSStyleBorder(Border $pStyle)
+ private function createCSSStyleBorder(Border $border)
{
// Create CSS - add !important to non-none border styles for merged cells
- $borderStyle = $this->mapBorderStyle($pStyle->getBorderStyle());
+ $borderStyle = $this->mapBorderStyle($border->getBorderStyle());
- return $borderStyle . ' #' . $pStyle->getColor()->getRGB() . (($borderStyle == 'none') ? '' : ' !important');
+ return $borderStyle . ' #' . $border->getColor()->getRGB() . (($borderStyle == 'none') ? '' : ' !important');
}
/**
* Create CSS style (Fill).
*
- * @param Fill $pStyle Fill
+ * @param Fill $fill Fill
*
* @return array
*/
- private function createCSSStyleFill(Fill $pStyle)
+ private function createCSSStyleFill(Fill $fill)
{
// Construct HTML
$css = [];
// Create CSS
- $value = $pStyle->getFillType() == Fill::FILL_NONE ?
- 'white' : '#' . $pStyle->getStartColor()->getRGB();
+ $value = $fill->getFillType() == Fill::FILL_NONE ?
+ 'white' : '#' . $fill->getStartColor()->getRGB();
$css['background-color'] = $value;
return $css;
@@ -1132,13 +1109,13 @@ class Html extends BaseWriter
return $html;
}
- private function generateTableTagInline($pSheet, $id)
+ private function generateTableTagInline(Worksheet $worksheet, $id)
{
$style = isset($this->cssStyles['table']) ?
$this->assembleCSS($this->cssStyles['table']) : '';
- $prntgrid = $pSheet->getPrintGridlines();
- $viewgrid = $this->isPdf ? $prntgrid : $pSheet->getShowGridlines();
+ $prntgrid = $worksheet->getPrintGridlines();
+ $viewgrid = $this->isPdf ? $prntgrid : $worksheet->getShowGridlines();
if ($viewgrid && $prntgrid) {
$html = " " . PHP_EOL;
} elseif ($viewgrid) {
@@ -1152,28 +1129,28 @@ class Html extends BaseWriter
return $html;
}
- private function generateTableTag($pSheet, $id, &$html, $sheetIndex): void
+ private function generateTableTag(Worksheet $worksheet, $id, &$html, $sheetIndex): void
{
if (!$this->useInlineCss) {
- $gridlines = $pSheet->getShowGridlines() ? ' gridlines' : '';
- $gridlinesp = $pSheet->getPrintGridlines() ? ' gridlinesp' : '';
+ $gridlines = $worksheet->getShowGridlines() ? ' gridlines' : '';
+ $gridlinesp = $worksheet->getPrintGridlines() ? ' gridlinesp' : '';
$html .= " " . PHP_EOL;
} else {
- $html .= $this->generateTableTagInline($pSheet, $id);
+ $html .= $this->generateTableTagInline($worksheet, $id);
}
}
/**
* Generate table header.
*
- * @param Worksheet $pSheet The worksheet for the table we are writing
+ * @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($pSheet, $showid = true)
+ private function generateTableHeader(Worksheet $worksheet, $showid = true)
{
- $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
+ $sheetIndex = $worksheet->getParent()->getIndex($worksheet);
// Construct HTML
$html = '';
@@ -1184,10 +1161,10 @@ class Html extends BaseWriter
$html .= "\n";
}
- $this->generateTableTag($pSheet, $id, $html, $sheetIndex);
+ $this->generateTableTag($worksheet, $id, $html, $sheetIndex);
// Write
elements
- $highestColumnIndex = Coordinate::columnIndexFromString($pSheet->getHighestColumn()) - 1;
+ $highestColumnIndex = Coordinate::columnIndexFromString($worksheet->getHighestColumn()) - 1;
$i = -1;
while ($i++ < $highestColumnIndex) {
if (!$this->useInlineCss) {
@@ -1213,20 +1190,19 @@ class Html extends BaseWriter
/**
* Generate row start.
*
- * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
* @param int $sheetIndex Sheet index (0-based)
- * @param int $pRow row number
+ * @param int $row row number
*
* @return string
*/
- private function generateRowStart(Worksheet $pSheet, $sheetIndex, $pRow)
+ private function generateRowStart(Worksheet $worksheet, $sheetIndex, $row)
{
$html = '';
- if (count($pSheet->getBreaks()) > 0) {
- $breaks = $pSheet->getBreaks();
+ if (count($worksheet->getBreaks()) > 0) {
+ $breaks = $worksheet->getBreaks();
// check if a break is needed before this row
- if (isset($breaks['A' . $pRow])) {
+ if (isset($breaks['A' . $row])) {
// close table:
$html .= $this->generateTableFooter();
if ($this->isPdf && $this->useInlineCss) {
@@ -1234,17 +1210,17 @@ class Html extends BaseWriter
}
// open table again: + etc.
- $html .= $this->generateTableHeader($pSheet, false);
+ $html .= $this->generateTableHeader($worksheet, false);
$html .= '' . PHP_EOL;
}
}
// Write row start
if (!$this->useInlineCss) {
- $html .= ' ' . PHP_EOL;
+ $html .= '
' . PHP_EOL;
} else {
- $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow])
- ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : '';
+ $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row])
+ ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]) : '';
$html .= '
' . PHP_EOL;
}
@@ -1252,12 +1228,12 @@ class Html extends BaseWriter
return $html;
}
- private function generateRowCellCss($pSheet, $cellAddress, $pRow, $colNum)
+ private function generateRowCellCss(Worksheet $worksheet, $cellAddress, $row, $columnNumber)
{
- $cell = ($cellAddress > '') ? $pSheet->getCell($cellAddress) : '';
- $coordinate = Coordinate::stringFromColumnIndex($colNum + 1) . ($pRow + 1);
+ $cell = ($cellAddress > '') ? $worksheet->getCell($cellAddress) : '';
+ $coordinate = Coordinate::stringFromColumnIndex($columnNumber + 1) . ($row + 1);
if (!$this->useInlineCss) {
- $cssClass = 'column' . $colNum;
+ $cssClass = 'column' . $columnNumber;
} else {
$cssClass = [];
// The statements below do nothing.
@@ -1298,7 +1274,7 @@ class Html extends BaseWriter
// Convert UTF8 data to PCDATA
$cellText = $element->getText();
- $cellData .= htmlspecialchars($cellText);
+ $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags());
$cellData .= $cellEnd;
@@ -1306,44 +1282,48 @@ class Html extends BaseWriter
} else {
// Convert UTF8 data to PCDATA
$cellText = $element->getText();
- $cellData .= htmlspecialchars($cellText);
+ $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags());
}
}
}
- private function generateRowCellDataValue($pSheet, $cell, &$cellData): void
+ private function generateRowCellDataValue(Worksheet $worksheet, $cell, &$cellData): void
{
if ($cell->getValue() instanceof RichText) {
$this->generateRowCellDataValueRich($cell, $cellData);
} else {
$origData = $this->preCalculateFormulas ? $cell->getCalculatedValue() : $cell->getValue();
- $cellData = NumberFormat::toFormattedString(
- $origData,
- $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(),
- [$this, 'formatColor']
- );
- if ($cellData === $origData) {
- $cellData = htmlspecialchars($cellData);
+ $formatCode = $worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode();
+ if ($formatCode !== null) {
+ $cellData = NumberFormat::toFormattedString(
+ $origData,
+ $formatCode,
+ [$this, 'formatColor']
+ );
}
- if ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) {
+
+ if ($cellData === $origData) {
+ $cellData = htmlspecialchars($cellData ?? '', Settings::htmlEntityFlags());
+ }
+ if ($worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) {
$cellData = '' . $cellData . '';
- } elseif ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) {
+ } elseif ($worksheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) {
$cellData = '' . $cellData . '';
}
}
}
- private function generateRowCellData($pSheet, $cell, &$cssClass, $cellType)
+ private function generateRowCellData(Worksheet $worksheet, $cell, &$cssClass, $cellType)
{
$cellData = ' ';
if ($cell instanceof Cell) {
$cellData = '';
// Don't know what this does, and no test cases.
//if ($cell->getParent() === null) {
- // $cell->attach($pSheet);
+ // $cell->attach($worksheet);
//}
// Value
- $this->generateRowCellDataValue($pSheet, $cell, $cellData);
+ $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"
@@ -1368,7 +1348,7 @@ class Html extends BaseWriter
}
// General horizontal alignment: Actual horizontal alignment depends on dataType
- $sharedStyle = $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex());
+ $sharedStyle = $worksheet->getParent()->getCellXfByIndex($cell->getXfIndex());
if (
$sharedStyle->getAlignment()->getHorizontal() == Alignment::HORIZONTAL_GENERAL
&& isset($this->cssStyles['.' . $cell->getDataType()]['text-align'])
@@ -1386,9 +1366,9 @@ class Html extends BaseWriter
return $cellData;
}
- private function generateRowIncludeCharts($pSheet, $coordinate)
+ private function generateRowIncludeCharts(Worksheet $worksheet, $coordinate)
{
- return $this->includeCharts ? $this->writeChartInCell($pSheet, $coordinate) : '';
+ return $this->includeCharts ? $this->writeChartInCell($worksheet, $coordinate) : '';
}
private function generateRowSpans($html, $rowSpan, $colSpan)
@@ -1399,12 +1379,12 @@ class Html extends BaseWriter
return $html;
}
- private function generateRowWriteCell(&$html, $pSheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $pRow): void
+ private function generateRowWriteCell(&$html, Worksheet $worksheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $row): void
{
// Image?
- $htmlx = $this->writeImageInCell($pSheet, $coordinate);
+ $htmlx = $this->writeImageInCell($worksheet, $coordinate);
// Chart?
- $htmlx .= $this->generateRowIncludeCharts($pSheet, $coordinate);
+ $htmlx .= $this->generateRowIncludeCharts($worksheet, $coordinate);
// Column start
$html .= ' <' . $cellType;
if (!$this->useInlineCss && !$this->isPdf) {
@@ -1434,8 +1414,8 @@ class Html extends BaseWriter
// We must also explicitly write the height of the | element because TCPDF
// does not recognize e.g. |
- if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) {
- $height = $this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'];
+ 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 **
@@ -1450,7 +1430,7 @@ class Html extends BaseWriter
$html .= '>';
$html .= $htmlx;
- $html .= $this->writeComment($pSheet, $coordinate);
+ $html .= $this->writeComment($worksheet, $coordinate);
// Cell data
$html .= $cellData;
@@ -1462,58 +1442,57 @@ class Html extends BaseWriter
/**
* Generate row.
*
- * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
- * @param array $pValues Array containing cells in a row
- * @param int $pRow Row number (0-based)
+ * @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 $pSheet, array $pValues, $pRow, $cellType)
+ private function generateRow(Worksheet $worksheet, array $values, $row, $cellType)
{
// Sheet index
- $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
- $html = $this->generateRowStart($pSheet, $sheetIndex, $pRow);
+ $sheetIndex = $worksheet->getParent()->getIndex($worksheet);
+ $html = $this->generateRowStart($worksheet, $sheetIndex, $row);
// Write cells
$colNum = 0;
- foreach ($pValues as $cellAddress) {
- [$cell, $cssClass, $coordinate] = $this->generateRowCellCss($pSheet, $cellAddress, $pRow, $colNum);
+ foreach ($values as $cellAddress) {
+ [$cell, $cssClass, $coordinate] = $this->generateRowCellCss($worksheet, $cellAddress, $row, $colNum);
$colSpan = 1;
$rowSpan = 1;
// Cell Data
- $cellData = $this->generateRowCellData($pSheet, $cell, $cssClass, $cellType);
+ $cellData = $this->generateRowCellData($worksheet, $cell, $cssClass, $cellType);
// Hyperlink?
- if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) {
- $cellData = '' . $cellData . '';
+ if ($worksheet->hyperlinkExists($coordinate) && !$worksheet->getHyperlink($coordinate)->isInternal()) {
+ $cellData = '' . $cellData . '';
}
// Should the cell be written or is it swallowed by a rowspan or colspan?
- $writeCell = !(isset($this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])
- && $this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]);
+ $writeCell = !(isset($this->isSpannedCell[$worksheet->getParent()->getIndex($worksheet)][$row + 1][$colNum])
+ && $this->isSpannedCell[$worksheet->getParent()->getIndex($worksheet)][$row + 1][$colNum]);
// Colspan and Rowspan
$colspan = 1;
$rowspan = 1;
- if (isset($this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) {
- $spans = $this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum];
+ if (isset($this->isBaseCell[$worksheet->getParent()->getIndex($worksheet)][$row + 1][$colNum])) {
+ $spans = $this->isBaseCell[$worksheet->getParent()->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) . ($pRow + $rowSpan);
+ $endCellCoord = Coordinate::stringFromColumnIndex($colNum + $colSpan) . ($row + $rowSpan);
if (!$this->useInlineCss) {
- $cssClass .= ' style' . $pSheet->getCell($endCellCoord)->getXfIndex();
+ $cssClass .= ' style' . $worksheet->getCell($endCellCoord)->getXfIndex();
}
}
// Write
if ($writeCell) {
- $this->generateRowWriteCell($html, $pSheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $pRow);
+ $this->generateRowWriteCell($html, $worksheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $row);
}
// Next column
@@ -1532,10 +1511,10 @@ class Html extends BaseWriter
*
* @return string
*/
- private function assembleCSS(array $pValue = [])
+ private function assembleCSS(array $values = [])
{
$pairs = [];
- foreach ($pValue as $property => $value) {
+ foreach ($values as $property => $value) {
$pairs[] = $property . ':' . $value;
}
$string = implode('; ', $pairs);
@@ -1556,13 +1535,13 @@ class Html extends BaseWriter
/**
* Set images root.
*
- * @param string $pValue
+ * @param string $imagesRoot
*
* @return $this
*/
- public function setImagesRoot($pValue)
+ public function setImagesRoot($imagesRoot)
{
- $this->imagesRoot = $pValue;
+ $this->imagesRoot = $imagesRoot;
return $this;
}
@@ -1580,13 +1559,13 @@ class Html extends BaseWriter
/**
* Set embed images.
*
- * @param bool $pValue
+ * @param bool $embedImages
*
* @return $this
*/
- public function setEmbedImages($pValue)
+ public function setEmbedImages($embedImages)
{
- $this->embedImages = $pValue;
+ $this->embedImages = $embedImages;
return $this;
}
@@ -1604,13 +1583,13 @@ class Html extends BaseWriter
/**
* Set use inline CSS?
*
- * @param bool $pValue
+ * @param bool $useInlineCss
*
* @return $this
*/
- public function setUseInlineCss($pValue)
+ public function setUseInlineCss($useInlineCss)
{
- $this->useInlineCss = $pValue;
+ $this->useInlineCss = $useInlineCss;
return $this;
}
@@ -1632,7 +1611,7 @@ class Html extends BaseWriter
/**
* Set use embedded CSS?
*
- * @param bool $pValue
+ * @param bool $useEmbeddedCSS
*
* @return $this
*
@@ -1640,9 +1619,9 @@ class Html extends BaseWriter
*
* @deprecated no longer used
*/
- public function setUseEmbeddedCSS($pValue)
+ public function setUseEmbeddedCSS($useEmbeddedCSS)
{
- $this->useEmbeddedCSS = $pValue;
+ $this->useEmbeddedCSS = $useEmbeddedCSS;
return $this;
}
@@ -1650,32 +1629,32 @@ class Html extends BaseWriter
/**
* Add color to formatted string as inline style.
*
- * @param string $pValue Plain formatted value without color
- * @param string $pFormat Format code
+ * @param string $value Plain formatted value without color
+ * @param string $format Format code
*
* @return string
*/
- public function formatColor($pValue, $pFormat)
+ 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, $pFormat, $matches)) {
+ if (preg_match($color_regex, $format, $matches)) {
$color = str_replace(['[', ']'], '', $matches[0]);
$color = strtolower($color);
}
// convert to PCDATA
- $value = htmlspecialchars($pValue);
+ $result = htmlspecialchars($value, Settings::htmlEntityFlags());
// color span tag
if ($color !== null) {
- $value = '' . $value . '';
+ $result = '' . $result . '';
}
- return $value;
+ return $result;
}
/**
@@ -1703,11 +1682,11 @@ class Html extends BaseWriter
$first = $cells[0];
$last = $cells[1];
- [$fc, $fr] = Coordinate::coordinateFromString($first);
- $fc = Coordinate::columnIndexFromString($fc) - 1;
+ [$fc, $fr] = Coordinate::indexesFromString($first);
+ $fc = $fc - 1;
- [$lc, $lr] = Coordinate::coordinateFromString($last);
- $lc = Coordinate::columnIndexFromString($lc) - 1;
+ [$lc, $lr] = Coordinate::indexesFromString($last);
+ $lc = $lc - 1;
// loop through the individual cells in the individual merge
$r = $fr - 1;
@@ -1785,12 +1764,16 @@ class Html extends BaseWriter
*
* @return string
*/
- private function writeComment(Worksheet $pSheet, $coordinate)
+ private function writeComment(Worksheet $worksheet, $coordinate)
{
$result = '';
- if (!$this->isPdf && isset($pSheet->getComments()[$coordinate])) {
+ if (!$this->isPdf && isset($worksheet->getComments()[$coordinate])) {
$sanitizer = new HTMLPurifier();
- $sanitizedString = $sanitizer->purify($pSheet->getComment($coordinate)->getText()->getPlainText());
+ $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 .= '';
$result .= '';
@@ -1801,6 +1784,11 @@ class Html extends BaseWriter
return $result;
}
+ public function getOrientation(): ?string
+ {
+ return null;
+ }
+
/**
* Generate @page declarations.
*
@@ -1826,17 +1814,17 @@ class Html extends BaseWriter
// Loop all sheets
$sheetId = 0;
- foreach ($sheets as $pSheet) {
+ foreach ($sheets as $worksheet) {
$htmlPage .= "@page page$sheetId { ";
- $left = StringHelper::formatNumber($pSheet->getPageMargins()->getLeft()) . 'in; ';
+ $left = StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()) . 'in; ';
$htmlPage .= 'margin-left: ' . $left;
- $right = StringHelper::FormatNumber($pSheet->getPageMargins()->getRight()) . 'in; ';
+ $right = StringHelper::FormatNumber($worksheet->getPageMargins()->getRight()) . 'in; ';
$htmlPage .= 'margin-right: ' . $right;
- $top = StringHelper::FormatNumber($pSheet->getPageMargins()->getTop()) . 'in; ';
+ $top = StringHelper::FormatNumber($worksheet->getPageMargins()->getTop()) . 'in; ';
$htmlPage .= 'margin-top: ' . $top;
- $bottom = StringHelper::FormatNumber($pSheet->getPageMargins()->getBottom()) . 'in; ';
+ $bottom = StringHelper::FormatNumber($worksheet->getPageMargins()->getBottom()) . 'in; ';
$htmlPage .= 'margin-bottom: ' . $bottom;
- $orientation = $pSheet->getPageSetup()->getOrientation();
+ $orientation = $this->getOrientation() ?? $worksheet->getPageSetup()->getOrientation();
if ($orientation === \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE) {
$htmlPage .= 'size: landscape; ';
} elseif ($orientation === \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_PORTRAIT) {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/IWriter.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/IWriter.php
index 5129d65583e..b0a6272602d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/IWriter.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/IWriter.php
@@ -6,8 +6,12 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet;
interface IWriter
{
+ public const SAVE_WITH_CHARTS = 1;
+
/**
* IWriter constructor.
+ *
+ * @param Spreadsheet $spreadsheet The spreadsheet that we want to save using this Writer
*/
public function __construct(Spreadsheet $spreadsheet);
@@ -25,11 +29,11 @@ interface IWriter
* 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 $pValue
+ * @param bool $includeCharts
*
* @return IWriter
*/
- public function setIncludeCharts($pValue);
+ public function setIncludeCharts($includeCharts);
/**
* Get Pre-Calculate Formulas flag
@@ -48,18 +52,18 @@ interface IWriter
* 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 $pValue Pre-Calculate Formulas?
+ * @param bool $precalculateFormulas Pre-Calculate Formulas?
*
* @return IWriter
*/
- public function setPreCalculateFormulas($pValue);
+ public function setPreCalculateFormulas($precalculateFormulas);
/**
* Save PhpSpreadsheet to file.
*
- * @param resource|string $pFilename Name of the file to save
+ * @param resource|string $filename Name of the file to save
*/
- public function save($pFilename);
+ public function save($filename, int $flags = 0): void;
/**
* Get use disk caching where possible?
@@ -71,12 +75,12 @@ interface IWriter
/**
* Set use disk caching where possible?
*
- * @param bool $pValue
- * @param string $pDirectory Disk caching directory
+ * @param bool $useDiskCache
+ * @param string $cacheDirectory Disk caching directory
*
* @return IWriter
*/
- public function setUseDiskCaching($pValue, $pDirectory = null);
+ public function setUseDiskCaching($useDiskCache, $cacheDirectory = null);
/**
* Get disk caching directory.
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods.php
index 36f3e9caf8b..decd82bcd39 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods.php
@@ -2,7 +2,6 @@
namespace PhpOffice\PhpSpreadsheet\Writer;
-use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
use PhpOffice\PhpSpreadsheet\Writer\Ods\Content;
@@ -18,13 +17,6 @@ use ZipStream\ZipStream;
class Ods extends BaseWriter
{
- /**
- * Private writer parts.
- *
- * @var Ods\WriterPart[]
- */
- private $writerParts = [];
-
/**
* Private PhpSpreadsheet.
*
@@ -32,6 +24,41 @@ class Ods extends BaseWriter
*/
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.
*/
@@ -39,62 +66,77 @@ class Ods extends BaseWriter
{
$this->setSpreadsheet($spreadsheet);
- $writerPartsArray = [
- 'content' => Content::class,
- 'meta' => Meta::class,
- 'meta_inf' => MetaInf::class,
- 'mimetype' => Mimetype::class,
- 'settings' => Settings::class,
- 'styles' => Styles::class,
- 'thumbnails' => Thumbnails::class,
- ];
-
- foreach ($writerPartsArray as $writer => $class) {
- $this->writerParts[$writer] = new $class($this);
- }
+ $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);
}
- /**
- * Get writer part.
- *
- * @param string $pPartName Writer part name
- *
- * @return null|Ods\WriterPart
- */
- public function getWriterPart($pPartName)
+ public function getWriterPartContent(): Content
{
- if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) {
- return $this->writerParts[strtolower($pPartName)];
- }
+ return $this->writerPartContent;
+ }
- return null;
+ 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 $pFilename
+ * @param resource|string $filename
*/
- public function save($pFilename): void
+ public function save($filename, int $flags = 0): void
{
if (!$this->spreadSheet) {
throw new WriterException('PhpSpreadsheet object unassigned.');
}
+ $this->processFlags($flags);
+
// garbage collect
$this->spreadSheet->garbageCollect();
- $this->openFileHandle($pFilename);
+ $this->openFileHandle($filename);
$zip = $this->createZip();
- $zip->addFile('META-INF/manifest.xml', $this->getWriterPart('meta_inf')->writeManifest());
- $zip->addFile('Thumbnails/thumbnail.png', $this->getWriterPart('thumbnails')->writeThumbnail());
- $zip->addFile('content.xml', $this->getWriterPart('content')->write());
- $zip->addFile('meta.xml', $this->getWriterPart('meta')->write());
- $zip->addFile('mimetype', $this->getWriterPart('mimetype')->write());
- $zip->addFile('settings.xml', $this->getWriterPart('settings')->write());
- $zip->addFile('styles.xml', $this->getWriterPart('styles')->write());
+ $zip->addFile('META-INF/manifest.xml', $this->getWriterPartMetaInf()->write());
+ $zip->addFile('Thumbnails/thumbnail.png', $this->getWriterPartthumbnails()->write());
+ $zip->addFile('content.xml', $this->getWriterPartcontent()->write());
+ $zip->addFile('meta.xml', $this->getWriterPartmeta()->write());
+ $zip->addFile('mimetype', $this->getWriterPartmimetype()->write());
+ $zip->addFile('settings.xml', $this->getWriterPartsettings()->write());
+ $zip->addFile('styles.xml', $this->getWriterPartstyles()->write());
// Close file
try {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php
new file mode 100644
index 00000000000..cf0450f199f
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php
@@ -0,0 +1,63 @@
+objWriter = $objWriter;
+ $this->spreadsheet = $spreadsheet;
+ }
+
+ public function write(): void
+ {
+ $wrapperWritten = false;
+ $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}";
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php
new file mode 100644
index 00000000000..f8aae20c0b7
--- /dev/null
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php
@@ -0,0 +1,178 @@
+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
+ if ($fill = $style->getFill()) {
+ $this->writeFillStyle($fill);
+ }
+
+ $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');
+ }
+
+ if ($color = $font->getColor()) {
+ $this->writer->writeAttribute('fo:color', sprintf('#%s', $color->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
+ }
+
+ 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
+ }
+}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Content.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Content.php
index 96e66850df1..a589e54923e 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Content.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Content.php
@@ -7,13 +7,12 @@ use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
-use PhpOffice\PhpSpreadsheet\Style\Fill;
-use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Worksheet\Row;
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
@@ -22,7 +21,6 @@ class Content extends WriterPart
{
const NUMBER_COLS_REPEATED_MAX = 1024;
const NUMBER_ROWS_REPEATED_MAX = 1048576;
- const CELL_STYLE_PREFIX = 'ce';
private $formulaConvertor;
@@ -41,7 +39,7 @@ class Content extends WriterPart
*
* @return string XML Output
*/
- public function write()
+ public function write(): string
{
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
@@ -103,6 +101,7 @@ class Content extends WriterPart
$this->writeSheets($objWriter);
+ (new AutoFilters($objWriter, $this->getParentWriter()->getSpreadsheet()))->write();
// Defined names (ranges and formulae)
(new NamedExpressions($objWriter, $this->getParentWriter()->getSpreadsheet(), $this->formulaConvertor))->write();
@@ -185,7 +184,7 @@ class Content extends WriterPart
// Style XF
$style = $cell->getXfIndex();
if ($style !== null) {
- $objWriter->writeAttribute('table:style-name', self::CELL_STYLE_PREFIX . $style);
+ $objWriter->writeAttribute('table:style-name', Style::CELL_STYLE_PREFIX . $style);
}
switch ($cell->getDataType()) {
@@ -196,7 +195,10 @@ class Content extends WriterPart
break;
case DataType::TYPE_ERROR:
- throw new Exception('Writing of error not implemented yet.');
+ $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:
@@ -217,10 +219,6 @@ class Content extends WriterPart
$objWriter->writeAttribute('office:value', $formulaValue);
$objWriter->writeElement('text:p', $formulaValue);
- break;
- case DataType::TYPE_INLINE:
- throw new Exception('Writing of inline not implemented yet.');
-
break;
case DataType::TYPE_NUMERIC:
$objWriter->writeAttribute('office:value-type', 'float');
@@ -228,6 +226,8 @@ class Content extends WriterPart
$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());
@@ -274,89 +274,9 @@ class Content extends WriterPart
*/
private function writeXfStyles(XMLWriter $writer, Spreadsheet $spreadsheet): void
{
+ $styleWriter = new Style($writer);
foreach ($spreadsheet->getCellXfCollection() as $style) {
- $writer->startElement('style:style');
- $writer->writeAttribute('style:name', self::CELL_STYLE_PREFIX . $style->getIndex());
- $writer->writeAttribute('style:family', 'table-cell');
- $writer->writeAttribute('style:parent-style-name', 'Default');
-
- // style:text-properties
-
- // Font
- $writer->startElement('style:text-properties');
-
- $font = $style->getFont();
-
- if ($font->getBold()) {
- $writer->writeAttribute('fo:font-weight', 'bold');
- $writer->writeAttribute('style:font-weight-complex', 'bold');
- $writer->writeAttribute('style:font-weight-asian', 'bold');
- }
-
- if ($font->getItalic()) {
- $writer->writeAttribute('fo:font-style', 'italic');
- }
-
- if ($color = $font->getColor()) {
- $writer->writeAttribute('fo:color', sprintf('#%s', $color->getRGB()));
- }
-
- if ($family = $font->getName()) {
- $writer->writeAttribute('fo:font-family', $family);
- }
-
- if ($size = $font->getSize()) {
- $writer->writeAttribute('fo:font-size', sprintf('%.1Fpt', $size));
- }
-
- if ($font->getUnderline() && $font->getUnderline() != Font::UNDERLINE_NONE) {
- $writer->writeAttribute('style:text-underline-style', 'solid');
- $writer->writeAttribute('style:text-underline-width', 'auto');
- $writer->writeAttribute('style:text-underline-color', 'font-color');
-
- switch ($font->getUnderline()) {
- case Font::UNDERLINE_DOUBLE:
- $writer->writeAttribute('style:text-underline-type', 'double');
-
- break;
- case Font::UNDERLINE_SINGLE:
- $writer->writeAttribute('style:text-underline-type', 'single');
-
- break;
- }
- }
-
- $writer->endElement(); // Close style:text-properties
-
- // style:table-cell-properties
-
- $writer->startElement('style:table-cell-properties');
- $writer->writeAttribute('style:rotation-align', 'none');
-
- // Fill
- if ($fill = $style->getFill()) {
- switch ($fill->getFillType()) {
- case Fill::FILL_SOLID:
- $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:
- }
- }
-
- $writer->endElement(); // Close style:table-cell-properties
-
- // End
-
- $writer->endElement(); // Close style:style
+ $styleWriter->write($style);
}
}
@@ -374,7 +294,7 @@ class Content extends WriterPart
$start = Coordinate::coordinateFromString($startCell);
$end = Coordinate::coordinateFromString($endCell);
$columnSpan = Coordinate::columnIndexFromString($end[0]) - Coordinate::columnIndexFromString($start[0]) + 1;
- $rowSpan = $end[1] - $start[1] + 1;
+ $rowSpan = ((int) $end[1]) - ((int) $start[1]) + 1;
$objWriter->writeAttribute('table:number-columns-spanned', $columnSpan);
$objWriter->writeAttribute('table:number-rows-spanned', $rowSpan);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Meta.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Meta.php
index 365221f77da..16f7c8b540d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Meta.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Meta.php
@@ -2,6 +2,8 @@
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
+use PhpOffice\PhpSpreadsheet\Document\Properties;
+use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
@@ -10,15 +12,11 @@ class Meta extends WriterPart
/**
* Write meta.xml to XML format.
*
- * @param Spreadsheet $spreadsheet
- *
* @return string XML Output
*/
- public function write(?Spreadsheet $spreadsheet = null)
+ public function write(): string
{
- if (!$spreadsheet) {
- $spreadsheet = $this->getParentWriter()->getSpreadsheet();
- }
+ $spreadsheet = $this->getParentWriter()->getSpreadsheet();
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
@@ -45,15 +43,24 @@ class Meta extends WriterPart
$objWriter->writeElement('meta:initial-creator', $spreadsheet->getProperties()->getCreator());
$objWriter->writeElement('dc:creator', $spreadsheet->getProperties()->getCreator());
- $objWriter->writeElement('meta:creation-date', date(DATE_W3C, $spreadsheet->getProperties()->getCreated()));
- $objWriter->writeElement('dc:date', date(DATE_W3C, $spreadsheet->getProperties()->getCreated()));
+ $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());
- $keywords = explode(' ', $spreadsheet->getProperties()->getKeywords());
- foreach ($keywords as $keyword) {
- $objWriter->writeElement('meta:keyword', $keyword);
- }
+ $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);
+ //}
//
$objWriter->startElement('meta:user-defined');
@@ -66,10 +73,50 @@ class Meta extends WriterPart
$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();
+ }
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/MetaInf.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/MetaInf.php
index c9085cf8ce7..f3f0d5fc9f0 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/MetaInf.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/MetaInf.php
@@ -11,7 +11,7 @@ class MetaInf extends WriterPart
*
* @return string XML Output
*/
- public function writeManifest()
+ public function write(): string
{
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Mimetype.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Mimetype.php
index 4aac3685255..e109e6e7ebc 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Mimetype.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Mimetype.php
@@ -2,18 +2,14 @@
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
-use PhpOffice\PhpSpreadsheet\Spreadsheet;
-
class Mimetype extends WriterPart
{
/**
* Write mimetype to plain text format.
*
- * @param Spreadsheet $spreadsheet
- *
* @return string XML Output
*/
- public function write(?Spreadsheet $spreadsheet = null)
+ public function write(): string
{
return 'application/vnd.oasis.opendocument.spreadsheet';
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php
index 9edc5c6448c..e309dab117e 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php
@@ -10,24 +10,29 @@ 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, $formulaConvertor)
+ public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet, Formula $formulaConvertor)
{
$this->objWriter = $objWriter;
$this->spreadsheet = $spreadsheet;
$this->formulaConvertor = $formulaConvertor;
}
- public function write(): void
+ public function write(): string
{
$this->objWriter->startElement('table:named-expressions');
$this->writeExpressions();
$this->objWriter->endElement();
+
+ return '';
}
private function writeExpressions(): void
@@ -49,23 +54,29 @@ class NamedExpressions
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(), $definedName->getWorksheet()->getTitle())
+ $this->formulaConvertor->convertFormula($definedName->getValue(), $title)
);
$this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress(
$definedName,
- "'" . (($definedName->getWorksheet() !== null) ? $definedName->getWorksheet()->getTitle() : $defaultWorksheet->getTitle()) . "'!\$A\$1"
+ "'" . $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,
- "'" . $definedName->getWorksheet()->getTitle() . "'!\$A\$1"
+ $baseCell
));
$this->objWriter->writeAttribute('table:cell-range-address', $this->convertAddress($definedName, $definedName->getValue()));
}
@@ -98,7 +109,10 @@ class NamedExpressions
if (empty($worksheet)) {
if (($offset === 0) || ($address[$offset - 1] !== ':')) {
// We need a worksheet
- $worksheet = $definedName->getWorksheet()->getTitle();
+ $ws = $definedName->getWorksheet();
+ if ($ws !== null) {
+ $worksheet = $ws->getTitle();
+ }
}
} else {
$worksheet = str_replace("''", "'", trim($worksheet, "'"));
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Settings.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Settings.php
index d458e8c2bdc..047bd410b2d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Settings.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Settings.php
@@ -2,21 +2,18 @@
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
+use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
-use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Settings extends WriterPart
{
/**
* Write settings.xml to XML format.
*
- * @param Spreadsheet $spreadsheet
- *
* @return string XML Output
*/
- public function write(?Spreadsheet $spreadsheet = null)
+ public function write(): string
{
- $objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
$objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
} else {
@@ -39,13 +36,52 @@ class Settings extends WriterPart
$objWriter->writeAttribute('config:name', 'ooo:view-settings');
$objWriter->startElement('config:config-item-map-indexed');
$objWriter->writeAttribute('config:name', 'Views');
- $objWriter->endElement();
- $objWriter->endElement();
+ $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');
+ $objWriter->writeAttribute('config:name', 'Tables');
+ foreach ($spreadsheet->getWorksheetIterator() as $ws) {
+ $objWriter->startElement('config:config-item-map-entry');
+ $objWriter->writeAttribute('config:name', $ws->getTitle());
+ $selected = $ws->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($colSel);
+ $objWriter->endElement();
+ $objWriter->startElement('config:config-item');
+ $objWriter->writeAttribute('config:name', 'CursorPositionY');
+ $objWriter->writeAttribute('config:type', 'int');
+ $objWriter->text($rowSel);
+ $objWriter->endElement();
+ }
+ $objWriter->endElement(); // config:config-item-map-entry
+ }
+ $objWriter->endElement(); // config:config-item-map-named
+ $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();
- $objWriter->endElement();
- $objWriter->endElement();
+ $objWriter->endElement(); // config:config-item-set ooo:configuration-settings
+ $objWriter->endElement(); // office:settings
+ $objWriter->endElement(); // office:document-settings
return $objWriter->getData();
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Styles.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Styles.php
index 7ba7eba7356..448b1eff131 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Styles.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Styles.php
@@ -3,18 +3,15 @@
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
-use PhpOffice\PhpSpreadsheet\Spreadsheet;
class Styles extends WriterPart
{
/**
* Write styles.xml to XML format.
*
- * @param Spreadsheet $spreadsheet
- *
* @return string XML Output
*/
- public function write(?Spreadsheet $spreadsheet = null)
+ public function write(): string
{
$objWriter = null;
if ($this->getParentWriter()->getUseDiskCaching()) {
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php
index dfab0654c61..db9579d0c2d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php
@@ -2,18 +2,14 @@
namespace PhpOffice\PhpSpreadsheet\Writer\Ods;
-use PhpOffice\PhpSpreadsheet\Spreadsheet;
-
class Thumbnails extends WriterPart
{
/**
* Write Thumbnails/thumbnail.png to PNG format.
*
- * @param Spreadsheet $spreadsheet
- *
* @return string XML Output
*/
- public function writeThumbnail(?Spreadsheet $spreadsheet = null)
+ public function write(): string
{
return '';
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/WriterPart.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/WriterPart.php
index 1982c4506ba..17d5d169315 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/WriterPart.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/WriterPart.php
@@ -30,4 +30,6 @@ abstract class WriterPart
{
$this->parentWriter = $writer;
}
+
+ abstract public function write(): string;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf.php
index 872204589ff..493bbba3e5d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf.php
@@ -26,14 +26,14 @@ abstract class Pdf extends Html
/**
* Orientation (Over-ride).
*
- * @var string
+ * @var ?string
*/
protected $orientation;
/**
* Paper size (Over-ride).
*
- * @var int
+ * @var ?int
*/
protected $paperSize;
@@ -155,7 +155,7 @@ abstract class Pdf extends Html
/**
* Get Paper Size.
*
- * @return int
+ * @return ?int
*/
public function getPaperSize()
{
@@ -165,23 +165,21 @@ abstract class Pdf extends Html
/**
* Set Paper Size.
*
- * @param string $pValue Paper size see PageSetup::PAPERSIZE_*
+ * @param int $paperSize Paper size see PageSetup::PAPERSIZE_*
*
* @return self
*/
- public function setPaperSize($pValue)
+ public function setPaperSize($paperSize)
{
- $this->paperSize = $pValue;
+ $this->paperSize = $paperSize;
return $this;
}
/**
* Get Orientation.
- *
- * @return string
*/
- public function getOrientation()
+ public function getOrientation(): ?string
{
return $this->orientation;
}
@@ -189,13 +187,13 @@ abstract class Pdf extends Html
/**
* Set Orientation.
*
- * @param string $pValue Page orientation see PageSetup::ORIENTATION_*
+ * @param string $orientation Page orientation see PageSetup::ORIENTATION_*
*
* @return self
*/
- public function setOrientation($pValue)
+ public function setOrientation($orientation)
{
- $this->orientation = $pValue;
+ $this->orientation = $orientation;
return $this;
}
@@ -213,16 +211,16 @@ abstract class Pdf extends Html
/**
* Set temporary storage directory.
*
- * @param string $pValue Temporary storage directory
+ * @param string $temporaryDirectory Temporary storage directory
*
* @return self
*/
- public function setTempDir($pValue)
+ public function setTempDir($temporaryDirectory)
{
- if (is_dir($pValue)) {
- $this->tempDir = $pValue;
+ if (is_dir($temporaryDirectory)) {
+ $this->tempDir = $temporaryDirectory;
} else {
- throw new WriterException("Directory does not exist: $pValue");
+ throw new WriterException("Directory does not exist: $temporaryDirectory");
}
return $this;
@@ -231,14 +229,14 @@ abstract class Pdf extends Html
/**
* Save Spreadsheet to PDF file, pre-save.
*
- * @param string $pFilename Name of the file to save as
+ * @param string $filename Name of the file to save as
*
* @return resource
*/
- protected function prepareForSave($pFilename)
+ protected function prepareForSave($filename)
{
// Open file
- $this->openFileHandle($pFilename);
+ $this->openFileHandle($filename);
return $this->fileHandle;
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php
index 9ae2ccee358..fc96f904945 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php
@@ -20,52 +20,33 @@ class Dompdf extends Pdf
/**
* Save Spreadsheet to file.
*
- * @param string $pFilename Name of the file to save as
+ * @param string $filename Name of the file to save as
*/
- public function save($pFilename): void
+ public function save($filename, int $flags = 0): void
{
- $fileHandle = parent::prepareForSave($pFilename);
+ $fileHandle = parent::prepareForSave($filename);
// Default PDF paper size
$paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.)
// Check for paper size and page orientation
- if ($this->getSheetIndex() === null) {
- $orientation = ($this->spreadsheet->getSheet(0)->getPageSetup()->getOrientation()
- == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
- $printPaperSize = $this->spreadsheet->getSheet(0)->getPageSetup()->getPaperSize();
- } else {
- $orientation = ($this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation()
- == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
- $printPaperSize = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize();
- }
+ $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();
$orientation = ($orientation == 'L') ? 'landscape' : 'portrait';
- // Override Page Orientation
- if ($this->getOrientation() !== null) {
- $orientation = ($this->getOrientation() == PageSetup::ORIENTATION_DEFAULT)
- ? PageSetup::ORIENTATION_PORTRAIT
- : $this->getOrientation();
- }
- // Override Paper Size
- if ($this->getPaperSize() !== null) {
- $printPaperSize = $this->getPaperSize();
- }
-
- if (isset(self::$paperSizes[$printPaperSize])) {
- $paperSize = self::$paperSizes[$printPaperSize];
- }
-
// Create PDF
$pdf = $this->createExternalWriterInstance();
- $pdf->setPaper(strtolower($paperSize), $orientation);
+ $pdf->setPaper($paperSize, $orientation);
$pdf->loadHtml($this->generateHTMLAll());
$pdf->render();
// Write to file
- fwrite($fileHandle, $pdf->output());
+ fwrite($fileHandle, $pdf->output() ?? '');
parent::restoreStateAfterSave();
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php
index 75e0010d5fa..281e1a4f9b5 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php
@@ -3,6 +3,7 @@
namespace PhpOffice\PhpSpreadsheet\Writer\Pdf;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
+use PhpOffice\PhpSpreadsheet\Writer\Html;
use PhpOffice\PhpSpreadsheet\Writer\Pdf;
class Mpdf extends Pdf
@@ -22,49 +23,24 @@ class Mpdf extends Pdf
/**
* Save Spreadsheet to file.
*
- * @param string $pFilename Name of the file to save as
+ * @param string $filename Name of the file to save as
*/
- public function save($pFilename): void
+ public function save($filename, int $flags = 0): void
{
- $fileHandle = parent::prepareForSave($pFilename);
-
- // Default PDF paper size
- $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.)
+ $fileHandle = parent::prepareForSave($filename);
// Check for paper size and page orientation
- if (null === $this->getSheetIndex()) {
- $orientation = ($this->spreadsheet->getSheet(0)->getPageSetup()->getOrientation()
- == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
- $printPaperSize = $this->spreadsheet->getSheet(0)->getPageSetup()->getPaperSize();
- } else {
- $orientation = ($this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation()
- == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
- $printPaperSize = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize();
- }
- $this->setOrientation($orientation);
-
- // Override Page Orientation
- if (null !== $this->getOrientation()) {
- $orientation = ($this->getOrientation() == PageSetup::ORIENTATION_DEFAULT)
- ? PageSetup::ORIENTATION_PORTRAIT
- : $this->getOrientation();
- }
- $orientation = strtoupper($orientation);
-
- // Override Paper Size
- if (null !== $this->getPaperSize()) {
- $printPaperSize = $this->getPaperSize();
- }
-
- if (isset(self::$paperSizes[$printPaperSize])) {
- $paperSize = self::$paperSizes[$printPaperSize];
- }
+ $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(strtoupper($paperSize), $ortmp);
+ $pdf->_setPageSize($paperSize, $ortmp);
$pdf->DefOrientation = $orientation;
$pdf->AddPageByArray([
'orientation' => $orientation,
@@ -82,6 +58,14 @@ class Mpdf extends Pdf
$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));
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php
index 7530b1efe0e..d29d4764876 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php
@@ -24,7 +24,7 @@ class Tcpdf extends Pdf
*
* @param string $orientation Page orientation
* @param string $unit Unit measure
- * @param string $paperSize Paper size
+ * @param array|string $paperSize Paper size
*
* @return \TCPDF implementation
*/
@@ -36,42 +36,22 @@ class Tcpdf extends Pdf
/**
* Save Spreadsheet to file.
*
- * @param string $pFilename Name of the file to save as
+ * @param string $filename Name of the file to save as
*/
- public function save($pFilename): void
+ public function save($filename, int $flags = 0): void
{
- $fileHandle = parent::prepareForSave($pFilename);
+ $fileHandle = parent::prepareForSave($filename);
// Default PDF paper size
$paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.)
// Check for paper size and page orientation
- if ($this->getSheetIndex() === null) {
- $orientation = ($this->spreadsheet->getSheet(0)->getPageSetup()->getOrientation()
- == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
- $printPaperSize = $this->spreadsheet->getSheet(0)->getPageSetup()->getPaperSize();
- $printMargins = $this->spreadsheet->getSheet(0)->getPageMargins();
- } else {
- $orientation = ($this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation()
- == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
- $printPaperSize = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize();
- $printMargins = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageMargins();
- }
-
- // Override Page Orientation
- if ($this->getOrientation() !== null) {
- $orientation = ($this->getOrientation() == PageSetup::ORIENTATION_LANDSCAPE)
- ? 'L'
- : 'P';
- }
- // Override Paper Size
- if ($this->getPaperSize() !== null) {
- $printPaperSize = $this->getPaperSize();
- }
-
- if (isset(self::$paperSizes[$printPaperSize])) {
- $paperSize = self::$paperSizes[$printPaperSize];
- }
+ $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);
@@ -97,7 +77,7 @@ class Tcpdf extends Pdf
$pdf->SetCreator($this->spreadsheet->getProperties()->getCreator());
// Write to file
- fwrite($fileHandle, $pdf->output($pFilename, 'S'));
+ fwrite($fileHandle, $pdf->output($filename, 'S'));
parent::restoreStateAfterSave();
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php
index d71541c8053..4f506070526 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php
@@ -5,8 +5,13 @@ namespace PhpOffice\PhpSpreadsheet\Writer;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\HashTable;
-use PhpOffice\PhpSpreadsheet\Shared\File;
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;
@@ -37,13 +42,6 @@ class Xlsx extends BaseWriter
*/
private $office2003compatibility = false;
- /**
- * Private writer parts.
- *
- * @var Xlsx\WriterPart[]
- */
- private $writerParts = [];
-
/**
* Private Spreadsheet.
*
@@ -61,49 +59,49 @@ class Xlsx extends BaseWriter
/**
* Private unique Conditional HashTable.
*
- * @var HashTable
+ * @var HashTable
*/
private $stylesConditionalHashTable;
/**
* Private unique Style HashTable.
*
- * @var HashTable
+ * @var HashTable<\PhpOffice\PhpSpreadsheet\Style\Style>
*/
private $styleHashTable;
/**
* Private unique Fill HashTable.
*
- * @var HashTable
+ * @var HashTable
*/
private $fillHashTable;
/**
* Private unique \PhpOffice\PhpSpreadsheet\Style\Font HashTable.
*
- * @var HashTable
+ * @var HashTable
*/
private $fontHashTable;
/**
* Private unique Borders HashTable.
*
- * @var HashTable
+ * @var HashTable
*/
private $bordersHashTable;
/**
* Private unique NumberFormat HashTable.
*
- * @var HashTable
+ * @var HashTable
*/
private $numFmtHashTable;
/**
* Private unique \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable.
*
- * @var HashTable
+ * @var HashTable
*/
private $drawingHashTable;
@@ -114,6 +112,71 @@ class Xlsx extends BaseWriter
*/
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 Workbook
+ */
+ private $writerPartWorkbook;
+
+ /**
+ * @var Worksheet
+ */
+ private $writerPartWorksheet;
+
/**
* Create a new Xlsx Writer.
*/
@@ -122,68 +185,115 @@ class Xlsx extends BaseWriter
// Assign PhpSpreadsheet
$this->setSpreadsheet($spreadsheet);
- $writerPartsArray = [
- 'stringtable' => StringTable::class,
- 'contenttypes' => ContentTypes::class,
- 'docprops' => DocProps::class,
- 'rels' => Rels::class,
- 'theme' => Theme::class,
- 'style' => Style::class,
- 'workbook' => Workbook::class,
- 'worksheet' => Worksheet::class,
- 'drawing' => Drawing::class,
- 'comments' => Comments::class,
- 'chart' => Chart::class,
- 'relsvba' => RelsVBA::class,
- 'relsribbonobjects' => RelsRibbon::class,
- ];
-
- // Initialise writer parts
- // and Assign their parent IWriters
- foreach ($writerPartsArray as $writer => $class) {
- $this->writerParts[$writer] = new $class($this);
- }
-
- $hashTablesArray = ['stylesConditionalHashTable', 'fillHashTable', 'fontHashTable',
- 'bordersHashTable', 'numFmtHashTable', 'drawingHashTable',
- 'styleHashTable',
- ];
+ $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->writerPartWorkbook = new Workbook($this);
+ $this->writerPartWorksheet = new Worksheet($this);
// Set HashTable variables
- foreach ($hashTablesArray as $tableName) {
- $this->$tableName = new HashTable();
- }
+ // @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();
}
- /**
- * Get writer part.
- *
- * @param string $pPartName Writer part name
- *
- * @return \PhpOffice\PhpSpreadsheet\Writer\Xlsx\WriterPart
- */
- public function getWriterPart($pPartName)
+ public function getWriterPartChart(): Chart
{
- if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) {
- return $this->writerParts[strtolower($pPartName)];
- }
+ return $this->writerPartChart;
+ }
- return null;
+ 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 getWriterPartWorkbook(): Workbook
+ {
+ return $this->writerPartWorkbook;
+ }
+
+ public function getWriterPartWorksheet(): Worksheet
+ {
+ return $this->writerPartWorksheet;
}
/**
* Save PhpSpreadsheet to file.
*
- * @param resource|string $pFilename
+ * @param resource|string $filename
*/
- public function save($pFilename): void
+ public function save($filename, int $flags = 0): void
{
+ $this->processFlags($flags);
+
// garbage collect
$this->pathNames = [];
$this->spreadSheet->garbageCollect();
- $this->openFileHandle($pFilename);
-
$saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog();
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false);
$saveDateReturnType = Functions::getReturnDateType();
@@ -192,91 +302,86 @@ class Xlsx extends BaseWriter
// Create string lookup table
$this->stringTable = [];
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
- $this->stringTable = $this->getWriterPart('StringTable')->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable);
+ $this->stringTable = $this->getWriterPartStringTable()->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable);
}
// Create styles dictionaries
- $this->styleHashTable->addFromSource($this->getWriterPart('Style')->allStyles($this->spreadSheet));
- $this->stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->spreadSheet));
- $this->fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->spreadSheet));
- $this->fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->spreadSheet));
- $this->bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->spreadSheet));
- $this->numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->spreadSheet));
+ $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->getWriterPart('Drawing')->allDrawings($this->spreadSheet));
-
- $options = new Archive();
- $options->setEnableZip64(false);
- $options->setOutputStream($this->fileHandle);
-
- $this->zip = new ZipStream(null, $options);
+ $this->drawingHashTable->addFromSource($this->getWriterPartDrawing()->allDrawings($this->spreadSheet));
+ $zipContent = [];
// Add [Content_Types].xml to ZIP file
- $this->addZipFile('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->spreadSheet, $this->includeCharts));
+ $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 ?
- $this->addZipFile('xl/vbaProject.bin', $macrosCode); //allways in 'xl', allways named vbaProject.bin
+ $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
- $this->addZipFile('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate());
- $this->addZipFile('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet));
+ $zipContent['xl/vbaProjectSignature.bin'] = $this->spreadSheet->getMacrosCertificate();
+ $zipContent['xl/_rels/vbaProject.bin.rels'] = $this->getWriterPartRelsVBA()->writeVBARelationships($this->spreadSheet);
}
}
}
//a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels)
if ($this->spreadSheet->hasRibbon()) {
$tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target');
- $this->addZipFile($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data'));
+ $zipContent[$tmpRibbonTarget] = $this->spreadSheet->getRibbonXMLData('data');
if ($this->spreadSheet->hasRibbonBinObjects()) {
$tmpRootPath = dirname($tmpRibbonTarget) . '/';
$ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write
foreach ($ribbonBinObjects as $aPath => $aContent) {
- $this->addZipFile($tmpRootPath . $aPath, $aContent);
+ $zipContent[$tmpRootPath . $aPath] = $aContent;
}
//the rels for files
- $this->addZipFile($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet));
+ $zipContent[$tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels'] = $this->getWriterPartRelsRibbon()->writeRibbonRelationships($this->spreadSheet);
}
}
// Add relationships to ZIP file
- $this->addZipFile('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->spreadSheet));
- $this->addZipFile('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->spreadSheet));
+ $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
- $this->addZipFile('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->spreadSheet));
- $this->addZipFile('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->spreadSheet));
- $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->spreadSheet);
+ $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) {
- $this->addZipFile('docProps/custom.xml', $customPropertiesPart);
+ $zipContent['docProps/custom.xml'] = $customPropertiesPart;
}
// Add theme to ZIP file
- $this->addZipFile('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->spreadSheet));
+ $zipContent['xl/theme/theme1.xml'] = $this->getWriterPartTheme()->writeTheme($this->spreadSheet);
// Add string table to ZIP file
- $this->addZipFile('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->stringTable));
+ $zipContent['xl/sharedStrings.xml'] = $this->getWriterPartStringTable()->writeStringTable($this->stringTable);
// Add styles to ZIP file
- $this->addZipFile('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->spreadSheet));
+ $zipContent['xl/styles.xml'] = $this->getWriterPartStyle()->writeStyles($this->spreadSheet);
// Add workbook to ZIP file
- $this->addZipFile('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas));
+ $zipContent['xl/workbook.xml'] = $this->getWriterPartWorkbook()->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas);
$chartCount = 0;
// Add worksheets
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
- $this->addZipFile('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts));
+ $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) {
- $this->addZipFile('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas));
+ $zipContent['xl/charts/chart' . ($chartCount + 1) . '.xml'] = $this->getWriterPartChart()->writeChart($chart, $this->preCalculateFormulas);
++$chartCount;
}
}
@@ -287,19 +392,19 @@ class Xlsx extends BaseWriter
// Add worksheet relationships (drawings, ...)
for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
// Add relationships
- $this->addZipFile('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts));
+ $zipContent['xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts);
// Add unparsedLoadedData
$sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName();
$unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData();
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) {
- $this->addZipFile($ctrlProp['filePath'], $ctrlProp['content']);
+ $zipContent[$ctrlProp['filePath']] = $ctrlProp['content'];
}
}
if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) {
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) {
- $this->addZipFile($ctrlProp['filePath'], $ctrlProp['content']);
+ $zipContent[$ctrlProp['filePath']] = $ctrlProp['content'];
}
}
@@ -312,13 +417,13 @@ class Xlsx extends BaseWriter
// Add drawing and image relationship parts
if (($drawingCount > 0) || ($chartCount > 0)) {
// Drawing relationships
- $this->addZipFile('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts));
+ $zipContent['xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts);
// Drawings
- $this->addZipFile('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
+ $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts);
} elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) {
// Drawings
- $this->addZipFile('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
+ $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts);
}
// Add unparsed drawings
@@ -326,39 +431,51 @@ class Xlsx extends BaseWriter
foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['Drawings'] as $relId => $drawingXml) {
$drawingFile = array_search($relId, $unparsedLoadedData['sheets'][$sheetCodeName]['drawingOriginalIds']);
if ($drawingFile !== false) {
- $drawingFile = ltrim($drawingFile, '.');
- $this->addZipFile('xl' . $drawingFile, $drawingXml);
+ //$drawingFile = ltrim($drawingFile, '.');
+ //$zipContent['xl' . $drawingFile] = $drawingXml;
+ $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $drawingXml;
}
}
}
// Add comment relationship parts
if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) {
+ // VML Comments relationships
+ $zipContent['xl/drawings/_rels/vmlDrawing' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeVMLDrawingRelationships($this->spreadSheet->getSheet($i));
+
// VML Comments
- $this->addZipFile('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i)));
+ $zipContent['xl/drawings/vmlDrawing' . ($i + 1) . '.vml'] = $this->getWriterPartComments()->writeVMLComments($this->spreadSheet->getSheet($i));
// Comments
- $this->addZipFile('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i)));
+ $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) {
- $this->addZipFile($vmlDrawing['filePath'], $vmlDrawing['content']);
+ $zipContent[$vmlDrawing['filePath']] = $vmlDrawing['content'];
}
}
// Add header/footer relationship parts
if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
// VML Drawings
- $this->addZipFile('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i)));
+ $zipContent['xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml'] = $this->getWriterPartDrawing()->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i));
// VML Drawing relationships
- $this->addZipFile('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i)));
+ $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) {
- $this->addZipFile('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
+ $zipContent['xl/media/' . $image->getIndexedFilename()] = file_get_contents($image->getPath());
}
}
}
@@ -381,7 +498,7 @@ class Xlsx extends BaseWriter
$imageContents = file_get_contents($imagePath);
}
- $this->addZipFile('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
+ $zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents;
} elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) {
ob_start();
call_user_func(
@@ -391,13 +508,23 @@ class Xlsx extends BaseWriter
$imageContents = ob_get_contents();
ob_end_clean();
- $this->addZipFile('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
+ $zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents;
}
}
Functions::setReturnDateType($saveDateReturnType);
Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
+ $this->openFileHandle($filename);
+
+ $options = new Archive();
+ $options->setEnableZip64(false);
+ $options->setOutputStream($this->fileHandle);
+
+ $this->zip = new ZipStream(null, $options);
+
+ $this->addZipFiles($zipContent);
+
// Close file
try {
$this->zip->finish();
@@ -445,7 +572,7 @@ class Xlsx extends BaseWriter
/**
* Get Style HashTable.
*
- * @return HashTable
+ * @return HashTable<\PhpOffice\PhpSpreadsheet\Style\Style>
*/
public function getStyleHashTable()
{
@@ -455,7 +582,7 @@ class Xlsx extends BaseWriter
/**
* Get Conditional HashTable.
*
- * @return HashTable
+ * @return HashTable
*/
public function getStylesConditionalHashTable()
{
@@ -465,7 +592,7 @@ class Xlsx extends BaseWriter
/**
* Get Fill HashTable.
*
- * @return HashTable
+ * @return HashTable
*/
public function getFillHashTable()
{
@@ -475,7 +602,7 @@ class Xlsx extends BaseWriter
/**
* Get \PhpOffice\PhpSpreadsheet\Style\Font HashTable.
*
- * @return HashTable
+ * @return HashTable
*/
public function getFontHashTable()
{
@@ -485,7 +612,7 @@ class Xlsx extends BaseWriter
/**
* Get Borders HashTable.
*
- * @return HashTable
+ * @return HashTable
*/
public function getBordersHashTable()
{
@@ -495,7 +622,7 @@ class Xlsx extends BaseWriter
/**
* Get NumberFormat HashTable.
*
- * @return HashTable
+ * @return HashTable
*/
public function getNumFmtHashTable()
{
@@ -505,7 +632,7 @@ class Xlsx extends BaseWriter
/**
* Get \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable.
*
- * @return HashTable
+ * @return HashTable
*/
public function getDrawingHashTable()
{
@@ -525,13 +652,13 @@ class Xlsx extends BaseWriter
/**
* Set Office2003 compatibility.
*
- * @param bool $pValue Office2003 compatibility?
+ * @param bool $office2003compatibility Office2003 compatibility?
*
* @return $this
*/
- public function setOffice2003Compatibility($pValue)
+ public function setOffice2003Compatibility($office2003compatibility)
{
- $this->office2003compatibility = $pValue;
+ $this->office2003compatibility = $office2003compatibility;
return $this;
}
@@ -545,4 +672,59 @@ class Xlsx extends BaseWriter
$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 (is_array($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;
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Chart.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Chart.php
index 583b262c355..23b78a2f2f3 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Chart.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Chart.php
@@ -30,7 +30,7 @@ class Chart extends WriterPart
*
* @return string XML Output
*/
- public function writeChart(\PhpOffice\PhpSpreadsheet\Chart\Chart $pChart, $calculateCellValues = true)
+ public function writeChart(\PhpOffice\PhpSpreadsheet\Chart\Chart $chart, $calculateCellValues = true)
{
$this->calculateCellValues = $calculateCellValues;
@@ -43,7 +43,7 @@ class Chart extends WriterPart
}
// Ensure that data series values are up-to-date before we save
if ($this->calculateCellValues) {
- $pChart->refresh();
+ $chart->refresh();
}
// XML header
@@ -69,22 +69,22 @@ class Chart extends WriterPart
$objWriter->startElement('c:chart');
- $this->writeTitle($objWriter, $pChart->getTitle());
+ $this->writeTitle($objWriter, $chart->getTitle());
$objWriter->startElement('c:autoTitleDeleted');
$objWriter->writeAttribute('val', 0);
$objWriter->endElement();
- $this->writePlotArea($objWriter, $pChart->getWorksheet(), $pChart->getPlotArea(), $pChart->getXAxisLabel(), $pChart->getYAxisLabel(), $pChart->getChartAxisX(), $pChart->getChartAxisY(), $pChart->getMajorGridlines(), $pChart->getMinorGridlines());
+ $this->writePlotArea($objWriter, $chart->getPlotArea(), $chart->getXAxisLabel(), $chart->getYAxisLabel(), $chart->getChartAxisX(), $chart->getChartAxisY(), $chart->getMajorGridlines(), $chart->getMinorGridlines());
- $this->writeLegend($objWriter, $pChart->getLegend());
+ $this->writeLegend($objWriter, $chart->getLegend());
$objWriter->startElement('c:plotVisOnly');
- $objWriter->writeAttribute('val', (int) $pChart->getPlotVisibleOnly());
+ $objWriter->writeAttribute('val', (int) $chart->getPlotVisibleOnly());
$objWriter->endElement();
$objWriter->startElement('c:dispBlanksAs');
- $objWriter->writeAttribute('val', $pChart->getDisplayBlanksAs());
+ $objWriter->writeAttribute('val', $chart->getDisplayBlanksAs());
$objWriter->endElement();
$objWriter->startElement('c:showDLblsOverMax');
@@ -103,9 +103,6 @@ class Chart extends WriterPart
/**
* Write Chart Title.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param Title $title
*/
private function writeTitle(XMLWriter $objWriter, ?Title $title = null): void
{
@@ -129,7 +126,7 @@ class Chart extends WriterPart
if ((is_array($caption)) && (count($caption) > 0)) {
$caption = $caption[0];
}
- $this->getParentWriter()->getWriterPart('stringtable')->writeRichTextForCharts($objWriter, $caption, 'a');
+ $this->getParentWriter()->getWriterPartstringtable()->writeRichTextForCharts($objWriter, $caption, 'a');
$objWriter->endElement();
$objWriter->endElement();
@@ -146,9 +143,6 @@ class Chart extends WriterPart
/**
* Write Chart Legend.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param Legend $legend
*/
private function writeLegend(XMLWriter $objWriter, ?Legend $legend = null): void
{
@@ -195,14 +189,8 @@ class Chart extends WriterPart
/**
* Write Chart Plot Area.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param Title $xAxisLabel
- * @param Title $yAxisLabel
- * @param Axis $xAxis
- * @param Axis $yAxis
*/
- private function writePlotArea(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pSheet, PlotArea $plotArea, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null, ?GridLines $majorGridlines = null, ?GridLines $minorGridlines = null): void
+ private function writePlotArea(XMLWriter $objWriter, PlotArea $plotArea, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null, ?GridLines $majorGridlines = null, ?GridLines $minorGridlines = null): void
{
if ($plotArea === null) {
return;
@@ -219,10 +207,12 @@ class Chart extends WriterPart
$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();
@@ -244,7 +234,7 @@ class Chart extends WriterPart
$this->writeDataLabels($objWriter, $layout);
- if ($chartType === DataSeries::TYPE_LINECHART) {
+ if ($chartType === DataSeries::TYPE_LINECHART && $plotGroup) {
// Line only, Line3D can't be smoothed
$objWriter->startElement('c:smooth');
$objWriter->writeAttribute('val', (int) $plotGroup->getSmoothLine());
@@ -316,10 +306,10 @@ class Chart extends WriterPart
if ($chartType === DataSeries::TYPE_BUBBLECHART) {
$this->writeValueAxis($objWriter, $xAxisLabel, $chartType, $id1, $id2, $catIsMultiLevelSeries, $xAxis, $majorGridlines, $minorGridlines);
} else {
- $this->writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $catIsMultiLevelSeries, $yAxis);
+ $this->writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $catIsMultiLevelSeries, $xAxis);
}
- $this->writeValueAxis($objWriter, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $xAxis, $majorGridlines, $minorGridlines);
+ $this->writeValueAxis($objWriter, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $yAxis, $majorGridlines, $minorGridlines);
}
$objWriter->endElement();
@@ -327,9 +317,6 @@ class Chart extends WriterPart
/**
* Write Data Labels.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param \PhpOffice\PhpSpreadsheet\Chart\Layout $chartLayout Chart layout
*/
private function writeDataLabels(XMLWriter $objWriter, ?Layout $chartLayout = null): void
{
@@ -376,13 +363,11 @@ class Chart extends WriterPart
/**
* Write Category Axis.
*
- * @param XMLWriter $objWriter XML Writer
- * @param Title $xAxisLabel
* @param string $id1
* @param string $id2
* @param bool $isMultiLevelSeries
*/
- private function writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $isMultiLevelSeries, Axis $yAxis): void
+ private function writeCategoryAxis(XMLWriter $objWriter, ?Title $xAxisLabel, $id1, $id2, $isMultiLevelSeries, Axis $yAxis): void
{
$objWriter->startElement('c:catAx');
@@ -493,14 +478,12 @@ class Chart extends WriterPart
/**
* Write Value Axis.
*
- * @param XMLWriter $objWriter XML Writer
- * @param Title $yAxisLabel
- * @param string $groupType Chart type
+ * @param null|string $groupType Chart type
* @param string $id1
* @param string $id2
* @param bool $isMultiLevelSeries
*/
- private function writeValueAxis($objWriter, $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, Axis $xAxis, GridLines $majorGridlines, GridLines $minorGridlines): void
+ private function writeValueAxis(XMLWriter $objWriter, ?Title $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, Axis $xAxis, GridLines $majorGridlines, GridLines $minorGridlines): void
{
$objWriter->startElement('c:valAx');
@@ -976,11 +959,9 @@ class Chart extends WriterPart
/**
* Get the data series type(s) for a chart plot series.
*
- * @param PlotArea $plotArea
- *
- * @return array|string
+ * @return string[]
*/
- private static function getChartType($plotArea)
+ private static function getChartType(PlotArea $plotArea): array
{
$groupCount = $plotArea->getPlotGroupCount();
@@ -1003,13 +984,10 @@ class Chart extends WriterPart
/**
* Method writing plot series values.
*
- * @param XMLWriter $objWriter XML Writer
- * @param int $val value for idx (default: 3)
- * @param string $fillColor hex color (default: FF9900)
- *
- * @return XMLWriter XML Writer
+ * @param int $val value for idx (default: 3)
+ * @param string $fillColor hex color (default: FF9900)
*/
- private function writePlotSeriesValuesElement($objWriter, $val = 3, $fillColor = 'FF9900')
+ private function writePlotSeriesValuesElement(XMLWriter $objWriter, $val = 3, $fillColor = 'FF9900'): void
{
$objWriter->startElement('c:dPt');
$objWriter->startElement('c:idx');
@@ -1028,21 +1006,17 @@ class Chart extends WriterPart
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
-
- return $objWriter;
}
/**
* Write Plot Group (series of related plots).
*
- * @param DataSeries $plotGroup
* @param string $groupType Type of plot for dataseries
- * @param XMLWriter $objWriter XML Writer
- * @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
+ * @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($plotGroup, $groupType, $objWriter, &$catIsMultiLevelSeries, &$valIsMultiLevelSeries, &$plotGroupingType): void
+ private function writePlotGroup(?DataSeries $plotGroup, $groupType, XMLWriter $objWriter, &$catIsMultiLevelSeries, &$valIsMultiLevelSeries, &$plotGroupingType): void
{
if ($plotGroup === null) {
return;
@@ -1079,11 +1053,12 @@ class Chart extends WriterPart
}
}
+ $plotSeriesIdx = 0;
foreach ($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) {
$objWriter->startElement('c:ser');
$plotLabel = $plotGroup->getPlotLabelByIndex($plotSeriesIdx);
- if ($plotLabel) {
+ if ($plotLabel && $groupType !== DataSeries::TYPE_LINECHART) {
$fillColor = $plotLabel->getFillColor();
if ($fillColor !== null && !is_array($fillColor)) {
$objWriter->startElement('c:spPr');
@@ -1141,6 +1116,15 @@ class Chart extends WriterPart
if ($groupType == DataSeries::TYPE_STOCKCHART) {
$objWriter->startElement('a:noFill');
$objWriter->endElement();
+ } elseif ($plotLabel) {
+ $fillColor = $plotLabel->getFillColor();
+ if (is_string($fillColor)) {
+ $objWriter->startElement('a:solidFill');
+ $objWriter->startElement('a:srgbClr');
+ $objWriter->writeAttribute('val', $fillColor);
+ $objWriter->endElement();
+ $objWriter->endElement();
+ }
}
$objWriter->endElement();
$objWriter->endElement();
@@ -1222,11 +1206,8 @@ class Chart extends WriterPart
/**
* Write Plot Series Label.
- *
- * @param DataSeriesValues $plotSeriesLabel
- * @param XMLWriter $objWriter XML Writer
*/
- private function writePlotSeriesLabel($plotSeriesLabel, $objWriter): void
+ private function writePlotSeriesLabel(?DataSeriesValues $plotSeriesLabel, XMLWriter $objWriter): void
{
if ($plotSeriesLabel === null) {
return;
@@ -1256,12 +1237,10 @@ class Chart extends WriterPart
/**
* Write Plot Series Values.
*
- * @param DataSeriesValues $plotSeriesValues
- * @param XMLWriter $objWriter XML Writer
* @param string $groupType Type of plot for dataseries
* @param string $dataType Datatype of series values
*/
- private function writePlotSeriesValues($plotSeriesValues, XMLWriter $objWriter, $groupType, $dataType = 'str'): void
+ private function writePlotSeriesValues(?DataSeriesValues $plotSeriesValues, XMLWriter $objWriter, $groupType, $dataType = 'str'): void
{
if ($plotSeriesValues === null) {
return;
@@ -1347,11 +1326,8 @@ class Chart extends WriterPart
/**
* Write Bubble Chart Details.
- *
- * @param DataSeriesValues $plotSeriesValues
- * @param XMLWriter $objWriter XML Writer
*/
- private function writeBubbles($plotSeriesValues, $objWriter): void
+ private function writeBubbles(?DataSeriesValues $plotSeriesValues, XMLWriter $objWriter): void
{
if ($plotSeriesValues === null) {
return;
@@ -1392,9 +1368,6 @@ class Chart extends WriterPart
/**
* Write Layout.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param Layout $layout
*/
private function writeLayout(XMLWriter $objWriter, ?Layout $layout = null): void
{
@@ -1460,10 +1433,8 @@ class Chart extends WriterPart
/**
* Write Alternate Content block.
- *
- * @param XMLWriter $objWriter XML Writer
*/
- private function writeAlternateContent($objWriter): void
+ private function writeAlternateContent(XMLWriter $objWriter): void
{
$objWriter->startElement('mc:AlternateContent');
$objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006');
@@ -1488,10 +1459,8 @@ class Chart extends WriterPart
/**
* Write Printer Settings.
- *
- * @param XMLWriter $objWriter XML Writer
*/
- private function writePrintSettings($objWriter): void
+ private function writePrintSettings(XMLWriter $objWriter): void
{
$objWriter->startElement('c:printSettings');
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Comments.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Comments.php
index 73c4308b8b5..ea0f1faa69f 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Comments.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Comments.php
@@ -13,7 +13,7 @@ class Comments extends WriterPart
*
* @return string XML Output
*/
- public function writeComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet)
+ public function writeComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet)
{
// Create XML writer
$objWriter = null;
@@ -27,7 +27,7 @@ class Comments extends WriterPart
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Comments cache
- $comments = $pWorksheet->getComments();
+ $comments = $worksheet->getComments();
// Authors cache
$authors = [];
@@ -65,21 +65,20 @@ class Comments extends WriterPart
/**
* Write comment to XML format.
*
- * @param XMLWriter $objWriter XML Writer
- * @param string $pCellReference Cell reference
- * @param Comment $pComment Comment
- * @param array $pAuthors Array of authors
+ * @param string $cellReference Cell reference
+ * @param Comment $comment Comment
+ * @param array $authors Array of authors
*/
- private function writeComment(XMLWriter $objWriter, $pCellReference, Comment $pComment, array $pAuthors): void
+ private function writeComment(XMLWriter $objWriter, $cellReference, Comment $comment, array $authors): void
{
// comment
$objWriter->startElement('comment');
- $objWriter->writeAttribute('ref', $pCellReference);
- $objWriter->writeAttribute('authorId', $pAuthors[$pComment->getAuthor()]);
+ $objWriter->writeAttribute('ref', $cellReference);
+ $objWriter->writeAttribute('authorId', $authors[$comment->getAuthor()]);
// text
$objWriter->startElement('text');
- $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText());
+ $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $comment->getText());
$objWriter->endElement();
$objWriter->endElement();
@@ -90,7 +89,7 @@ class Comments extends WriterPart
*
* @return string XML Output
*/
- public function writeVMLComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet)
+ public function writeVMLComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet)
{
// Create XML writer
$objWriter = null;
@@ -104,7 +103,7 @@ class Comments extends WriterPart
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Comments cache
- $comments = $pWorksheet->getComments();
+ $comments = $worksheet->getComments();
// xml
$objWriter->startElement('xml');
@@ -158,15 +157,13 @@ class Comments extends WriterPart
/**
* Write VML comment to XML format.
*
- * @param XMLWriter $objWriter XML Writer
- * @param string $pCellReference Cell reference, eg: 'A1'
- * @param Comment $pComment Comment
+ * @param string $cellReference Cell reference, eg: 'A1'
+ * @param Comment $comment Comment
*/
- private function writeVMLComment(XMLWriter $objWriter, $pCellReference, Comment $pComment): void
+ private function writeVMLComment(XMLWriter $objWriter, $cellReference, Comment $comment): void
{
// Metadata
- [$column, $row] = Coordinate::coordinateFromString($pCellReference);
- $column = Coordinate::columnIndexFromString($column);
+ [$column, $row] = Coordinate::indexesFromString($cellReference);
$id = 1024 + $column + $row;
$id = substr($id, 0, 4);
@@ -174,13 +171,19 @@ class Comments extends WriterPart
$objWriter->startElement('v:shape');
$objWriter->writeAttribute('id', '_x0000_s' . $id);
$objWriter->writeAttribute('type', '#_x0000_t202');
- $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $pComment->getMarginLeft() . ';margin-top:' . $pComment->getMarginTop() . ';width:' . $pComment->getWidth() . ';height:' . $pComment->getHeight() . ';z-index:1;visibility:' . ($pComment->getVisible() ? 'visible' : 'hidden'));
- $objWriter->writeAttribute('fillcolor', '#' . $pComment->getFillColor()->getRGB());
+ $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', '#' . $pComment->getFillColor()->getRGB());
+ $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
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php
index 2cff1a8f6fb..f62c14af70e 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php
@@ -141,7 +141,7 @@ class ContentTypes extends WriterPart
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));
+ $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);
@@ -158,6 +158,23 @@ class ContentTypes extends WriterPart
}
}
}
+
+ 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
@@ -183,35 +200,34 @@ class ContentTypes extends WriterPart
/**
* Get image mime type.
*
- * @param string $pFile Filename
+ * @param string $filename Filename
*
* @return string Mime Type
*/
- private function getImageMimeType($pFile)
+ private function getImageMimeType($filename)
{
- if (File::fileExists($pFile)) {
- $image = getimagesize($pFile);
+ if (File::fileExists($filename)) {
+ $image = getimagesize($filename);
- return image_type_to_mime_type($image[2]);
+ return image_type_to_mime_type((is_array($image) && count($image) >= 3) ? $image[2] : 0);
}
- throw new WriterException("File $pFile does not exist");
+ throw new WriterException("File $filename does not exist");
}
/**
* Write Default content type.
*
- * @param XMLWriter $objWriter XML Writer
- * @param string $pPartname Part name
- * @param string $pContentType Content type
+ * @param string $partName Part name
+ * @param string $contentType Content type
*/
- private function writeDefaultContentType(XMLWriter $objWriter, $pPartname, $pContentType): void
+ private function writeDefaultContentType(XMLWriter $objWriter, $partName, $contentType): void
{
- if ($pPartname != '' && $pContentType != '') {
+ if ($partName != '' && $contentType != '') {
// Write content type
$objWriter->startElement('Default');
- $objWriter->writeAttribute('Extension', $pPartname);
- $objWriter->writeAttribute('ContentType', $pContentType);
+ $objWriter->writeAttribute('Extension', $partName);
+ $objWriter->writeAttribute('ContentType', $contentType);
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
@@ -221,17 +237,16 @@ class ContentTypes extends WriterPart
/**
* Write Override content type.
*
- * @param XMLWriter $objWriter XML Writer
- * @param string $pPartname Part name
- * @param string $pContentType Content type
+ * @param string $partName Part name
+ * @param string $contentType Content type
*/
- private function writeOverrideContentType(XMLWriter $objWriter, $pPartname, $pContentType): void
+ private function writeOverrideContentType(XMLWriter $objWriter, $partName, $contentType): void
{
- if ($pPartname != '' && $pContentType != '') {
+ if ($partName != '' && $contentType != '') {
// Write content type
$objWriter->startElement('Override');
- $objWriter->writeAttribute('PartName', $pPartname);
- $objWriter->writeAttribute('ContentType', $pContentType);
+ $objWriter->writeAttribute('PartName', $partName);
+ $objWriter->writeAttribute('ContentType', $contentType);
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php
index 8c3da827a95..b8285fcbead 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php
@@ -2,6 +2,7 @@
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+use Exception;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\DefinedName;
@@ -11,8 +12,10 @@ use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class DefinedNames
{
+ /** @var XMLWriter */
private $objWriter;
+ /** @var Spreadsheet */
private $spreadsheet;
public function __construct(XMLWriter $objWriter, Spreadsheet $spreadsheet)
@@ -63,16 +66,132 @@ class DefinedNames
/**
* Write Defined Name for named range.
*/
- private function writeDefinedName(DefinedName $pDefinedName): void
+ private function writeDefinedName(DefinedName $definedName): void
{
// definedName for named range
+ $local = -1;
+ if ($definedName->getLocalOnly() && $definedName->getScope() !== null) {
+ try {
+ $local = $definedName->getScope()->getParent()->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', $pDefinedName->getName());
- if ($pDefinedName->getLocalOnly() && $pDefinedName->getScope() !== null) {
- $this->objWriter->writeAttribute('localSheetId', $pDefinedName->getScope()->getParent()->getIndex($pDefinedName->getScope()));
+ $this->objWriter->writeAttribute('name', $definedName->getName());
+ if ($local >= 0) {
+ $this->objWriter->writeAttribute(
+ 'localSheetId',
+ "$local"
+ );
}
- $definedRange = $pDefinedName->getValue();
+ $definedRange = $this->getDefinedRange($definedName);
+
+ $this->objWriter->writeRawData($definedRange);
+
+ $this->objWriter->endElement();
+ }
+
+ /**
+ * Write Defined Name for autoFilter.
+ */
+ private function writeNamedRangeForAutofilter(Worksheet $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]] = Worksheet::extractSheetTitle($range[0], true);
+
+ $range[0] = Coordinate::absoluteCoordinate($range[0]);
+ $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(Worksheet $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(Worksheet $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,
@@ -99,21 +218,17 @@ class DefinedNames
if (empty($worksheet)) {
if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) {
// We should have a worksheet
- $worksheet = $pDefinedName->getWorksheet()->getTitle();
+ $ws = $definedName->getWorksheet();
+ $worksheet = ($ws === null) ? null : $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;
- }
+ $newRange = "{$newRange}{$column}{$row}";
$definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length);
}
@@ -122,102 +237,6 @@ class DefinedNames
$definedRange = substr($definedRange, 1);
}
- $this->objWriter->writeRawData($definedRange);
-
- $this->objWriter->endElement();
- }
-
- /**
- * Write Defined Name for autoFilter.
- */
- private function writeNamedRangeForAutofilter(Worksheet $pSheet, int $pSheetId = 0): void
- {
- // NamedRange for autoFilter
- $autoFilterRange = $pSheet->getAutoFilter()->getRange();
- if (!empty($autoFilterRange)) {
- $this->objWriter->startElement('definedName');
- $this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase');
- $this->objWriter->writeAttribute('localSheetId', $pSheetId);
- $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
- [$ws, $range[0]] = Worksheet::extractSheetTitle($range[0], true);
-
- $range[0] = Coordinate::absoluteCoordinate($range[0]);
- $range[1] = Coordinate::absoluteCoordinate($range[1]);
- $range = implode(':', $range);
-
- $this->objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . $range);
-
- $this->objWriter->endElement();
- }
- }
-
- /**
- * Write Defined Name for PrintTitles.
- */
- private function writeNamedRangeForPrintTitles(Worksheet $pSheet, int $pSheetId = 0): void
- {
- // NamedRange for PrintTitles
- if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
- $this->objWriter->startElement('definedName');
- $this->objWriter->writeAttribute('name', '_xlnm.Print_Titles');
- $this->objWriter->writeAttribute('localSheetId', $pSheetId);
-
- // Setting string
- $settingString = '';
-
- // Columns to repeat
- if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
- $repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft();
-
- $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
- }
-
- // Rows to repeat
- if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
- if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) {
- $settingString .= ',';
- }
-
- $repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop();
-
- $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1];
- }
-
- $this->objWriter->writeRawData($settingString);
-
- $this->objWriter->endElement();
- }
- }
-
- /**
- * Write Defined Name for PrintTitles.
- */
- private function writeNamedRangeForPrintArea(Worksheet $pSheet, int $pSheetId = 0): void
- {
- // NamedRange for PrintArea
- if ($pSheet->getPageSetup()->isPrintAreaSet()) {
- $this->objWriter->startElement('definedName');
- $this->objWriter->writeAttribute('name', '_xlnm.Print_Area');
- $this->objWriter->writeAttribute('localSheetId', $pSheetId);
-
- // Print area
- $printArea = Coordinate::splitRange($pSheet->getPageSetup()->getPrintArea());
-
- $chunks = [];
- foreach ($printArea as $printAreaRect) {
- $printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]);
- $printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]);
- $chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect);
- }
-
- $this->objWriter->writeRawData(implode(',', $chunks));
-
- $this->objWriter->endElement();
- }
+ return $definedRange;
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php
index bcbc2379df4..43ce442fee7 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php
@@ -2,6 +2,8 @@
namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+use PhpOffice\PhpSpreadsheet\Document\Properties;
+use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\XMLWriter;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
@@ -137,13 +139,17 @@ class DocProps extends WriterPart
// dcterms:created
$objWriter->startElement('dcterms:created');
$objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF');
- $objWriter->writeRawData(date(DATE_W3C, $spreadsheet->getProperties()->getCreated()));
+ $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');
- $objWriter->writeRawData(date(DATE_W3C, $spreadsheet->getProperties()->getModified()));
+ $created = $spreadsheet->getProperties()->getModified();
+ $date = Date::dateTimeFromTimestamp("$created");
+ $objWriter->writeRawData($date->format(DATE_W3C));
$objWriter->endElement();
// dc:title
@@ -170,13 +176,13 @@ class DocProps extends WriterPart
/**
* Write docProps/custom.xml to XML format.
*
- * @return string XML Output
+ * @return null|string XML Output
*/
public function writeDocPropsCustom(Spreadsheet $spreadsheet)
{
$customPropertyList = $spreadsheet->getProperties()->getCustomProperties();
if (empty($customPropertyList)) {
- return;
+ return null;
}
// Create XML writer
@@ -205,21 +211,22 @@ class DocProps extends WriterPart
$objWriter->writeAttribute('name', $customProperty);
switch ($propertyType) {
- case 'i':
+ case Properties::PROPERTY_TYPE_INTEGER:
$objWriter->writeElement('vt:i4', $propertyValue);
break;
- case 'f':
+ case Properties::PROPERTY_TYPE_FLOAT:
$objWriter->writeElement('vt:r8', $propertyValue);
break;
- case 'b':
+ case Properties::PROPERTY_TYPE_BOOLEAN:
$objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false');
break;
- case 'd':
+ case Properties::PROPERTY_TYPE_DATE:
$objWriter->startElement('vt:filetime');
- $objWriter->writeRawData(date(DATE_W3C, $propertyValue));
+ $date = Date::dateTimeFromTimestamp("$propertyValue");
+ $objWriter->writeRawData($date->format(DATE_W3C));
$objWriter->endElement();
break;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php
index 1713b982297..fa77e2d7e63 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php
@@ -18,7 +18,7 @@ class Drawing extends WriterPart
*
* @return string XML Output
*/
- public function writeDrawings(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet, $includeCharts = false)
+ public function writeDrawings(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, $includeCharts = false)
{
// Create XML writer
$objWriter = null;
@@ -38,7 +38,7 @@ class Drawing extends WriterPart
// Loop through images and write drawings
$i = 1;
- $iterator = $pWorksheet->getDrawingCollection()->getIterator();
+ $iterator = $worksheet->getDrawingCollection()->getIterator();
while ($iterator->valid()) {
/** @var BaseDrawing $pDrawing */
$pDrawing = $iterator->current();
@@ -52,19 +52,19 @@ class Drawing extends WriterPart
}
if ($includeCharts) {
- $chartCount = $pWorksheet->getChartCount();
+ $chartCount = $worksheet->getChartCount();
// Loop through charts and write the chart position
if ($chartCount > 0) {
for ($c = 0; $c < $chartCount; ++$c) {
- $this->writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c + $i);
+ $this->writeChart($objWriter, $worksheet->getChartByIndex($c), $c + $i);
}
}
}
// unparsed AlternateContent
- $unparsedLoadedData = $pWorksheet->getParent()->getUnparsedLoadedData();
- if (isset($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingAlternateContents'])) {
- foreach ($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingAlternateContents'] as $drawingAlternateContent) {
+ $unparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData();
+ if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingAlternateContents'])) {
+ foreach ($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingAlternateContents'] as $drawingAlternateContent) {
$objWriter->writeRaw($drawingAlternateContent);
}
}
@@ -78,28 +78,27 @@ class Drawing extends WriterPart
/**
* Write drawings to XML format.
*
- * @param XMLWriter $objWriter XML Writer
- * @param int $pRelationId
+ * @param int $relationId
*/
- public function writeChart(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Chart\Chart $pChart, $pRelationId = -1): void
+ public function writeChart(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Chart\Chart $chart, $relationId = -1): void
{
- $tl = $pChart->getTopLeftPosition();
- $tl['colRow'] = Coordinate::coordinateFromString($tl['cell']);
- $br = $pChart->getBottomRightPosition();
- $br['colRow'] = Coordinate::coordinateFromString($br['cell']);
+ $tl = $chart->getTopLeftPosition();
+ $tlColRow = Coordinate::indexesFromString($tl['cell']);
+ $br = $chart->getBottomRightPosition();
+ $brColRow = Coordinate::indexesFromString($br['cell']);
$objWriter->startElement('xdr:twoCellAnchor');
$objWriter->startElement('xdr:from');
- $objWriter->writeElement('xdr:col', Coordinate::columnIndexFromString($tl['colRow'][0]) - 1);
+ $objWriter->writeElement('xdr:col', $tlColRow[0] - 1);
$objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['xOffset']));
- $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1);
+ $objWriter->writeElement('xdr:row', $tlColRow[1] - 1);
$objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['yOffset']));
$objWriter->endElement();
$objWriter->startElement('xdr:to');
- $objWriter->writeElement('xdr:col', Coordinate::columnIndexFromString($br['colRow'][0]) - 1);
+ $objWriter->writeElement('xdr:col', $brColRow[0] - 1);
$objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['xOffset']));
- $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1);
+ $objWriter->writeElement('xdr:row', $brColRow[1] - 1);
$objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['yOffset']));
$objWriter->endElement();
@@ -107,8 +106,8 @@ class Drawing extends WriterPart
$objWriter->writeAttribute('macro', '');
$objWriter->startElement('xdr:nvGraphicFramePr');
$objWriter->startElement('xdr:cNvPr');
- $objWriter->writeAttribute('name', 'Chart ' . $pRelationId);
- $objWriter->writeAttribute('id', 1025 * $pRelationId);
+ $objWriter->writeAttribute('name', 'Chart ' . $relationId);
+ $objWriter->writeAttribute('id', 1025 * $relationId);
$objWriter->endElement();
$objWriter->startElement('xdr:cNvGraphicFramePr');
$objWriter->startElement('a:graphicFrameLocks');
@@ -133,7 +132,7 @@ class Drawing extends WriterPart
$objWriter->startElement('c:chart');
$objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
$objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
- $objWriter->writeAttribute('r:id', 'rId' . $pRelationId);
+ $objWriter->writeAttribute('r:id', 'rId' . $relationId);
$objWriter->endElement();
$objWriter->endElement();
$objWriter->endElement();
@@ -148,31 +147,29 @@ class Drawing extends WriterPart
/**
* Write drawings to XML format.
*
- * @param XMLWriter $objWriter XML Writer
- * @param int $pRelationId
+ * @param int $relationId
* @param null|int $hlinkClickId
*/
- public function writeDrawing(XMLWriter $objWriter, BaseDrawing $pDrawing, $pRelationId = -1, $hlinkClickId = null): void
+ public function writeDrawing(XMLWriter $objWriter, BaseDrawing $drawing, $relationId = -1, $hlinkClickId = null): void
{
- if ($pRelationId >= 0) {
+ if ($relationId >= 0) {
// xdr:oneCellAnchor
$objWriter->startElement('xdr:oneCellAnchor');
// Image location
- $aCoordinates = Coordinate::coordinateFromString($pDrawing->getCoordinates());
- $aCoordinates[0] = Coordinate::columnIndexFromString($aCoordinates[0]);
+ $aCoordinates = Coordinate::indexesFromString($drawing->getCoordinates());
// xdr:from
$objWriter->startElement('xdr:from');
$objWriter->writeElement('xdr:col', $aCoordinates[0] - 1);
- $objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getOffsetX()));
+ $objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($drawing->getOffsetX()));
$objWriter->writeElement('xdr:row', $aCoordinates[1] - 1);
- $objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getOffsetY()));
+ $objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($drawing->getOffsetY()));
$objWriter->endElement();
// xdr:ext
$objWriter->startElement('xdr:ext');
- $objWriter->writeAttribute('cx', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getWidth()));
- $objWriter->writeAttribute('cy', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getHeight()));
+ $objWriter->writeAttribute('cx', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($drawing->getWidth()));
+ $objWriter->writeAttribute('cy', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($drawing->getHeight()));
$objWriter->endElement();
// xdr:pic
@@ -183,9 +180,9 @@ class Drawing extends WriterPart
// xdr:cNvPr
$objWriter->startElement('xdr:cNvPr');
- $objWriter->writeAttribute('id', $pRelationId);
- $objWriter->writeAttribute('name', $pDrawing->getName());
- $objWriter->writeAttribute('descr', $pDrawing->getDescription());
+ $objWriter->writeAttribute('id', $relationId);
+ $objWriter->writeAttribute('name', $drawing->getName());
+ $objWriter->writeAttribute('descr', $drawing->getDescription());
//a:hlinkClick
$this->writeHyperLinkDrawing($objWriter, $hlinkClickId);
@@ -210,7 +207,7 @@ class Drawing extends WriterPart
// a:blip
$objWriter->startElement('a:blip');
$objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
- $objWriter->writeAttribute('r:embed', 'rId' . $pRelationId);
+ $objWriter->writeAttribute('r:embed', 'rId' . $relationId);
$objWriter->endElement();
// a:stretch
@@ -225,7 +222,7 @@ class Drawing extends WriterPart
// a:xfrm
$objWriter->startElement('a:xfrm');
- $objWriter->writeAttribute('rot', \PhpOffice\PhpSpreadsheet\Shared\Drawing::degreesToAngle($pDrawing->getRotation()));
+ $objWriter->writeAttribute('rot', \PhpOffice\PhpSpreadsheet\Shared\Drawing::degreesToAngle($drawing->getRotation()));
$objWriter->endElement();
// a:prstGeom
@@ -237,25 +234,25 @@ class Drawing extends WriterPart
$objWriter->endElement();
- if ($pDrawing->getShadow()->getVisible()) {
+ if ($drawing->getShadow()->getVisible()) {
// a:effectLst
$objWriter->startElement('a:effectLst');
// a:outerShdw
$objWriter->startElement('a:outerShdw');
- $objWriter->writeAttribute('blurRad', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius()));
- $objWriter->writeAttribute('dist', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance()));
- $objWriter->writeAttribute('dir', \PhpOffice\PhpSpreadsheet\Shared\Drawing::degreesToAngle($pDrawing->getShadow()->getDirection()));
- $objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment());
+ $objWriter->writeAttribute('blurRad', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($drawing->getShadow()->getBlurRadius()));
+ $objWriter->writeAttribute('dist', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($drawing->getShadow()->getDistance()));
+ $objWriter->writeAttribute('dir', \PhpOffice\PhpSpreadsheet\Shared\Drawing::degreesToAngle($drawing->getShadow()->getDirection()));
+ $objWriter->writeAttribute('algn', $drawing->getShadow()->getAlignment());
$objWriter->writeAttribute('rotWithShape', '0');
// a:srgbClr
$objWriter->startElement('a:srgbClr');
- $objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB());
+ $objWriter->writeAttribute('val', $drawing->getShadow()->getColor()->getRGB());
// a:alpha
$objWriter->startElement('a:alpha');
- $objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000);
+ $objWriter->writeAttribute('val', $drawing->getShadow()->getAlpha() * 1000);
$objWriter->endElement();
$objWriter->endElement();
@@ -282,7 +279,7 @@ class Drawing extends WriterPart
*
* @return string XML Output
*/
- public function writeVMLHeaderFooterImages(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet)
+ public function writeVMLHeaderFooterImages(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet)
{
// Create XML writer
$objWriter = null;
@@ -296,7 +293,7 @@ class Drawing extends WriterPart
$objWriter->startDocument('1.0', 'UTF-8', 'yes');
// Header/footer images
- $images = $pWorksheet->getHeaderFooter()->getImages();
+ $images = $worksheet->getHeaderFooter()->getImages();
// xml
$objWriter->startElement('xml');
@@ -425,33 +422,31 @@ class Drawing extends WriterPart
/**
* Write VML comment to XML format.
*
- * @param XMLWriter $objWriter XML Writer
- * @param string $pReference Reference
- * @param HeaderFooterDrawing $pImage Image
+ * @param string $reference Reference
*/
- private function writeVMLHeaderFooterImage(XMLWriter $objWriter, $pReference, HeaderFooterDrawing $pImage): void
+ private function writeVMLHeaderFooterImage(XMLWriter $objWriter, $reference, HeaderFooterDrawing $image): void
{
// Calculate object id
- preg_match('{(\d+)}', md5($pReference), $m);
- $id = 1500 + (substr($m[1], 0, 2) * 1);
+ preg_match('{(\d+)}', md5($reference), $m);
+ $id = 1500 + ((int) substr($m[1], 0, 2) * 1);
// Calculate offset
- $width = $pImage->getWidth();
- $height = $pImage->getHeight();
- $marginLeft = $pImage->getOffsetX();
- $marginTop = $pImage->getOffsetY();
+ $width = $image->getWidth();
+ $height = $image->getHeight();
+ $marginLeft = $image->getOffsetX();
+ $marginTop = $image->getOffsetY();
// v:shape
$objWriter->startElement('v:shape');
- $objWriter->writeAttribute('id', $pReference);
+ $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' . $pReference);
- $objWriter->writeAttribute('o:title', $pImage->getName());
+ $objWriter->writeAttribute('o:relid', 'rId' . $reference);
+ $objWriter->writeAttribute('o:title', $image->getName());
$objWriter->endElement();
// o:lock
@@ -466,7 +461,7 @@ class Drawing extends WriterPart
/**
* Get an array of all drawings.
*
- * @return \PhpOffice\PhpSpreadsheet\Worksheet\Drawing[] All drawings in PhpSpreadsheet
+ * @return BaseDrawing[] All drawings in PhpSpreadsheet
*/
public function allDrawings(Spreadsheet $spreadsheet)
{
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Rels.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Rels.php
index 79841404bbd..5aa878760ab 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Rels.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Rels.php
@@ -4,6 +4,7 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
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;
@@ -160,12 +161,12 @@ class Rels extends WriterPart
* rId1 - Drawings
* rId_hyperlink_x - Hyperlinks
*
- * @param int $pWorksheetId
+ * @param int $worksheetId
* @param bool $includeCharts Flag indicating if we should write charts
*
* @return string XML Output
*/
- public function writeWorksheetRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet, $pWorksheetId = 1, $includeCharts = false)
+ public function writeWorksheetRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, $worksheetId = 1, $includeCharts = false)
{
// Create XML writer
$objWriter = null;
@@ -184,18 +185,18 @@ class Rels extends WriterPart
// Write drawing relationships?
$drawingOriginalIds = [];
- $unparsedLoadedData = $pWorksheet->getParent()->getUnparsedLoadedData();
- if (isset($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingOriginalIds'])) {
- $drawingOriginalIds = $unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingOriginalIds'];
+ $unparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData();
+ if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) {
+ $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'];
}
if ($includeCharts) {
- $charts = $pWorksheet->getChartCollection();
+ $charts = $worksheet->getChartCollection();
} else {
$charts = [];
}
- if (($pWorksheet->getDrawingCollection()->count() > 0) || (count($charts) > 0) || $drawingOriginalIds) {
+ if (($worksheet->getDrawingCollection()->count() > 0) || (count($charts) > 0) || $drawingOriginalIds) {
$rId = 1;
// Use original $relPath to get original $rId.
@@ -208,7 +209,7 @@ class Rels extends WriterPart
}
// Generate new $relPath to write drawing relationship
- $relPath = '../drawings/drawing' . $pWorksheetId . '.xml';
+ $relPath = '../drawings/drawing' . $worksheetId . '.xml';
$this->writeRelationship(
$objWriter,
$rId,
@@ -219,7 +220,7 @@ class Rels extends WriterPart
// Write hyperlink relationships?
$i = 1;
- foreach ($pWorksheet->getHyperlinkCollection() as $hyperlink) {
+ foreach ($worksheet->getHyperlinkCollection() as $hyperlink) {
if (!$hyperlink->isInternal()) {
$this->writeRelationship(
$objWriter,
@@ -235,50 +236,50 @@ class Rels extends WriterPart
// Write comments relationship?
$i = 1;
- if (count($pWorksheet->getComments()) > 0) {
+ if (count($worksheet->getComments()) > 0) {
$this->writeRelationship(
$objWriter,
'_comments_vml' . $i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
- '../drawings/vmlDrawing' . $pWorksheetId . '.vml'
+ '../drawings/vmlDrawing' . $worksheetId . '.vml'
);
$this->writeRelationship(
$objWriter,
'_comments' . $i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments',
- '../comments' . $pWorksheetId . '.xml'
+ '../comments' . $worksheetId . '.xml'
);
}
// Write header/footer relationship?
$i = 1;
- if (count($pWorksheet->getHeaderFooter()->getImages()) > 0) {
+ if (count($worksheet->getHeaderFooter()->getImages()) > 0) {
$this->writeRelationship(
$objWriter,
'_headerfooter_vml' . $i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing',
- '../drawings/vmlDrawingHF' . $pWorksheetId . '.vml'
+ '../drawings/vmlDrawingHF' . $worksheetId . '.vml'
);
}
- $this->writeUnparsedRelationship($pWorksheet, $objWriter, 'ctrlProps', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp');
- $this->writeUnparsedRelationship($pWorksheet, $objWriter, 'vmlDrawings', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing');
- $this->writeUnparsedRelationship($pWorksheet, $objWriter, 'printerSettings', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings');
+ $this->writeUnparsedRelationship($worksheet, $objWriter, 'ctrlProps', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp');
+ $this->writeUnparsedRelationship($worksheet, $objWriter, 'vmlDrawings', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing');
+ $this->writeUnparsedRelationship($worksheet, $objWriter, 'printerSettings', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings');
$objWriter->endElement();
return $objWriter->getData();
}
- private function writeUnparsedRelationship(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet, XMLWriter $objWriter, $relationship, $type): void
+ private function writeUnparsedRelationship(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, XMLWriter $objWriter, $relationship, $type): void
{
- $unparsedLoadedData = $pWorksheet->getParent()->getUnparsedLoadedData();
- if (!isset($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()][$relationship])) {
+ $unparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData();
+ if (!isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()][$relationship])) {
return;
}
- foreach ($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()][$relationship] as $rId => $value) {
+ foreach ($unparsedLoadedData['sheets'][$worksheet->getCodeName()][$relationship] as $rId => $value) {
$this->writeRelationship(
$objWriter,
$rId,
@@ -291,12 +292,12 @@ class Rels extends WriterPart
/**
* Write drawing relationships to XML format.
*
- * @param int &$chartRef Chart ID
+ * @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 $pWorksheet, &$chartRef, $includeCharts = false)
+ public function writeDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, &$chartRef, $includeCharts = false)
{
// Create XML writer
$objWriter = null;
@@ -315,20 +316,19 @@ class Rels extends WriterPart
// Loop through images and write relationships
$i = 1;
- $iterator = $pWorksheet->getDrawingCollection()->getIterator();
+ $iterator = $worksheet->getDrawingCollection()->getIterator();
while ($iterator->valid()) {
+ $drawing = $iterator->current();
if (
- $iterator->current() instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing
- || $iterator->current() instanceof MemoryDrawing
+ $drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing
+ || $drawing instanceof MemoryDrawing
) {
// Write relationship for image drawing
- /** @var \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $drawing */
- $drawing = $iterator->current();
$this->writeRelationship(
$objWriter,
$i,
'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
- '../media/' . str_replace(' ', '', $drawing->getIndexedFilename())
+ '../media/' . $drawing->getIndexedFilename()
);
$i = $this->writeDrawingHyperLink($objWriter, $drawing, $i);
@@ -340,7 +340,7 @@ class Rels extends WriterPart
if ($includeCharts) {
// Loop through charts and write relationships
- $chartCount = $pWorksheet->getChartCount();
+ $chartCount = $worksheet->getChartCount();
if ($chartCount > 0) {
for ($c = 0; $c < $chartCount; ++$c) {
$this->writeRelationship(
@@ -363,7 +363,7 @@ class Rels extends WriterPart
*
* @return string XML Output
*/
- public function writeHeaderFooterDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet)
+ public function writeHeaderFooterDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet)
{
// Create XML writer
$objWriter = null;
@@ -381,7 +381,7 @@ class Rels extends WriterPart
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');
// Loop through images and write relationships
- foreach ($pWorksheet->getHeaderFooter()->getImages() as $key => $value) {
+ foreach ($worksheet->getHeaderFooter()->getImages() as $key => $value) {
// Write relationship for image drawing
$this->writeRelationship(
$objWriter,
@@ -396,26 +396,62 @@ class Rels extends WriterPart
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', 'http://schemas.openxmlformats.org/package/2006/relationships');
+
+ // Loop through images and write relationships
+ foreach ($worksheet->getComments() as $comment) {
+ if (!$comment->hasBackgroundImage()) {
+ continue;
+ }
+
+ $bgImage = $comment->getBackgroundImage();
+ $this->writeRelationship(
+ $objWriter,
+ $bgImage->getImageIndex(),
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
+ '../media/' . $bgImage->getMediaFilename()
+ );
+ }
+
+ $objWriter->endElement();
+
+ return $objWriter->getData();
+ }
+
/**
* Write Override content type.
*
- * @param XMLWriter $objWriter XML Writer
- * @param int $pId Relationship ID. rId will be prepended!
- * @param string $pType Relationship type
- * @param string $pTarget Relationship target
- * @param string $pTargetMode Relationship target mode
+ * @param int $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, $pId, $pType, $pTarget, $pTargetMode = ''): void
+ private function writeRelationship(XMLWriter $objWriter, $id, $type, $target, $targetMode = ''): void
{
- if ($pType != '' && $pTarget != '') {
+ if ($type != '' && $target != '') {
// Write relationship
$objWriter->startElement('Relationship');
- $objWriter->writeAttribute('Id', 'rId' . $pId);
- $objWriter->writeAttribute('Type', $pType);
- $objWriter->writeAttribute('Target', $pTarget);
+ $objWriter->writeAttribute('Id', 'rId' . $id);
+ $objWriter->writeAttribute('Type', $type);
+ $objWriter->writeAttribute('Target', $target);
- if ($pTargetMode != '') {
- $objWriter->writeAttribute('TargetMode', $pTargetMode);
+ if ($targetMode != '') {
+ $objWriter->writeAttribute('TargetMode', $targetMode);
}
$objWriter->endElement();
@@ -424,14 +460,7 @@ class Rels extends WriterPart
}
}
- /**
- * @param $objWriter
- * @param \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $drawing
- * @param $i
- *
- * @return int
- */
- private function writeDrawingHyperLink($objWriter, $drawing, $i)
+ private function writeDrawingHyperLink(XMLWriter $objWriter, BaseDrawing $drawing, int $i): int
{
if ($drawing->getHyperlink() === null) {
return $i;
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php
index b0f7d6d4177..f9a2e711cea 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php
@@ -14,12 +14,12 @@ class StringTable extends WriterPart
/**
* Create worksheet stringtable.
*
- * @param Worksheet $pSheet Worksheet
- * @param string[] $pExistingTable Existing table to eventually merge with
+ * @param Worksheet $worksheet Worksheet
+ * @param string[] $existingTable Existing table to eventually merge with
*
* @return string[] String table for worksheet
*/
- public function createStringTable(Worksheet $pSheet, $pExistingTable = null)
+ public function createStringTable(Worksheet $worksheet, $existingTable = null)
{
// Create string lookup table
$aStringTable = [];
@@ -27,23 +27,23 @@ class StringTable extends WriterPart
$aFlippedStringTable = null; // For faster lookup
// Is an existing table given?
- if (($pExistingTable !== null) && is_array($pExistingTable)) {
- $aStringTable = $pExistingTable;
+ if (($existingTable !== null) && is_array($existingTable)) {
+ $aStringTable = $existingTable;
}
// Fill index array
$aFlippedStringTable = $this->flipStringTable($aStringTable);
// Loop through cells
- foreach ($pSheet->getCoordinates() as $coordinate) {
- $cell = $pSheet->getCell($coordinate);
+ foreach ($worksheet->getCoordinates() as $coordinate) {
+ $cell = $worksheet->getCell($coordinate);
$cellValue = $cell->getValue();
if (
!is_object($cellValue) &&
($cellValue !== null) &&
$cellValue !== '' &&
- !isset($aFlippedStringTable[$cellValue]) &&
- ($cell->getDataType() == DataType::TYPE_STRING || $cell->getDataType() == DataType::TYPE_STRING2 || $cell->getDataType() == DataType::TYPE_NULL)
+ ($cell->getDataType() == DataType::TYPE_STRING || $cell->getDataType() == DataType::TYPE_STRING2 || $cell->getDataType() == DataType::TYPE_NULL) &&
+ !isset($aFlippedStringTable[$cellValue])
) {
$aStringTable[] = $cellValue;
$aFlippedStringTable[$cellValue] = true;
@@ -63,11 +63,11 @@ class StringTable extends WriterPart
/**
* Write string table to XML format.
*
- * @param string[] $pStringTable
+ * @param string[] $stringTable
*
* @return string XML Output
*/
- public function writeStringTable(array $pStringTable)
+ public function writeStringTable(array $stringTable)
{
// Create XML writer
$objWriter = null;
@@ -83,10 +83,10 @@ class StringTable extends WriterPart
// String table
$objWriter->startElement('sst');
$objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main');
- $objWriter->writeAttribute('uniqueCount', count($pStringTable));
+ $objWriter->writeAttribute('uniqueCount', count($stringTable));
// Loop through string table
- foreach ($pStringTable as $textElement) {
+ foreach ($stringTable as $textElement) {
$objWriter->startElement('si');
if (!$textElement instanceof RichText) {
@@ -112,18 +112,16 @@ class StringTable extends WriterPart
/**
* Write Rich Text.
*
- * @param XMLWriter $objWriter XML Writer
- * @param RichText $pRichText Rich text
* @param string $prefix Optional Namespace prefix
*/
- public function writeRichText(XMLWriter $objWriter, RichText $pRichText, $prefix = null): void
+ public function writeRichText(XMLWriter $objWriter, RichText $richText, $prefix = null): void
{
if ($prefix !== null) {
$prefix .= ':';
}
// Loop through rich text elements
- $elements = $pRichText->getRichTextElements();
+ $elements = $richText->getRichTextElements();
foreach ($elements as $element) {
// r
$objWriter->startElement($prefix . 'r');
@@ -195,16 +193,15 @@ class StringTable extends WriterPart
/**
* Write Rich Text.
*
- * @param XMLWriter $objWriter XML Writer
- * @param RichText|string $pRichText text string or Rich text
+ * @param RichText|string $richText text string or Rich text
* @param string $prefix Optional Namespace prefix
*/
- public function writeRichTextForCharts(XMLWriter $objWriter, $pRichText = null, $prefix = null): void
+ public function writeRichTextForCharts(XMLWriter $objWriter, $richText = null, $prefix = null): void
{
- if (!$pRichText instanceof RichText) {
- $textRun = $pRichText;
- $pRichText = new RichText();
- $pRichText->createTextRun($textRun);
+ if (!$richText instanceof RichText) {
+ $textRun = $richText;
+ $richText = new RichText();
+ $richText->createTextRun($textRun);
}
if ($prefix !== null) {
@@ -212,7 +209,7 @@ class StringTable extends WriterPart
}
// Loop through rich text elements
- $elements = $pRichText->getRichTextElements();
+ $elements = $richText->getRichTextElements();
foreach ($elements as $element) {
// r
$objWriter->startElement($prefix . 'r');
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Style.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Style.php
index 0c43fbf490d..cb2e3850477 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Style.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Style.php
@@ -145,40 +145,34 @@ class Style extends WriterPart
/**
* Write Fill.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param Fill $pFill Fill style
*/
- private function writeFill(XMLWriter $objWriter, Fill $pFill): void
+ private function writeFill(XMLWriter $objWriter, Fill $fill): void
{
// Check if this is a pattern type or gradient type
if (
- $pFill->getFillType() === Fill::FILL_GRADIENT_LINEAR ||
- $pFill->getFillType() === Fill::FILL_GRADIENT_PATH
+ $fill->getFillType() === Fill::FILL_GRADIENT_LINEAR ||
+ $fill->getFillType() === Fill::FILL_GRADIENT_PATH
) {
// Gradient fill
- $this->writeGradientFill($objWriter, $pFill);
- } elseif ($pFill->getFillType() !== null) {
+ $this->writeGradientFill($objWriter, $fill);
+ } elseif ($fill->getFillType() !== null) {
// Pattern fill
- $this->writePatternFill($objWriter, $pFill);
+ $this->writePatternFill($objWriter, $fill);
}
}
/**
* Write Gradient Fill.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param Fill $pFill Fill style
*/
- private function writeGradientFill(XMLWriter $objWriter, Fill $pFill): void
+ private function writeGradientFill(XMLWriter $objWriter, Fill $fill): void
{
// fill
$objWriter->startElement('fill');
// gradientFill
$objWriter->startElement('gradientFill');
- $objWriter->writeAttribute('type', $pFill->getFillType());
- $objWriter->writeAttribute('degree', $pFill->getRotation());
+ $objWriter->writeAttribute('type', $fill->getFillType());
+ $objWriter->writeAttribute('degree', $fill->getRotation());
// stop
$objWriter->startElement('stop');
@@ -186,7 +180,7 @@ class Style extends WriterPart
// color
$objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
+ $objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB());
$objWriter->endElement();
$objWriter->endElement();
@@ -197,7 +191,7 @@ class Style extends WriterPart
// color
$objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
+ $objWriter->writeAttribute('rgb', $fill->getEndColor()->getARGB());
$objWriter->endElement();
$objWriter->endElement();
@@ -207,34 +201,38 @@ class Style extends WriterPart
$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.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param Fill $pFill Fill style
*/
- private function writePatternFill(XMLWriter $objWriter, Fill $pFill): void
+ private function writePatternFill(XMLWriter $objWriter, Fill $fill): void
{
// fill
$objWriter->startElement('fill');
// patternFill
$objWriter->startElement('patternFill');
- $objWriter->writeAttribute('patternType', $pFill->getFillType());
+ $objWriter->writeAttribute('patternType', $fill->getFillType());
- if ($pFill->getFillType() !== Fill::FILL_NONE) {
+ if (self::writePatternColors($fill)) {
// fgColor
- if ($pFill->getStartColor()->getARGB()) {
+ if ($fill->getStartColor()->getARGB()) {
$objWriter->startElement('fgColor');
- $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB());
+ $objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB());
$objWriter->endElement();
}
- }
- if ($pFill->getFillType() !== Fill::FILL_NONE) {
// bgColor
- if ($pFill->getEndColor()->getARGB()) {
+ if ($fill->getEndColor()->getARGB()) {
$objWriter->startElement('bgColor');
- $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB());
+ $objWriter->writeAttribute('rgb', $fill->getEndColor()->getARGB());
$objWriter->endElement();
}
}
@@ -246,11 +244,8 @@ class Style extends WriterPart
/**
* Write Font.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param Font $pFont Font style
*/
- private function writeFont(XMLWriter $objWriter, Font $pFont): void
+ private function writeFont(XMLWriter $objWriter, Font $font): void
{
// font
$objWriter->startElement('font');
@@ -261,62 +256,62 @@ class Style extends WriterPart
// 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 ($pFont->getBold() !== null) {
+ if ($font->getBold() !== null) {
$objWriter->startElement('b');
- $objWriter->writeAttribute('val', $pFont->getBold() ? '1' : '0');
+ $objWriter->writeAttribute('val', $font->getBold() ? '1' : '0');
$objWriter->endElement();
}
// Italic
- if ($pFont->getItalic() !== null) {
+ if ($font->getItalic() !== null) {
$objWriter->startElement('i');
- $objWriter->writeAttribute('val', $pFont->getItalic() ? '1' : '0');
+ $objWriter->writeAttribute('val', $font->getItalic() ? '1' : '0');
$objWriter->endElement();
}
// Strikethrough
- if ($pFont->getStrikethrough() !== null) {
+ if ($font->getStrikethrough() !== null) {
$objWriter->startElement('strike');
- $objWriter->writeAttribute('val', $pFont->getStrikethrough() ? '1' : '0');
+ $objWriter->writeAttribute('val', $font->getStrikethrough() ? '1' : '0');
$objWriter->endElement();
}
// Underline
- if ($pFont->getUnderline() !== null) {
+ if ($font->getUnderline() !== null) {
$objWriter->startElement('u');
- $objWriter->writeAttribute('val', $pFont->getUnderline());
+ $objWriter->writeAttribute('val', $font->getUnderline());
$objWriter->endElement();
}
// Superscript / subscript
- if ($pFont->getSuperscript() === true || $pFont->getSubscript() === true) {
+ if ($font->getSuperscript() === true || $font->getSubscript() === true) {
$objWriter->startElement('vertAlign');
- if ($pFont->getSuperscript() === true) {
+ if ($font->getSuperscript() === true) {
$objWriter->writeAttribute('val', 'superscript');
- } elseif ($pFont->getSubscript() === true) {
+ } elseif ($font->getSubscript() === true) {
$objWriter->writeAttribute('val', 'subscript');
}
$objWriter->endElement();
}
// Size
- if ($pFont->getSize() !== null) {
+ if ($font->getSize() !== null) {
$objWriter->startElement('sz');
- $objWriter->writeAttribute('val', StringHelper::formatNumber($pFont->getSize()));
+ $objWriter->writeAttribute('val', StringHelper::formatNumber($font->getSize()));
$objWriter->endElement();
}
// Foreground color
- if ($pFont->getColor()->getARGB() !== null) {
+ if ($font->getColor()->getARGB() !== null) {
$objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pFont->getColor()->getARGB());
+ $objWriter->writeAttribute('rgb', $font->getColor()->getARGB());
$objWriter->endElement();
}
// Name
- if ($pFont->getName() !== null) {
+ if ($font->getName() !== null) {
$objWriter->startElement('name');
- $objWriter->writeAttribute('val', $pFont->getName());
+ $objWriter->writeAttribute('val', $font->getName());
$objWriter->endElement();
}
@@ -325,16 +320,13 @@ class Style extends WriterPart
/**
* Write Border.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param Borders $pBorders Borders style
*/
- private function writeBorder(XMLWriter $objWriter, Borders $pBorders): void
+ private function writeBorder(XMLWriter $objWriter, Borders $borders): void
{
// Write border
$objWriter->startElement('border');
// Diagonal?
- switch ($pBorders->getDiagonalDirection()) {
+ switch ($borders->getDiagonalDirection()) {
case Borders::DIAGONAL_UP:
$objWriter->writeAttribute('diagonalUp', 'true');
$objWriter->writeAttribute('diagonalDown', 'false');
@@ -353,82 +345,78 @@ class Style extends WriterPart
}
// BorderPr
- $this->writeBorderPr($objWriter, 'left', $pBorders->getLeft());
- $this->writeBorderPr($objWriter, 'right', $pBorders->getRight());
- $this->writeBorderPr($objWriter, 'top', $pBorders->getTop());
- $this->writeBorderPr($objWriter, 'bottom', $pBorders->getBottom());
- $this->writeBorderPr($objWriter, 'diagonal', $pBorders->getDiagonal());
+ $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();
}
/**
* Write Cell Style Xf.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param \PhpOffice\PhpSpreadsheet\Style\Style $pStyle Style
- * @param Spreadsheet $spreadsheet Workbook
*/
- private function writeCellStyleXf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $pStyle, Spreadsheet $spreadsheet): void
+ private function writeCellStyleXf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $style, Spreadsheet $spreadsheet): void
{
// xf
$objWriter->startElement('xf');
$objWriter->writeAttribute('xfId', 0);
- $objWriter->writeAttribute('fontId', (int) $this->getParentWriter()->getFontHashTable()->getIndexForHashCode($pStyle->getFont()->getHashCode()));
- if ($pStyle->getQuotePrefix()) {
+ $objWriter->writeAttribute('fontId', (int) $this->getParentWriter()->getFontHashTable()->getIndexForHashCode($style->getFont()->getHashCode()));
+ if ($style->getQuotePrefix()) {
$objWriter->writeAttribute('quotePrefix', 1);
}
- if ($pStyle->getNumberFormat()->getBuiltInFormatCode() === false) {
- $objWriter->writeAttribute('numFmtId', (int) ($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($pStyle->getNumberFormat()->getHashCode()) + 164));
+ if ($style->getNumberFormat()->getBuiltInFormatCode() === false) {
+ $objWriter->writeAttribute('numFmtId', (int) ($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($style->getNumberFormat()->getHashCode()) + 164));
} else {
- $objWriter->writeAttribute('numFmtId', (int) $pStyle->getNumberFormat()->getBuiltInFormatCode());
+ $objWriter->writeAttribute('numFmtId', (int) $style->getNumberFormat()->getBuiltInFormatCode());
}
- $objWriter->writeAttribute('fillId', (int) $this->getParentWriter()->getFillHashTable()->getIndexForHashCode($pStyle->getFill()->getHashCode()));
- $objWriter->writeAttribute('borderId', (int) $this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($pStyle->getBorders()->getHashCode()));
+ $objWriter->writeAttribute('fillId', (int) $this->getParentWriter()->getFillHashTable()->getIndexForHashCode($style->getFill()->getHashCode()));
+ $objWriter->writeAttribute('borderId', (int) $this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($style->getBorders()->getHashCode()));
// Apply styles?
- $objWriter->writeAttribute('applyFont', ($spreadsheet->getDefaultStyle()->getFont()->getHashCode() != $pStyle->getFont()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyNumberFormat', ($spreadsheet->getDefaultStyle()->getNumberFormat()->getHashCode() != $pStyle->getNumberFormat()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyFill', ($spreadsheet->getDefaultStyle()->getFill()->getHashCode() != $pStyle->getFill()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyBorder', ($spreadsheet->getDefaultStyle()->getBorders()->getHashCode() != $pStyle->getBorders()->getHashCode()) ? '1' : '0');
- $objWriter->writeAttribute('applyAlignment', ($spreadsheet->getDefaultStyle()->getAlignment()->getHashCode() != $pStyle->getAlignment()->getHashCode()) ? '1' : '0');
- if ($pStyle->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) {
+ $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');
+ $objWriter->writeAttribute('applyAlignment', ($spreadsheet->getDefaultStyle()->getAlignment()->getHashCode() != $style->getAlignment()->getHashCode()) ? '1' : '0');
+ if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) {
$objWriter->writeAttribute('applyProtection', 'true');
}
// alignment
$objWriter->startElement('alignment');
- $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
- $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
+ $objWriter->writeAttribute('horizontal', $style->getAlignment()->getHorizontal());
+ $objWriter->writeAttribute('vertical', $style->getAlignment()->getVertical());
$textRotation = 0;
- if ($pStyle->getAlignment()->getTextRotation() >= 0) {
- $textRotation = $pStyle->getAlignment()->getTextRotation();
- } elseif ($pStyle->getAlignment()->getTextRotation() < 0) {
- $textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
+ if ($style->getAlignment()->getTextRotation() >= 0) {
+ $textRotation = $style->getAlignment()->getTextRotation();
+ } elseif ($style->getAlignment()->getTextRotation() < 0) {
+ $textRotation = 90 - $style->getAlignment()->getTextRotation();
}
$objWriter->writeAttribute('textRotation', $textRotation);
- $objWriter->writeAttribute('wrapText', ($pStyle->getAlignment()->getWrapText() ? 'true' : 'false'));
- $objWriter->writeAttribute('shrinkToFit', ($pStyle->getAlignment()->getShrinkToFit() ? 'true' : 'false'));
+ $objWriter->writeAttribute('wrapText', ($style->getAlignment()->getWrapText() ? 'true' : 'false'));
+ $objWriter->writeAttribute('shrinkToFit', ($style->getAlignment()->getShrinkToFit() ? 'true' : 'false'));
- if ($pStyle->getAlignment()->getIndent() > 0) {
- $objWriter->writeAttribute('indent', $pStyle->getAlignment()->getIndent());
+ if ($style->getAlignment()->getIndent() > 0) {
+ $objWriter->writeAttribute('indent', $style->getAlignment()->getIndent());
}
- if ($pStyle->getAlignment()->getReadOrder() > 0) {
- $objWriter->writeAttribute('readingOrder', $pStyle->getAlignment()->getReadOrder());
+ if ($style->getAlignment()->getReadOrder() > 0) {
+ $objWriter->writeAttribute('readingOrder', $style->getAlignment()->getReadOrder());
}
$objWriter->endElement();
// protection
- if ($pStyle->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) {
+ if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) {
$objWriter->startElement('protection');
- if ($pStyle->getProtection()->getLocked() != Protection::PROTECTION_INHERIT) {
- $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
+ if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT) {
+ $objWriter->writeAttribute('locked', ($style->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
}
- if ($pStyle->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) {
- $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == 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();
}
@@ -438,65 +426,62 @@ class Style extends WriterPart
/**
* Write Cell Style Dxf.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param \PhpOffice\PhpSpreadsheet\Style\Style $pStyle Style
*/
- private function writeCellStyleDxf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $pStyle): void
+ private function writeCellStyleDxf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $style): void
{
// dxf
$objWriter->startElement('dxf');
// font
- $this->writeFont($objWriter, $pStyle->getFont());
+ $this->writeFont($objWriter, $style->getFont());
// numFmt
- $this->writeNumFmt($objWriter, $pStyle->getNumberFormat());
+ $this->writeNumFmt($objWriter, $style->getNumberFormat());
// fill
- $this->writeFill($objWriter, $pStyle->getFill());
+ $this->writeFill($objWriter, $style->getFill());
// alignment
$objWriter->startElement('alignment');
- if ($pStyle->getAlignment()->getHorizontal() !== null) {
- $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal());
+ if ($style->getAlignment()->getHorizontal() !== null) {
+ $objWriter->writeAttribute('horizontal', $style->getAlignment()->getHorizontal());
}
- if ($pStyle->getAlignment()->getVertical() !== null) {
- $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical());
+ if ($style->getAlignment()->getVertical() !== null) {
+ $objWriter->writeAttribute('vertical', $style->getAlignment()->getVertical());
}
- if ($pStyle->getAlignment()->getTextRotation() !== null) {
+ if ($style->getAlignment()->getTextRotation() !== null) {
$textRotation = 0;
- if ($pStyle->getAlignment()->getTextRotation() >= 0) {
- $textRotation = $pStyle->getAlignment()->getTextRotation();
- } elseif ($pStyle->getAlignment()->getTextRotation() < 0) {
- $textRotation = 90 - $pStyle->getAlignment()->getTextRotation();
+ if ($style->getAlignment()->getTextRotation() >= 0) {
+ $textRotation = $style->getAlignment()->getTextRotation();
+ } elseif ($style->getAlignment()->getTextRotation() < 0) {
+ $textRotation = 90 - $style->getAlignment()->getTextRotation();
}
$objWriter->writeAttribute('textRotation', $textRotation);
}
$objWriter->endElement();
// border
- $this->writeBorder($objWriter, $pStyle->getBorders());
+ $this->writeBorder($objWriter, $style->getBorders());
// protection
- if (($pStyle->getProtection()->getLocked() !== null) || ($pStyle->getProtection()->getHidden() !== null)) {
+ if (($style->getProtection()->getLocked() !== null) || ($style->getProtection()->getHidden() !== null)) {
if (
- $pStyle->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT ||
- $pStyle->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT
+ $style->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT ||
+ $style->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT
) {
$objWriter->startElement('protection');
if (
- ($pStyle->getProtection()->getLocked() !== null) &&
- ($pStyle->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT)
+ ($style->getProtection()->getLocked() !== null) &&
+ ($style->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT)
) {
- $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
+ $objWriter->writeAttribute('locked', ($style->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
}
if (
- ($pStyle->getProtection()->getHidden() !== null) &&
- ($pStyle->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT)
+ ($style->getProtection()->getHidden() !== null) &&
+ ($style->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT)
) {
- $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
+ $objWriter->writeAttribute('hidden', ($style->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false'));
}
$objWriter->endElement();
}
@@ -508,20 +493,18 @@ class Style extends WriterPart
/**
* Write BorderPr.
*
- * @param XMLWriter $objWriter XML Writer
- * @param string $pName Element name
- * @param Border $pBorder Border style
+ * @param string $name Element name
*/
- private function writeBorderPr(XMLWriter $objWriter, $pName, Border $pBorder): void
+ private function writeBorderPr(XMLWriter $objWriter, $name, Border $border): void
{
// Write BorderPr
- if ($pBorder->getBorderStyle() != Border::BORDER_NONE) {
- $objWriter->startElement($pName);
- $objWriter->writeAttribute('style', $pBorder->getBorderStyle());
+ if ($border->getBorderStyle() != Border::BORDER_NONE) {
+ $objWriter->startElement($name);
+ $objWriter->writeAttribute('style', $border->getBorderStyle());
// color
$objWriter->startElement('color');
- $objWriter->writeAttribute('rgb', $pBorder->getColor()->getARGB());
+ $objWriter->writeAttribute('rgb', $border->getColor()->getARGB());
$objWriter->endElement();
$objWriter->endElement();
@@ -531,19 +514,17 @@ class Style extends WriterPart
/**
* Write NumberFormat.
*
- * @param XMLWriter $objWriter XML Writer
- * @param NumberFormat $pNumberFormat Number Format
- * @param int $pId Number Format identifier
+ * @param int $id Number Format identifier
*/
- private function writeNumFmt(XMLWriter $objWriter, NumberFormat $pNumberFormat, $pId = 0): void
+ private function writeNumFmt(XMLWriter $objWriter, NumberFormat $numberFormat, $id = 0): void
{
// Translate formatcode
- $formatCode = $pNumberFormat->getFormatCode();
+ $formatCode = $numberFormat->getFormatCode();
// numFmt
if ($formatCode !== null) {
$objWriter->startElement('numFmt');
- $objWriter->writeAttribute('numFmtId', ($pId + 164));
+ $objWriter->writeAttribute('numFmtId', ($id + 164));
$objWriter->writeAttribute('formatCode', $formatCode);
$objWriter->endElement();
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Theme.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Theme.php
index 3a47be7fb6f..991772926ce 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Theme.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Theme.php
@@ -10,7 +10,7 @@ class Theme extends WriterPart
/**
* Map of Major fonts to write.
*
- * @var array of string
+ * @var string[]
*/
private static $majorFonts = [
'Jpan' => 'MS Pゴシック',
@@ -48,7 +48,7 @@ class Theme extends WriterPart
/**
* Map of Minor fonts to write.
*
- * @var array of string
+ * @var string[]
*/
private static $minorFonts = [
'Jpan' => 'MS Pゴシック',
@@ -86,7 +86,7 @@ class Theme extends WriterPart
/**
* Map of core colours.
*
- * @var array of string
+ * @var string[]
*/
private static $colourScheme = [
'dk2' => '1F497D',
@@ -784,13 +784,9 @@ class Theme extends WriterPart
/**
* Write fonts to XML format.
*
- * @param XMLWriter $objWriter
- * @param string $latinFont
- * @param array of string $fontSet
- *
- * @return string XML Output
+ * @param string[] $fontSet
*/
- private function writeFonts($objWriter, $latinFont, $fontSet)
+ private function writeFonts(XMLWriter $objWriter, string $latinFont, array $fontSet): void
{
// a:latin
$objWriter->startElement('a:latin');
@@ -817,12 +813,8 @@ class Theme extends WriterPart
/**
* Write colour scheme to XML format.
- *
- * @param XMLWriter $objWriter
- *
- * @return string XML Output
*/
- private function writeColourScheme($objWriter)
+ private function writeColourScheme(XMLWriter $objWriter): void
{
foreach (self::$colourScheme as $colourName => $colourValue) {
$objWriter->startElement('a:' . $colourName);
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php
index 0a20ea9d9f5..f9d7197d7a6 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php
@@ -66,8 +66,6 @@ class Workbook extends WriterPart
/**
* Write file version.
- *
- * @param XMLWriter $objWriter XML Writer
*/
private function writeFileVersion(XMLWriter $objWriter): void
{
@@ -81,8 +79,6 @@ class Workbook extends WriterPart
/**
* Write WorkbookPr.
- *
- * @param XMLWriter $objWriter XML Writer
*/
private function writeWorkbookPr(XMLWriter $objWriter): void
{
@@ -99,8 +95,6 @@ class Workbook extends WriterPart
/**
* Write BookViews.
- *
- * @param XMLWriter $objWriter XML Writer
*/
private function writeBookViews(XMLWriter $objWriter, Spreadsheet $spreadsheet): void
{
@@ -127,8 +121,6 @@ class Workbook extends WriterPart
/**
* Write WorkbookProtection.
- *
- * @param XMLWriter $objWriter XML Writer
*/
private function writeWorkbookProtection(XMLWriter $objWriter, Spreadsheet $spreadsheet): void
{
@@ -153,7 +145,6 @@ class Workbook extends WriterPart
/**
* Write calcPr.
*
- * @param XMLWriter $objWriter XML Writer
* @param bool $recalcRequired Indicate whether formulas should be recalculated before writing
*/
private function writeCalcPr(XMLWriter $objWriter, $recalcRequired = true): void
@@ -175,8 +166,6 @@ class Workbook extends WriterPart
/**
* Write sheets.
- *
- * @param XMLWriter $objWriter XML Writer
*/
private function writeSheets(XMLWriter $objWriter, Spreadsheet $spreadsheet): void
{
@@ -200,23 +189,22 @@ class Workbook extends WriterPart
/**
* Write sheet.
*
- * @param XMLWriter $objWriter XML Writer
- * @param string $pSheetname Sheet name
- * @param int $pSheetId Sheet id
- * @param int $pRelId Relationship ID
+ * @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, $pSheetname, $pSheetId = 1, $pRelId = 1, $sheetState = 'visible'): void
+ private function writeSheet(XMLWriter $objWriter, $worksheetName, $worksheetId = 1, $relId = 1, $sheetState = 'visible'): void
{
- if ($pSheetname != '') {
+ if ($worksheetName != '') {
// Write sheet
$objWriter->startElement('sheet');
- $objWriter->writeAttribute('name', $pSheetname);
- $objWriter->writeAttribute('sheetId', $pSheetId);
+ $objWriter->writeAttribute('name', $worksheetName);
+ $objWriter->writeAttribute('sheetId', $worksheetId);
if ($sheetState !== 'visible' && $sheetState != '') {
$objWriter->writeAttribute('state', $sheetState);
}
- $objWriter->writeAttribute('r:id', 'rId' . $pRelId);
+ $objWriter->writeAttribute('r:id', 'rId' . $relId);
$objWriter->endElement();
} else {
throw new WriterException('Invalid parameters passed.');
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php
index 8faa7ae259e..494dc70ac6f 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php
@@ -5,9 +5,12 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
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\AutoFilter\Column;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule;
use PhpOffice\PhpSpreadsheet\Worksheet\SheetView;
@@ -18,12 +21,12 @@ class Worksheet extends WriterPart
/**
* Write worksheet to XML format.
*
- * @param string[] $pStringTable
+ * @param string[] $stringTable
* @param bool $includeCharts Flag indicating if we should write charts
*
* @return string XML Output
*/
- public function writeWorksheet(PhpspreadsheetWorksheet $pSheet, $pStringTable = null, $includeCharts = false)
+ public function writeWorksheet(PhpspreadsheetWorksheet $worksheet, $stringTable = null, $includeCharts = false)
{
// Create XML writer
$objWriter = null;
@@ -44,75 +47,80 @@ class Worksheet extends WriterPart
$objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
$objWriter->writeAttribute('xmlns:x14', 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main');
+ $objWriter->writeAttribute('xmlns:xm', 'http://schemas.microsoft.com/office/excel/2006/main');
$objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006');
$objWriter->writeAttribute('mc:Ignorable', 'x14ac');
$objWriter->writeAttribute('xmlns:x14ac', 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac');
// sheetPr
- $this->writeSheetPr($objWriter, $pSheet);
+ $this->writeSheetPr($objWriter, $worksheet);
// Dimension
- $this->writeDimension($objWriter, $pSheet);
+ $this->writeDimension($objWriter, $worksheet);
// sheetViews
- $this->writeSheetViews($objWriter, $pSheet);
+ $this->writeSheetViews($objWriter, $worksheet);
// sheetFormatPr
- $this->writeSheetFormatPr($objWriter, $pSheet);
+ $this->writeSheetFormatPr($objWriter, $worksheet);
// cols
- $this->writeCols($objWriter, $pSheet);
+ $this->writeCols($objWriter, $worksheet);
// sheetData
- $this->writeSheetData($objWriter, $pSheet, $pStringTable);
+ $this->writeSheetData($objWriter, $worksheet, $stringTable);
// sheetProtection
- $this->writeSheetProtection($objWriter, $pSheet);
+ $this->writeSheetProtection($objWriter, $worksheet);
// protectedRanges
- $this->writeProtectedRanges($objWriter, $pSheet);
+ $this->writeProtectedRanges($objWriter, $worksheet);
// autoFilter
- $this->writeAutoFilter($objWriter, $pSheet);
+ $this->writeAutoFilter($objWriter, $worksheet);
// mergeCells
- $this->writeMergeCells($objWriter, $pSheet);
+ $this->writeMergeCells($objWriter, $worksheet);
// conditionalFormatting
- $this->writeConditionalFormatting($objWriter, $pSheet);
+ $this->writeConditionalFormatting($objWriter, $worksheet);
// dataValidations
- $this->writeDataValidations($objWriter, $pSheet);
+ $this->writeDataValidations($objWriter, $worksheet);
// hyperlinks
- $this->writeHyperlinks($objWriter, $pSheet);
+ $this->writeHyperlinks($objWriter, $worksheet);
// Print options
- $this->writePrintOptions($objWriter, $pSheet);
+ $this->writePrintOptions($objWriter, $worksheet);
// Page margins
- $this->writePageMargins($objWriter, $pSheet);
+ $this->writePageMargins($objWriter, $worksheet);
// Page setup
- $this->writePageSetup($objWriter, $pSheet);
+ $this->writePageSetup($objWriter, $worksheet);
// Header / footer
- $this->writeHeaderFooter($objWriter, $pSheet);
+ $this->writeHeaderFooter($objWriter, $worksheet);
// Breaks
- $this->writeBreaks($objWriter, $pSheet);
+ $this->writeBreaks($objWriter, $worksheet);
// Drawings and/or Charts
- $this->writeDrawings($objWriter, $pSheet, $includeCharts);
+ $this->writeDrawings($objWriter, $worksheet, $includeCharts);
// LegacyDrawing
- $this->writeLegacyDrawing($objWriter, $pSheet);
+ $this->writeLegacyDrawing($objWriter, $worksheet);
// LegacyDrawingHF
- $this->writeLegacyDrawingHF($objWriter, $pSheet);
+ $this->writeLegacyDrawingHF($objWriter, $worksheet);
// AlternateContent
- $this->writeAlternateContent($objWriter, $pSheet);
+ $this->writeAlternateContent($objWriter, $worksheet);
+
+ // ConditionalFormattingRuleExtensionList
+ // (Must be inserted last. Not insert last, an Excel parse error will occur)
+ $this->writeExtLst($objWriter, $worksheet);
$objWriter->endElement();
@@ -122,42 +130,41 @@ class Worksheet extends WriterPart
/**
* Write SheetPr.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// sheetPr
$objWriter->startElement('sheetPr');
- if ($pSheet->getParent()->hasMacros()) {
+ if ($worksheet->getParent()->hasMacros()) {
//if the workbook have macros, we need to have codeName for the sheet
- if (!$pSheet->hasCodeName()) {
- $pSheet->setCodeName($pSheet->getTitle());
+ if (!$worksheet->hasCodeName()) {
+ $worksheet->setCodeName($worksheet->getTitle());
}
- $objWriter->writeAttribute('codeName', $pSheet->getCodeName());
+ self::writeAttributeNotNull($objWriter, 'codeName', $worksheet->getCodeName());
}
- $autoFilterRange = $pSheet->getAutoFilter()->getRange();
+ $autoFilterRange = $worksheet->getAutoFilter()->getRange();
if (!empty($autoFilterRange)) {
$objWriter->writeAttribute('filterMode', 1);
- $pSheet->getAutoFilter()->showHideRows();
+ if (!$worksheet->getAutoFilter()->getEvaluated()) {
+ $worksheet->getAutoFilter()->showHideRows();
+ }
}
// tabColor
- if ($pSheet->isTabColorSet()) {
+ if ($worksheet->isTabColorSet()) {
$objWriter->startElement('tabColor');
- $objWriter->writeAttribute('rgb', $pSheet->getTabColor()->getARGB());
+ $objWriter->writeAttribute('rgb', $worksheet->getTabColor()->getARGB());
$objWriter->endElement();
}
// outlinePr
$objWriter->startElement('outlinePr');
- $objWriter->writeAttribute('summaryBelow', ($pSheet->getShowSummaryBelow() ? '1' : '0'));
- $objWriter->writeAttribute('summaryRight', ($pSheet->getShowSummaryRight() ? '1' : '0'));
+ $objWriter->writeAttribute('summaryBelow', ($worksheet->getShowSummaryBelow() ? '1' : '0'));
+ $objWriter->writeAttribute('summaryRight', ($worksheet->getShowSummaryRight() ? '1' : '0'));
$objWriter->endElement();
// pageSetUpPr
- if ($pSheet->getPageSetup()->getFitToPage()) {
+ if ($worksheet->getPageSetup()->getFitToPage()) {
$objWriter->startElement('pageSetUpPr');
$objWriter->writeAttribute('fitToPage', '1');
$objWriter->endElement();
@@ -168,32 +175,26 @@ class Worksheet extends WriterPart
/**
* Write Dimension.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// dimension
$objWriter->startElement('dimension');
- $objWriter->writeAttribute('ref', $pSheet->calculateWorksheetDimension());
+ $objWriter->writeAttribute('ref', $worksheet->calculateWorksheetDimension());
$objWriter->endElement();
}
/**
* Write SheetViews.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// sheetViews
$objWriter->startElement('sheetViews');
// Sheet selected?
$sheetSelected = false;
- if ($this->getParentWriter()->getSpreadsheet()->getIndex($pSheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) {
+ if ($this->getParentWriter()->getSpreadsheet()->getIndex($worksheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) {
$sheetSelected = true;
}
@@ -203,55 +204,54 @@ class Worksheet extends WriterPart
$objWriter->writeAttribute('workbookViewId', '0');
// Zoom scales
- if ($pSheet->getSheetView()->getZoomScale() != 100) {
- $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale());
+ if ($worksheet->getSheetView()->getZoomScale() != 100) {
+ $objWriter->writeAttribute('zoomScale', $worksheet->getSheetView()->getZoomScale());
}
- if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) {
- $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal());
+ if ($worksheet->getSheetView()->getZoomScaleNormal() != 100) {
+ $objWriter->writeAttribute('zoomScaleNormal', $worksheet->getSheetView()->getZoomScaleNormal());
}
// Show zeros (Excel also writes this attribute only if set to false)
- if ($pSheet->getSheetView()->getShowZeros() === false) {
+ if ($worksheet->getSheetView()->getShowZeros() === false) {
$objWriter->writeAttribute('showZeros', 0);
}
// View Layout Type
- if ($pSheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) {
- $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView());
+ if ($worksheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) {
+ $objWriter->writeAttribute('view', $worksheet->getSheetView()->getView());
}
// Gridlines
- if ($pSheet->getShowGridlines()) {
+ if ($worksheet->getShowGridlines()) {
$objWriter->writeAttribute('showGridLines', 'true');
} else {
$objWriter->writeAttribute('showGridLines', 'false');
}
// Row and column headers
- if ($pSheet->getShowRowColHeaders()) {
+ if ($worksheet->getShowRowColHeaders()) {
$objWriter->writeAttribute('showRowColHeaders', '1');
} else {
$objWriter->writeAttribute('showRowColHeaders', '0');
}
// Right-to-left
- if ($pSheet->getRightToLeft()) {
+ if ($worksheet->getRightToLeft()) {
$objWriter->writeAttribute('rightToLeft', 'true');
}
- $activeCell = $pSheet->getActiveCell();
- $sqref = $pSheet->getSelectedCells();
+ $topLeftCell = $worksheet->getTopLeftCell();
+ $activeCell = $worksheet->getActiveCell();
+ $sqref = $worksheet->getSelectedCells();
// Pane
$pane = '';
- if ($pSheet->getFreezePane()) {
- [$xSplit, $ySplit] = Coordinate::coordinateFromString($pSheet->getFreezePane());
+ if ($worksheet->getFreezePane()) {
+ [$xSplit, $ySplit] = Coordinate::coordinateFromString($worksheet->getFreezePane() ?? '');
$xSplit = Coordinate::columnIndexFromString($xSplit);
--$xSplit;
--$ySplit;
- $topLeftCell = $pSheet->getTopLeftCell();
-
// pane
$pane = 'topRight';
$objWriter->startElement('pane');
@@ -262,7 +262,7 @@ class Worksheet extends WriterPart
$objWriter->writeAttribute('ySplit', $ySplit);
$pane = ($xSplit > 0) ? 'bottomRight' : 'bottomLeft';
}
- $objWriter->writeAttribute('topLeftCell', $topLeftCell);
+ self::writeAttributeNotNull($objWriter, 'topLeftCell', $topLeftCell);
$objWriter->writeAttribute('activePane', $pane);
$objWriter->writeAttribute('state', 'frozen');
$objWriter->endElement();
@@ -276,6 +276,8 @@ class Worksheet extends WriterPart
$objWriter->writeAttribute('pane', 'bottomLeft');
$objWriter->endElement();
}
+ } else {
+ self::writeAttributeNotNull($objWriter, 'topLeftCell', $topLeftCell);
}
// Selection
@@ -296,39 +298,36 @@ class Worksheet extends WriterPart
/**
* Write SheetFormatPr.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// sheetFormatPr
$objWriter->startElement('sheetFormatPr');
// Default row height
- if ($pSheet->getDefaultRowDimension()->getRowHeight() >= 0) {
+ if ($worksheet->getDefaultRowDimension()->getRowHeight() >= 0) {
$objWriter->writeAttribute('customHeight', 'true');
- $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($pSheet->getDefaultRowDimension()->getRowHeight()));
+ $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($worksheet->getDefaultRowDimension()->getRowHeight()));
} else {
$objWriter->writeAttribute('defaultRowHeight', '14.4');
}
// Set Zero Height row
if (
- (string) $pSheet->getDefaultRowDimension()->getZeroHeight() === '1' ||
- strtolower((string) $pSheet->getDefaultRowDimension()->getZeroHeight()) == 'true'
+ (string) $worksheet->getDefaultRowDimension()->getZeroHeight() === '1' ||
+ strtolower((string) $worksheet->getDefaultRowDimension()->getZeroHeight()) == 'true'
) {
$objWriter->writeAttribute('zeroHeight', '1');
}
// Default column width
- if ($pSheet->getDefaultColumnDimension()->getWidth() >= 0) {
- $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($pSheet->getDefaultColumnDimension()->getWidth()));
+ if ($worksheet->getDefaultColumnDimension()->getWidth() >= 0) {
+ $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($worksheet->getDefaultColumnDimension()->getWidth()));
}
// Outline level - row
$outlineLevelRow = 0;
- foreach ($pSheet->getRowDimensions() as $dimension) {
+ foreach ($worksheet->getRowDimensions() as $dimension) {
if ($dimension->getOutlineLevel() > $outlineLevelRow) {
$outlineLevelRow = $dimension->getOutlineLevel();
}
@@ -337,7 +336,7 @@ class Worksheet extends WriterPart
// Outline level - column
$outlineLevelCol = 0;
- foreach ($pSheet->getColumnDimensions() as $dimension) {
+ foreach ($worksheet->getColumnDimensions() as $dimension) {
if ($dimension->getOutlineLevel() > $outlineLevelCol) {
$outlineLevelCol = $dimension->getOutlineLevel();
}
@@ -349,20 +348,17 @@ class Worksheet extends WriterPart
/**
* Write Cols.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// cols
- if (count($pSheet->getColumnDimensions()) > 0) {
+ if (count($worksheet->getColumnDimensions()) > 0) {
$objWriter->startElement('cols');
- $pSheet->calculateColumnWidths();
+ $worksheet->calculateColumnWidths();
// Loop through column dimensions
- foreach ($pSheet->getColumnDimensions() as $colDimension) {
+ foreach ($worksheet->getColumnDimensions() as $colDimension) {
// col
$objWriter->startElement('col');
$objWriter->writeAttribute('min', Coordinate::columnIndexFromString($colDimension->getColumnIndex()));
@@ -387,7 +383,7 @@ class Worksheet extends WriterPart
}
// Custom width?
- if ($colDimension->getWidth() != $pSheet->getDefaultColumnDimension()->getWidth()) {
+ if ($colDimension->getWidth() != $worksheet->getDefaultColumnDimension()->getWidth()) {
$objWriter->writeAttribute('customWidth', 'true');
}
@@ -413,16 +409,13 @@ class Worksheet extends WriterPart
/**
* Write SheetProtection.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// sheetProtection
$objWriter->startElement('sheetProtection');
- $protection = $pSheet->getProtection();
+ $protection = $worksheet->getProtection();
if ($protection->getAlgorithm()) {
$objWriter->writeAttribute('algorithmName', $protection->getAlgorithm());
@@ -459,6 +452,13 @@ class Worksheet extends WriterPart
}
}
+ private static function writeAttributeNotNull(XMLWriter $objWriter, string $attr, ?string $val): void
+ {
+ if ($val !== null) {
+ $objWriter->writeAttribute($attr, $val);
+ }
+ }
+
private static function writeElementIf(XMLWriter $objWriter, $condition, string $attr, string $val): void
{
if ($condition) {
@@ -503,19 +503,104 @@ class Worksheet extends WriterPart
}
}
+ 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) {
+ $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) {
+ $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, $dataBar): void
+ {
+ /** @var ConditionalDataBar $dataBar */
+ 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.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// Conditional id
$id = 1;
// Loop through styles in the current worksheet
- foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
+ foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
foreach ($conditionalStyles as $conditional) {
// WHY was this again?
// if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') {
@@ -529,26 +614,40 @@ class Worksheet extends WriterPart
// cfRule
$objWriter->startElement('cfRule');
$objWriter->writeAttribute('type', $conditional->getConditionType());
- $objWriter->writeAttribute('dxfId', $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()));
+ self::writeAttributeIf(
+ $objWriter,
+ ($conditional->getConditionType() != Conditional::CONDITION_DATABAR),
+ 'dxfId',
+ (string) $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode())
+ );
$objWriter->writeAttribute('priority', $id++);
self::writeAttributeif(
$objWriter,
- ($conditional->getConditionType() == Conditional::CONDITION_CELLIS || $conditional->getConditionType() == Conditional::CONDITION_CONTAINSTEXT)
- && $conditional->getOperatorType() != Conditional::OPERATOR_NONE,
+ (
+ $conditional->getConditionType() === Conditional::CONDITION_CELLIS
+ || $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT
+ || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT
+ ) && $conditional->getOperatorType() !== Conditional::OPERATOR_NONE,
'operator',
$conditional->getOperatorType()
);
self::writeAttributeIf($objWriter, $conditional->getStopIfTrue(), 'stopIfTrue', '1');
- if ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSTEXT) {
+ if (
+ $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT
+ || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT
+ ) {
self::writeTextCondElements($objWriter, $conditional, $cellCoordinate);
} else {
self::writeOtherCondElements($objWriter, $conditional, $cellCoordinate);
}
- $objWriter->endElement();
+ //
+ self::writeDataBarElements($objWriter, $conditional->getDataBar());
+
+ $objWriter->endElement(); //end cfRule
$objWriter->endElement();
}
@@ -558,14 +657,11 @@ class Worksheet extends WriterPart
/**
* Write DataValidations.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// Datavalidation collection
- $dataValidationCollection = $pSheet->getDataValidationCollection();
+ $dataValidationCollection = $worksheet->getDataValidationCollection();
// Write data validations?
if (!empty($dataValidationCollection)) {
@@ -606,7 +702,7 @@ class Worksheet extends WriterPart
$objWriter->writeAttribute('prompt', $dv->getPrompt());
}
- $objWriter->writeAttribute('sqref', $coordinate);
+ $objWriter->writeAttribute('sqref', $dv->getSqref() ?? $coordinate);
if ($dv->getFormula1() !== '') {
$objWriter->writeElement('formula1', $dv->getFormula1());
@@ -624,14 +720,11 @@ class Worksheet extends WriterPart
/**
* Write Hyperlinks.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// Hyperlink collection
- $hyperlinkCollection = $pSheet->getHyperlinkCollection();
+ $hyperlinkCollection = $worksheet->getHyperlinkCollection();
// Relation ID
$relationId = 1;
@@ -665,18 +758,15 @@ class Worksheet extends WriterPart
/**
* Write ProtectedRanges.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
- if (count($pSheet->getProtectedCells()) > 0) {
+ if (count($worksheet->getProtectedCells()) > 0) {
// protectedRanges
$objWriter->startElement('protectedRanges');
// Loop protectedRanges
- foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) {
+ foreach ($worksheet->getProtectedCells() as $protectedCell => $passwordHash) {
// protectedRange
$objWriter->startElement('protectedRange');
$objWriter->writeAttribute('name', 'p' . md5($protectedCell));
@@ -693,18 +783,15 @@ class Worksheet extends WriterPart
/**
* Write MergeCells.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
- if (count($pSheet->getMergeCells()) > 0) {
+ if (count($worksheet->getMergeCells()) > 0) {
// mergeCells
$objWriter->startElement('mergeCells');
// Loop mergeCells
- foreach ($pSheet->getMergeCells() as $mergeCell) {
+ foreach ($worksheet->getMergeCells() as $mergeCell) {
// mergeCell
$objWriter->startElement('mergeCell');
$objWriter->writeAttribute('ref', $mergeCell);
@@ -717,23 +804,20 @@ class Worksheet extends WriterPart
/**
* Write PrintOptions.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// printOptions
$objWriter->startElement('printOptions');
- $objWriter->writeAttribute('gridLines', ($pSheet->getPrintGridlines() ? 'true' : 'false'));
+ $objWriter->writeAttribute('gridLines', ($worksheet->getPrintGridlines() ? 'true' : 'false'));
$objWriter->writeAttribute('gridLinesSet', 'true');
- if ($pSheet->getPageSetup()->getHorizontalCentered()) {
+ if ($worksheet->getPageSetup()->getHorizontalCentered()) {
$objWriter->writeAttribute('horizontalCentered', 'true');
}
- if ($pSheet->getPageSetup()->getVerticalCentered()) {
+ if ($worksheet->getPageSetup()->getVerticalCentered()) {
$objWriter->writeAttribute('verticalCentered', 'true');
}
@@ -742,32 +826,26 @@ class Worksheet extends WriterPart
/**
* Write PageMargins.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// pageMargins
$objWriter->startElement('pageMargins');
- $objWriter->writeAttribute('left', StringHelper::formatNumber($pSheet->getPageMargins()->getLeft()));
- $objWriter->writeAttribute('right', StringHelper::formatNumber($pSheet->getPageMargins()->getRight()));
- $objWriter->writeAttribute('top', StringHelper::formatNumber($pSheet->getPageMargins()->getTop()));
- $objWriter->writeAttribute('bottom', StringHelper::formatNumber($pSheet->getPageMargins()->getBottom()));
- $objWriter->writeAttribute('header', StringHelper::formatNumber($pSheet->getPageMargins()->getHeader()));
- $objWriter->writeAttribute('footer', StringHelper::formatNumber($pSheet->getPageMargins()->getFooter()));
+ $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.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
- $autoFilterRange = $pSheet->getAutoFilter()->getRange();
+ $autoFilterRange = $worksheet->getAutoFilter()->getRange();
if (!empty($autoFilterRange)) {
// autoFilter
$objWriter->startElement('autoFilter');
@@ -781,13 +859,13 @@ class Worksheet extends WriterPart
$objWriter->writeAttribute('ref', str_replace('$', '', $range));
- $columns = $pSheet->getAutoFilter()->getColumns();
+ $columns = $worksheet->getAutoFilter()->getColumns();
if (count($columns) > 0) {
foreach ($columns as $columnID => $column) {
$rules = $column->getRules();
if (count($rules) > 0) {
$objWriter->startElement('filterColumn');
- $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID));
+ $objWriter->writeAttribute('colId', $worksheet->getAutoFilter()->getColumnOffset($columnID));
$objWriter->startElement($column->getFilterType());
if ($column->getJoin() == Column::AUTOFILTER_COLUMN_JOIN_AND) {
@@ -807,15 +885,18 @@ class Worksheet extends WriterPart
$objWriter->writeAttribute('type', $rule->getGrouping());
$val = $column->getAttribute('val');
if ($val !== null) {
- $objWriter->writeAttribute('val', $val);
+ $objWriter->writeAttribute('val', "$val");
}
$maxVal = $column->getAttribute('maxVal');
if ($maxVal !== null) {
- $objWriter->writeAttribute('maxVal', $maxVal);
+ $objWriter->writeAttribute('maxVal', "$maxVal");
}
} elseif ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) {
// Top 10 Filter Rule
- $objWriter->writeAttribute('val', $rule->getValue());
+ $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 {
@@ -827,14 +908,18 @@ class Worksheet extends WriterPart
}
if ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_DATEGROUP) {
// Date Group filters
- foreach ($rule->getValue() as $key => $value) {
- if ($value > '') {
- $objWriter->writeAttribute($key, $value);
+ $ruleValue = $rule->getValue();
+ if (is_array($ruleValue)) {
+ foreach ($ruleValue as $key => $value) {
+ $objWriter->writeAttribute($key, "$value");
}
}
$objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping());
} else {
- $objWriter->writeAttribute('val', $rule->getValue());
+ $ruleValue = $rule->getValue();
+ if (!is_array($ruleValue)) {
+ $objWriter->writeAttribute('val', "$ruleValue");
+ }
}
$objWriter->endElement();
@@ -853,39 +938,36 @@ class Worksheet extends WriterPart
/**
* Write PageSetup.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// pageSetup
$objWriter->startElement('pageSetup');
- $objWriter->writeAttribute('paperSize', $pSheet->getPageSetup()->getPaperSize());
- $objWriter->writeAttribute('orientation', $pSheet->getPageSetup()->getOrientation());
+ $objWriter->writeAttribute('paperSize', $worksheet->getPageSetup()->getPaperSize());
+ $objWriter->writeAttribute('orientation', $worksheet->getPageSetup()->getOrientation());
- if ($pSheet->getPageSetup()->getScale() !== null) {
- $objWriter->writeAttribute('scale', $pSheet->getPageSetup()->getScale());
+ if ($worksheet->getPageSetup()->getScale() !== null) {
+ $objWriter->writeAttribute('scale', $worksheet->getPageSetup()->getScale());
}
- if ($pSheet->getPageSetup()->getFitToHeight() !== null) {
- $objWriter->writeAttribute('fitToHeight', $pSheet->getPageSetup()->getFitToHeight());
+ if ($worksheet->getPageSetup()->getFitToHeight() !== null) {
+ $objWriter->writeAttribute('fitToHeight', $worksheet->getPageSetup()->getFitToHeight());
} else {
$objWriter->writeAttribute('fitToHeight', '0');
}
- if ($pSheet->getPageSetup()->getFitToWidth() !== null) {
- $objWriter->writeAttribute('fitToWidth', $pSheet->getPageSetup()->getFitToWidth());
+ if ($worksheet->getPageSetup()->getFitToWidth() !== null) {
+ $objWriter->writeAttribute('fitToWidth', $worksheet->getPageSetup()->getFitToWidth());
} else {
$objWriter->writeAttribute('fitToWidth', '0');
}
- if ($pSheet->getPageSetup()->getFirstPageNumber() !== null) {
- $objWriter->writeAttribute('firstPageNumber', $pSheet->getPageSetup()->getFirstPageNumber());
+ if ($worksheet->getPageSetup()->getFirstPageNumber() !== null) {
+ $objWriter->writeAttribute('firstPageNumber', $worksheet->getPageSetup()->getFirstPageNumber());
$objWriter->writeAttribute('useFirstPageNumber', '1');
}
- $objWriter->writeAttribute('pageOrder', $pSheet->getPageSetup()->getPageOrder());
+ $objWriter->writeAttribute('pageOrder', $worksheet->getPageSetup()->getPageOrder());
- $getUnparsedLoadedData = $pSheet->getParent()->getUnparsedLoadedData();
- if (isset($getUnparsedLoadedData['sheets'][$pSheet->getCodeName()]['pageSetupRelId'])) {
- $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$pSheet->getCodeName()]['pageSetupRelId']);
+ $getUnparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData();
+ if (isset($getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'])) {
+ $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId']);
}
$objWriter->endElement();
@@ -893,40 +975,34 @@ class Worksheet extends WriterPart
/**
* Write Header / Footer.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// headerFooter
$objWriter->startElement('headerFooter');
- $objWriter->writeAttribute('differentOddEven', ($pSheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false'));
- $objWriter->writeAttribute('differentFirst', ($pSheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false'));
- $objWriter->writeAttribute('scaleWithDoc', ($pSheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false'));
- $objWriter->writeAttribute('alignWithMargins', ($pSheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false'));
+ $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', $pSheet->getHeaderFooter()->getOddHeader());
- $objWriter->writeElement('oddFooter', $pSheet->getHeaderFooter()->getOddFooter());
- $objWriter->writeElement('evenHeader', $pSheet->getHeaderFooter()->getEvenHeader());
- $objWriter->writeElement('evenFooter', $pSheet->getHeaderFooter()->getEvenFooter());
- $objWriter->writeElement('firstHeader', $pSheet->getHeaderFooter()->getFirstHeader());
- $objWriter->writeElement('firstFooter', $pSheet->getHeaderFooter()->getFirstFooter());
+ $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.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// Get row and column breaks
$aRowBreaks = [];
$aColumnBreaks = [];
- foreach ($pSheet->getBreaks() as $cell => $breakType) {
+ foreach ($worksheet->getBreaks() as $cell => $breakType) {
if ($breakType == PhpspreadsheetWorksheet::BREAK_ROW) {
$aRowBreaks[] = $cell;
} elseif ($breakType == PhpspreadsheetWorksheet::BREAK_COLUMN) {
@@ -974,27 +1050,25 @@ class Worksheet extends WriterPart
/**
* Write SheetData.
*
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
- * @param string[] $pStringTable String table
+ * @param string[] $stringTable String table
*/
- private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, array $pStringTable): void
+ private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, array $stringTable): void
{
// Flipped stringtable, for faster index searching
- $aFlippedStringTable = $this->getParentWriter()->getWriterPart('stringtable')->flipStringTable($pStringTable);
+ $aFlippedStringTable = $this->getParentWriter()->getWriterPartstringtable()->flipStringTable($stringTable);
// sheetData
$objWriter->startElement('sheetData');
// Get column count
- $colCount = Coordinate::columnIndexFromString($pSheet->getHighestColumn());
+ $colCount = Coordinate::columnIndexFromString($worksheet->getHighestColumn());
// Highest row number
- $highestRow = $pSheet->getHighestRow();
+ $highestRow = $worksheet->getHighestRow();
// Loop through cells
$cellsByRow = [];
- foreach ($pSheet->getCoordinates() as $coordinate) {
+ foreach ($worksheet->getCoordinates() as $coordinate) {
$cellAddress = Coordinate::coordinateFromString($coordinate);
$cellsByRow[$cellAddress[1]][] = $coordinate;
}
@@ -1002,7 +1076,7 @@ class Worksheet extends WriterPart
$currentRow = 0;
while ($currentRow++ < $highestRow) {
// Get row dimension
- $rowDimension = $pSheet->getRowDimension($currentRow);
+ $rowDimension = $worksheet->getRowDimension($currentRow);
// Write current row?
$writeCurrentRow = isset($cellsByRow[$currentRow]) || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() == false || $rowDimension->getCollapsed() == true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null;
@@ -1044,7 +1118,7 @@ class Worksheet extends WriterPart
if (isset($cellsByRow[$currentRow])) {
foreach ($cellsByRow[$currentRow] as $cellAddress) {
// Write cell
- $this->writeCell($objWriter, $pSheet, $cellAddress, $aFlippedStringTable);
+ $this->writeCell($objWriter, $worksheet, $cellAddress, $aFlippedStringTable);
}
}
@@ -1063,25 +1137,28 @@ class Worksheet extends WriterPart
{
$objWriter->writeAttribute('t', $mappedType);
if (!$cellValue instanceof RichText) {
- $objWriter->writeElement('t', StringHelper::controlCharacterPHP2OOXML(htmlspecialchars($cellValue)));
+ $objWriter->writeElement(
+ 't',
+ StringHelper::controlCharacterPHP2OOXML(htmlspecialchars($cellValue, Settings::htmlEntityFlags()))
+ );
} elseif ($cellValue instanceof RichText) {
$objWriter->startElement('is');
- $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $cellValue);
+ $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $cellValue);
$objWriter->endElement();
}
}
/**
* @param RichText|string $cellValue
- * @param string[] $pFlippedStringTable
+ * @param string[] $flippedStringTable
*/
- private function writeCellString(XMLWriter $objWriter, string $mappedType, $cellValue, array $pFlippedStringTable): void
+ private function writeCellString(XMLWriter $objWriter, string $mappedType, $cellValue, array $flippedStringTable): void
{
$objWriter->writeAttribute('t', $mappedType);
if (!$cellValue instanceof RichText) {
- self::writeElementIf($objWriter, isset($pFlippedStringTable[$cellValue]), 'v', $pFlippedStringTable[$cellValue] ?? '');
+ self::writeElementIf($objWriter, isset($flippedStringTable[$cellValue]), 'v', $flippedStringTable[$cellValue] ?? '');
} else {
- $objWriter->writeElement('v', $pFlippedStringTable[$cellValue->getHashCode()]);
+ $objWriter->writeElement('v', $flippedStringTable[$cellValue->getHashCode()]);
}
}
@@ -1115,9 +1192,9 @@ class Worksheet extends WriterPart
$objWriter->writeElement('v', $cellIsFormula ? $formulaerr : $cellValue);
}
- private function writeCellFormula(XMLWriter $objWriter, string $cellValue, Cell $pCell): void
+ private function writeCellFormula(XMLWriter $objWriter, string $cellValue, Cell $cell): void
{
- $calculatedValue = $this->getParentWriter()->getPreCalculateFormulas() ? $pCell->getCalculatedValue() : $cellValue;
+ $calculatedValue = $this->getParentWriter()->getPreCalculateFormulas() ? $cell->getCalculatedValue() : $cellValue;
if (is_string($calculatedValue)) {
if (\PhpOffice\PhpSpreadsheet\Calculation\Functions::isError($calculatedValue)) {
$this->writeCellError($objWriter, 'e', $cellValue, $calculatedValue);
@@ -1125,46 +1202,45 @@ class Worksheet extends WriterPart
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(substr($cellValue, 1));
+ $objWriter->endElement();
+ } else {
+ $objWriter->writeElement('f', Xlfn::addXlfnStripEquals($cellValue));
+ self::writeElementIf(
+ $objWriter,
+ $this->getParentWriter()->getOffice2003Compatibility() === false,
+ 'v',
+ ($this->getParentWriter()->getPreCalculateFormulas() && !is_array($calculatedValue) && substr($calculatedValue, 0, 1) !== '#')
+ ? StringHelper::formatNumber($calculatedValue) : '0'
+ );
}
- // array values are not yet supported
- //$attributes = $pCell->getFormulaAttributes();
- //if (($attributes['t'] ?? null) === 'array') {
- // $objWriter->startElement('f');
- // $objWriter->writeAttribute('t', 'array');
- // $objWriter->writeAttribute('ref', $pCellAddress);
- // $objWriter->writeAttribute('aca', '1');
- // $objWriter->writeAttribute('ca', '1');
- // $objWriter->text(substr($cellValue, 1));
- // $objWriter->endElement();
- //} else {
- // $objWriter->writeElement('f', Xlfn::addXlfnStripEquals($cellValue));
- //}
- $objWriter->writeElement('f', Xlfn::addXlfnStripEquals($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 XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
- * @param string $pCellAddress Cell Address
- * @param string[] $pFlippedStringTable String table (flipped), for faster index searching
+ * @param string $cellAddress Cell Address
+ * @param string[] $flippedStringTable String table (flipped), for faster index searching
*/
- private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, string $pCellAddress, array $pFlippedStringTable): void
+ private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, string $cellAddress, array $flippedStringTable): void
{
// Cell
- $pCell = $pSheet->getCell($pCellAddress);
+ $pCell = $worksheet->getCell($cellAddress);
$objWriter->startElement('c');
- $objWriter->writeAttribute('r', $pCellAddress);
+ $objWriter->writeAttribute('r', $cellAddress);
// Sheet styles
$xfi = $pCell->getXfIndex();
@@ -1183,7 +1259,7 @@ class Worksheet extends WriterPart
break;
case 's': // String
- $this->writeCellString($objWriter, $mappedType, $cellValue, $pFlippedStringTable);
+ $this->writeCellString($objWriter, $mappedType, $cellValue, $flippedStringTable);
break;
case 'f': // Formula
@@ -1209,16 +1285,14 @@ class Worksheet extends WriterPart
/**
* Write Drawings.
*
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
* @param bool $includeCharts Flag indicating if we should include drawing details for charts
*/
- private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, $includeCharts = false): void
+ private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, $includeCharts = false): void
{
- $unparsedLoadedData = $pSheet->getParent()->getUnparsedLoadedData();
- $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds']);
- $chartCount = ($includeCharts) ? $pSheet->getChartCollection()->count() : 0;
- if ($chartCount == 0 && $pSheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) {
+ $unparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData();
+ $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']);
+ $chartCount = ($includeCharts) ? $worksheet->getChartCollection()->count() : 0;
+ if ($chartCount == 0 && $worksheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) {
return;
}
@@ -1226,8 +1300,8 @@ class Worksheet extends WriterPart
$objWriter->startElement('drawing');
$rId = 'rId1';
- if (isset($unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds'])) {
- $drawingOriginalIds = $unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds'];
+ 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);
@@ -1239,14 +1313,11 @@ class Worksheet extends WriterPart
/**
* Write LegacyDrawing.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// If sheet contains comments, add the relationships
- if (count($pSheet->getComments()) > 0) {
+ if (count($worksheet->getComments()) > 0) {
$objWriter->startElement('legacyDrawing');
$objWriter->writeAttribute('r:id', 'rId_comments_vml1');
$objWriter->endElement();
@@ -1255,28 +1326,60 @@ class Worksheet extends WriterPart
/**
* Write LegacyDrawingHF.
- *
- * @param XMLWriter $objWriter XML Writer
- * @param PhpspreadsheetWorksheet $pSheet Worksheet
*/
- private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
// If sheet contains images, add the relationships
- if (count($pSheet->getHeaderFooter()->getImages()) > 0) {
+ if (count($worksheet->getHeaderFooter()->getImages()) > 0) {
$objWriter->startElement('legacyDrawingHF');
$objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1');
$objWriter->endElement();
}
}
- private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet): void
+ private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void
{
- if (empty($pSheet->getParent()->getUnparsedLoadedData()['sheets'][$pSheet->getCodeName()]['AlternateContents'])) {
+ if (empty($worksheet->getParent()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'])) {
return;
}
- foreach ($pSheet->getParent()->getUnparsedLoadedData()['sheets'][$pSheet->getCodeName()]['AlternateContents'] as $alternateContent) {
+ foreach ($worksheet->getParent()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'] as $alternateContent) {
$objWriter->writeRaw($alternateContent);
}
}
+
+ /**
+ * write
+ * 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();
+ // @phpstan-ignore-next-line
+ 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
+ }
+ }
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php
index a9137dfc858..0bfb356d83d 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php
@@ -26,8 +26,8 @@ abstract class WriterPart
/**
* Set parent Xlsx object.
*/
- public function __construct(Xlsx $pWriter)
+ public function __construct(Xlsx $writer)
{
- $this->parentWriter = $pWriter;
+ $this->parentWriter = $writer;
}
}
diff --git a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php
index 8f7c07e83ae..c88ef245b63 100644
--- a/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php
+++ b/lib/phpspreadsheet/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php
@@ -10,6 +10,7 @@ class Xlfn
. '|beta[.]inv'
. '|binom[.]dist'
. '|binom[.]inv'
+ . '|ceiling[.]precise'
. '|chisq[.]dist'
. '|chisq[.]dist[.]rt'
. '|chisq[.]inv'
@@ -27,6 +28,7 @@ class Xlfn
. '|f[.]inv'
. '|f[.]inv[.]rt'
. '|f[.]test'
+ . '|floor[.]precise'
. '|gamma[.]dist'
. '|gamma[.]inv'
. '|gammaln[.]precise'
@@ -138,6 +140,11 @@ class Xlfn
. '|unique'
. '|xlookup'
. '|xmatch'
+ . '|arraytotext'
+ . '|call'
+ . '|let'
+ . '|register[.]id'
+ . '|valuetotext'
. ')(?=\\s*[(])/i';
/**